2015-07-29 1 views
0

Я начал использовать jcaptcha library для реализации простого изображения на основе captcha для моего проекта, и все прошло хорошо, отлично. Но теперь я хочу интегрировать звук captcha, а также с image captcha. Прошу прощения, как я могу его реализовать, используя библиотеку jcaptcha в Java.Как реализовать звуковую капчу с помощью библиотеки jcaptcha?

Вот фрагмент кода я работал на:

//captcha engine config 

public class CustomCaptchaEngine extends ListImageCaptchaEngine { 

@Override 
protected void buildInitialFactories() { 
    // TODO Auto-generated method stub 

    WordGenerator wordGen=new RandomWordGenerator("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzxyz"); 

    RandomRangeColorGenerator colorGen=new RandomRangeColorGenerator(new int[]{100,255},new int[]{50,200}, new int[]{50,150}); 

    TextPaster textPaster = new RandomTextPaster(new Integer(4), new Integer(5), colorGen, Boolean.TRUE); 

    BackgroundGenerator backgroundGenerator = new FileReaderRandomBackgroundGenerator(new Integer(200), new Integer(100), "C:/Users/pandabhi/eclipseworkspace/CaptchaTest/WebContent/captcha_backgrounds/"); 

    Font[] fontsList = new Font[] { new Font("Arial", Font.TYPE1_FONT, 10), new Font("Arial", 0, 14), new Font("Vardana", 0, 17), }; 

    FontGenerator fontGenerator = new RandomFontGenerator(20, 50, fontsList); 

    WordToImage wordToImage=new ComposedWordToImage(fontGenerator, backgroundGenerator, textPaster); 

    this.addFactory(new GimpyFactory(wordGen, wordToImage)); 
} 

} 


//captcha servlet 

public class ImageCaptchaServlet extends HttpServlet { 


/** 
* 
*/ 
private static final long serialVersionUID = 1L; 


public void init(ServletConfig servletConfig) throws ServletException { 

    super.init(servletConfig); 

} 


protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { 

    byte[] captchaChallengeAsJpeg = null; 
    // the output stream to render the captcha image as jpeg into 
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); 
    try { 
    // get the session id that will identify the generated captcha. 
    //the same id must be used to validate the response, the session id is a good candidate! 
    String captchaId = httpServletRequest.getSession().getId(); 
    // call the ImageCaptchaService getChallenge method 
     BufferedImage challenge = 
       CaptchaServiceInstance.getInstance().getImageChallengeForID(captchaId, 
         httpServletRequest.getLocale()); 

     // a jpeg encoder 
     ImageIO.write(challenge, "jpg", jpegOutputStream); 
    } catch (IllegalArgumentException e) { 
     httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); 
     return; 
    } catch (CaptchaServiceException e) { 
     httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
     return; 
    } 

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); 

    // flush it in the response 
    httpServletResponse.setHeader("Cache-Control", "no-store"); 
    httpServletResponse.setHeader("Pragma", "no-cache"); 
    httpServletResponse.setDateHeader("Expires", 0); 
    httpServletResponse.setContentType("image/jpeg"); 
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream(); 
    responseOutputStream.write(captchaChallengeAsJpeg); 
    responseOutputStream.flush(); 
    responseOutputStream.close(); 
} 
} 

//captcha service instance 

public class CaptchaServiceInstance { 

    private static ImageCaptchaService instance = 
       new DefaultManageableImageCaptchaService(new FastHashMapCaptchaStore(),new CustomCaptchaEngine(), 180,100000,75000); 


public static ImageCaptchaService getInstance(){ 
    return instance; 
} 
} 
+0

Что пробовали? Ваш пост может быть улучшен, если вы включили код, который вы в настоящее время пытаетесь использовать. Кроме того, SO запрещает людям запрашивать внешние ресурсы, такие как мысли о прогулках или учебные пособия. –

+1

спасибо за предложение @richard. добавлен код для более подробной информации. –

+0

Спасибо. Кроме того, я редактировал форматирование вашего кода (которое не будет отображаться до тех пор, пока мое редактирование не будет рассмотрено). Блоки кода форматируются с четырьмя пробелами. Выходы используются только для форматирования наклона (сначала форматирование SO может быть сложным). –

ответ

1
// Captcha sound generator 
//remember to change Voice.java file's deallocation() method as it was creating problems while compilation.Rebuild freetts source and use that. 

public class CustomSoundCaptchaService { 
private static SoundCaptchaService instanceSound=null; 

public static SoundCaptchaService getInstance(WordGenerator wordGen){ 

    SoundConfigurator soundConfig = new FreeTTSSoundConfigurator("kevin16", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory", 1.0f, 100, 100); 

    WordToSound word2sound = new FreeTTSWordToSound(soundConfig,6,7); 

    CaptchaFactory[] factories = new CaptchaFactory[]{new GimpySoundFactory(wordGen, word2sound)}; 

    CaptchaEngine captchaEngine = new GenericCaptchaEngine(factories); 

    instanceSound = new GenericManageableCaptchaService(captchaEngine, 180,180000, 75000); 
    return instanceSound; 
    } 
} 



//invoking servlet 
public class SoundCaptchaServlet extends HttpServlet { 
private static final long serialVersionUID = 1L; 


/** 
* @see HttpServlet#HttpServlet() 
*/ 
public SoundCaptchaServlet() { 
    super(); 
    // TODO Auto-generated constructor stub 
} 

/** 
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
*/ 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 

    AudioInputStream audioCaptcha=null; 
    try { 
     String captchaId = request.getSession().getId(); 
     WordGenerator wordGen= new RandomWordGenerator("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzxyz"); 
     audioCaptcha=CustomSoundCaptchaServlet.getInstance(worGen).getSoundChallengeForID(captchaId); 

    } catch (IllegalArgumentException e) { 
     e.printStackTrace(); 
     throw new RuntimeException(e); 
    } catch (CaptchaServiceException e) { 
     e.printStackTrace(); 
     throw new RuntimeException(e); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     throw new RuntimeException(e); 
    } 

    response.setDateHeader("Expires", 0); 
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); 
    response.addHeader("Cache-Control", "post-check=0, pre-check=0"); 
    response.setHeader("Pragma", "no-cache"); 
    response.setContentType("audio/mpeg"); 
    ServletOutputStream out = response.getOutputStream(); 
    ByteArrayOutputStream soundByteOutputStream = new ByteArrayOutputStream(); 
    AudioSystem.write(audioCaptcha,javax.sound.sampled.AudioFileFormat.Type.WAVE,soundByteOutputStream); 
    out.write(soundByteOutputStream.toByteArray()); 
    out.flush(); 
    out.close(); 
} 

/** 
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
*/ 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 
} 

//replace existing code in Voice.java with following 
public void deallocate() { 
setLoaded(false); 
utteranceProcessors.clear(); 

    if (!externalAudioPlayer) { 
     if (audioPlayer != null) { 
      audioPlayer.close(); 
      audioPlayer = null; 
     } 
    } 

if (!externalOutputQueue) { 

} 
} 
Смежные вопросы