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    public int getHeight()
046    {
047        return height;
048    }
049
050    public int getWidth()
051    {
052        return width;
053    }
054
055    public BufferedImage createImage(String text)
056    {
057        return producer.createImage(text);
058    }
059
060    public String createText()
061    {
062        return producer.createText();
063    }
064
065    private static Properties toProperties(Map<String, String> map)
066    {
067        Properties result = new Properties();
068
069        for (String key : map.keySet())
070        {
071            result.put(key, map.get(key));
072        }
073
074        return result;
075
076    }
077}