com.jason.thrift.TransmitHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.jason.thrift.TransmitHandler.java

Source

package com.jason.thrift;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.thrift.TException;

import com.cnpc.Wgs2Mars;
import com.jason.bean.AlarmBean;
import com.jason.bean.GPS4Json;
import com.jason.bean.GPSInfoBean;
import com.jason.car.AlarmHandler;
import com.jason.car.CarHandler;
import com.jason.ot.Encrypt;
import com.jason.thrift.Transmit.AsyncProcessor.test;
import com.jason.tools.MD5Util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 
 * @author Jason Liu
 * v1.0
 * v1.1 ????
 */
public class TransmitHandler implements Transmit.Iface {

    // private HashMap<Integer,SharedStruct> log;
    //   public Wgs2Mars encrypter;

    private Encrypt encryptor;

    public TransmitHandler() {
        // log = new HashMap<Integer, SharedStruct>();
        //      System.out.println("??");
        //      encrypter = new Wgs2Mars();
        //      encrypter.InitTable();
        //      System.out.println("??");

        encryptor = new Encrypt();

    }

    /**
     * ?
     */
    @Override
    public String get_alarm(String alarmid) throws TException {
        AlarmHandler ah = new AlarmHandler();
        AlarmBean ab = ah.get_alarm(alarmid);
        JSONObject ab_json = JSONObject.fromObject(ab);
        return ab_json + "";
    }

    /**
     * ????
     */
    @Override
    public String get_track(String idnumber, String bt, String et) throws TException {
        String err_msg = "";
        String type = "";
        String res_str = "";
        CarHandler ch = new CarHandler();
        List<GPSInfoBean> gpsl = ch.get_track(idnumber, bt, et);

        Date dst, det;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            dst = sdf.parse(bt);
            det = sdf.parse(et);
            long intver = det.getTime() - dst.getTime();
            long day = intver / 1000 / 60 / 60;
            // System.out.println("interval day:"+day);
            if (day < 0 || day > 24 * 7) {
                err_msg = "";
            } else if (day > 24 && day < 24 * 7) {
                // ftp,ftp??
                type = "ftp";
                int len = gpsl.size();
                List<GPS4Json> gps_json_l = new LinkedList<GPS4Json>();

                for (int i = 0; i < len; i++) {
                    GPSInfoBean gib = gpsl.get(i);

                    //               BigDecimal bjd = new BigDecimal(gib.getJd());
                    //               bjd.setScale(15,BigDecimal.ROUND_HALF_UP);
                    //               BigDecimal bwd = new BigDecimal(gib.getWd());
                    //               bwd.setScale(15,BigDecimal.ROUND_HALF_UP);
                    String[] afenc = this.encryptor.encryptLocation(gib.getJd() + "", gib.getWd() + "");

                    String fx = this.encryptor.decodeFxj(gib.getFxj());

                    gps_json_l
                            .add(new GPS4Json(gib.getFormat_time(), idnumber, gib.getSd() + "", gib.getCar_status(),
                                    afenc[0], afenc[1], gib.getPs(), fx, gib.getAlarm_status(), gib.getLc() + ""));
                    //                     gib.getPs(), gib.getFxj()+"", gib.getAlarm_status(), gib.getLc()+"" ));
                }
                JSONArray ja_json = JSONArray.fromObject(gps_json_l);

                try {
                    String str = ja_json.toString();
                    str = "{\"data\":" + str + "}";
                    String filename = MD5Util.MD5(idnumber + System.currentTimeMillis()) + ".json"; //"test.txt";
                    String path = "/tmp";
                    String pathname = path + "/" + filename;
                    boolean wf = this.write2file(str, path, filename);
                    System.out.println("write file res:" + wf);
                    if (wf) {
                        FileInputStream in = new FileInputStream(new File(pathname));
                        System.out.println("UP :" + pathname);
                        //uploadFile(String url, int port, String username,
                        // String password, String path, String filename, InputStream input)

                        boolean upres = this.uploadFile("10.185.234.139", 21, "ftpuser", "Xxzx2013@)!#", "/",
                                filename, in);
                        System.out.println("Upload res:" + upres);
                        if (upres) {
                            res_str = filename;
                        } else {
                            err_msg = "";
                        }
                    } else {
                        err_msg = "";
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (day <= 24 && day >= 0) {
                //  json
                //msg = "json";
                type = "json";

                List<GPS4Json> gps_json_l = new LinkedList<GPS4Json>();
                int len = gpsl.size();
                for (int i = 0; i < len; i++) {
                    GPSInfoBean gib = gpsl.get(i);
                    //               System.out.println("JD:"+gib.getJd() +",WD:"+gib.getWd() );
                    //               BigDecimal bjd = new BigDecimal(gib.getJd());
                    //               bjd.setScale(15,BigDecimal.ROUND_HALF_UP);
                    //               BigDecimal bwd = new BigDecimal(gib.getWd());
                    //               bwd.setScale(15,BigDecimal.ROUND_HALF_UP);
                    String[] afenc = this.encryptor.encryptLocation(gib.getJd() + "", gib.getWd() + "");
                    String fx = this.encryptor.decodeFxj(gib.getFxj());
                    gps_json_l
                            .add(new GPS4Json(gib.getFormat_time(), idnumber, gib.getSd() + "", gib.getCar_status(),
                                    afenc[0], afenc[1], gib.getPs(), fx, gib.getAlarm_status(), gib.getLc() + ""));
                }
                JSONArray ja = JSONArray.fromObject(gps_json_l);
                res_str = ja.toString();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (err_msg.length() > 0) {
            res_str = "{\"success\":\"false\",\"data\":" + err_msg + "}";
        } else {
            if (type.equals("ftp")) {
                res_str = "{\"success\":\"ftp\",\"data\":\"" + res_str + "\"}";
            } else if (type.equals("json")) {
                res_str = "{\"success\":\"json\",\"data\":" + res_str + "}";
            }
        }

        return res_str;
    }

    public boolean write2file(String str, String path, String filename) {
        String pathname = path + "/" + filename;
        File file = new File(pathname);
        System.out.println("create file:" + pathname);
        boolean res = false;
        FileOutputStream o = null;
        try {
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            o = new FileOutputStream(pathname);
            o.write(str.getBytes("UTF-8"));
            o.close();
            res = true;
            // true = append file
            //         FileWriter fileWritter = new FileWriter(file.getName(), true);
            //         BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            //         bufferWritter.write(str);
            //         bufferWritter.flush();
            //         bufferWritter.close();

        } catch (IOException e) {
            e.printStackTrace();
            res = false;
        }
        return res;
    }

    /**
     * Description: ?FTP?
     * 
     * @Version1.0 Jul 27, 2008 4:31:09 PM by ?cuihongbao@d-heaven.com
     * @param url
     *            FTP?hostname
     * @param port
     *            FTP??
     * @param username
     *            FTP?
     * @param password
     *            FTP?
     * @param path
     *            FTP??
     * @param filename
     *            FTP???
     * @param input
     *            ?
     * @return ?true?false
     */
    public static boolean uploadFile(String url, int port, String username, String password, String path,
            String filename, InputStream input) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(url, port);// FTP?
            // ??ftp.connect(url)?FTP?
            ftp.login(username, password);// 
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            ftp.changeWorkingDirectory(path);
            ftp.storeFile(filename, input);

            input.close();
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }

    @Override
    public String test(String name) throws TException {
        return "Hello " + name;
    }

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

        String res = new TransmitHandler().get_track("?RA1839", "2014-11-18 09:00:00", "2014-11-20 11:00:00");
        System.out.println(" RES" + res);

        //      TransmitHandler th = new TransmitHandler();
        //      try {
        //         String str = "uuiouiq ??";
        //         String filename = "test.txt";
        //         String path = "/tmp";
        //         boolean wf = th.write2file(str, path, filename);
        //         System.out.println("write file:"+wf);
        //         
        //         FileInputStream in = new FileInputStream(new File(
        //               path+"/"+filename));
        //         boolean flag = th.uploadFile("10.185.234.139",
        //               21, "ftpuser", "Xxzx2013@)!#",
        //               path, filename, in);
        //         // = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp",
        //         // "test.txt", in);
        //         System.out.println(flag);
        //      } catch (FileNotFoundException e) {
        //         e.printStackTrace();
        //      }

        /*
         * String bt = "2014-11-10 10:11:10"; String et = "2014-11-11 8:11:10";
         * Date dst, det; String msg; SimpleDateFormat sdf = new
         * SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { dst = sdf.parse(bt);
         * det = sdf.parse(et); long intver = det.getTime() - dst.getTime();
         * long day = intver/1000/60/60;
         * System.out.println("interval day:"+day); if (!dst.before(det)) { msg
         * = "?"; } // System.out.println("Date:"+st.before(et)); } catch
         * (ParseException e) { e.printStackTrace(); }
         */
    }

}