Example usage for java.io IOException toString

List of usage examples for java.io IOException toString

Introduction

In this page you can find the example usage for java.io IOException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:gov.nih.cadsr.transform.FilesTransformation.java

public static String transformFormToCSV(String xmlFile) {

    StringBuffer sb = null;/*from   w  w w . ja v a  2s .com*/

    try {

        File tf = new File("/local/content/cadsrapi/transform/xslt/", "formbuilder.xslt"); // template file
        String path = "/local/content/cadsrapi/transform/data/";
        String ext = "txt";
        File dir = new File(path);
        String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext);
        File rf = new File(dir, name);

        if (tf == null || !tf.exists() || !tf.canRead()) {
            System.out.println("File path incorrect");
            return "";
        }

        long startTime = System.currentTimeMillis();

        //Obtain a new instance of a TransformerFactory. 
        TransformerFactory f = TransformerFactory.newInstance();
        // Process the Source into a Transformer Object...Construct a StreamSource from a File.
        Transformer t = f.newTransformer(new StreamSource(tf));

        //Construct a StreamSource from input and output
        Source s;
        try {
            s = new StreamSource((new ByteArrayInputStream(xmlFile.getBytes("utf-8"))));
            Result r = new StreamResult(rf);

            //Transform the XML Source to a Result.
            t.transform(s, r);
            System.out.println("Tranformation completed ...");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            System.out.println(e1.toString());
        }

        //convert output file to string                                       
        try {
            BufferedReader bf = new BufferedReader(new FileReader(rf));
            sb = new StringBuffer();
            try {
                String currentLine;
                while ((currentLine = bf.readLine()) != null) {
                    sb.append(currentLine).append("\n");
                    //System.out.println(bf.readLine());

                }
            } catch (IOException e) {

                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("Transformation took " + (endTime - startTime) + " milliseconds");
        System.out.println("Transformation took " + (endTime - startTime) / 1000 + " seconds");
    }

    catch (TransformerConfigurationException e) {
        System.out.println(e.toString());

    } catch (TransformerException e) {
        System.out.println(e.toString());

    }

    return sb.toString();
}

From source file:com.cheusov.Jrep.java

private static void grep(String[] args) throws Exception {
    if (args.length == 0)
        args = stdinFilenames;/*w  ww. ja  v  a  2 s .c o  m*/

    for (String fileOrDir : args) {
        try {
            Iterator fileIterator;
            File file = new File(fileOrDir);
            boolean isDir = false;
            if (opt_directories != Directories.READ)
                isDir = file.isDirectory();

            if (isDir && opt_directories == Directories.SKIP)
                continue;

            if (isDir && opt_directories == Directories.RECURSE) {
                fileIterator = FileUtils.iterateFiles(file, fileFilter, DirectoryFileFilter.DIRECTORY);
            } else {
                fileIterator = Arrays.asList(fileOrDir).iterator();
            }

            while (fileIterator.hasNext()) {
                Object fileObj = fileIterator.next();
                String filename;
                if (fileObj instanceof String)
                    filename = (String) fileObj;
                else
                    filename = ((File) fileObj).getPath().replaceAll("^^[.]/", "");

                if (filename.equals("-")) {
                    processFile(System.in, label);
                } else {
                    if (fileFilter.accept(new File(filename))) {
                        FileInputStream in = new FileInputStream(filename);
                        processFile(in, filename);
                        in.close();
                    }
                }
            }
        } catch (IOException e) {
            if (!opt_s)
                System.err.println(e.toString());

            exitStatus = 2;
        }
    }
}

From source file:gov.nih.cadsr.transform.FilesTransformation.java

public static String transformCdeToCSV(String xmlFile) {

    StringBuffer sb = null;/*from   w w  w .j av a2  s  . com*/

    try {

        File tf = new File("/local/content/cadsrapi/transform/xslt/", "cdebrowser.xslt"); // template file

        String path = "/local/content/cadsrapi/transform/data/";
        String ext = "txt";
        File dir = new File(path);
        String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext);
        File rf = new File(dir, name);

        if (tf == null || !tf.exists() || !tf.canRead()) {
            System.out.println("File path incorrect");
            return "";
        }

        long startTime = System.currentTimeMillis();

        //Obtain a new instance of a TransformerFactory. 
        TransformerFactory f = TransformerFactory.newInstance();
        // Process the Source into a Transformer Object...Construct a StreamSource from a File.
        Transformer t = f.newTransformer(new StreamSource(tf));

        /*
        Source s = new StreamSource(xmlFile);
        Result r = new StreamResult(rf); 
                 
        //Transform the XML Source to a Result.
        t.transform(s,r);
        System.out.println("Tranformation completed ...");   */

        //Construct a StreamSource from input and output
        Source s;
        try {
            s = new StreamSource((new ByteArrayInputStream(xmlFile.getBytes("utf-8"))));
            Result r = new StreamResult(rf);

            //Transform the XML Source to a Result.
            t.transform(s, r);
            System.out.println("Tranformation completed ...");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            System.out.println(e1.toString());
        }

        try {
            BufferedReader bf = new BufferedReader(new FileReader(rf));
            sb = new StringBuffer();
            try {
                String currentLine;
                while ((currentLine = bf.readLine()) != null) {
                    sb.append(currentLine).append("\n");
                    //System.out.println(bf.readLine());

                }
            } catch (IOException e) {

                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("Transformation took " + (endTime - startTime) + " milliseconds");
        System.out.println("Transformation took " + (endTime - startTime) / 1000 + " seconds");
    }

    catch (TransformerConfigurationException e) {
        System.out.println(e.toString());
        e.printStackTrace();

    } catch (TransformerException e) {
        System.out.println(e.toString());

    }

    return sb.toString();
}

From source file:com.streamsets.pipeline.lib.util.ProtobufTypeUtil.java

/**
 * Serializes a field path in a record to a protobuf message using the specified descriptor.
 *
 * @param record                    Record with the field to serialize
 * @param field                     The field to serialize
 * @param fieldPath                 The field path of the specified field
 * @param desc                      Protobuf descriptor
 * @param messageTypeToExtensionMap Protobuf extension map
 * @param defaultValueMap           Protobuf default field values
 * @return serialized message/*from w  w  w.ja  va2s .c o m*/
 * @throws DataGeneratorException
 */
private static DynamicMessage sdcFieldToProtobufMsg(Record record, Field field, String fieldPath,
        Descriptors.Descriptor desc, Map<String, Set<Descriptors.FieldDescriptor>> messageTypeToExtensionMap,
        Map<String, Object> defaultValueMap) throws DataGeneratorException {
    if (field == null) {
        return null;
    }

    // compute all fields to look for including extensions
    DynamicMessage.Builder builder = DynamicMessage.newBuilder(desc);
    List<Descriptors.FieldDescriptor> fields = new ArrayList<>();
    fields.addAll(desc.getFields());
    if (messageTypeToExtensionMap.containsKey(desc.getFullName())) {
        fields.addAll(messageTypeToExtensionMap.get(desc.getFullName()));
    }

    // root field is always a Map in a record representing protobuf data
    Map<String, Field> valueAsMap = field.getValueAsMap();

    for (Descriptors.FieldDescriptor f : fields) {
        Field mapField = valueAsMap.get(f.getName());
        // Repeated field
        if (f.isMapField()) {
            handleMapField(record, mapField, fieldPath, messageTypeToExtensionMap, defaultValueMap, f, builder);
        } else if (f.isRepeated()) {
            handleRepeatedField(record, mapField, fieldPath, messageTypeToExtensionMap, defaultValueMap, f,
                    builder);
        } else {
            // non repeated field
            handleNonRepeatedField(record, valueAsMap, fieldPath, messageTypeToExtensionMap, defaultValueMap,
                    desc, f, builder);
        }
    }

    // if record has unknown fields for this field path, handle it
    try {
        handleUnknownFields(record, fieldPath, builder);
    } catch (IOException e) {
        throw new DataGeneratorException(Errors.PROTOBUF_05, e.toString(), e);
    }

    return builder.build();
}

From source file:com.iitb.cse.Utils.java

public static boolean startExperiment(int expId, String timeout, String logBgTraffic) {

    File file = null;//from   www  .  j  av  a 2 s.c o  m
    File file1 = null;

    if (Constants.experimentDetailsDirectory.endsWith("/")) {
        file = new File(Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId()
                + "/" + Constants.configFile);
        file1 = new File(
                Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId());
    } else {
        file = new File(Constants.experimentDetailsDirectory + "/"
                + Constants.currentSession.getCurrentExperimentId() + "/" + Constants.configFile);
        file1 = new File(
                Constants.experimentDetailsDirectory + "/" + Constants.currentSession.getCurrentExperimentId());
    }

    if (file.exists()) {
        Charset charset = Charset.forName("UTF-8");
        String line = null;

        String[] data = new String[1000];//
        int index = 0;
        data[index] = "";
        try {
            BufferedReader reader = Files.newBufferedReader(file.toPath(), charset);
            Calendar cal = Calendar.getInstance();
            while ((line = reader.readLine()) != null) {

                System.out.println("\nLENGTH : " + line.length());

                if (line.isEmpty() || line.trim().equals("")) {
                    System.out.println("\nCASE1");
                    continue;
                } else if (line.trim().equals("*****\n")) {
                    System.out.println("\nCASE2");
                    data[index] = expId + "\n" + data[index];
                    index++;
                    data[index] = "";
                    continue;
                } else if (line.trim().equals("*****")) {
                    System.out.println("\nCASE3");
                    data[index] = expId + "\n" + data[index];
                    index++;
                    data[index] = "";
                    continue;
                }

                String[] lineVariables = line.split(" ");

                //   int offset = Integer.parseInt(lineVariables[1]);
                //   cal.add(Calendar.SECOND, offset);
                //****************************************************
                double time = Double.parseDouble(lineVariables[1]);

                int sec = (int) time;
                double rem = time % 1;
                int remainder = (int) (rem * 1000);
                //       Calendar cal = Calendar.getInstance();
                //   System.out.println("\nSec : " + sec + "\nMiSec : " + remainder + "\nTime : " + cal.getTime());
                int flag = 0;
                if (remainder < 100) {
                    flag = 1;
                    remainder = remainder + 100;
                    cal.add(Calendar.SECOND, sec);
                    cal.add(Calendar.MILLISECOND, remainder);
                    cal.add(Calendar.MILLISECOND, -100);
                } else {
                    cal.add(Calendar.SECOND, sec);
                    cal.add(Calendar.MILLISECOND, remainder);
                }

                //****************************************************
                if (lineVariables.length == 5) {
                    //       System.out.println("\nINSIDE");
                    data[index] += generateLine(cal, lineVariables[2], lineVariables[0], lineVariables[3],
                            lineVariables[4]);
                } else {
                    //    System.out.println("\nOUTSIDE");
                    data[index] += generateLine(cal, lineVariables[2], lineVariables[0], lineVariables[3]);
                }

                if (flag == 1) {
                    cal.add(Calendar.SECOND, -1 * sec);
                    cal.add(Calendar.MILLISECOND, -1 * remainder);
                    cal.add(Calendar.MILLISECOND, 100);
                } else {
                    cal.add(Calendar.SECOND, -1 * sec);
                    cal.add(Calendar.MILLISECOND, -1 * remainder);
                }

            }

            data[index] = expId + "\n" + data[index];

        } catch (IOException ex) {
            System.out.println(ex.toString());
            return false;
        }

        int controlFileIndex = 0;
        for (DeviceInfo d : Constants.currentSession.getFilteredClients()) {

            if (controlFileIndex >= Constants.currentSession.getFilteredClients().size()) {
                break;
            } else if (data[controlFileIndex] != null) {

                String jsonString = Utils.getControlFileJson(data[controlFileIndex], timeout, logBgTraffic);
                System.out.println("\njsonString : " + jsonString);
                System.out.println("\nControl FIle : " + data[controlFileIndex]);

                /* Locally keep the corresponding control file to each client*/
                PrintWriter writer;
                try {
                    writer = new PrintWriter(file1 + "/" + d.macAddress + "_confFile");
                    writer.write(data[controlFileIndex]);
                    writer.flush();
                    writer.close();
                } catch (FileNotFoundException ex) {
                    System.out.println("\nException : " + ex.toString());
                }

                //writer.close();
                System.out.println("\nDevice Info : IP " + d.ip + " Port " + d.port + " Mac " + d.macAddress);
                Thread sendData = new Thread(new SendData(expId, d, 0, jsonString, data[controlFileIndex]));
                sendData.start();
            } else {
                break;
            }
            controlFileIndex++;
        }
    } else {
        System.out.println("\nConfig FIle not found in location : " + Constants.experimentDetailsDirectory
                + Constants.currentSession.getCurrentExperimentId());
    }

    return true;
}

From source file:com.streamsets.pipeline.lib.util.ProtobufTypeUtil.java

/**
 * Converts a protobuf message to an SDC Record Field.
 *
 * @param record                    SDC Record to add field to
 * @param fieldPath                 location in record where to insert field.
 * @param descriptor                protobuf descriptor instance
 * @param messageTypeToExtensionMap protobuf extensions map
 * @param message                   message to decode and insert into the specified field path
 * @return new Field instance representing the decoded message
 * @throws DataParserException//w  ww.j  a  v a  2s . c o  m
 */
public static Field protobufToSdcField(Record record, String fieldPath, Descriptors.Descriptor descriptor,
        Map<String, Set<Descriptors.FieldDescriptor>> messageTypeToExtensionMap, Object message)
        throws DataParserException {
    Map<String, Field> sdcRecordMapFieldValue = new HashMap<>();

    // get all the expected fields from the proto file
    Map<String, Descriptors.FieldDescriptor> protobufFields = new LinkedHashMap<>();
    for (Descriptors.FieldDescriptor fieldDescriptor : descriptor.getFields()) {
        protobufFields.put(fieldDescriptor.getName(), fieldDescriptor);
    }

    // get all fields in the read message
    Map<Descriptors.FieldDescriptor, Object> values = ((DynamicMessage) message).getAllFields();

    // for every field present in the proto definition create an sdc field.
    for (Descriptors.FieldDescriptor fieldDescriptor : protobufFields.values()) {
        Object value = values.get(fieldDescriptor);
        sdcRecordMapFieldValue.put(fieldDescriptor.getName(),
                createField(record, fieldPath, fieldDescriptor, messageTypeToExtensionMap, value));
    }

    // handle applicable extensions for this message type
    if (messageTypeToExtensionMap.containsKey(descriptor.getFullName())) {
        for (Descriptors.FieldDescriptor fieldDescriptor : messageTypeToExtensionMap
                .get(descriptor.getFullName())) {
            if (values.containsKey(fieldDescriptor)) {
                Object value = values.get(fieldDescriptor);
                sdcRecordMapFieldValue.put(fieldDescriptor.getName(),
                        createField(record, fieldPath, fieldDescriptor, messageTypeToExtensionMap, value));
            }
        }
    }

    // handle unknown fields
    // unknown fields can go into the record header
    UnknownFieldSet unknownFields = ((DynamicMessage) message).getUnknownFields();
    if (!unknownFields.asMap().isEmpty()) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        try {
            unknownFields.writeDelimitedTo(bOut);
            bOut.flush();
            bOut.close();
        } catch (IOException e) {
            throw new DataParserException(Errors.PROTOBUF_10, e.toString(), e);
        }
        String path = fieldPath.isEmpty() ? FORWARD_SLASH : fieldPath;
        byte[] bytes = org.apache.commons.codec.binary.Base64.encodeBase64(bOut.toByteArray());
        record.getHeader().setAttribute(PROTOBUF_UNKNOWN_FIELDS_PREFIX + path,
                new String(bytes, StandardCharsets.UTF_8));
    }

    return Field.create(sdcRecordMapFieldValue);
}

From source file:edu.umd.cs.eclipse.courseProjectManager.EclipseLaunchEventLog.java

static void postEventLogToServer(IProject project) {
    // Log to the course project manager log (visible to users).
    AutoCVSPlugin.getPlugin().getEventLog()
            .logMessage(new Date() + "\t" + "Collecting data for the Marmoset Project.");

    // Look up the EclipseLaunchEventLog for this project. This creates one
    // if it/*from   w w  w .  j  a  v  a  2  s .  c  o m*/
    // doesn't already exist.
    EclipseLaunchEventLog eclipseLaunchEventLog = EclipseLaunchEventLog.getLog(project);

    // NOTE: Don't try to upload if the user has disabled AutoCVS
    // or has shut off Eclipse launch event monitoring.
    IResource submitUserFile = project.findMember(AutoCVSPlugin.SUBMITUSER);

    // Don't log anything if we don't have a submitUser file,
    // autoCVS mode is disabled, or runlogging is disabled
    if (submitUserFile == null || !AutoCVSPlugin.hasAutoCVSNature(project)
            || !AutoCVSPlugin.hasAutoRunLogNature(project)) {
        return;
    }

    Debug.print("Trying to upload directly to the SubmitServer using a .submitUser file");

    // Find the .submitProject file.
    // This file will only exist for projects controlled by Marmoset.
    IResource submitProjectFile = project.findMember(AutoCVSPlugin.SUBMITPROJECT);
    if (submitProjectFile == null) {
        Debug.print("Can't find .submit file!");
        AutoCVSPlugin.getPlugin().getEventLog()
                .logMessage("project " + project.getName() + " does not contain a "
                        + AutoCVSPlugin.SUBMITPROJECT + " file.  This project is therefore probably not a "
                        + " Computer Science programming assignment that you checked out of CVS.  "
                        + " Thus you can ignore this message.");
        return;
    }

    try {
        Properties props = new Properties();
        FileInputStream fileInputStream = new FileInputStream(submitProjectFile.getRawLocation().toString());
        props.load(fileInputStream);
        fileInputStream.close();

        props.putAll(TurninProjectAction.getUserProperties(submitUserFile));
        Debug.print("Loaded the properties in the .submitUser file");

        // Nothing to report!
        if (eclipseLaunchEventLog.isEmpty())
            return;
        // Check for launch events that have been queued to the logfile.
        String allEvents = eclipseLaunchEventLog.getEvents();
        Debug.print("Grabbed queued events from logfile");

        Debug.print("Uploading!");

        uploadMessages(allEvents, props);

        // Now clear the .cpmLOG
        eclipseLaunchEventLog.clear();
    } catch (IOException e) {
        AutoCVSPlugin.getPlugin().getEventLog()
                .logError("Unable to post Eclipse launch events to the server: " + e.getMessage() + "\n"
                        + "This error is related to data gathering for the Marmoset project and should not "
                        + "affect your ability to work on your project.");
        Debug.print("Unable to log eclipse launch event to the server: " + e.toString());
        // e.printStackTrace();
    }
}

From source file:com.bonsai.wallet32.HDWallet.java

public static JSONObject deserialize(WalletApplication walletApp, KeyCrypter keyCrypter, KeyParameter aesKey)
        throws IOException, InvalidCipherTextException, JSONException {

    File file = walletApp.getHDWalletFile(null);
    String path = file.getPath();

    try {// w  w w .  ja v  a  2 s .co  m
        mLogger.info("restoring HDWallet from " + path);
        int len = (int) file.length();

        // Open persisted file.
        DataInputStream dis = new DataInputStream(new FileInputStream(file));

        // Read IV from file.
        byte[] iv = new byte[KeyCrypterGroestl.BLOCK_LENGTH/*KeyCrypterScrypt.BLOCK_LENGTH*/];
        dis.readFully(iv);

        // Read the ciphertext from the file.
        byte[] cipherBytes = new byte[len - iv.length];
        dis.readFully(cipherBytes);
        dis.close();

        // Decrypt the ciphertext.
        ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.getKey()), iv);
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, keyWithIv);
        int minimumSize = cipher.getOutputSize(cipherBytes.length);
        byte[] outputBuffer = new byte[minimumSize];
        int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, outputBuffer, 0);
        int length2 = cipher.doFinal(outputBuffer, length1);
        int actualLength = length1 + length2;
        byte[] decryptedBytes = new byte[actualLength];
        System.arraycopy(outputBuffer, 0, decryptedBytes, 0, actualLength);

        // Parse the decryptedBytes.
        String jsonstr = new String(decryptedBytes);

        /*
        // THIS CONTAINS THE SEED!
        // Have to break the message into chunks for big messages ...
        String msg = jsonstr;
        while (msg.length() > 1024) {
        String chunk = msg.substring(0, 1024);
        mLogger.error(chunk);
        msg = msg.substring(1024);
        }
        mLogger.error(msg);
        */

        JSONObject node = new JSONObject(jsonstr);
        return node;

    } catch (IOException ex) {
        mLogger.warn("trouble reading " + path + ": " + ex.toString());
        throw ex;
    } catch (RuntimeException ex) {
        mLogger.warn("trouble restoring wallet: " + ex.toString());
        throw ex;
    } catch (InvalidCipherTextException ex) {
        mLogger.warn("wallet decrypt failed: " + ex.toString());
        throw ex;
    }
}

From source file:com.iitb.cse.ConnectionInfo.java

static void handleConnection(Socket sock, Session session, int tid) {

    System.out.println("\n\n\n---------------->>>>>>>>>[" + tid + "]");

    try {/*from  w ww.ja v a  2 s. c  o m*/
        int count = 0;
        boolean newConnection = true;
        String ip_add = sock.getInetAddress().toString();
        String[] _ip_add = ip_add.split("/");

        String macAddress = "";
        DeviceInfo myDevice = null;
        InputStream in = sock.getInputStream();
        OutputStream out = sock.getOutputStream();
        DataInputStream dis = new DataInputStream(in);
        DataOutputStream dos = new DataOutputStream(out);

        while (true) {

            System.out.println("\n[" + tid + "] My Socket : " + sock);

            String receivedData = ClientConnection.readFromStream(sock, dis, dos).trim();
            if (receivedData.equals("") || receivedData == null) {
                System.out.println("\n[Empty/Null Data][" + tid + "]");

            } else {

                System.out.println("\nReceived : " + receivedData);

                Map<String, String> jsonMap = null;
                JSONParser parser = new JSONParser();

                ContainerFactory containerFactory = new ContainerFactory() {

                    @SuppressWarnings("rawtypes")
                    @Override
                    public List creatArrayContainer() {
                        return new LinkedList();
                    }

                    @SuppressWarnings("rawtypes")
                    @Override
                    public Map createObjectContainer() {
                        return new LinkedHashMap();
                    }
                };

                try {
                    jsonMap = (Map<String, String>) parser.parse(receivedData, containerFactory);

                    if (jsonMap != null) {

                        String action = jsonMap.get(Constants.action);

                        if (action.compareTo(Constants.heartBeat) == 0
                                || action.compareTo(Constants.heartBeat1) == 0
                                || action.compareTo(Constants.heartBeat2) == 0) {

                            macAddress = jsonMap.get(Constants.macAddress);
                            // heartbeat    
                            System.out.println("\n [" + tid + "] HeartBeat Received : " + (++count));

                            DeviceInfo device = session.connectedClients.get(jsonMap.get(Constants.macAddress));
                            if (device == null) { // first time from this device. ie new connection

                                System.out.println("<<<== 1 ==>>>");
                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));
                                newDevice.setBssid(jsonMap.get(Constants.bssid));
                                newDevice.setSsid(jsonMap.get(Constants.ssid));
                                // newDevice.setSsid(jsonMap.get(Constants.bssidList));

                                /* String apInfo = jsonMap.get(Constants.bssidList);
                                        
                                if (apInfo != null || !apInfo.equals("")) {
                                  System.out.println("\nInside Bssid List1");
                                String[] bssidInfo = apInfo.split(";");
                                NeighbourAccessPointDetails[] obj = new NeighbourAccessPointDetails[bssidInfo.length];
                                        
                                for (int i = 0; i < bssidInfo.length; i++) {
                                    String[] info = bssidInfo[i].split(",");
                                    obj[i].setBssid(info[0]);
                                    obj[i].setRssi(info[1]);
                                    obj[i].setRssi(info[2]);
                                }
                                newDevice.setBssidList(obj);
                                }*/
                                Date date = Utils.getCurrentTimeStamp();
                                newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setConnectionStatus(true);
                                newDevice.setThread(Thread.currentThread());
                                newDevice.setSocket(sock);
                                newDevice.setGetlogrequestsend(false);

                                /*
                                remaining parameters needs to be added!!!
                                 */
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                            } else // subsequent heartbeats /  reconnection from same client
                            if (newConnection) { // reconnection from same client

                                System.out.println("<<<== 2 ==>>>");
                                if (device.thread != null) {
                                    device.thread.interrupt();
                                    System.out.println("\n@#1[" + tid + "] Interrupting old thread");
                                }

                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));

                                newDevice.setBssid(jsonMap.get(Constants.bssid));
                                newDevice.setSsid(jsonMap.get(Constants.ssid));

                                /* String apInfo = jsonMap.get(Constants.bssidList);
                                if (apInfo != null || !apInfo.equals("")) {
                                    System.out.println("\nInside Bssid List");
                                                    
                                    String[] bssidInfo = apInfo.split(";");
                                    NeighbourAccessPointDetails[] obj = new NeighbourAccessPointDetails[bssidInfo.length];
                                    for (int i = 0; i < bssidInfo.length; i++) {
                                        String[] info = bssidInfo[i].split(",");
                                        obj[i].setBssid(info[0]);
                                        obj[i].setRssi(info[1]);
                                        obj[i].setRssi(info[2]);
                                    }
                                    newDevice.setBssidList(obj);
                                }*/
                                Date date = Utils.getCurrentTimeStamp();
                                newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setSocket(sock);

                                newDevice.setThread(Thread.currentThread());
                                newDevice.setConnectionStatus(true);
                                newDevice.setGetlogrequestsend(false);
                                /*
                                remaining parameters needs to be added!!!
                                 */
                                session.connectedClients.remove(device.macAddress);
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                                if (session.filteredClients.contains(device)) {
                                    session.filteredClients.remove(device);
                                    session.filteredClients.add(newDevice);
                                }

                            } else { // heartbeat

                                System.out.println("<<<== 3 ==>>>");

                                Date date = Utils.getCurrentTimeStamp();
                                device.setLastHeartBeatTime(date);
                                device.setSocket(sock);
                                device.setConnectionStatus(true);
                            }

                        } else if (action.compareTo(Constants.experimentOver) == 0) {

                            macAddress = jsonMap.get(Constants.macAddress);

                            System.out.println("\n[" + tid + "] Experiment Over Mesage received");
                            // experiment over
                            // i need mac address from here
                            // ip and port also preferred
                            DeviceInfo device = session.connectedClients.get(jsonMap.get(Constants.macAddress));

                            if (device == null) { // new connection

                                System.out.println("<<<== 4 ==>>>");

                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));
                                //Date date = Utils.getCurrentTimeStamp();
                                //newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setSocket(sock);
                                newDevice.setThread(Thread.currentThread());
                                newDevice.setGetlogrequestsend(false);
                                newDevice.setConnectionStatus(true);

                                newDevice.setExpOver(1); //

                                if (DBManager.updateExperimentOverStatus(
                                        Integer.parseInt(jsonMap.get(Constants.experimentNumber)),
                                        newDevice.getMacAddress())) {
                                    System.out.println("\nDB Update ExpOver Success");
                                } else {
                                    System.out.println("\nDB Update ExpOver Failed");
                                }

                                /*
                                remaining parameters needs to be added!!!
                                 */
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                            } else if (newConnection) { // reconnction from the same client

                                System.out.println("<<<== 5 ==>>>");

                                if (device.thread != null) {
                                    device.thread.interrupt();
                                    System.out.println("\n@#2[" + tid + "] Interrupting old thread");
                                }

                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));
                                //Date date = Utils.getCurrentTimeStamp();
                                //newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setSocket(sock);

                                newDevice.setThread(Thread.currentThread());
                                newDevice.setGetlogrequestsend(false);
                                newDevice.setConnectionStatus(true);

                                /*
                                remaining parameters needs to be added!!!
                                 */
                                newDevice.setExpOver(1); //

                                if (DBManager.updateExperimentOverStatus(
                                        Integer.parseInt(jsonMap.get(Constants.experimentNumber)),
                                        newDevice.getMacAddress())) {
                                    System.out.println("\nDB Update ExpOver Success");
                                } else {
                                    System.out.println("\nDB Update ExpOver Failed");
                                }

                                session.connectedClients.remove(device.macAddress);
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                                if (session.filteredClients.contains(device)) {
                                    session.filteredClients.remove(device);
                                    session.filteredClients.add(newDevice);
                                }

                            } else {

                                System.out.println("<<<== 6 ==>>>");

                                // alread connected client
                                // device.setExpOver(jsonMap.get(Constants.macAddress))
                                device.setConnectionStatus(true);
                                device.setSocket(sock);
                                device.setExpOver(1); //

                                if (DBManager.updateExperimentOverStatus(
                                        Integer.parseInt(jsonMap.get(Constants.experimentNumber)),
                                        device.getMacAddress())) {
                                    System.out.println("\nDB Update ExpOver Success");
                                } else {
                                    System.out.println("\nDB Update ExpOver Failed");
                                }

                            }

                        } else if (action.compareTo(Constants.acknowledgement) == 0) {

                            System.out.println("\nAcknowledgement Received -->");
                            int expNumber = Integer.parseInt(jsonMap.get(Constants.experimentNumber));
                            System.out.println("\nExperiment number : " + expNumber);
                            //int sessionId = Utils.getCurrentSessionID();
                            int expId = 1;
                            ///important                                int expId =1;// Utils.getCurrentExperimentID(Integer.toString(1));
                            System.out.println("\nExperiment number : " + expNumber + "== " + expId);

                            //            if (expNumber == expId) {
                            if (macAddress != null && !macAddress.equals("")) {
                                DeviceInfo device = session.connectedClients.get(macAddress);
                                session.actualFilteredDevices.add(device);
                                System.out.println("\n Ack : " + expNumber + " Acknowledgement Received!!!");

                                if (DBManager.updateControlFileSendStatus(expNumber, macAddress, 1,
                                        "Successfully sent Control File")) {
                                    System.out.println("\n Ack : " + expNumber + " DB updated Successfully");
                                } else {
                                    System.out.println("\n Ack : " + expNumber + " DB updation Failed");
                                }
                                ///important                                        Utils.addExperimentDetails(expId, device, false);
                            }
                            //              }
                            // update the db.
                        } else {
                            System.out.println("\n[" + tid + "] Some Other Operation...");
                        }
                        newConnection = false;
                    }
                } catch (Exception ex) {
                    System.out.println("Json Ex : " + ex.toString());
                }
            }

            try {
                Thread.sleep(5000); // wait for interrupt
            } catch (InterruptedException ex) {
                System.out.println("\n[" + tid + "] InterruptedException 1 : " + ex.toString() + "\n");

                try {
                    sock.close();
                } catch (IOException ex1) {
                    System.out.println("\n[" + tid + "] IOException5 : " + ex1.toString() + "\n");
                }
                break; //
            }
        }

    } catch (IOException ex) {
        System.out.println("\n [" + tid + "] IOException1 : " + ex.toString() + "\n");
        try {
            sock.close();
            //    session.connectedClients.remove(conn);
        } catch (IOException ex1) {
            System.out.println("\n[" + tid + "] IOException2 : " + ex1.toString() + "\n");
        }
    } catch (Exception ex) {
        System.out.println("\n[" + tid + "] IOException3 : " + ex.toString() + "\n");
        try {
            sock.close();
            //    session.connectedClients.remove(conn);
        } catch (IOException ex1) {
            System.out.println("\n[" + tid + "] IOException4 : " + ex1.toString() + "\n");
        }
    }

}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Attempts to retrieve the job managers address in the network through an
 * IP broadcast. This method should be called by the task manager.
 * /*from w  w w.  j a v  a  2 s.  c  om*/
 * @return the socket address of the job manager in the network
 * @throws DiscoveryException
 *         thrown if the job manager's socket address could not be
 *         discovered
 */
public static InetSocketAddress getJobManagerAddress() throws DiscoveryException {

    final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER);
    final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT);

    InetSocketAddress jobManagerAddress = null;
    DatagramSocket socket = null;

    try {

        final Set<InetAddress> targetAddresses = getBroadcastAddresses();

        if (targetAddresses.isEmpty()) {
            throw new DiscoveryException("Could not find any broadcast addresses available to this host");
        }

        socket = new DatagramSocket();

        LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT);
        socket.setSoTimeout(CLIENTSOCKETTIMEOUT);

        final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE],
                RESPONSE_PACKET_SIZE);

        for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) {

            final DatagramPacket lookupRequest = createJobManagerLookupRequestPacket(magicNumber);

            for (InetAddress broadcast : targetAddresses) {
                lookupRequest.setAddress(broadcast);
                lookupRequest.setPort(discoveryPort);
                LOG.debug("Sending discovery request to " + lookupRequest.getSocketAddress());
                socket.send(lookupRequest);
            }

            try {
                socket.receive(responsePacket);
            } catch (SocketTimeoutException ste) {
                LOG.debug("Timeout wainting for discovery reply. Retrying...");
                continue;
            }

            if (!isPacketForUs(responsePacket, magicNumber)) {
                LOG.debug("Received packet which is not destined to this Nephele setup");
                continue;
            }

            final int packetTypeID = getPacketTypeID(responsePacket);
            if (packetTypeID != JM_LOOKUP_REPLY_ID) {
                LOG.debug("Received unexpected packet type " + packetTypeID + ", discarding... ");
                continue;
            }

            final int ipcPort = extractIpcPort(responsePacket);

            // Replace port from discovery service with the actual RPC port
            // of the job manager
            if (USE_IPV6) {
                // TODO: No connection possible unless we remove the scope identifier
                if (responsePacket.getAddress() instanceof Inet6Address) {
                    try {
                        jobManagerAddress = new InetSocketAddress(
                                InetAddress.getByAddress(responsePacket.getAddress().getAddress()), ipcPort);
                    } catch (UnknownHostException e) {
                        throw new DiscoveryException(StringUtils.stringifyException(e));
                    }
                } else {
                    throw new DiscoveryException(responsePacket.getAddress() + " is not a valid IPv6 address");
                }
            } else {
                jobManagerAddress = new InetSocketAddress(responsePacket.getAddress(), ipcPort);
            }
            LOG.debug("Discovered job manager at " + jobManagerAddress);
            break;
        }

    } catch (IOException ioe) {
        throw new DiscoveryException(ioe.toString());
    } finally {
        if (socket != null) {
            socket.close();
        }
    }

    if (jobManagerAddress == null) {
        LOG.debug("Unable to discover Jobmanager via IP broadcast");
        throw new DiscoveryException("Unable to discover JobManager via IP broadcast!");
    }

    return jobManagerAddress;
}