Example usage for java.io DataInputStream read

List of usage examples for java.io DataInputStream read

Introduction

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

Prototype

public final int read(byte b[]) throws IOException 

Source Link

Document

Reads some number of bytes from the contained input stream and stores them into the buffer array b.

Usage

From source file:com.packetsender.android.PacketListenerService.java

@Override
protected void onHandleIntent(Intent intent) {

    dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0));

    listenportTCP = dataStore.getTCPPort();
    listenportUDP = dataStore.getUDPPort();
    Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP));

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startNotification();//w  w w. j  a v  a 2s . com

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ByteBuffer response = null;
    try {
        response = encoder.encode(CharBuffer.wrap("response"));
    } catch (CharacterCodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {

        SocketAddress localportTCP = new InetSocketAddress(listenportTCP);
        SocketAddress localportUDP = new InetSocketAddress(listenportUDP);

        tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localportTCP);

        udpserver = DatagramChannel.open();
        udpserver.socket().bind(localportUDP);

        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        receiveBuffer.clear();

        shutdownListener = new Runnable() {
            public void run() {

                if (false) {

                    try {
                        tcpserver.close();
                    } catch (IOException e) {
                    }
                    try {
                        udpserver.close();
                    } catch (IOException e) {
                    }
                    stopSelf();
                } else {
                    mHandler.postDelayed(shutdownListener, 2000);

                }

            }
        };

        sendListener = new Runnable() {
            public void run() {

                //Packet fetchedPacket = mDbHelper.needSendPacket();
                Packet[] fetchedPackets = dataStore.fetchAllServicePackets();

                if (fetchedPackets.length > 0) {
                    dataStore.clearServicePackets();
                    Log.d("service",
                            DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets"));

                    for (int i = 0; i < fetchedPackets.length; i++) {
                        Packet fetchedPacket = fetchedPackets[i];
                        Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));

                    }

                    new SendPacketsTask().execute(fetchedPackets);
                }

                mHandler.postDelayed(sendListener, 2000);

            }
        };

        //start shutdown listener
        mHandler.postDelayed(shutdownListener, 2000);

        //start send listener
        mHandler.postDelayed(sendListener, 5000);

        while (true) {
            try { // Handle per-connection problems below
                  // Wait for a client to connect
                Log.d("service", DataStorage.FILE_LINE("waiting for connection"));
                selector.select();
                Log.d("service", DataStorage.FILE_LINE("client connection"));

                Set keys = selector.selectedKeys();

                for (Iterator i = keys.iterator(); i.hasNext();) {

                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    Channel c = (Channel) key.channel();

                    if (key.isAcceptable() && c == tcpserver) {

                        SocketChannel client = tcpserver.accept();

                        if (client != null) {

                            Socket tcpSocket = client.socket();
                            packetCounter++;

                            DataInputStream in = new DataInputStream(tcpSocket.getInputStream());

                            byte[] buffer = new byte[1024];
                            int received = in.read(buffer);
                            byte[] bufferConvert = new byte[received];
                            System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "TCP";
                            storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = tcpSocket.getPort();
                            storepacket.port = tcpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            Log.i("service", DataStorage.FILE_LINE("Got TCP"));
                            //dataStore.SavePacket(storepacket);

                            /*
                            Intent tcpIntent = new Intent();
                            tcpIntent.setAction(ResponseReceiver.ACTION_RESP);
                            tcpIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name);
                            sendBroadcast(tcpIntent);
                            */

                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "TCP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = tcpSocket.getInetAddress().getHostAddress();
                                storepacket.fromPort = tcpSocket.getLocalPort();
                                storepacket.port = tcpSocket.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                                client.write(response); // send response
                            }

                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {

                        DatagramSocket udpSocket;
                        DatagramPacket udpPacket;

                        byte[] buffer = new byte[2048];
                        // Create a packet to receive data into the buffer
                        udpPacket = new DatagramPacket(buffer, buffer.length);

                        udpSocket = udpserver.socket();

                        receiveBuffer.clear();

                        InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer);

                        if (clientAddress != null) {

                            String fromAddress = clientAddress.getAddress().getHostAddress();

                            packetCounter++;

                            int received = receiveBuffer.position();
                            byte[] bufferConvert = new byte[received];

                            System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "UDP";
                            storepacket.fromIP = clientAddress.getAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = clientAddress.getPort();
                            storepacket.port = udpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            //dataStore.SavePacket(storepacket);
                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "UDP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = clientAddress.getAddress().getHostAddress();
                                storepacket.fromPort = udpSocket.getLocalPort();
                                storepacket.port = clientAddress.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                //dataStore.SavePacket(storepacket);
                                udpserver.send(response, clientAddress);
                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                Log.i("service", DataStorage.FILE_LINE("IOException "));
            } catch (Exception e) {
                Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e)));
            }
        }
    } catch (BindException e) {

        //mDbHelper.putServiceError("Error binding to port");
        dataStore.putToast("Port already in use.");
        Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e)));

    } catch (Exception e) {
        //mDbHelper.putServiceError("Fatal Error starting service");
        Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e)));
    }

    stopNotification();

}

From source file:org.apache.accumulo.core.client.mock.MockTableOperations.java

@Override
public void importDirectory(String tableName, String dir, String failureDir, boolean setTime)
        throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException {
    long time = System.currentTimeMillis();
    MockTable table = acu.tables.get(tableName);
    if (table == null) {
        throw new TableNotFoundException(null, tableName, "The table was not found");
    }//from  ww w.  j a  v  a  2s .c o m
    Path importPath = new Path(dir);
    Path failurePath = new Path(failureDir);

    FileSystem fs = acu.getFileSystem();
    /*
     * check preconditions
     */
    // directories are directories
    if (fs.isFile(importPath)) {
        throw new IOException("Import path must be a directory.");
    }
    if (fs.isFile(failurePath)) {
        throw new IOException("Failure path must be a directory.");
    }
    // failures are writable
    Path createPath = failurePath.suffix("/.createFile");
    FSDataOutputStream createStream = null;
    try {
        createStream = fs.create(createPath);
    } catch (IOException e) {
        throw new IOException("Error path is not writable.");
    } finally {
        if (createStream != null) {
            createStream.close();
        }
    }
    fs.delete(createPath, false);
    // failures are empty
    FileStatus[] failureChildStats = fs.listStatus(failurePath);
    if (failureChildStats.length > 0) {
        throw new IOException("Error path must be empty.");
    }
    /*
     * Begin the import - iterate the files in the path
     */
    for (FileStatus importStatus : fs.listStatus(importPath)) {
        try {
            FileSKVIterator importIterator = FileOperations.getInstance().newReaderBuilder()
                    .forFile(importStatus.getPath().toString(), fs, fs.getConf())
                    .withTableConfiguration(AccumuloConfiguration.getDefaultConfiguration()).seekToBeginning()
                    .build();
            while (importIterator.hasTop()) {
                Key key = importIterator.getTopKey();
                Value value = importIterator.getTopValue();
                if (setTime) {
                    key.setTimestamp(time);
                }
                Mutation mutation = new Mutation(key.getRow());
                if (!key.isDeleted()) {
                    mutation.put(key.getColumnFamily(), key.getColumnQualifier(),
                            new ColumnVisibility(key.getColumnVisibilityData().toArray()), key.getTimestamp(),
                            value);
                } else {
                    mutation.putDelete(key.getColumnFamily(), key.getColumnQualifier(),
                            new ColumnVisibility(key.getColumnVisibilityData().toArray()), key.getTimestamp());
                }
                table.addMutation(mutation);
                importIterator.next();
            }
        } catch (Exception e) {
            FSDataOutputStream failureWriter = null;
            DataInputStream failureReader = null;
            try {
                failureWriter = fs.create(failurePath.suffix("/" + importStatus.getPath().getName()));
                failureReader = fs.open(importStatus.getPath());
                int read = 0;
                byte[] buffer = new byte[1024];
                while (-1 != (read = failureReader.read(buffer))) {
                    failureWriter.write(buffer, 0, read);
                }
            } finally {
                if (failureReader != null)
                    failureReader.close();
                if (failureWriter != null)
                    failureWriter.close();
            }
        }
        fs.delete(importStatus.getPath(), true);
    }
}

From source file:org.cloudata.core.commitlog.CommitLogClient.java

public void open() throws UnmatchedLogException, CommitLogInterruptedException, IOException {
    pipeKey = generateUniqueKey();/*from   w w w .j ava  2s  .  co  m*/

    if (LOG.isDebugEnabled()) {
        String msg = "";
        for (String addr : ipAddressList) {
            msg = msg + addr + ", ";
        }
        LOG.debug("Open new pipe with timeout[" + this.timeout + "], key [" + pipeKey + "], -> " + msg);
    }

    String ret = null;
    Socket s = null;
    try {
        sc = SocketChannel.open();

        s = sc.socket();
        s.setTcpNoDelay(true);
        s.setSoTimeout(timeout);

        int addressIndex = 0;
        if (verifiedAddressIndex >= 0) {
            addressIndex = verifiedAddressIndex;
        }
        LOG.debug("open pipe to " + pipeAddressList[addressIndex]);
        sc.connect(pipeAddressList[addressIndex]);
    } catch (ClosedByInterruptException e) {
        internalClose();
        throw new CommitLogInterruptedException();
    } catch (IOException e) {
        throw new CommitLogShutDownException(e);
    }

    try {
        byte[] body = buildBody();

        currentStream = new DataOutputStream(new BufferedOutputStream(s.getOutputStream(), 8192));
        checkInputStream = new DataInputStream(s.getInputStream());
        currentStream.write(MAGIC_KEY);
        currentStream.writeInt(0);
        currentStream.writeInt(body.length);
        currentStream.write(body);
        currentStream.flush();

        DataInputStream dis = new DataInputStream(s.getInputStream());
        byte[] key = new byte[MAGIC_KEY.length];

        if (dis.read(key) < 0) {
            throw new IOException("Fail to establish pipe connection to " + getPipeAddressListStr());
        }

        if (!Arrays.equals(MAGIC_KEY, key)) {
            throw new IOException(
                    "Fail to establish pipe connection to " + getPipeAddressList() + "due to wrong magic key");
        }
        int opCode = dis.readInt();
        int replyLength = dis.readInt();

        body = new byte[replyLength];
        dis.read(body);
        ret = new String(body);
    } catch (ClosedByInterruptException e) {
        internalClose();
        throw new CommitLogInterruptedException();
    } catch (IOException e) {
        LOG.warn("Fail to establish pipe to " + getPipeAddressListStr() + " due to " + e, e);
        internalClose();
        throw new IOException("Fail to establish pipe connection to " + getPipeAddressListStr(), e);
    }

    if (!ret.equals(Constants.PIPE_CONNECTED)) {
        internalClose();

        if (ret.equals("Log files are unmatched among commit log servers")) {
            throw new UnmatchedLogException("Log files are unmatched among commit log servers");
        }

        throw new IOException(
                "Fail to establish pipe connection to " + getPipeAddressListStr() + ". response : " + ret);
    } else {
        closed = false;
    }
}

From source file:org.apache.tajo.ws.rs.resources.TestQueryResultResource.java

@Test
public void testGetQueryResultSet() throws Exception {
    String sessionId = generateNewSessionAndGetId();
    URI queryIdURI = sendNewQueryResquest(sessionId, "select * from lineitem");
    URI queryResultURI = new URI(queryIdURI + "/result");

    GetQueryResultDataResponse response = restClient.target(queryResultURI).request()
            .header(tajoSessionIdHeaderName, sessionId)
            .get(new GenericType<GetQueryResultDataResponse>(GetQueryResultDataResponse.class));

    assertNotNull(response);/*from  w  w w .  j a va 2s  .co  m*/
    assertNotNull(response.getResultCode());
    assertTrue(ErrorUtil.isOk(response.getResultCode()));
    assertNotNull(response.getSchema());
    assertEquals(16, response.getSchema().getRootColumns().size());
    assertNotNull(response.getResultset());
    assertTrue(response.getResultset().getId() != 0);
    assertNotNull(response.getResultset().getLink());

    URI queryResultSetURI = response.getResultset().getLink();

    Response queryResultSetResponse = restClient.target(queryResultSetURI).queryParam("count", 100).request()
            .header(tajoSessionIdHeaderName, sessionId).get();

    assertNotNull(queryResultSetResponse);
    String tajoDigest = queryResultSetResponse.getHeaderString(tajoDigestHeaderName);
    assertTrue(tajoDigest != null && !tajoDigest.isEmpty());

    DataInputStream queryResultSetInputStream = new DataInputStream(
            new BufferedInputStream(queryResultSetResponse.readEntity(InputStream.class)));

    assertNotNull(queryResultSetInputStream);

    boolean isFinished = false;
    List<Tuple> tupleList = TUtil.newList();
    RowStoreUtil.RowStoreDecoder decoder = RowStoreUtil.createDecoder(response.getSchema());
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
    while (!isFinished) {
        try {
            int length = queryResultSetInputStream.readInt();
            byte[] dataByteArray = new byte[length];
            int readBytes = queryResultSetInputStream.read(dataByteArray);

            assertEquals(length, readBytes);

            tupleList.add(decoder.toTuple(dataByteArray));
            messageDigest.update(dataByteArray);
        } catch (EOFException eof) {
            isFinished = true;
        }
    }

    assertEquals(5, tupleList.size());
    assertEquals(tajoDigest, Base64.encodeBase64String(messageDigest.digest()));

    for (Tuple aTuple : tupleList) {
        assertTrue(aTuple.getInt4(response.getSchema().getColumnId("l_orderkey")) > 0);
    }
}

From source file:org.apache.tajo.ws.rs.resources.TestQueryResultResource.java

@Test
public void testGetQueryResultSetWithDefaultCount() throws Exception {
    String sessionId = generateNewSessionAndGetId();
    URI queryIdURI = sendNewQueryResquest(sessionId, "select * from lineitem");
    URI queryResultURI = new URI(queryIdURI + "/result");

    GetQueryResultDataResponse response = restClient.target(queryResultURI).request()
            .header(tajoSessionIdHeaderName, sessionId)
            .get(new GenericType<GetQueryResultDataResponse>(GetQueryResultDataResponse.class));

    assertNotNull(response);/*  w w w .  j  a v a  2s .c om*/
    assertNotNull(response.getResultCode());
    assertTrue(isOk(response.getResultCode()));
    assertNotNull(response.getSchema());
    assertEquals(16, response.getSchema().getRootColumns().size());
    assertNotNull(response.getResultset());
    assertTrue(response.getResultset().getId() != 0);
    assertNotNull(response.getResultset().getLink());

    URI queryResultSetURI = response.getResultset().getLink();

    Response queryResultSetResponse = restClient.target(queryResultSetURI).request()
            .header(tajoSessionIdHeaderName, sessionId).get();

    assertNotNull(queryResultSetResponse);
    String tajoDigest = queryResultSetResponse.getHeaderString(tajoDigestHeaderName);
    int offset = Integer.valueOf(queryResultSetResponse.getHeaderString(tajoOffsetHeaderName));
    int count = Integer.valueOf(queryResultSetResponse.getHeaderString(tajoCountHeaderName));
    boolean eos = Boolean.valueOf(queryResultSetResponse.getHeaderString(tajoEOSHeaderName));

    assertTrue(tajoDigest != null && !tajoDigest.isEmpty());
    assertTrue(eos);
    assertEquals(0, offset);
    assertEquals(5, count);

    DataInputStream queryResultSetInputStream = new DataInputStream(
            new BufferedInputStream(queryResultSetResponse.readEntity(InputStream.class)));

    assertNotNull(queryResultSetInputStream);

    boolean isFinished = false;
    List<Tuple> tupleList = TUtil.newList();
    RowStoreUtil.RowStoreDecoder decoder = RowStoreUtil.createDecoder(response.getSchema());
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
    while (!isFinished) {
        try {
            int length = queryResultSetInputStream.readInt();
            byte[] dataByteArray = new byte[length];
            int readBytes = queryResultSetInputStream.read(dataByteArray);

            assertEquals(length, readBytes);

            tupleList.add(decoder.toTuple(dataByteArray));
            messageDigest.update(dataByteArray);
        } catch (EOFException eof) {
            isFinished = true;
        }
    }

    assertEquals(5, tupleList.size());
    assertEquals(tajoDigest, Base64.encodeBase64String(messageDigest.digest()));

    for (Tuple aTuple : tupleList) {
        assertTrue(aTuple.getInt4(response.getSchema().getColumnId("l_orderkey")) > 0);
    }
}

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void loadData(File f, boolean clearData) throws IOException {
    BufferedInputStream inReader = new BufferedInputStream(new FileInputStream(f), 1000000);// RandomAccessFile in = new
    // RandomAccessFile(f, "r");
    DataInputStream in = new DataInputStream(inReader);
    int tot = in.readInt();
    wide = in.readInt();/*from   www .  j a va  2s  . c  om*/
    high = in.readInt();

    short[][][] holder = new short[tot][wide][high];

    byte[] inputHolder = new byte[high * 2];
    for (int i = 0; i < tot; i++) {
        Date d = new Date(in.readLong());
        for (int x = 0; x < wide; x++) {
            in.read(inputHolder);
            for (int y = 0; y < high; y++) {
                holder[i][wide - 1 - x][high - y - 1] = BinaryToolkit.readShort(inputHolder, y * 2);
            }
            // for (int y = 0; y < high; y++)
            // {
            // holder[i][x][y] = in.readShort();
            // }
        }
        addData(d, holder[i]);
    }
    ((SpinnerNumberModel) currentValue.getModel()).setMaximum(imageData.size() - 1);
    in.close();
    setCurrentImage(0);
    image.updateMaxMin();
}

From source file:org.wso2.iot.agent.services.FileDownloadService.java

/**
 * This method is used to download the file using HTTP client.
 *
 * @param operation      - Operation object.
 * @param url            - file url to download file.
 * @param savingLocation - location to save file in device.
 * @throws AndroidAgentException - Android agent exception.
 *///from  www .  j  a  va  2s  . c  o m
private void downloadFileUsingHTTPClient(Operation operation, String url, String userName, String password,
        String savingLocation) throws AndroidAgentException {
    checkHTTPAuthentication(userName, password);
    InputStream inputStream = null;
    DataInputStream dataInputStream = null;
    FileOutputStream fileOutputStream = null;
    String fileName = "Unknown";
    try {
        fileName = url.substring(url.lastIndexOf('/') + 1);
        URL link = new URL(url);
        inputStream = link.openStream();
        dataInputStream = new DataInputStream(inputStream);
        byte[] buffer = new byte[1024];
        int length;
        fileOutputStream = new FileOutputStream(new File(savingLocation + File.separator + fileName));
        while ((length = dataInputStream.read(buffer)) > 0) {
            fileOutputStream.write(buffer, 0, length);
        }
        operation.setStatus(resources.getString(R.string.operation_value_completed));
        operation.setOperationResponse("File uploaded to the device successfully ( " + fileName + " ).");
    } catch (IOException e) {
        handleOperationError(operation, fileTransferExceptionCause(e, fileName), e);
    } finally {
        cleanupStreams(inputStream, null, null, fileOutputStream, null, null, dataInputStream, null);
    }
}

From source file:com.linkedin.pinot.common.utils.DataTable.java

private Map<String, String> deserializeMetadata(byte[] buffer) {
    Map<String, String> map = new HashMap<String, String>();
    try {/*from ww w.  ja  va  2s  . c  o  m*/
        final ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
        final DataInputStream in = new DataInputStream(bais);
        int size = in.readInt();
        for (int i = 0; i < size; i++) {
            Integer keyLength = in.readInt();
            byte[] keyBytes = new byte[keyLength];
            in.read(keyBytes);
            int valueLength = in.readInt();
            byte[] valueBytes = new byte[valueLength];
            in.read(valueBytes);
            map.put(new String(keyBytes, UTF8), new String(valueBytes, UTF8));
        }
    } catch (Exception e) {
        LOGGER.error("Exception while deserializing dictionary", e);
    }
    return map;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.harvester.FileHarvestController.java

private void doDownloadTemplatePost(HttpServletRequest request, HttpServletResponse response) {

    VitroRequest vreq = new VitroRequest(request);
    FileHarvestJob job = getJob(vreq, vreq.getParameter(PARAMETER_JOB));
    File fileToSend = new File(job.getTemplateFilePath());

    response.setContentType("application/octet-stream");
    response.setContentLength((int) (fileToSend.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileToSend.getName() + "\"");

    try {//from  w  w w. j a  v a2 s  .  c  o m
        byte[] byteBuffer = new byte[(int) (fileToSend.length())];
        DataInputStream inStream = new DataInputStream(new FileInputStream(fileToSend));

        ServletOutputStream outputStream = response.getOutputStream();
        for (int length = inStream.read(byteBuffer); length != -1; length = inStream.read(byteBuffer)) {
            outputStream.write(byteBuffer, 0, length);
        }

        inStream.close();
        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        log.error(e, e);
    }
}

From source file:com.linkedin.pinot.common.utils.DataTable.java

private Map<String, Map<Integer, String>> deserializeDictionary(byte[] buffer) {
    Map<String, Map<Integer, String>> map = new HashMap<String, Map<Integer, String>>();
    try {// ww w  . j a  va  2s .c o  m
        final ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
        final DataInputStream in = new DataInputStream(bais);
        int size = in.readInt();
        byte[] temp;
        for (int i = 0; i < size; i++) {
            int readLength = in.readInt();
            temp = new byte[readLength];
            in.read(temp);
            Map<Integer, String> childMap = new HashMap<Integer, String>();
            map.put(new String(temp, UTF8), childMap);
            int childMapSize = in.readInt();
            for (int j = 0; j < childMapSize; j++) {
                Integer key = in.readInt();
                int valueLength = in.readInt();
                temp = new byte[valueLength];
                in.read(temp);
                childMap.put(key, new String(temp, UTF8));
            }
        }
    } catch (Exception e) {
        LOGGER.error("Exception while deserializing dictionary", e);
    }
    return map;
}