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:com.opensoc.json.serialization.JSONKafkaSerializer.java

@SuppressWarnings("unchecked")
public JSONObject fromBytes(byte[] input) {

    ByteArrayInputStream inputBuffer = new ByteArrayInputStream(input);
    DataInputStream data = new DataInputStream(inputBuffer);

    JSONObject output = new JSONObject();

    try {/*  ww w . j a  v  a2 s  . c om*/
        int mapSize = data.readInt();

        for (int i = 0; i < mapSize; i++) {
            String key = (String) getObject(data);
            // System.out.println("Key Found"+ key);
            Object val = getObject(data);
            output.put(key, val);
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    return output;
}

From source file:fr.insalyon.creatis.vip.query.server.rpc.FileDownload.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String queryId = req.getParameter("queryid");
    String path = req.getParameter("path");
    String queryName = req.getParameter("name");
    String tab[] = path.split("/");

    if (user != null && queryId != null && !queryId.isEmpty()) {

        try {//from  w ww  . ja  v  a 2  s  .  c o  m

            String k = new String();

            int l = tab.length;
            for (int i = 0; i < l - 1; i++) {
                k += "//" + tab[i];
            }
            File file = new File(k);
            logger.info("that" + k);
            if (file.isDirectory()) {

                file = new File(k + "/" + tab[l - 1]);

            }
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'.");

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            //name of the file in servlet download
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + queryName + "_"
                    + getCurrentTimeStamp().toString().replaceAll(" ", "_") + ".txt" + "\"");

            byte[] bbuf = new byte[4096];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();
        } catch (Exception ex) {
            logger.error(ex);
        }

    }
}

From source file:es.logongas.util.seguridad.CodigoVerificacionSeguro.java

public boolean isValido() {
    try {/*from  w w  w. j  a v a2s .  co  m*/
        Base32 base32 = new Base32();
        byte datos[] = base32.decode(valor);
        DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(datos));
        int key = dataInputStream.readInt();
        int numeroAleatorio = dataInputStream.readInt();
        int crcReal = dataInputStream.readInt();

        CRC crc = new CRC();
        crc.update(key).update(numeroAleatorio);

        if (crcReal == crc.getCRC()) {
            return true;
        } else {
            return false;
        }
    } catch (IOException ex) {
        return false;
    }
}

From source file:com.stefanbrenner.droplet.service.impl.ArduinoService.java

@Override
public synchronized boolean connect(final CommPortIdentifier portId, final IDropletContext context) {
    try {//ww w.j  a va  2  s  .  c  o m
        ArduinoService.dropletContext = context;

        ArduinoService.LOGGER.debug("Connect to port: " + portId.getName());

        // try to open a connection to the serial port
        ArduinoService.connSerialPort = (SerialPort) portId.open(this.getClass().getName(),
                ArduinoService.TIME_OUT);

        // set port parameters
        ArduinoService.connSerialPort.setSerialPortParams(ArduinoService.DATA_RATE, SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        // open the streams
        ArduinoService.input = new DataInputStream(ArduinoService.connSerialPort.getInputStream());
        ArduinoService.output = new DataOutputStream(ArduinoService.connSerialPort.getOutputStream());

        // add event listeners
        ArduinoService.connSerialPort.addEventListener(this);
        ArduinoService.connSerialPort.notifyOnDataAvailable(true);
        ArduinoService.connSerialPort.notifyOnCarrierDetect(true);

        // set connected flag
        setConnected(true);

        ArduinoService.LOGGER.info("Connection to port " + portId.getName() + " successful established");

        return true;

    } catch (PortInUseException e) {
        ArduinoService.LOGGER.error("Error connecting to port {}", portId.getName(), e);
    } catch (UnsupportedCommOperationException e) {
        ArduinoService.LOGGER.error("Error connecting to port {}", portId.getName(), e);
    } catch (IOException e) {
        ArduinoService.LOGGER.error("Error connecting to port {}", portId.getName(), e);
    } catch (TooManyListenersException e) {
        ArduinoService.LOGGER.error("Error connecting to port {}", portId.getName(), e);
    }

    setConnected(false);
    return false;
}

From source file:net.mybox.mybox.ClientStatus.java

private boolean getLastSync() {

    try {/*w  w w. jav  a  2s. co m*/
        FileInputStream fin = new FileInputStream(lastSyncFile);
        DataInputStream din = new DataInputStream(fin);
        lastSync = din.readLong();
        din.close();
    } catch (Exception e) {
        return false;
    }

    return true;
}

From source file:org.mobisocial.corral.CorralS3Connector.java

Uri downloadAndDecrypt(String ticket, String datestr, String objName, File cachefile, String mykey,
        CorralDownloadFuture future, DownloadProgressCallback callback)
        throws IOException, GeneralSecurityException {
    Log.d(TAG, "-----DOWNLOAD+DECRYPT START-----" + (String.valueOf(System.currentTimeMillis())));
    Log.d(TAG, SERVER_URL + objName);
    Log.d(TAG, "Authorization: AWS " + ticket);
    Log.d(TAG, "Date: " + datestr);

    HttpClient http = new DefaultHttpClient();
    HttpGet get = new HttpGet(SERVER_URL + objName);
    get.addHeader("Authorization", "AWS " + ticket);
    get.addHeader("Date", datestr);
    HttpResponse response = http.execute(get);

    DataInputStream is = new DataInputStream(response.getEntity().getContent());
    long contentLength = response.getEntity().getContentLength();

    if (!cachefile.exists()) {
        File tmpFile = new File(cachefile.getAbsoluteFile() + ".tmp");
        tmpFile.getParentFile().mkdirs();
        try {/*from www  . j av  a2 s.c  o  m*/
            CryptUtil cu = new CryptUtil(mykey);
            cu.InitCiphers();
            FileOutputStream fos = new FileOutputStream(tmpFile);
            cu.decrypt(is, fos, contentLength, callback);
            try {
                is.close();
            } catch (IOException e) {
            }
            try {
                fos.close();
            } catch (IOException e) {
            }

            tmpFile.renameTo(cachefile);

        } catch (IOException e) {
            if (tmpFile.exists()) {
                tmpFile.delete();
            }
            throw e;
        } catch (GeneralSecurityException e) {
            throw e;
        }
    }
    return cachefile.exists() ? Uri.fromFile(cachefile) : null;
}

From source file:org.nd4j.linalg.api.test.NDArrayTests.java

@Test
public void testReadWrite() throws Exception {
    Nd4j.dtype = DataBuffer.FLOAT;
    INDArray write = Nd4j.linspace(1, 4, 4);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    Nd4j.write(write, dos);/*from ww w  .ja  v a 2 s  .  c  om*/

    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    DataInputStream dis = new DataInputStream(bis);
    INDArray read = Nd4j.read(dis);
    assertEquals(write, read);

}

From source file:edu.cornell.med.icb.goby.compression.FastBufferedMessageChunksReader.java

private void reposition(final long start, final long end) throws IOException {
    assert end >= start : "end must be larger than start ";
    if (start == 0 && input.position() == 0) {

        return;/*from  w  w  w  .  j  a v a  2s . co  m*/
    }

    /*  if (start > input.length()) {
    withinSlice = false;
    return;
    }*/
    input.position(start);
    if (input.position() != start) {
        // must have happened because we are past the end of stream.
        withinSlice = false;
        return;
    }
    in = new DataInputStream(input);
    int contiguousDelimiterBytes = 0;
    long skipped = 0;
    long position = 0;

    withinSlice = true;
    boolean codecSeen = false;
    // search though the input stream until a delimiter chunk, end of stream, or end of slice is reached
    int b;
    while ((b = in.read()) != -1 && input.position() < end) {

        final byte c = (byte) b;
        //     System.out.printf("%2X(%d) ", c, contiguousDelimiterBytes);
        //    System.out.flush();
        if (!codecSeen && hasValidCodecCode(c)) {
            skipped++;
            contiguousDelimiterBytes++;
            codecSeen = true;
            continue;
        }
        if (codecSeen && c == MessageChunksWriter.DELIMITER_CONTENT) {
            contiguousDelimiterBytes++;

        } else {
            if (contiguousDelimiterBytes == MessageChunksWriter.DELIMITER_LENGTH + 1) {
                chunkCodec = ChunkCodecHelper.withRegistrationCode(lastCodecCodeSeen);
                // position exactly after the 7th 0xFF byte, past the first byte of the size:
                // the first byte of size was already read and is provided in c.
                long positionBeforeValidation = input.position();
                if (!chunkCodec.validate(c, in)) {
                    LOG.warn(String.format("Found spurious boundary around position %d ", input.position()));
                    contiguousDelimiterBytes = 0;
                    chunkCodec = null;
                    lastCodecCodeSeen = 0;
                    codecSeen = true;
                    continue;
                }

                final long newPosition = positionBeforeValidation - (MessageChunksWriter.DELIMITER_LENGTH + 2);
                input.position(newPosition);
                return;

            }
            if (skipped > MessageChunksWriter.DELIMITER_LENGTH + 1) {
                contiguousDelimiterBytes = 0;
                codecSeen = false;
            }

        }
        ++skipped;
    }
    if (b == -1 || input.position() >= end) {
        withinSlice = false;
    }
    position = start + skipped;
    streamPositionAtStart = input.position();

}

From source file:com.simiacryptus.mindseye.test.data.MNIST.java

private static Stream<byte[]> binaryStream(@Nonnull final String name, final int skip, final int recordSize)
        throws IOException {
    @Nullable//from   w w  w  . ja v  a 2s  .co m
    InputStream stream = null;
    try {
        stream = Util.cacheStream(TestUtil.S3_ROOT.resolve(name));
    } catch (@Nonnull NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
    final byte[] fileData = IOUtils
            .toByteArray(new BufferedInputStream(new GZIPInputStream(new BufferedInputStream(stream))));
    @Nonnull
    final DataInputStream in = new DataInputStream(new ByteArrayInputStream(fileData));
    in.skip(skip);
    return MNIST.toIterator(new BinaryChunkIterator(in, recordSize));
}

From source file:android.core.SSLSocketTest.java

/**
 * Does a number of HTTPS requests on some host and consumes the response.
 * We don't use the HttpsUrlConnection class, but do this on our own
 * with the SSLSocket class. This gives us a chance to test the basic
 * behavior of SSL./* w w w . j a  v  a 2s  .  co m*/
 *
 * @param host      The host name the request is being sent to.
 * @param port      The port the request is being sent to.
 * @param path      The path being requested (e.g. "/index.html").
 * @param outerLoop The number of times we reconnect and do the request.
 * @param innerLoop The number of times we do the request for each
 *                  connection (using HTTP keep-alive).
 * @param delay     The delay after each request (in seconds).
 * @throws IOException When a problem occurs.
 */
private void fetch(SSLSocketFactory socketFactory, String host, int port, boolean secure, String path,
        int outerLoop, int innerLoop, int delay, int timeout) throws IOException {
    InetSocketAddress address = new InetSocketAddress(host, port);

    for (int i = 0; i < outerLoop; i++) {
        // Connect to the remote host
        Socket socket = secure ? socketFactory.createSocket() : new Socket();
        if (timeout >= 0) {
            socket.setKeepAlive(true);
            socket.setSoTimeout(timeout * 1000);
        }
        socket.connect(address);

        // Get the streams
        OutputStream output = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(output);

        try {
            DataInputStream input = new DataInputStream(socket.getInputStream());
            try {
                for (int j = 0; j < innerLoop; j++) {
                    android.util.Log.d("SSLSocketTest", "GET https://" + host + path + " HTTP/1.1");

                    // Send a request
                    writer.println("GET https://" + host + path + " HTTP/1.1\r");
                    writer.println("Host: " + host + "\r");
                    writer.println("Connection: " + (j == innerLoop - 1 ? "Close" : "Keep-Alive") + "\r");
                    writer.println("\r");
                    writer.flush();

                    int length = -1;
                    boolean chunked = false;

                    String line = input.readLine();

                    if (line == null) {
                        throw new IOException("No response from server");
                        // android.util.Log.d("SSLSocketTest", "No response from server");
                    }

                    // Consume the headers, check content length and encoding type
                    while (line != null && line.length() != 0) {
                        //                    System.out.println(line);
                        int dot = line.indexOf(':');
                        if (dot != -1) {
                            String key = line.substring(0, dot).trim();
                            String value = line.substring(dot + 1).trim();

                            if ("Content-Length".equalsIgnoreCase(key)) {
                                length = Integer.valueOf(value);
                            } else if ("Transfer-Encoding".equalsIgnoreCase(key)) {
                                chunked = "Chunked".equalsIgnoreCase(value);
                            }

                        }
                        line = input.readLine();
                    }

                    assertTrue("Need either content length or chunked encoding", length != -1 || chunked);

                    // Consume the content itself
                    if (chunked) {
                        length = Integer.parseInt(input.readLine(), 16);
                        while (length != 0) {
                            byte[] buffer = new byte[length];
                            input.readFully(buffer);
                            input.readLine();
                            length = Integer.parseInt(input.readLine(), 16);
                        }
                        input.readLine();
                    } else {
                        byte[] buffer = new byte[length];
                        input.readFully(buffer);
                    }

                    // Sleep for the given number of seconds
                    try {
                        Thread.sleep(delay * 1000);
                    } catch (InterruptedException ex) {
                        // Shut up!
                    }
                }
            } finally {
                input.close();
            }
        } finally {
            writer.close();
        }
        // Close the connection
        socket.close();
    }
}