001// Copyright 2011 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007// http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.kaptcha.internal.services;
016
017import com.google.code.kaptcha.impl.DefaultKaptcha;
018import com.google.code.kaptcha.util.Config;
019import org.apache.tapestry5.kaptcha.services.KaptchaProducer;
020
021import java.awt.image.BufferedImage;
022import java.util.Map;
023import java.util.Properties;
024
025public class KaptchaProducerImpl implements KaptchaProducer
026{
027    private final DefaultKaptcha producer;
028
029    private final int height;
030
031    private final int width;
032
033    public KaptchaProducerImpl(Map<String, String> configuration)
034    {
035        producer = new DefaultKaptcha();
036
037        Config config = new Config(toProperties(configuration));
038
039        producer.setConfig(config);
040
041        height = config.getHeight();
042        width = config.getWidth();
043    }
044
045    @Override
046    public int getHeight()
047    {
048        return height;
049    }
050
051    @Override
052    public int getWidth()
053    {
054        return width;
055    }
056
057    @Override
058    public BufferedImage createImage(String text)
059    {
060        return producer.createImage(text);
061    }
062
063    @Override
064    public String createText()
065    {
066        return producer.createText();
067    }
068
069    private static Properties toProperties(Map<String, String> map)
070    {
071        Properties result = new Properties();
072
073        for (String key : map.keySet())
074        {
075            result.put(key, map.get(key));
076        }
077
078        return result;
079
080    }
081}