Saturday, June 13, 2015

Crear Traductor usando API http://spa.hablaa.com/ con Primefaces

Crear Traductor usando API http://spa.hablaa.com/ con Primefaces

Hablaa.com es un direccionario en linea que ofrece un servicio de traducción grauito

Podemos implementar nuestro traductor, permitiendo al usuario que seleccione el idioma origen y el destino y realicemos la conversión.



Para las traducciones utilizamos el url, donde especificamos la palabra a traducir, el idioma origien (3 caracteres) y el idioma destino(3 caracteres)
En este ejemplo traducimos la palabra apple de ingles a español y nos devuelve un json
[{"text":"la manzana","pos":{"code":null,"title":null},"source":"Hablaa.com"},{"text":"manzana","pos":{"code":null,"title":null},"source":"Hablaa.com"}]


Luego solo nos queda procesar el json y obtener el atributo text que contiene la palabra.
Para ver la lista de idiomas soportados













LectorJSON.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.javscaz.girosjsd.generales;


import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;


/**
*
* @author avbravo
*/
@Named(value = "lectorJSON")
@SessionScoped
public class LectorJSON implements Serializable {


   private String lectura;
   private String origen;
   private String destino;
   private String languageorigen;
   private String languagedestino;


   public String getLanguageorigen() {
       return languageorigen;
   }


   public void setLanguageorigen(String languageorigen) {
       this.languageorigen = languageorigen;
   }


   public String getLanguagedestino() {
       return languagedestino;
   }


   public void setLanguagedestino(String languagedestino) {
       this.languagedestino = languagedestino;
   }


   public String getOrigen() {
       return origen;
   }


   public void setOrigen(String origen) {
       this.origen = origen;
   }


   public String getDestino() {
       return destino;
   }


   public void setDestino(String destino) {
       this.destino = destino;
   }


   public String getLectura() {
       return lectura;
   }


   public void setLectura(String lectura) {
       this.lectura = lectura;
   }


   /**
    * Creates a new instance of LectorJSON
    */
   public LectorJSON() {
   }


   public String lector() throws IOException {
       try {
                 origen = origen.trim();
           destino = "";
           URL url = new URL("http://spa.hablaa.com/hs/translation/" + origen + "/" + languageorigen + "-" + languagedestino + "/");
           InputStream is = url.openStream();


           JsonParser parser = Json.createParser(is);
           while (parser.hasNext()) {
               Event e = parser.next();
               if (e == Event.KEY_NAME) {
                   switch (parser.getString()) {
                       case "text":
                           parser.next();                        
                           destino = parser.getString();
                           break;
                   }
               }
           }


       } catch (Exception ex) {
           JSFUtil.addErrorMessage("lector() " + ex.getLocalizedMessage());
       }
       return null;
   }


}

















Página .xhtml


<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
     xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
     xmlns:p="http://primefaces.org/ui"
     xmlns:h="http://xmlns.jcp.org/jsf/html"
     xmlns:f="http://xmlns.jcp.org/jsf/core"


     xmlns:b="http://bootsfaces.net/ui">


   <body>


       <ui:composition template="./template.xhtml">
           <ui:define name="content">
               <f:view>
                   <h:form>
                      <b:panel look="primary" title="#{app['application.title']}">
                     <h:panelGrid columns="4" cellpadding="5">
                              <h:outputText value="origen:"/>
                               <b:inputText value="#{lectorJSON.origen}">
                                   <f:facet name="prepend">
                                       <h:outputText value="" />
                                   </f:facet>
                               </b:inputText>
                               <h:outputText  value="traducida:"/>
                               <b:inputText id="salida" value="#{lectorJSON.destino}">
                               </b:inputText>
                               <h:outputText  value="De"/>
<b:selectOneMenu  value="#{lectorJSON.languageorigen}"                
                                                 required="true"
                                                 >
                             <f:selectItem itemLabel="Español" itemValue="spa" />
                            <f:selectItem itemLabel="Chino(simplificado)" itemValue="zho" />
                            <f:selectItem itemLabel="Ingles" itemValue="eng" />
</b:selectOneMenu>
                              <h:outputText  value="A"/>
             <b:selectOneMenu  value="#{lectorJSON.languagedestino}"                     
                                                 required="true"
                                                 >
                             <f:selectItem itemLabel="Chino(simplificado)" itemValue="zho" />
                             <f:selectItem itemLabel="Ingles" itemValue="eng" />
                             <f:selectItem itemLabel="Español" itemValue="spa" />
         </b:selectOneMenu>


<p:commandButton value="Traducir" actionListener="#{lectorJSON.lector()}"
                                              update="salida,growl"
                                               />
                           </h:panelGrid>
                       </b:panel>
                       <p:growl id="growl" showDetail="true" />
                       <p:growl id="messages" showDetail="true" life="2000" />
                   </h:form>
              </f:view>
           </ui:define>


           <!--            <ui:define name="bottom">
                           bottom
                       </ui:define>-->


       </ui:composition>


   </body>
</html>

















No comments: