-1

I am trying to create a java application that translates spanish into english. I am facing problem while translating spanish into english. But when i translate english into spansih it works. Here is my code. Here is my code. Can you please tell me my error. This code is working right now but when i change the values of fromLang to toLang from en to es it does not work.

import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.*;  
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;

public class GuiApp1 {  

    private static final String CLIENT_ID = "FREE_TRIAL_ACCOUNT";
    private static final String CLIENT_SECRET = "PUBLIC_SECRET";
    private static final String ENDPOINT = "http://api.whatsmate.net/v1/translation/translate";



    public static void main(String[] args) throws Exception {  


    GuiApp1 g = new GuiApp1();

    JFrame f=new JFrame();//creating instance of JFrame  

    f.setAlwaysOnTop( true );


    JButton b=new JButton("Translate");//creating instance of JButton  
    b.setBounds(90,150,100, 40);//x axis, y axis, width, height  

    f.add(b);//adding button in JFrame  

    JTextArea t1,t2;  
    t1=new JTextArea(2,2); 
    String spanish; 
    t1.setBounds(50,100, 200,30);  
    t2=new JTextArea(2,2);  
    t2.setBounds(50,200, 200,30);  
    f.add(t1); f.add(t2);
    f.setPreferredSize(new Dimension(200, 900));    
    f.setLayout(null);//using no layout managers  
    f.setVisible(true);//making the frame visible  


    b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){

      String text = t1.getText();
      text = text.trim();
      text = text.toLowerCase();




      System.out.println(text);

      String fromLang = "en";
      String toLang = "es";

      //String text = "Cuál es su nombre";
    try{

  translate(fromLang, toLang, text);
    }catch(Exception e){
        System.out.println(e);
    }

   }
});
    }

  /**
   * Sends out a WhatsApp message via WhatsMate WA Gateway.
   */
  public static void translate(String fromLang, String toLang, String text) throws Exception {
    // TODO: Should have used a 3rd party library to make a JSON string from an object
    String jsonPayload = new StringBuilder()
      .append("{")
      .append("\"fromLang\":\"")
      .append(fromLang)
      .append("\",")
      .append("\"toLang\":\"")
      .append(toLang)
      .append("\",")
      .append("\"text\":\"")
      .append(text)
      .append("\"")
      .append("}")
      .toString();

    URL url = new URL(ENDPOINT);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("X-WM-CLIENT-ID", CLIENT_ID);
    conn.setRequestProperty("X-WM-CLIENT-SECRET", CLIENT_SECRET);
    conn.setRequestProperty("Content-Type", "application/json");

    OutputStream os = conn.getOutputStream();
    os.write(jsonPayload.getBytes());
    os.flush();
    os.close();

    int statusCode = conn.getResponseCode();
    System.out.println("Status Code: " + statusCode);
    BufferedReader br = new BufferedReader(new InputStreamReader(
        (statusCode == 200) ? conn.getInputStream() : conn.getErrorStream()
      ));
    String output;
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }
    conn.disconnect();
  }  
}  
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    Consider adding an explanation of what `its not working` means. What response / statusCode do you receive? – second Nov 30 '19 at 09:56

1 Answers1

0

Perhaps you've now exceeded the Free Trial usage limit of 10.

In any case, the code does work. It will translate from English to Spanish OR Spanish to English. All you need to do is make sure you have a means to select which translation direction you want to go with. Currently you do not have this and are translating via a default of en to es. If you change the fromLang variable contents to "es" and the toLang variable contents to en and enter a Spanish word into the JTextArea t1 then hit the Translate button you will receive the translation into the Console Window (instead of the JTextArea, t2). The received string should be placed into JTextArea, t2. In order to place the returned string into the JTextArea t2 you will want to make the tranlate() method return a String type then in the while loop at the bottom of the method, instead of sending the returned data to console do something like this:

public static String translate(String fromLang, String toLang, String text) throws Exception {

    // ... Most method code here ...

    String output;
    StringBuilder sb = new StringBuilder();
    while ((output = br.readLine()) != null) {
        sb.append(output).append(System.lineSeparator());
        System.out.println(output);  // Optional - For testing
    }
    conn.disconnect();

    return sb.toString();
}

Now, where the translate() method is called, do this instead:

try {
    String translation = translate(fromLang, toLang, text);
    t2.setText(translation);
} 
catch (Exception e) {
    System.out.println(e);
}

Now the returned translation will be placed within the t2 JTextArea. I have taken the above mentioned modifications and applied them to your code provided below:

enter image description here

import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.Border;

public class Translator {
    private static final String CLIENT_ID = "FREE_TRIAL_ACCOUNT";
    private static final String CLIENT_SECRET = "PUBLIC_SECRET";
    private static final String ENDPOINT = "http://api.whatsmate.net/v1/translation/translate";

    @SuppressWarnings("Convert2Lambda")
    public static void main(String[] args) throws Exception {
        Translator g = new Translator();

        JFrame f = new JFrame();//creating instance of JFrame  
        f.setTitle("Translator");
        f.setAlwaysOnTop(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setPreferredSize(new Dimension(295, 300));
        f.setLayout(null);  //using no layout manager (*** BAD IDEA!! ***)

        String[] transDirection = {"English To Spanish", "Spanish To English"};        
        JComboBox<String> jc = new JComboBox<>(transDirection);
        jc.setSelectedIndex(0);
        jc.setBounds(60, 30, 160, 25);
        f.add(jc);

        JButton b = new JButton("Translate");//creating instance of JButton  
        b.setBounds(90, 140, 100, 30);//x axis, y axis, width, height  
        f.add(b);//adding button in JFrame  

        Border border = BorderFactory.createLineBorder(Color.decode("#33acff"));
        JTextArea t1 = new JTextArea(2, 2);
        t1.setBounds(40, 80, 200, 50);
        t1.setBorder(border);
        t1.setLineWrap(true);
        t1.setWrapStyleWord(true);
        JScrollPane sp1 = new JScrollPane(t1);
        sp1.setBounds(40, 80, 200, 50);
        // ---------------------
        JTextArea t2 = new JTextArea(2, 2);
        t2.setBounds(40, 180, 200, 50);
        t2.setBorder(border);
        t2.setLineWrap(true);
        t2.setWrapStyleWord(true);
        JScrollPane sp2 = new JScrollPane(t2);
        sp2.setBounds(40, 180, 200, 50);
        f.add(sp1, BorderLayout.CENTER);
        f.add(sp2, BorderLayout.CENTER);

        f.pack();
        f.setVisible(true);//making the frame visible  
        f.setLocationRelativeTo(null); // Must be after setVisible().

        t1.requestFocus(); // Set focus on t1 when started

        // Button Action Listener...
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                String text = t1.getText().trim();

                //Make sure there is text to translate...
                if (text.equals("")) {
                    JOptionPane.showMessageDialog(f, "There is no text supplied to translate!", 
                                                  "Translation Error!", JOptionPane.WARNING_MESSAGE);
                    return;     // Get out of this event.
                }
                // Get selected language translation direction...
                String fromLang = "";
                String toLang = "";                
                switch (jc.getSelectedItem().toString().toLowerCase()) {
                    case "english to spanish":
                        fromLang = "en";
                        toLang = "es";
                        break;
                    case "spanish to english":
                        fromLang = "es";
                        toLang = "en";
                        break;
                    default:
                        fromLang = "en";
                        toLang = "es";
                }

                try {
                    String translation = translate(fromLang, toLang, text);
                    t2.setText(translation);
                }
                catch (Exception e) {
                    System.out.println(e);
                }
            }
        });
    }

    /**
     * Sends out a WhatsApp message via WhatsMate WA Gateway.<br><br>
     * @param fromLang
     * @param toLang
     * @param text
     * @return 
     * @throws java.lang.Exception
     */
    public static String translate(String fromLang, String toLang, String text) throws Exception {
        // TODO: Should have used a 3rd party library to make a JSON string from an object
        String jsonPayload = new StringBuilder()
                .append("{")
                .append("\"fromLang\":\"")
                .append(fromLang)
                .append("\",")
                .append("\"toLang\":\"")
                .append(toLang)
                .append("\",")
                .append("\"text\":\"")
                .append(text)
                .append("\"")
                .append("}")
                .toString();

        URL url = new URL(ENDPOINT);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("X-WM-CLIENT-ID", CLIENT_ID);
        conn.setRequestProperty("X-WM-CLIENT-SECRET", CLIENT_SECRET);
        conn.setRequestProperty("Content-Type", "application/json");

        // 'Try With Resources' used here to auto-close stream.
        try (OutputStream os = conn.getOutputStream()) {
            os.write(jsonPayload.getBytes());
            os.flush();
        }

        int statusCode = conn.getResponseCode();
        System.out.println("Status Code: " + statusCode);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (statusCode == 200) ? conn.getInputStream() : conn.getErrorStream()
        ));

        String output;
        StringBuilder sb = new StringBuilder();
        while ((output = br.readLine()) != null) {
            sb.append(output).append(System.lineSeparator());
            System.out.println(output);
        }
        conn.disconnect();

        return sb.toString();
    }
}

On a side note: You use no layout manager (null) in the creation of your Form by choice. This is actually a bad idea, here's why (be sure to read the comments as well).

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22