1. 程式人生 > >一個簡單的java web程式(servlet實現介面)

一個簡單的java web程式(servlet實現介面)

幫同學寫介面的時候,又重新回顧了一下servlet,發現自己基礎實在是差到可以~、在此記錄一下。

在servlet寫執行緒是很不好的、但是推薦演算法耗費的時間實在是多。只能開個執行緒讓它自己跑、有什麼好方法提供的請不吝賜教~

執行緒類:MusicRecThread.java

package com.musicRec.Code;

import com.musicRec.Utils.MusicRec;

import java.util.Map;

/**
 * Created by Administrator on 2017/6/11.
 */
public class MusicRecThread implements Runnable{

    private String userId;

    public MusicRecThread(String userId){
        this.userId = userId;
        System.out.println("start thread...");
    }

    public void run(){

        if(MusicRec.downLoadFiles(userId)){
            //執行推薦演算法
            Map<String,Object> result = MusicRec.excuteMusicRec(userId);
            if(result.get("success").equals(false)){
                result.put("msg","推薦演算法執行出錯");
            }
        };

    }
}
servlet:
package com.musicRec.Servlet;

import com.alibaba.fastjson.JSON;
import com.musicRec.Code.MusicRecThread;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/10.
 */
//@WebServlet("/getRecResult")
public class ExecuteRec extends HttpServlet {

    @Override
    public void init() throws ServletException {
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Map<String,Object> result = new HashMap<>();

        // 獲取使用者的name
        String userId = request.getParameter("userId");
        String jsonString = "";
// 設定輸出
        response.setContentType("text/html;charset=GBK");
        PrintWriter printWriter = response.getWriter();
        // 對name進行轉碼
        if (userId != null) {
            userId = new String(userId.getBytes("ISO-8859-1"), "GBK");
            System.out.println("userId=" + userId);
            Thread t = new Thread(new MusicRecThread(userId));
            t.start();
            System.out.println("thread starting...");
            result.put("success",true);
        } else {
            result.put("success",false);
            result.put("msg","沒有傳入userId");
        }
        jsonString = JSON.toJSONString(result);
        printWriter.println(jsonString);
        printWriter.close();
    }

    @Override
    public void destroy() {
        super.destroy();
    }

}
推薦類:主要是連線伺服器執行linux指令的一些操作。
package com.musicRec.Utils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.musicRec.Entity.RecordInfo;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Administrator on 2017/6/10.
 */
public class MusicRec {

    private static String url = "";
    private static String charset = "utf-8";
    private static HttpClientUtil httpClientUtil = new HttpClientUtil();;
    //ftp伺服器
    private static String FTPHOSTNAME = "";
    private static String FTPNAME = "";
    private static String FTPPASSWORD = "";
    private static String REMOTEPATH = "";
    private static String LOCALPATH = "/home/ubuntu/Desktop/music_rec/user_sim/audio";
    //演算法伺服器
    private static String HOSTNAME = "";
    private static String NAME = "";
    private static String PASSWORD = "";
    //TODO:生成推薦資訊檔案
    private static String TARGETFILEPATH = "/home/ubuntu/Desktop/music_rec/user_sim/result/xyy_result_m10d2.json";

    /**
     * 根據post回來的資訊下載檔案到演算法伺服器上
     * @param userId
     * @return
     */
    public static boolean downLoadFiles(String userId){

        String httpOrgCreateTest = url + "hmzmysql/cors/getRecordInfo";
        Map<String,String> createMap = new HashMap<>();
        createMap.put("userId",userId);
        String httpOrgCreateTestRtn = httpClientUtil.doPost(httpOrgCreateTest,createMap,charset);
        System.out.println("result:" + httpOrgCreateTestRtn);

        JSONObject jsonObj = JSON.parseObject(httpOrgCreateTestRtn);

        JSONArray recordInfoArray = jsonObj.getJSONArray("recordInfo");

        List<RecordInfo> recordInfo = JSON.parseArray(recordInfoArray.toJSONString(), RecordInfo.class);

        for (RecordInfo r:recordInfo){
            System.out.println(r.getIsFlag());
            System.out.println(r.getUrl());
//            System.out.println();
//            System.out.println();
        }

//        Boolean flag = FtpClientUtils.downFile(FTPHOSTNAME,21,FTPNAME,FTPPASSWORD,REMOTEPATH,fileName,LOCALPATH);
//        return flag;
        return true;
    }


    /**
     * 執行推薦演算法
     * @param userId
     * @return
     */
    public static Map<String,Object> excuteMusicRec(String userId){
        Map<String,Object> map = new HashMap<>();
        try {
        Connection conn = new Connection(HOSTNAME);
        conn.connect();//連線
        Boolean flg = conn.authenticateWithPassword(NAME, PASSWORD);//認證
        if (flg) {
            System.out.println("=====第一個步驟=====");
            Session session = conn.openSession();//開啟一個會話
            //TODO:多條命令
            session.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim;echo \"123\" | sudo  -S ./caculate_tim_sim.sh similar");//執行命令
            String result = RemoteExecuteCommand.processStdout(session.getStdout(), charset);
            //如果為得到標準輸出為空,說明指令碼執行出錯了
            if ("".equals(result)) {
                System.out.println("指令碼出錯");
                result = RemoteExecuteCommand.processStdout(session.getStderr(), charset);
            }
            System.out.println(result);
            session.close();

//            System.out.println("=====第二個步驟=====");
//            Session session2 = conn.openSession();//開啟一個會話
//            //TODO:多條命令
//            session2.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim/result;cat xyy_result_m10d.json");//執行命令
//            String result2 = RemoteExecuteCommand.processStdout(session2.getStdout(), charset);
//            //如果為得到標準輸出為空,說明指令碼執行出錯了
//            if ("".equals(result2)) {
//                System.out.println("指令碼出錯");
//                result2 = RemoteExecuteCommand.processStdout(session2.getStderr(), charset);
//            }
//            System.out.println(result2);
//            map.put("jsonData",result2);
//            session2.close();

            System.out.println("=====第三個步驟=====");
            Session session3 = conn.openSession();//開啟一個會話
            //TODO:多條命令
            session3.execCommand("cd /home/ubuntu/Desktop/music_rec/effective_range_of_singing_voice;python batch.py");//執行命令
//                session2.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim/result;ls");//執行命令
            String result3 = RemoteExecuteCommand.processStdout(session3.getStdout(), charset);
            //如果為得到標準輸出為空,說明指令碼執行出錯了
            if ("".equals(result3)) {
                System.out.println("指令碼出錯");
                result3 = RemoteExecuteCommand.processStdout(session3.getStderr(), charset);
            }
            System.out.println(result3);
            session3.close();

            System.out.println("=====第四個步驟(生成推薦結果)=====");
            Session session4 = conn.openSession();//開啟一個會話
            //TODO:多條命令
            session4.execCommand("cd /home/ubuntu/Desktop/music_rec/recommendation;python recomendation.py");//執行命令
            String result4 = RemoteExecuteCommand.processStdout(session4.getStdout() , charset);
            //如果為得到標準輸出為空,說明指令碼執行出錯了
            if ("".equals(result4)) {
                System.out.println("指令碼出錯");
                result4 = RemoteExecuteCommand.processStdout(session4.getStderr(), charset);
            }
            System.out.println(result4);
//            map.put("recResult", result4);
            session4.close();

            conn.close();
            map.put("success",true);
        }else {
            System.err.println("連線失敗!");
            map.put("success",false);
        }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 得到推薦結果
     * @param userId
     * @return
     */
    public static Map<String,Object> getMusicRecResult(String userId){
        Map<String,Object> resultMap = new HashMap<>();
        try {
            Connection conn = new Connection(HOSTNAME);
            conn.connect();//連線
            Boolean flg = conn.authenticateWithPassword(NAME, PASSWORD);//認證
            if (flg) {

                System.out.println("=====1.得到Json=====");
                Session session = conn.openSession();//開啟一個會話
                //TODO:多條命令
                session.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim/result;cat xyy_result_m10d.json");//執行命令
                String result = RemoteExecuteCommand.processStdout(session.getStdout(), charset);
                //如果為得到標準輸出為空,說明指令碼執行出錯了
                if ("".equals(result)) {
                    System.out.println("指令碼出錯");
                    result = RemoteExecuteCommand.processStdout(session.getStderr(), charset);
                }
                System.out.println(result);
                resultMap.put("jsonData",result.replace("\n",""));
                session.close();

                System.out.println("=====2.得到推薦結果=====");
                Session session2 = conn.openSession();//開啟一個會話
                //TODO:多條命令
                session2.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim/result;cat sorted_result.txt");//執行命令
                String result2 = RemoteExecuteCommand.processStdout(session2.getStdout(), charset);
                //如果為得到標準輸出為空,說明指令碼執行出錯了
                if ("".equals(result2)) {
                    System.out.println("指令碼出錯");
                    result2 = RemoteExecuteCommand.processStdout(session2.getStderr(), charset);
                }
                System.out.println(result2);
                resultMap.put("recResult", result2.replace("\t","_").replace("\n",","));
                session2.close();

                conn.close();
                resultMap.put("success",true);
            }else {
                System.err.println("連線失敗!");
                resultMap.put("success",false);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return resultMap;
    }




    public static void main(String[] args) {

    }


}