0
\$\begingroup\$

I have to use SwingWorker for the first time today, and I'm pretty pleased with the result. Would you mind helping check that I used it correctly?

My class starts a GUI, sends messages to Salesforce Live Agent (chat) endpoints, and uses a SwingWorker to listen for messages sent from the Salesforce Live Agent to the visitor.

I'm mostly interested to learn whether I used SwingWorker correctly, and whether I'm doing the HTTP connections correctly as well.

As far as I can tell, my code works fine...no issues. However, I wonder if I'm doing things the right way.

import java.net.*;

import java.io.*;
import java.util.*;
import javax.json.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;

public class LiveAgentGUIWithSwingWorker extends JPanel implements ActionListener {

    protected JTextField textField;
    public JTextArea textArea;
    private final static String newline = "\n";

    String deploymentId;
    String organizationId;
    String buttonId;
    String keyStr;
    String affinityTokenStr;
    String test;

    private class LiveAgentLongPollingTask extends SwingWorker<Void, String>{
        @Override
        protected Void doInBackground(){
            //initiate the Chat
            //do loop for getting messages from the Live Agent
            //use publish to put new messages

            try{
                while(true){
                    URL liveAgentURL = new URL("https://someDomain/chat/rest/System/Messages");
                    System.out.println("Starting listener loop.");
                    HttpURLConnection con = (HttpURLConnection)liveAgentURL.openConnection();
                    con.setRequestMethod("GET");
                    con.setRequestProperty("X-LIVEAGENT-API-VERSION", "44");
                    con.setRequestProperty("X-LIVEAGENT-AFFINITY", affinityTokenStr);
                    con.setRequestProperty("X-LIVEAGENT-SESSION-KEY", keyStr);

                    InputStream is = con.getInputStream();

                    JsonReader rdr;
                    if(con.getResponseCode() != 204){
                        rdr = Json.createReader(is);
                        JsonObject obj = rdr.readObject();
                        JsonArray messages = obj.getJsonArray("messages");
                        JsonObject message = messages.getJsonObject(0);
                        String type = message.getString("type");
                        if(type != null && type.equalsIgnoreCase("ChatMessage")){ 
                            /*publish(message.getJsonObject("message").getString("text"));
                            int i = getProgress();
                            System.out.println("Progress: "+i);
                            setProgress(++i);*/
                            textArea.append("Live Agent: " + message.getJsonObject("message").getString("text") + "\n");
                        }           
                    }
                    con.disconnect();
                    System.out.println("Leaving listener loop.");
                }

            }catch(IOException ioe){
                System.out.println(ioe);
            }

            return null;
        }

    }

    public LiveAgentGUIWithSwingWorker() {
            super(new BorderLayout());

        deploymentId = "someId";
        organizationId = "anotherId";
        buttonId = "yetAnotherId";
        initiateChat();

        Font myFont = new Font("myFont", Font.PLAIN, 20);

            textField = new JTextField(40);
        textField.setFont(myFont);
        //System.out.println("Font size: " + textField.getFont().getSize());

            textField.addActionListener(this);

            textArea = new JTextArea(30, 40);
            textArea.setEditable(false);
        textArea.setFont(myFont);
            JScrollPane scrollPane = new JScrollPane(textArea);

            //Add Components to this panel.
            add(scrollPane, BorderLayout.NORTH);
            add(textField, BorderLayout.SOUTH);

        JFrame frame = new JFrame("Live Agent GUI");
        frame.setResizable(false);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            //Add contents to the window.
            frame.add(this);

            //Display the window.
            frame.pack();
            frame.setVisible(true);
        LiveAgentLongPollingTask listener = new LiveAgentLongPollingTask();
        listener.addPropertyChangeListener(
            new PropertyChangeListener() {
                public  void propertyChange(PropertyChangeEvent evt) {
                        System.out.println("Property name: "+evt.getPropertyName());
                    if ("progress".equals(evt.getPropertyName())) {

                        textArea.append("Live Agent: " + (String)evt.getNewValue() + "\n");
                    }
                }
            });
        listener.execute();

    }

    public void actionPerformed(ActionEvent evt) {

            String text = textField.getText();

        sendMessage(affinityTokenStr, keyStr, text);

            textArea.append("You: " + text + newline);
            textField.selectAll();
        textField.setText(null);

            //Make sure the new text is visible, even if there
            //was a selection in the text area.
            textArea.setCaretPosition(textArea.getDocument().getLength());

    }

    public void writeToTextArea(String str){
        textArea.append(str);

    }


    public static void main(String[] args) {
            //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new LiveAgentGUIWithSwingWorker();
            }
        });

    }

    public int sendMessage(String affinityToken, String sessionKey, String message){

        System.out.println("Starting sendMessage.");
        int responseCode = -1;

        try{
            URL liveAgentURLSend = new URL("https://someDomain/chat/rest/Chasitor/ChatMessage");
            HttpURLConnection con = (HttpURLConnection)liveAgentURLSend.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("X-LIVEAGENT-API-VERSION", "44");
            con.setRequestProperty("X-LIVEAGENT-AFFINITY", affinityToken);
            con.setRequestProperty("X-LIVEAGENT-SESSION-KEY", sessionKey);
            con.setRequestProperty("Content-Type", "application/json");
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            String postBody = "{\"text\" : \"" + message + "\"}";
            wr.writeBytes(postBody);
            wr.flush();
            wr.close();
            responseCode = con.getResponseCode();
            con.disconnect();
        }catch(IOException ioe){
            System.out.println(ioe);
        }
        System.out.println("Leaving sendMessage. Code: "+responseCode);
        return responseCode;        

    }

    public void initiateChat(){
        System.out.println("Starting initiateChat.");
        try{
            URL liveAgentURL = new URL("https://someDomain/chat/rest/System/SessionId");
                    HttpURLConnection con = (HttpURLConnection) liveAgentURL.openConnection();
                    con.setRequestMethod("GET");
                    con.setRequestProperty("X-LIVEAGENT-API-VERSION", "44");
                    con.setRequestProperty("X-LIVEAGENT-AFFINITY", "null");
            con.connect();

            JsonReader rdr = Json.createReader(con.getInputStream());
            JsonObject obj = rdr.readObject();
            keyStr = obj.getString("key");
            String idStr = obj.getString("id");
            affinityTokenStr = obj.getString("affinityToken");

            con.disconnect();                       

            liveAgentURL = new URL("https://someDomain/chat/rest/Chasitor/ChasitorInit");
            con = (HttpURLConnection)liveAgentURL.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("X-LIVEAGENT-API-VERSION", "44");
            con.setRequestProperty("X-LIVEAGENT-AFFINITY", affinityTokenStr);
            con.setRequestProperty("X-LIVEAGENT-SESSION-KEY", keyStr);
            con.setRequestProperty("X-LIVEAGENT-SEQUENCE", "1");
            con.setRequestProperty("Content-Type", "application/json");

            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            String postBody = "{\"organizationId\": \"" + organizationId + "\",\n"+
                    "\"deploymentId\": \"" + deploymentId + "\",\n"+
                    "\"buttonId\": \""+buttonId+"\",\n"+
                    "\"sessionId\": \""+idStr+"\",\n"+
                    "\"userAgent\": \"Lynx/2.8.8\",\n"+
                    "\"language\": \"en-US\",\n"+
                    "\"screenResolution\": \"1900x1080\",\n"+
                    "\"visitorName\": \"John Galt\",\n"+
                    "\"prechatDetails\": [],\n"+
                    "\"prechatEntities\": [],\n"+
                    "\"receiveQueueUpdates\": true,\n"+
                    "\"isPost\": true}";
            wr.writeBytes(postBody);
            wr.flush();
            wr.close();
            int responseCode = con.getResponseCode();
            con.disconnect();

        }catch(IOException ioe){
            System.out.println(ioe);
        }
        System.out.println("Leaving initiateChat.");
    }

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.