Example usage for java.io DataInputStream DataInputStream

List of usage examples for java.io DataInputStream DataInputStream

Introduction

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

Prototype

public DataInputStream(InputStream in) 

Source Link

Document

Creates a DataInputStream that uses the specified underlying InputStream.

Usage

From source file:jdroidremote.ServerFrame.java

public void initEventDriven() {
    jbtRunServer.addActionListener(new ActionListener() {
        @Override//from ww  w  .j  a v a  2  s.  c o m
        public void actionPerformed(ActionEvent e) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        serverSocket = new ServerSocket(5005);
                        System.out.println("Server is running...");
                        clientSocket = serverSocket.accept();
                        dis = new DataInputStream(clientSocket.getInputStream());
                        dos = new DataOutputStream(clientSocket.getOutputStream());
                        System.out.println(
                                "some device connected us from address: " + clientSocket.getInetAddress());

                        thReceiveMouseCoords.start();
                        thStartMonitoring.start();

                    } catch (IOException ex) {
                        Logger.getLogger(ServerFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }).start();

            thReceiveMouseCoords = new Thread(new Runnable() {
                @Override
                public void run() {

                    System.out.println("START RECEIVING COORDS.............");

                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    double width = screenSize.getWidth();
                    double height = screenSize.getHeight();

                    while (1 == 1) {
                        try {
                            String receivedStr = dis.readUTF();

                            if (receivedStr.contains("left_click")) {
                                robot.mousePress(KeyEvent.BUTTON1_DOWN_MASK);
                                robot.mouseRelease(KeyEvent.BUTTON1_DOWN_MASK);
                            } else if (receivedStr.contains("right_click")) {
                                robot.mousePress(KeyEvent.BUTTON3_DOWN_MASK);
                                robot.mouseRelease(KeyEvent.BUTTON3_DOWN_MASK);
                            } else if (receivedStr.contains("coords")) {
                                System.out.println(receivedStr);
                                String[] mouseCoords = receivedStr.split(":");

                                int x = (int) (Integer.parseInt(mouseCoords[0]) * width / 100);
                                int y = (int) (Integer.parseInt(mouseCoords[1]) * height / 100);

                                robot.mouseMove(x, y);
                            } else {
                                String[] dataArr = receivedStr.split("-");

                                typeCharacter(dataArr[1]);
                            }
                        } catch (IOException ex) {
                            Logger.getLogger(ServerFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            });
        }
    });
}

From source file:com.aliyun.openservices.tablestore.hadoop.MultiCriteria.java

public static MultiCriteria deserialize(String in) {
    byte[] buf = Base64.decodeBase64(in);
    ByteArrayInputStream is = new ByteArrayInputStream(buf);
    DataInputStream din = new DataInputStream(is);
    try {//from w  w w .  j  av a  2 s. c  o  m
        return read(din);
    } catch (IOException ex) {
        return null;
    }
}

From source file:net.jradius.webservice.WebServiceListener.java

public JRadiusEvent parseRequest(ListenerRequest listenerRequest, ByteBuffer byteBuffer,
        InputStream inputStream) throws IOException, WebServiceException {
    DataInputStream reader = new DataInputStream(inputStream);
    WebServiceRequest request = new WebServiceRequest();

    String line = null;//from  www  .  java  2s  .com

    try {
        line = reader.readLine();
    } catch (SocketException e) {
        return null;
    }

    if (line == null)
        throw new WebServiceException("Invalid relay request");

    StringTokenizer tokens = new StringTokenizer(line);
    String method = tokens.nextToken();
    String uri = tokens.nextToken();
    String httpVersion = tokens.nextToken();

    if ("GET".equals(method))
        request.setMethod(WebServiceRequest.GET);
    else if ("POST".equals(method))
        request.setMethod(WebServiceRequest.POST);
    else if ("PUT".equals(method))
        request.setMethod(WebServiceRequest.PUT);
    else
        throw new WebServiceException("Does not handle HTTP request method: " + method);

    request.setHttpVersion(httpVersion);

    try {
        request.setUri(new URI(uri));
    } catch (URISyntaxException e) {
        throw new WebServiceException(e.getMessage());
    }

    Map<String, String> headers = getHeaders(reader);
    request.setHeaderMap(headers);

    String clen = headers.get("content-length");
    if (clen != null) {
        request.setContent(getContent(reader, Integer.parseInt(clen)));
    }

    return request;
}

From source file:edu.cornell.med.icb.goby.alignments.perms.PermutationReader.java

public PermutationReader(String basename) throws IOException {
    this.basename = AlignmentReaderImpl.getBasename(basename);
    FastBufferedInputStream inputStream = null;
    final String filename = basename + ".perm";

    try {/*  www  .  j  a va 2  s.  c  o  m*/

        inputStream = new FastBufferedInputStream(new FileInputStream(filename));
        dataInput = new DataInputStream(inputStream);
        input = inputStream;
        makeIndex(inputStream);
    } catch (FileNotFoundException e) {
        final String error = String.format(
                "A permutation file called %s could not be found, but is required to reconstruct original query indices to complete this task.",
                filename);
        LOG.error(error, e);
        inputStream = null;
        assert inputStream != null : error;
    }

}

From source file:dmsl.smartbill.GoogleShoppingAPIHelperClass.java

/**
 * Sends an HTTP request to Google API for Shopping and retrieves a JSON
 * String of a product, based on the barcode number given in the search
 * criteria./* w w  w. j ava  2 s . c o  m*/
 * 
 * @param barcodeContents
 *            The product's barcode which we use to find that product.
 * @return The JSON String that holds information about the product.
 */
private String getJsonStringFromGoogleShopping(String barcodeContents) {
    URL u;
    InputStream is = null;
    DataInputStream dis = null;
    String s;
    StringBuilder sb = new StringBuilder();
    String jsonString = null;
    try {
        u = new URL("https://www.googleapis.com/shopping/search/v1/public/products?key=" + SHOPPING_API_KEY
                + "&country=US&restrictBy=gtin:" + barcodeContents + "&startIndex=1&maxResults=1");
        is = u.openStream();
        dis = new DataInputStream(new BufferedInputStream(is));
        while ((s = dis.readLine()) != null) {
            sb = sb.append(s + "\n");
        }
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    jsonString = sb.toString();
    return jsonString;
}

From source file:net.pms.util.OpenSubtitle.java

public static String computeHash(InputStream stream, long length) throws IOException {
    int chunkSizeForFile = (int) Math.min(HASH_CHUNK_SIZE, length);

    // Buffer that will contain the head and the tail chunk, chunks will overlap if length is smaller than two chunks
    byte[] chunkBytes = new byte[(int) Math.min(2 * HASH_CHUNK_SIZE, length)];
    long head;/*from  w w w .  ja  va2 s. c  o m*/
    long tail;
    try (DataInputStream in = new DataInputStream(stream)) {
        // First chunk
        in.readFully(chunkBytes, 0, chunkSizeForFile);

        long position = chunkSizeForFile;
        long tailChunkPosition = length - chunkSizeForFile;

        // Seek to position of the tail chunk, or not at all if length is smaller than two chunks
        while (position < tailChunkPosition && (position += in.skip(tailChunkPosition - position)) >= 0)
            ;

        // Second chunk, or the rest of the data if length is smaller than two chunks
        in.readFully(chunkBytes, chunkSizeForFile, chunkBytes.length - chunkSizeForFile);

        head = computeHashForChunk(ByteBuffer.wrap(chunkBytes, 0, chunkSizeForFile));
        tail = computeHashForChunk(
                ByteBuffer.wrap(chunkBytes, chunkBytes.length - chunkSizeForFile, chunkSizeForFile));
    }
    return String.format("%016x", length + head + tail);
}

From source file:edu.indiana.d2i.htrc.io.index.lucene.LuceneIDFormat.java

@Override
public List<InputSplit> getSplits(JobContext job) throws IOException {
    int numIdsInSplit = job.getConfiguration().getInt(HTRCConstants.MAX_IDNUM_SPLIT, (int) 1e6);

    String line = null;// w  w  w  .  j  av  a2 s . co  m
    IDInputSplit split = new IDInputSplit();
    List<InputSplit> splits = new ArrayList<InputSplit>();
    Path[] dirs = getInputPaths(job);

    try {
        for (int i = 0; i < dirs.length; i++) {
            FileSystem fs = dirs[i].getFileSystem(job.getConfiguration());
            DataInputStream fsinput = new DataInputStream(fs.open(dirs[i]));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fsinput));
            while ((line = reader.readLine()) != null) {
                split.addID(line);
                if (split.getLength() >= numIdsInSplit) {
                    splits.add(split);
                    split = new IDInputSplit();
                }
            }
            reader.close();
        }
        if (split != null && split.getLength() != 0)
            splits.add(split);
    } catch (InterruptedException e) {
        logger.error(e);
    }

    logger.info("#Splits " + splits.size());
    return splits;
}

From source file:com.intuit.tank.harness.functions.CSVReader.java

private void readCSV(String fileName) {

    DataInputStream in = null;/*from w  ww  . j  a  va 2 s . c  o m*/
    try {
        lines = new ArrayList<String[]>();
        // Open the file that is the first
        // command line parameter
        String datafileDir = "src/test/resources";
        try {
            datafileDir = APITestHarness.getInstance().getTankConfig().getAgentConfig()
                    .getAgentDataFileStorageDir();
        } catch (Exception e) {
            logger.warn("Cannot read config. Using datafileDir of " + datafileDir);
        }
        File csvFile = new File(datafileDir, fileName);
        logger.debug(LogUtil.getLogMessage("READING CSV FILE: " + csvFile.getAbsolutePath()));
        FileInputStream fstream = new FileInputStream(csvFile);
        // Get the object of DataInputStream
        in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        String strLine;
        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            lines.add(strLine.split(","));
        }
        logger.debug(LogUtil
                .getLogMessage("CSV file " + csvFile.getAbsolutePath() + " has " + lines.size() + " lines."));

    } catch (Exception e) {// Catch exception if any
        logger.error(LogUtil.getLogMessage("Error reading CSV file: " + e.toString()), e);
    } finally {
        // Close the input stream
        IOUtils.closeQuietly(in);
    }

}

From source file:com.knewton.mapreduce.io.StudentEventWritableTest.java

@Test
public void testSerialization() throws DecoderException, TException, IOException {
    byte[] studentEventDataBytes = Hex.decodeHex(eventDataString.toCharArray());
    StudentEventData studentEventData = new StudentEventData();
    deserializer.deserialize(studentEventData, studentEventDataBytes);
    StudentEvent studentEvent = new StudentEvent(1, studentEventData);
    StudentEventWritable sew = new StudentEventWritable(studentEvent, 10L);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(byteArrayOutputStream);
    sew.write(dout);/*  w ww  .  j a va 2 s .c  o m*/

    StudentEventWritable deserializedWritable = new StudentEventWritable();
    InputStream is = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    DataInputStream dis = new DataInputStream(is);
    deserializedWritable.readFields(dis);
    assertEquals(sew.getStudentEvent(), deserializedWritable.getStudentEvent());
    assertEquals(sew.getTimestamp(), deserializedWritable.getTimestamp());
}

From source file:com.karpenstein.signalmon.NetConnHandler.java

@Override
public void run() {

    server.addListener(this);

    String line;/*from ww w . j a v  a 2 s  .com*/
    try {
        Log.d("NetConnHandler", "about to create input and output streams");
        // Get input from the client
        DataInputStream in = new DataInputStream(sock.getInputStream());
        PrintStream out = new PrintStream(sock.getOutputStream());

        Log.d("NetConnHandler", "about to start looping");
        while ((line = in.readLine()) != null && line.equals("G")) {
            if (stateChanged) {
                stateChanged = false;
                out.println(state.toString());
            } else
                out.println(nullObj);
        }

        sock.close();
    } catch (IOException ioe) {
        Log.e("SignalMonitor.NetConnHandler", "IOException on socket r/w: " + ioe, ioe);
    }

}