com.ibm.responseclassifier.MainPage.java Source code

Java tutorial

Introduction

Here is the source code for com.ibm.responseclassifier.MainPage.java

Source

/*
 *    Author: Fabian Dubacher
   Year:   2015
    
   This file is part of ResponseClassifier.
    
ResponseClassifier is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
ResponseClassifier is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with ResponseClassifier. If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package com.ibm.responseclassifier;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.application.FacesMessage;
import javax.servlet.ServletContext;

import org.apache.commons.io.IOUtils;
import org.primefaces.json.JSONObject;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

@ManagedBean(name = "MainPage")
@SessionScoped
public class MainPage {
    private UploadedFile fileUpload;
    private String fileUploadPath;
    private String fileDownloadPath;
    private StreamedContent fileDownload;
    private ServletContext servletContext;
    private boolean bDownloadReady = false;
    private String state = "not ready for download";

    public MainPage() {
        servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
    }

    public StreamedContent getFileDownload() {
        try {
            if (!bDownloadReady) {
                throw new Exception("Download is not ready yet. Please wait until the document is classfied.");
            }

            InputStream stream = new FileInputStream(new File(fileDownloadPath));
            fileDownload = new DefaultStreamedContent(stream, "text/plain",
                    fileUpload.getFileName() + "_classified.csv");
        } catch (Exception e) {
            FacesMessage message = new FacesMessage("Error", "Download failed.\nException: " + e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, message);
            e.printStackTrace(System.out);
        }

        return fileDownload;
    }

    public String getFileUploadPath() {
        return fileUploadPath;
    }

    public UploadedFile getFileUpload() {
        return fileUpload;
    }

    public void setFileUpload(UploadedFile file) {
        this.fileUpload = file;
    }

    public String getFileDownloadPath() {
        return fileDownloadPath;
    }

    public String getState() {
        return state;
    }

    //handleUpload is called when the user hits submit
    public void handleUpload() {
        try {
            if (!fileUpload.getFileName().matches("^.*\\.(csv|CSV)$")) {
                throw new Exception("File is not in CSV format");
            }

            copyUpload(fileUpload.getFileName(), fileUpload.getSize(), fileUpload.getInputstream());
            classifyUpload();
            bDownloadReady = true;
            state = "ready for download";

            FacesMessage message = new FacesMessage("Succesful", fileUpload.getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, message);
        } catch (Exception e) {
            FacesMessage message = new FacesMessage("Error",
                    "Upload was not successful.\nException: " + e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, message);
            e.printStackTrace(System.out);
        }
    }

    //copyUpload() copies the uploaded file from memory to the disk
    private void copyUpload(String fileName, long size, InputStream in) throws Exception {
        fileUploadPath = servletContext.getRealPath("/") + fileName;

        try {
            OutputStream out = new FileOutputStream(new File(fileUploadPath));
            int read = 0;
            byte[] bytes = new byte[(int) size];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            throw e;
        }
    }

    //classifyUpload() reads the file from 'fileUploadPath', classifies it and then replaces the original upload file with the translated one
    public void classifyUpload() throws Exception {
        try {
            fileDownloadPath = servletContext.getRealPath("/") + fileUpload.getFileName() + "_download";

            FileReader fr = new FileReader(fileUploadPath);
            BufferedReader br = new BufferedReader(fr);
            FileWriter fw = new FileWriter(fileDownloadPath, false);

            String line = "";
            String classification = "";
            while ((line = br.readLine()) != null) {
                classification = getWatsonClassification(line);
                fw.append(line + "," + classification + "\n");
            }

            /* THIS SNIPPET READS THE UPLOADED FILE INTO THE VARIABLE 'fileUploadContent'
            fileUploadContent = fileUpload.getFileName();
                
            String line = "";
            while((line = br.readLine()) != null)
            {
               fileUploadContent = fileUploadContent + "<br/>" + line;
            }
              */
            br.close();
            fw.close();
        } catch (Exception e) {
            throw e;
        }
    }

    private String getWatsonClassification(String text) throws Exception {
        try {
            HttpURLConnection con = (HttpURLConnection) new URL(
                    "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/5DFC4Cx1-nlc-79/classify?text="
                            + URLEncoder.encode(text, "UTF-8")).openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Authorization",
                    "Basic NzdjMjAzY2EtZjk2NC00ZTk5LWI3ZmUtMTI4MGMxYzllNWFiOmpyTHZ2MU1HY3Rwbw==");

            InputStream in = con.getInputStream();
            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer);
            String strResponse = writer.toString();
            JSONObject jObj = new JSONObject(strResponse);
            return jObj.getString("top_class");
        } catch (Exception e) {
            throw e;
        }
    }
}