Example usage for java.net UnknownHostException printStackTrace

List of usage examples for java.net UnknownHostException printStackTrace

Introduction

In this page you can find the example usage for java.net UnknownHostException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:it.isislab.dmason.util.SystemManagement.Master.thrower.DMasonMaster.java

private Address getFPTAddress() {
    InetAddress thisIp;/*from w w w . j  a va2s. co  m*/
    try {
        thisIp = InetAddress.getLocalHost(); //Note: It starts with Master
        return new Address(thisIp.getHostAddress(), FTP_PORT);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:edu.mit.viral.shen.DroidFish.java

private void sendDataLocal(final int sq) {
    new Thread(new Runnable() {
        @Override/*w  w  w  .  j a  va 2 s  .  co m*/
        public void run() {
            Socket socket = null;
            DataOutputStream dataOutputStream = null;
            DataInputStream dataInputStream = null;
            try {
                socket = new Socket(Const.IP_ADD_LOCAL, 8890);
                dataOutputStream = new DataOutputStream(socket.getOutputStream());
                String sq_string = Integer.toString(sq);
                dataOutputStream.writeUTF(sq_string);

            }

            catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

From source file:edu.mit.viral.shen.DroidFish.java

private void sendComment(final String comment) {
    new Thread(new Runnable() {
        @Override//from ww  w  .j a  v  a 2  s . c  o  m
        public void run() {
            Socket socket = null;
            DataOutputStream dataOutputStream = null;
            DataInputStream dataInputStream = null;
            try {
                // String[] words = longfen.split(" ");
                // String fen=words[0];               
                socket = new Socket(Const.IP_ADD_LOCAL, 8890);
                dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeUTF(comment);

            }

            catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

From source file:com.yeahka.android.lepos.Device.java

/**
 * ??// w  w w . j  ava2s  .co  m
 *
 * @param strOrderID
 * @param amount
 * @param strPinpadID
 * @param strTrack2Data
 * @param strTrack3Data
 * @param strPin
 * @param strLongitude
 * @param strLatitude
 * @param strCardSerialNo
 * @param strICCardInfo
 * @param strDiffuseFactor
 * @param deviceType
 * @param host
 * @param port
 * @return
 */
//-----------terence add --2016-03-17 t+0 ---------
//-----------terence add --2016-05-16   marketType---------
public ResultModel zhongciPayRequest(String strOrderID, Integer amount, String strPinpadID,
        String strTrack2Data, String strTrack3Data, String strPin, String strLongitude, String strLatitude,
        String strCardSerialNo, String strICCardInfo, String strDiffuseFactor, Integer deviceType, String host,
        Integer port, Integer nT0Flag, Integer marketType) {
    if (YeahkaDevice.getDeviceVersionType() == YeahkaDevice.DEVICE_VERSION_TYPE_PIN_WITH_OPERATE) {
        if (!TextUtils.isEmpty(strPin)) {
            strPin = strPin + PIN_BACK;
        }
    }
    //        String tag = "zhongciPayRequest";
    byte[] head = Device.nativeFunction10004(device);
    byte[] body = Device.nativeFunction10005(device, strOrderID, amount, strPinpadID, strTrack2Data,
            strTrack3Data, strPin, strLongitude, strLatitude, strCardSerialNo, strICCardInfo, strDiffuseFactor,
            deviceType, nT0Flag, marketType);
    byte[] sendData = Device.nativeFunction60(device, head, intToFourByte(Device.nativeFunction66(device)),
            body);
    InetAddress address;
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(sendData);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket);
        if (bGetHead == false) {
            //                MyLog.d(TAG, "get head =" + bGetHead);
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            //                MyLog.d(TAG, "len is not 4 ");
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntLowByteFirst();
        if (dataLength < 0) {
            //                MyLog.d(TAG, "data len less than 0 ");
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        if (length != dataLength) {
            //                MyLog.d(TAG, "len not equal data lenth ");
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        String sc = new String(bytes, "UTF-8");
        return new ResultModel(sc);
    } catch (UnknownHostException e) {
        e.printStackTrace();
        MyLog.d(TAG, "UnknownHostException ");
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        e1.printStackTrace();
        MyLog.d(TAG, "SocketException ");
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        e2.printStackTrace();
        MyLog.d(TAG, "IOException ");
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }

}

From source file:cycronix.ctudp.CTudp.java

public CTudp(String[] arg) {
    String[] chanName = new String[32];
    String defaultChanName = "udpchan";
    String[] csvChanNames = null;
    int ssNum[] = new int[32];
    int defaultPort = 4445;
    double dt[] = new double[32];
    double defaultDT = 0.0;
    int numChan = 0;

    // For communicating with UDP server; we send a "keep alive" heartbeat message to this server
    // and will receive UDP packets from this server
    DatagramSocket clientSocket = null; // This socket will be shared by UDPread and UDPHeartbeatTask classes
    InetAddress udpserverIP = null;
    int udpserverPort = -1;
    int heartbeatPeriod_msec = -1;
    boolean bCSVTest = false; // If the "-csvtest" option has been specified along with the "-udpserver" option, then the heartbeat message itself is a CSV string that can be used for testing CTudp in loopback mode.

    // Optional local UDP server that can be started to serve test data
    int testserverPort = -1;
    int testserverPeriod_msec = -1;

    ///*w w  w  .  ja v  a  2s  .  c  o  m*/
    // Argument processing using Apache Commons CLI
    //
    // 1. Setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "Print this message.");
    options.addOption("pack", false,
            "Blocks of data should be packed?  default = " + Boolean.toString(packMode) + ".");
    options.addOption(Option.builder("s").argName("source name").hasArg()
            .desc("Name of source to write packets to; default = \"" + srcName + "\".").build());
    options.addOption(Option.builder("c").argName("channel name").hasArg()
            .desc("Name of channel to write packets to; default = \"" + defaultChanName + "\".").build());
    options.addOption(Option.builder("csplit").argName("channel name(s)").hasArg().desc(
            "Comma-separated list of channel names; split an incoming CSV string into a series of channels with the given names; supported channel name suffixes and their associated data types: .txt (string), .csv or no suffix (numeric), .f32 (32-bit floating point), .f64 (64-bit floating point).")
            .build());
    options.addOption(Option.builder("e").argName("exception val").hasArg().desc(
            "If a CSV string is being parsed (using the -csplit option) and there is an error saving a string component as a floating point value, use this \"exception value\" in its place; default = "
                    + Double.toString(exceptionVal) + ".")
            .build());
    options.addOption(Option.builder("m").argName("multicast address").hasArg()
            .desc("Multicast UDP address (224.0.0.1 to 239.255.255.255).").build());
    options.addOption(Option.builder("p").argName("UDP port").hasArg()
            .desc("Port number to listen for UDP packets on; default = " + Integer.toString(defaultPort) + ".")
            .build());
    options.addOption(Option.builder("d").argName("delta-Time").hasArg()
            .desc("Fixed delta-time (msec) between frames; specify 0 to use arrival-times; default = "
                    + Double.toString(defaultDT) + ".")
            .build());
    options.addOption(Option.builder("f").argName("autoFlush").hasArg().desc(
            "Flush interval (sec); amount of data per zipfile; default = " + Double.toString(autoFlush) + ".")
            .build());
    options.addOption(Option.builder("t").argName("trim-Time").hasArg()
            .desc("Trim (ring-buffer loop) time (sec); specify 0 for indefinite; default = "
                    + Double.toString(trimTime) + ".")
            .build());
    options.addOption(Option.builder("udpserver").argName("IP,port,period_msec").hasArg().desc(
            "Talk to a UDP server; send a periodic keep-alive message to the given IP:port at the specified period and receive packets from this server; not to be used with the \"-p\" option.")
            .build());
    options.addOption(Option.builder("testserver").argName("port,period_msec").hasArg().desc(
            "Start a UDP server on the local machine to serve CSV strings at the specified period with the format specified by the \"-csplit\" option (if no \"-csplit\" option has been specified, a simple text message is output). The test server waits for a message from the client before starting packet flow. This feature can be used along with the \"-udpserver\" option for local/loopback testing (NOTE: make sure the server ports match).")
            .build());
    options.addOption(Option.builder("bps").argName("blocks_per_seg").hasArg()
            .desc("Number of blocks per segment; specify 0 for no segments; default = "
                    + Long.toString(blocksPerSegment) + ".")
            .build());
    options.addOption("w", false, "Split the captured string on white space rather than commas.");
    options.addOption("x", "debug", false, "Debug mode.");

    // 2. Parse command line options
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, arg);
    } catch (ParseException exp) { // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    // 3. Retrieve the command line values
    if (line.hasOption("help")) { // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp("CTudp", options);
        return;
    }

    srcName = line.getOptionValue("s", srcName);

    String chanNameL = line.getOptionValue("c", defaultChanName);
    chanName = chanNameL.split(",");
    numChan = chanName.length;

    if (line.hasOption("csplit")) {
        chanNameL = line.getOptionValue("csplit");
        csvChanNames = chanNameL.split(",");
        if (numChan > 1) {
            System.err.println(
                    "Error: don't use the \"-csplit\" option when receiving packets from multiple UDP ports.");
            System.exit(0);
        }
        // Make sure that the channel names either have no suffix or will end in .txt, .csv, .f32, .f64
        for (int i = 0; i < csvChanNames.length; ++i) {
            int dotIdx = csvChanNames[i].lastIndexOf('.');
            if ((dotIdx > -1) && (!csvChanNames[i].endsWith(".txt")) && (!csvChanNames[i].endsWith(".csv"))
                    && (!csvChanNames[i].endsWith(".f32")) && (!csvChanNames[i].endsWith(".f64"))) {
                System.err.println(
                        "Error: illegal channel name specified in the \"-csplit\" list: " + csvChanNames[i]);
                System.err.println(
                        "\tAccepted channel names: channels with no suffix or with .txt, .csv, .f32 or .f64 suffixes.");
                System.exit(0);
            }
        }
    }

    String exceptionValStr = line.getOptionValue("e", Double.toString(exceptionVal));
    try {
        exceptionVal = Double.parseDouble(exceptionValStr);
    } catch (NumberFormatException nfe) {
        System.err.println("Error parsing the given exception value (\"-e\" flag).");
        System.exit(0);
    }

    multiCast = line.getOptionValue("m", multiCast);

    String nss = line.getOptionValue("p", Integer.toString(defaultPort));
    String[] ssnums = nss.split(",");
    numSock = ssnums.length;
    for (int i = 0; i < numSock; i++)
        ssNum[i] = Integer.parseInt(ssnums[i]);

    String sdt = line.getOptionValue("d", Double.toString(defaultDT));
    String[] ssdt = sdt.split(",");
    for (int i = 0; i < ssdt.length; i++)
        dt[i] = Double.parseDouble(ssdt[i]);

    autoFlush = Double.parseDouble(line.getOptionValue("f", "" + autoFlush));

    trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime)));

    blocksPerSegment = Long.parseLong(line.getOptionValue("bps", Long.toString(blocksPerSegment)));

    if (line.hasOption("pack")) {
        packMode = true;
    }

    bSplitOnWhiteSpace = line.hasOption("w");

    debug = line.hasOption("debug");

    // Parameters when talking to a UDP server
    // Can't specify both "-p" and "-udpserver"
    if (line.hasOption("p") && line.hasOption("udpserver")) {
        System.err.println(
                "Specify either \"-p\" (to listen on the given port(s)) or \"-udpserver\" (to talk to UDP server), not both.");
        System.exit(0);
    }
    if (line.hasOption("udpserver")) {
        String udpserverStr = line.getOptionValue("udpserver");
        // Parse the server,port,period_msec from this string
        String[] udpserverConfigCSV = udpserverStr.split(",");
        if (udpserverConfigCSV.length != 3) {
            System.err.println(
                    "Error: the \"-udpserver\" argument must contain 3 parameters: IP,port,period_msec");
            System.exit(0);
        }
        try {
            udpserverIP = InetAddress.getByName(udpserverConfigCSV[0]);
        } catch (UnknownHostException e) {
            System.err.println("Error processing the \"-udpserver\" server name:\n" + e);
            System.exit(0);
        }
        try {
            udpserverPort = Integer.parseInt(udpserverConfigCSV[1]);
            if (udpserverPort <= 0) {
                throw new Exception("Invalid port number");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-udpserver\" port must be an integer greater than 0.");
            System.exit(0);
        }
        try {
            heartbeatPeriod_msec = Integer.parseInt(udpserverConfigCSV[2]);
            if (heartbeatPeriod_msec <= 0) {
                throw new Exception("Invalid period");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-udpserver\" period_msec must be an integer greater than 0.");
            System.exit(0);
        }
    }

    if (line.hasOption("testserver")) {
        String testserverStr = line.getOptionValue("testserver");
        // Parse the port,period_msec from this string
        String[] testserverConfigCSV = testserverStr.split(",");
        if (testserverConfigCSV.length != 2) {
            System.err
                    .println("Error: the \"-testserver\" argument must contain 2 parameters: port,period_msec");
            System.exit(0);
        }
        try {
            testserverPort = Integer.parseInt(testserverConfigCSV[0]);
            if (testserverPort <= 0) {
                throw new Exception("Invalid port number");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-testserver\" port must be an integer greater than 0.");
            System.exit(0);
        }
        try {
            testserverPeriod_msec = Integer.parseInt(testserverConfigCSV[1]);
            if (testserverPeriod_msec <= 0) {
                throw new Exception("Invalid period");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-testserver\" period_msec must be an integer greater than 0.");
            System.exit(0);
        }
    }

    if (numSock != numChan) {
        System.err.println("Error:  must specify same number of channels and ports!");
        System.exit(0);
    }
    if (multiCast != null && numSock > 1) {
        System.err.println("Error: can only have one multicast socket!");
        System.exit(0);
    }
    if (numSock == 0)
        numSock = 1; // use defaults

    System.err.println("Source name: " + srcName);
    if (udpserverIP == null) {
        for (int i = 0; i < numSock; i++) {
            System.err.println("Channel[" + i + "]: " + chanName[i]);
            System.err.println("UDPport[" + i + "]: " + ssNum[i]);
        }
    }
    if (csvChanNames != null) {
        System.err.println("\nIncoming csv strings will be split into the following channels:");
        for (int i = 0; i < (csvChanNames.length - 1); ++i) {
            System.err.print(csvChanNames[i] + ",");
        }
        System.err.println(csvChanNames[csvChanNames.length - 1]);
    }

    //
    // If user has requested it, start the test UDP server
    //
    if (testserverPort > -1) {
        UDPserver svr = null;
        try {
            svr = new UDPserver(testserverPort, testserverPeriod_msec, csvChanNames);
        } catch (SocketException se) {
            System.err.println("Error: caught exception trying to start test server:\n" + se);
            System.exit(0);
        }
        svr.start();
    }

    //
    // If user requested it, initialize communication with the UDP server
    //
    if (udpserverIP != null) {
        try {
            // This DatagramSocket will be shared by UDPread and UDPHeartbeatTask classes
            clientSocket = new DatagramSocket();
        } catch (SocketException e) {
            System.err.println("Error creating DatagramSocket:\n" + e);
            System.exit(0);
        }
        Timer time = new Timer();
        UDPHeartbeatTask heartbeatTask = new UDPHeartbeatTask(clientSocket, udpserverIP, udpserverPort);
        time.schedule(heartbeatTask, 0, heartbeatPeriod_msec);
    }

    //
    // setup CTwriter
    //
    try {
        ctw = new CTwriter(srcName, trimTime);
        ctw.setBlockMode(packMode, zipMode);
        CTinfo.setDebug(debug);
        ctw.autoSegment(blocksPerSegment);
        autoFlushMillis = (long) (autoFlush * 1000.);
        // ctw.autoFlush(autoFlush);      // auto flush to zip once per interval (sec) of data
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }

    //
    // start a thread for each port
    // if we are talking to a UDP server, there is only 1 instance of UDPread
    //
    if (clientSocket != null) {
        System.err.println("Talk to UDP server at " + udpserverIP + ":" + udpserverPort);
        new UDPread(clientSocket, chanName[0], csvChanNames, dt[0]).start();
    } else {
        for (int i = 0; i < numSock; i++) {
            System.err.println("start thread for port: " + ssNum[i] + ", chan: " + chanName[i]);
            new UDPread(ssNum[i], chanName[i], csvChanNames, dt[i]).start();
        }
    }
}

From source file:Tcpbw100.java

public boolean test_s2c(Protocol ctl, Socket ctlSocket) throws IOException {
    byte buff[] = new byte[8192];
    Message msg = new Message();
    if ((tests & TEST_S2C) == TEST_S2C) {
        showStatus(messages.getString("inboundTest"));
        results.append(messages.getString("runningInboundTest") + " ");
        statistics.append(messages.getString("runningInboundTest") + " ");
        emailText += messages.getString("runningInboundTest") + " ";
        pub_status = "runningInboundTest";

        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }//w w  w .j  a  v  a2 s .c  o m
        if (msg.type != TEST_PREPARE) {
            errmsg = messages.getString("inboundWrongMessage") + "\n";
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }
        int s2cport = Integer.parseInt(new String(msg.body));

        Socket inSocket;
        try {
            inSocket = new Socket(host, s2cport);
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + host);
            errmsg = "unknown server\n";
            return true;
        } catch (IOException e) {
            System.err.println("Couldn't get 3rd connection to: " + host);
            errmsg = "Server Failed while receiving data\n";
            return true;
        }

        InputStream srvin = inSocket.getInputStream();
        int bytes = 0;
        int inlth;

        // wait here for signal from server application 
        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("unknownServer") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_START) {
            errmsg = messages.getString("serverFail") + "\n";
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }

        inSocket.setSoTimeout(15000);
        t = System.currentTimeMillis();
        pub_time = t;
        try {
            while ((inlth = srvin.read(buff, 0, buff.length)) > 0) {
                bytes += inlth;
                pub_bytes = bytes;
                if ((System.currentTimeMillis() - t) > 14500)
                    break;
            }
        } catch (IOException e) {
        }

        t = System.currentTimeMillis() - t;
        System.out.println(bytes + " bytes " + (8.0 * bytes) / t + " kb/s " + t / 1000 + " secs");
        s2cspd = ((8.0 * bytes) / 1000) / t;

        /* receive the s2cspd from the server */
        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_MSG) {
            errmsg = messages.getString("inboundWrongMessage") + "\n";
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }
        try {
            String tmpstr3 = new String(msg.body);
            int k1 = tmpstr3.indexOf(" ");
            int k2 = tmpstr3.substring(k1 + 1).indexOf(" ");
            ss2cspd = Double.parseDouble(tmpstr3.substring(0, k1)) / 1000.0;
            ssndqueue = Integer.parseInt(tmpstr3.substring(k1 + 1).substring(0, k2));
            sbytes = Double.parseDouble(tmpstr3.substring(k1 + 1).substring(k2 + 1));
        } catch (Exception e) {
            e.printStackTrace();
            errmsg = messages.getString("inboundWrongMessage") + "\n";
            return true;
        }

        if (s2cspd < 1.0) {
            results.append(prtdbl(s2cspd * 1000) + "kb/s\n");
            statistics.append(prtdbl(s2cspd * 1000) + "kb/s\n");
            emailText += prtdbl(s2cspd * 1000) + "kb/s\n%0A";
        } else {
            results.append(prtdbl(s2cspd) + "Mb/s\n");
            statistics.append(prtdbl(s2cspd) + "Mb/s\n");
            emailText += prtdbl(s2cspd) + "Mb/s\n%0A";
        }

        // Expose download speed to JavaScript clients
        pub_s2cspd = s2cspd;
        dnlLbl.setText(String.format(padding + "%.3f Mbps", s2cspd));
        pub_status = "done";

        srvin.close();
        inSocket.close();

        buff = Double.toString(s2cspd * 1000).getBytes();
        String tmpstr4 = new String(buff, 0, buff.length);
        System.out.println("Sending '" + tmpstr4 + "' back to server");
        ctl.send_msg(TEST_MSG, buff);

        /* get web100 variables from server */
        tmpstr = "";
        int i = 0;

        // Try setting a 5 second timer here to break out if the read fails.
        ctlSocket.setSoTimeout(5000);
        try {
            for (;;) {
                if (ctl.recv_msg(msg) != 0) {
                    errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                            + " instead\n";
                    return true;
                }
                if (msg.type == TEST_FINALIZE) {
                    break;
                }
                if (msg.type != TEST_MSG) {
                    errmsg = messages.getString("inboundWrongMessage") + "\n";
                    if (msg.type == MSG_ERROR) {
                        errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
                    }
                    return true;
                }
                tmpstr += new String(msg.body);
                i++;
            }
        } catch (IOException e) {
        }
        ctlSocket.setSoTimeout(0);
    }
    pub_status = "done";
    return false;
}

From source file:at.alladin.rmbt.controlServer.ResultResource.java

@Post("json")
public String request(final String entity) {
    final String secret = getContext().getParameters().getFirstValue("RMBT_SECRETKEY");

    addAllowOrigin();/* w  w w .  j a v  a 2 s  .  c om*/

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();

    System.out.println(MessageFormat.format(labels.getString("NEW_RESULT"), getIP()));

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);
            System.out.println(request);

            final String lang = request.optString("client_language");

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            }

            //                System.out.println(request.toString(4));

            if (conn != null) {

                conn.setAutoCommit(false);

                final Test test = new Test(conn);

                if (request.optString("test_token").length() > 0) {

                    final String[] token = request.getString("test_token").split("_");

                    try {

                        // Check if UUID
                        final UUID testUuid = UUID.fromString(token[0]);

                        final String data = token[0] + "_" + token[1];

                        final String hmac = Helperfunctions.calculateHMAC(secret, data);
                        if (hmac.length() == 0)
                            errorList.addError("ERROR_TEST_TOKEN");

                        if (token[2].length() > 0 && hmac.equals(token[2])) {

                            final List<String> clientNames = Arrays
                                    .asList(settings.getString("RMBT_CLIENT_NAME").split(",\\s*"));
                            final List<String> clientVersions = Arrays
                                    .asList(settings.getString("RMBT_VERSION_NUMBER").split(",\\s*"));

                            if (test.getTestByUuid(testUuid) > 0)
                                if (clientNames.contains(request.optString("client_name"))
                                        && clientVersions.contains(request.optString("client_version"))) {

                                    test.setFields(request);

                                    final String networkOperator = request
                                            .optString("telephony_network_operator");
                                    if (MCC_MNC_PATTERN.matcher(networkOperator).matches())
                                        test.getField("network_operator").setString(networkOperator);
                                    else
                                        test.getField("network_operator").setString(null);

                                    final String networkSimOperator = request
                                            .optString("telephony_network_sim_operator");
                                    if (MCC_MNC_PATTERN.matcher(networkSimOperator).matches())
                                        test.getField("network_sim_operator").setString(networkSimOperator);
                                    else
                                        test.getField("network_sim_operator").setString(null);

                                    // RMBTClient Info

                                    final String ipLocalRaw = request.optString("test_ip_local", null);
                                    if (ipLocalRaw != null) {
                                        final InetAddress ipLocalAddress = InetAddresses.forString(ipLocalRaw);
                                        // original address (not filtered)
                                        test.getField("client_ip_local")
                                                .setString(InetAddresses.toAddrString(ipLocalAddress));
                                        // anonymized local address
                                        final String ipLocalAnonymized = Helperfunctions
                                                .anonymizeIp(ipLocalAddress);
                                        test.getField("client_ip_local_anonymized")
                                                .setString(ipLocalAnonymized);
                                        // type of local ip
                                        test.getField("client_ip_local_type")
                                                .setString(Helperfunctions.IpType(ipLocalAddress));
                                        // public ip
                                        final InetAddress ipPublicAddress = InetAddresses
                                                .forString(test.getField("client_public_ip").toString());
                                        test.getField("nat_type").setString(
                                                Helperfunctions.getNatType(ipLocalAddress, ipPublicAddress));
                                    }

                                    final String ipServer = request.optString("test_ip_server", null);
                                    if (ipServer != null) {
                                        final InetAddress testServerInetAddress = InetAddresses
                                                .forString(ipServer);
                                        test.getField("server_ip")
                                                .setString(InetAddresses.toAddrString(testServerInetAddress));
                                    }

                                    //log IP address
                                    final String ipSource = getIP();
                                    test.getField("source_ip").setString(ipSource);

                                    //log anonymized address
                                    try {
                                        final InetAddress ipSourceIP = InetAddress.getByName(ipSource);
                                        final String ipSourceAnonymized = Helperfunctions
                                                .anonymizeIp(ipSourceIP);
                                        test.getField("source_ip_anonymized").setString(ipSourceAnonymized);
                                    } catch (UnknownHostException e) {
                                        System.out.println("Exception thrown:" + e);
                                    }

                                    // Additional Info

                                    //////////////////////////////////////////////////
                                    // extended test stats:
                                    //////////////////////////////////////////////////
                                    final TestStat extendedTestStat = TestStat
                                            .checkForSubmittedTestStats(request, test.getUid());
                                    if (extendedTestStat != null) {
                                        final TestStatDao testStatDao = new TestStatDao(conn);
                                        testStatDao.save(extendedTestStat);
                                    }

                                    //////////////////////////////////////////////////

                                    JSONArray speedData = request.optJSONArray("speed_detail");

                                    if (speedData != null && !test.hasError()) {
                                        final PreparedStatement psSpeed = conn.prepareStatement(
                                                "INSERT INTO test_speed (test_id, upload, thread, time, bytes) VALUES (?,?,?,?,?)");
                                        psSpeed.setLong(1, test.getUid());
                                        for (int i = 0; i < speedData.length(); i++) {
                                            final JSONObject item = speedData.getJSONObject(i);

                                            final String direction = item.optString("direction");
                                            if (direction != null && (direction.equals("download")
                                                    || direction.equals("upload"))) {
                                                psSpeed.setBoolean(2, direction.equals("upload"));
                                                psSpeed.setInt(3, item.optInt("thread"));
                                                psSpeed.setLong(4, item.optLong("time"));
                                                psSpeed.setLong(5, item.optLong("bytes"));

                                                psSpeed.executeUpdate();
                                            }
                                        }
                                    }

                                    final JSONArray pingData = request.optJSONArray("pings");

                                    if (pingData != null && !test.hasError()) {
                                        final PreparedStatement psPing = conn.prepareStatement(
                                                "INSERT INTO ping (test_id, value, value_server, time_ns) "
                                                        + "VALUES(?,?,?,?)");
                                        psPing.setLong(1, test.getUid());

                                        for (int i = 0; i < pingData.length(); i++) {

                                            final JSONObject pingDataItem = pingData.getJSONObject(i);

                                            long valueClient = pingDataItem.optLong("value", -1);
                                            if (valueClient >= 0)
                                                psPing.setLong(2, valueClient);
                                            else
                                                psPing.setNull(2, Types.BIGINT);

                                            long valueServer = pingDataItem.optLong("value_server", -1);
                                            if (valueServer >= 0)
                                                psPing.setLong(3, valueServer);
                                            else
                                                psPing.setNull(3, Types.BIGINT);

                                            long timeNs = pingDataItem.optLong("time_ns", -1);
                                            if (timeNs >= 0)
                                                psPing.setLong(4, timeNs);
                                            else
                                                psPing.setNull(4, Types.BIGINT);

                                            psPing.executeUpdate();
                                        }
                                    }

                                    final JSONArray geoData = request.optJSONArray("geoLocations");

                                    if (geoData != null && !test.hasError())
                                        for (int i = 0; i < geoData.length(); i++) {

                                            final JSONObject geoDataItem = geoData.getJSONObject(i);

                                            if (geoDataItem.optLong("tstamp", 0) != 0
                                                    && geoDataItem.optDouble("geo_lat", 0) != 0
                                                    && geoDataItem.optDouble("geo_long", 0) != 0) {

                                                final GeoLocation geoloc = new GeoLocation(conn);

                                                geoloc.setTest_id(test.getUid());

                                                final long clientTime = geoDataItem.optLong("tstamp");
                                                final Timestamp tstamp = java.sql.Timestamp
                                                        .valueOf(new Timestamp(clientTime).toString());

                                                geoloc.setTime(tstamp, test.getField("timezone").toString());
                                                geoloc.setAccuracy(
                                                        (float) geoDataItem.optDouble("accuracy", 0));
                                                geoloc.setAltitude(geoDataItem.optDouble("altitude", 0));
                                                geoloc.setBearing((float) geoDataItem.optDouble("bearing", 0));
                                                geoloc.setSpeed((float) geoDataItem.optDouble("speed", 0));
                                                geoloc.setProvider(geoDataItem.optString("provider", ""));
                                                geoloc.setGeo_lat(geoDataItem.optDouble("geo_lat", 0));
                                                geoloc.setGeo_long(geoDataItem.optDouble("geo_long", 0));
                                                geoloc.setTime_ns(geoDataItem.optLong("time_ns", 0));

                                                geoloc.storeLocation();

                                                // Store Last Geolocation as
                                                // Testlocation
                                                if (i == geoData.length() - 1) {
                                                    if (geoDataItem.has("geo_lat"))
                                                        test.getField("geo_lat").setField(geoDataItem);

                                                    if (geoDataItem.has("geo_long"))
                                                        test.getField("geo_long").setField(geoDataItem);

                                                    if (geoDataItem.has("accuracy"))
                                                        test.getField("geo_accuracy").setField(geoDataItem);

                                                    if (geoDataItem.has("provider"))
                                                        test.getField("geo_provider").setField(geoDataItem);
                                                }

                                                if (geoloc.hasError()) {
                                                    errorList.addError(geoloc.getError());
                                                    break;
                                                }

                                            }

                                        }

                                    final JSONArray cellData = request.optJSONArray("cellLocations");

                                    if (cellData != null && !test.hasError())
                                        for (int i = 0; i < cellData.length(); i++) {

                                            final JSONObject cellDataItem = cellData.getJSONObject(i);

                                            final Cell_location cellloc = new Cell_location(conn);

                                            cellloc.setTest_id(test.getUid());

                                            final long clientTime = cellDataItem.optLong("time");
                                            final Timestamp tstamp = java.sql.Timestamp
                                                    .valueOf(new Timestamp(clientTime).toString());

                                            cellloc.setTime(tstamp, test.getField("timezone").toString());

                                            cellloc.setTime_ns(cellDataItem.optLong("time_ns", 0));

                                            cellloc.setLocation_id(cellDataItem.optInt("location_id", 0));
                                            cellloc.setArea_code(cellDataItem.optInt("area_code", 0));

                                            cellloc.setPrimary_scrambling_code(
                                                    cellDataItem.optInt("primary_scrambling_code", 0));

                                            cellloc.storeLocation();

                                            if (cellloc.hasError()) {
                                                errorList.addError(cellloc.getError());
                                                break;
                                            }

                                        }

                                    int signalStrength = Integer.MAX_VALUE; //measured as RSSI (GSM,UMTS,Wifi)
                                    int lteRsrp = Integer.MAX_VALUE; // signal strength measured as RSRP
                                    int lteRsrq = Integer.MAX_VALUE; // signal quality of LTE measured as RSRQ
                                    int linkSpeed = UNKNOWN;
                                    final int networkType = test.getField("network_type").intValue();

                                    final JSONArray signalData = request.optJSONArray("signals");

                                    if (signalData != null && !test.hasError()) {

                                        for (int i = 0; i < signalData.length(); i++) {

                                            final JSONObject signalDataItem = signalData.getJSONObject(i);

                                            final Signal signal = new Signal(conn);

                                            signal.setTest_id(test.getUid());

                                            final long clientTime = signalDataItem.optLong("time");
                                            final Timestamp tstamp = java.sql.Timestamp
                                                    .valueOf(new Timestamp(clientTime).toString());

                                            signal.setTime(tstamp, test.getField("timezone").toString());

                                            final int thisNetworkType = signalDataItem.optInt("network_type_id",
                                                    0);
                                            signal.setNetwork_type_id(thisNetworkType);

                                            final int thisSignalStrength = signalDataItem
                                                    .optInt("signal_strength", UNKNOWN);
                                            if (thisSignalStrength != UNKNOWN)
                                                signal.setSignal_strength(thisSignalStrength);
                                            signal.setGsm_bit_error_rate(
                                                    signalDataItem.optInt("gsm_bit_error_rate", 0));
                                            final int thisLinkSpeed = signalDataItem.optInt("wifi_link_speed",
                                                    0);
                                            signal.setWifi_link_speed(thisLinkSpeed);
                                            final int rssi = signalDataItem.optInt("wifi_rssi", UNKNOWN);
                                            if (rssi != UNKNOWN)
                                                signal.setWifi_rssi(rssi);

                                            lteRsrp = signalDataItem.optInt("lte_rsrp", UNKNOWN);
                                            lteRsrq = signalDataItem.optInt("lte_rsrq", UNKNOWN);
                                            final int lteRssnr = signalDataItem.optInt("lte_rssnr", UNKNOWN);
                                            final int lteCqi = signalDataItem.optInt("lte_cqi", UNKNOWN);
                                            final long timeNs = signalDataItem.optLong("time_ns", UNKNOWN);
                                            signal.setLte_rsrp(lteRsrp);
                                            signal.setLte_rsrq(lteRsrq);
                                            signal.setLte_rssnr(lteRssnr);
                                            signal.setLte_cqi(lteCqi);
                                            signal.setTime_ns(timeNs);

                                            signal.storeSignal();

                                            if (networkType == 99) // wlan
                                            {
                                                if (rssi < signalStrength && rssi != UNKNOWN)
                                                    signalStrength = rssi;
                                            } else if (thisSignalStrength < signalStrength
                                                    && thisSignalStrength != UNKNOWN)
                                                signalStrength = thisSignalStrength;

                                            if (thisLinkSpeed != 0
                                                    && (linkSpeed == UNKNOWN || thisLinkSpeed < linkSpeed))
                                                linkSpeed = thisLinkSpeed;

                                            if (signal.hasError()) {
                                                errorList.addError(signal.getError());
                                                break;
                                            }

                                        }
                                        // set rssi value (typically GSM,UMTS, but also old LTE-phones)
                                        if (signalStrength != Integer.MAX_VALUE && signalStrength != UNKNOWN
                                                && signalStrength != 0) // 0 dBm is out of range
                                            ((IntField) test.getField("signal_strength"))
                                                    .setValue(signalStrength);
                                        // set rsrp value (typically LTE)
                                        if (lteRsrp != Integer.MAX_VALUE && lteRsrp != UNKNOWN && lteRsrp != 0) // 0 dBm is out of range
                                            ((IntField) test.getField("lte_rsrp")).setValue(lteRsrp);
                                        // set rsrq value (LTE)
                                        if (lteRsrq != Integer.MAX_VALUE && lteRsrq != UNKNOWN)
                                            ((IntField) test.getField("lte_rsrq")).setValue(lteRsrq);

                                        if (linkSpeed != Integer.MAX_VALUE && linkSpeed != UNKNOWN)
                                            ((IntField) test.getField("wifi_link_speed")).setValue(linkSpeed);
                                    }

                                    // use max network type

                                    final String sqlMaxNetworkType = "SELECT nt.uid" + " FROM signal s"
                                            + " JOIN network_type nt" + " ON s.network_type_id=nt.uid"
                                            + " WHERE test_id=?" + " ORDER BY nt.technology_order DESC"
                                            + " LIMIT 1";

                                    final PreparedStatement psMaxNetworkType = conn
                                            .prepareStatement(sqlMaxNetworkType);
                                    psMaxNetworkType.setLong(1, test.getUid());
                                    if (psMaxNetworkType.execute()) {
                                        final ResultSet rs = psMaxNetworkType.getResultSet();
                                        if (rs.next()) {
                                            final int maxNetworkType = rs.getInt("uid");
                                            if (maxNetworkType != 0)
                                                ((IntField) test.getField("network_type"))
                                                        .setValue(maxNetworkType);
                                        }
                                    }

                                    /*
                                     * check for different types (e.g.
                                     * 2G/3G)
                                     */
                                    final String sqlAggSignal = "WITH agg AS"
                                            + " (SELECT array_agg(DISTINCT nt.group_name ORDER BY nt.group_name) agg"
                                            + " FROM signal s"
                                            + " JOIN network_type nt ON s.network_type_id=nt.uid WHERE test_id=?)"
                                            + " SELECT uid FROM agg JOIN network_type nt ON nt.aggregate=agg";

                                    final PreparedStatement psAgg = conn.prepareStatement(sqlAggSignal);
                                    psAgg.setLong(1, test.getUid());
                                    if (psAgg.execute()) {
                                        final ResultSet rs = psAgg.getResultSet();
                                        if (rs.next()) {
                                            final int newNetworkType = rs.getInt("uid");
                                            if (newNetworkType != 0)
                                                ((IntField) test.getField("network_type"))
                                                        .setValue(newNetworkType);
                                        }
                                    }

                                    if (test.getField("network_type").intValue() <= 0)
                                        errorList.addError("ERROR_NETWORK_TYPE");

                                    final IntField downloadField = (IntField) test.getField("speed_download");
                                    if (downloadField.isNull() || downloadField.intValue() <= 0
                                            || downloadField.intValue() > 10000000) // 10 gbit/s limit
                                        errorList.addError("ERROR_DOWNLOAD_INSANE");

                                    final IntField upField = (IntField) test.getField("speed_upload");
                                    if (upField.isNull() || upField.intValue() <= 0
                                            || upField.intValue() > 10000000) // 10 gbit/s limit
                                        errorList.addError("ERROR_UPLOAD_INSANE");

                                    //clients still report eg: "test_ping_shortest":9195040 (note the 'test_' prefix there!)
                                    final LongField pingField = (LongField) test.getField("ping_shortest");
                                    if (pingField.isNull() || pingField.longValue() <= 0
                                            || pingField.longValue() > 60000000000L) // 1 min limit
                                        errorList.addError("ERROR_PING_INSANE");

                                    if (errorList.isEmpty())
                                        test.getField("status").setString("FINISHED");
                                    else
                                        test.getField("status").setString("ERROR");

                                    test.storeTestResults(false);

                                    if (test.hasError())
                                        errorList.addError(test.getError());

                                } else
                                    errorList.addError("ERROR_CLIENT_VERSION");
                        } else
                            errorList.addError("ERROR_TEST_TOKEN_MALFORMED");
                    } catch (final IllegalArgumentException e) {
                        e.printStackTrace();
                        errorList.addError("ERROR_TEST_TOKEN_MALFORMED");
                    }

                } else
                    errorList.addError("ERROR_TEST_TOKEN_MISSING");

                conn.commit();
            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
            e.printStackTrace();
        } catch (final SQLException e) {
            System.out.println("Error while storing data " + e.toString());
            e.printStackTrace();
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    return answer.toString();
}