001/* 002 * Copyright 2022 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.core.captcha; 017 018import java.util.Map; 019import java.util.stream.Collectors; 020 021import org.apache.avalon.framework.component.Component; 022import org.apache.avalon.framework.service.ServiceException; 023import org.apache.avalon.framework.service.ServiceManager; 024import org.apache.avalon.framework.service.Serviceable; 025 026import org.ametys.runtime.i18n.I18nizableText; 027import org.ametys.runtime.model.Enumerator; 028 029/** 030 * {@link Enumerator} for the captchas. 031 */ 032public class CaptchaEnumerator implements Enumerator<String>, Serviceable, Component 033{ 034 /** Avalon role */ 035 public static final String ROLE = org.ametys.core.captcha.CaptchaEnumerator.class.getName(); 036 037 /** The captcha extension point */ 038 private CaptchaExtensionPoint _captchaExtensionPoint; 039 private ServiceManager _manager; 040 041 @Override 042 public void service(ServiceManager manager) throws ServiceException 043 { 044 _manager = manager; 045 } 046 047 private CaptchaExtensionPoint getCaptchaExtensionPoint() 048 { 049 if (_captchaExtensionPoint == null) 050 { 051 try 052 { 053 _captchaExtensionPoint = (CaptchaExtensionPoint) _manager.lookup(CaptchaExtensionPoint.ROLE); 054 } 055 catch (ServiceException e) 056 { 057 // Can be called during application startup 058 return null; 059 } 060 } 061 return _captchaExtensionPoint; 062 } 063 064 @Override 065 public I18nizableText getEntry(String value) throws Exception 066 { 067 CaptchaExtensionPoint captchaExtensionPoint = getCaptchaExtensionPoint(); 068 069 if (captchaExtensionPoint != null) 070 { 071 return captchaExtensionPoint.getExtension(value).getLabel(); 072 } 073 else 074 { 075 // Can be called during application startup 076 return new I18nizableText(value); 077 } 078 } 079 080 @Override 081 public Map<String, I18nizableText> getTypedEntries() throws Exception 082 { 083 return getCaptchaExtensionPoint().getExtensionsIds() 084 .stream() 085 .map(extensionId -> _captchaExtensionPoint.getExtension(extensionId)) 086 .collect(Collectors.toMap(Captcha::getId, Captcha::getLabel)); 087 } 088}