Example usage for java.io DataInputStream readUTF

List of usage examples for java.io DataInputStream readUTF

Introduction

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

Prototype

public final String readUTF() throws IOException 

Source Link

Document

See the general contract of the readUTF method of DataInput.

Usage

From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java

@Override
public SecureToken decryptData(final String token) {
    if (token == null || StringUtils.isBlank(token)) {
        throw new IllegalArgumentException("missing token");
    }/*from  w ww . j  a va  2s .  c  o  m*/
    try {
        final byte[] decryptedBytes = decrypt(token, encryptionKeyBytes);

        // Last 16 bytes are the MD5 signature
        final int decryptedBytesDataLength = decryptedBytes.length - MD5_LENGTH;
        if (!validateSignature(decryptedBytes, 0, decryptedBytesDataLength, decryptedBytes,
                decryptedBytesDataLength, signatureKeyBytes)) {
            throw new IllegalArgumentException("Invalid signature in cookie");
        }
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decryptedBytes, 0,
                decryptedBytesDataLength);
        final DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);

        skipPadding(dataInputStream);

        final String userIdentifier = dataInputStream.readUTF();
        final String userChecksum = dataInputStream.readUTF();
        if (userChecksum == null || !userChecksum.equals(createChecksum(userIdentifier))) {
            throw new IllegalArgumentException("invalid token");
        }
        final long timeStampInSeconds = dataInputStream.readLong();

        return new SecureToken(userIdentifier, timeStampInSeconds);
    } catch (final IOException e) {
        LOG.error("Could not decrypt token", e);
        throw new SystemException(e.toString(), e);
    } catch (final GeneralSecurityException e) {
        LOG.warn("Could not decrypt token: " + e.toString());
        throw new IllegalArgumentException("Invalid token", e);
    }
}

From source file:org.hyperic.hq.bizapp.agent.server.SSLConnectionListener.java

private SSLServerConnection handleNewConn(SSLSocket sock)
        throws AgentConnectionException, SocketTimeoutException {
    SSLServerConnection res;/*w w w .  j  av a2  s .  c  o m*/
    InetAddress remoteAddr;
    TokenData token;
    String authToken;
    boolean doSave;

    remoteAddr = sock.getInetAddress();
    this.log.debug("Handling SSL connection from " + remoteAddr);
    res = new SSLServerConnection(sock);

    // Validate the actual auth token which is sent
    try {
        DataInputStream dIs;

        dIs = new DataInputStream(sock.getInputStream());

        this.log.debug("Starting to read authToken for SSL connection");
        authToken = dIs.readUTF();
        this.log.debug("Finished reading authToken for SSL connection");
    } catch (SocketTimeoutException exc) {
        throw exc;
    } catch (IOException exc) {
        throw new AgentConnectionException("Error negotiating auth: " + exc.getMessage(), exc);
    }

    // Set the token from pending to locked, if need be
    doSave = false;
    try {
        token = this.tokenManager.getToken(authToken);
    } catch (TokenNotFoundException exc) {
        this.log.error(
                "Rejecting client from " + remoteAddr + ": Passed an invalid auth token (" + authToken + ")",
                exc);
        // Due to 20 second expiration, the tokens in the manager
        // may not match what is in the tokendata.
        List l = this.tokenManager.getTokens();
        for (Iterator i = l.iterator(); i.hasNext();) {
            TokenData data = (TokenData) i.next();
            this.log.debug("Token: " + data.getToken() + ":" + data.getCreateTime() + ":"
                    + (data.isLocked() ? "locked" : "pending"));
        }

        try {
            res.readCommand();
            res.sendErrorResponse("Unauthorized");
        } catch (AgentConnectionException iExc) {
            log.debug(iExc, iExc);
        } catch (EOFException e) {
            log.debug(e, e);
        }

        throw new AgentConnectionException("Client from " + remoteAddr + " unauthorized");
    }

    if (!token.isLocked()) {
        try {
            this.log.info("Locking auth token");
            this.tokenManager.setTokenLocked(token, true);
            doSave = true;
        } catch (TokenNotFoundException exc) {
            // This should never occur
            this.log.error("Error setting token '" + token + "' to " + "locked state -- it no longer exists");
        }
    }

    // If set the token, re-store the data.
    if (doSave) {
        try {
            this.tokenManager.store();
        } catch (IOException exc) {
            this.log.error("Error storing token data: " + exc.getMessage());
        }
    }
    this.log.debug("Done connecting SSL");
    return res;
}

From source file:com.bigdata.dastor.db.RowMutation.java

private Map<String, ColumnFamily> defreezeTheMaps(DataInputStream dis) throws IOException {
    Map<String, ColumnFamily> map = new HashMap<String, ColumnFamily>();
    int size = dis.readInt();
    for (int i = 0; i < size; ++i) {
        String key = dis.readUTF();
        ColumnFamily cf = ColumnFamily.serializer().deserialize(dis);
        map.put(key, cf);//from   w ww  .j  a  v a 2  s .  com
    }
    return map;
}

From source file:MixedRecordEnumerationExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);// w w  w  .  ja  va2s . c  o  m
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString[] = { "First Record", "Second Record", "Third Record" };
            int outputInteger[] = { 15, 10, 5 };
            boolean outputBoolean[] = { true, false, true };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeBoolean(outputBoolean[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
            }
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            StringBuffer buffer = new StringBuffer();
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            recordEnumeration = recordstore.enumerateRecords(null, null, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append("\n");
                buffer.append(inputDataStream.readBoolean());
                buffer.append("\n");
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
            inputStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
                recordEnumeration.destroy();
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:ReadWriteStreams.java

public void readStream() {
    try {/*from   w  ww  .  ja  va 2s.c  o m*/
        // Careful: Make sure this is big enough!
        // Better yet, test and reallocate if necessary      
        byte[] recData = new byte[50];

        // Read from the specified byte array
        ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);

        // Read Java data types from the above byte array
        DataInputStream strmDataType = new DataInputStream(strmBytes);

        for (int i = 1; i <= rs.getNumRecords(); i++) {
            // Get data into the byte array
            rs.getRecord(i, recData, 0);

            // Read back the data types      
            System.out.println("Record #" + i);
            System.out.println("UTF: " + strmDataType.readUTF());
            System.out.println("Boolean: " + strmDataType.readBoolean());
            System.out.println("Int: " + strmDataType.readInt());
            System.out.println("--------------------");

            // Reset so read starts at beginning of array 
            strmBytes.reset();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}

From source file:com.igormaznitsa.jhexed.hexmap.HexFieldLayer.java

public HexFieldLayer(final InputStream in) throws IOException {
    final DataInputStream din = in instanceof DataInputStream ? (DataInputStream) in : new DataInputStream(in);
    this.name = din.readUTF();
    this.comments = din.readUTF();

    final int valuesNum = din.readShort() & 0xFFFF;
    for (int i = 0; i < valuesNum; i++) {
        final HexFieldValue value = HexFieldValue.readValue(in);
        value.setIndex(i);/* w  w w  .  j  av a2  s .  c  o m*/
        this.values.add(value);
    }

    this.columns = din.readInt();
    this.rows = din.readInt();
    this.visible = din.readBoolean();

    final byte[] packedLayerData = new byte[din.readInt()];
    IOUtils.readFully(din, packedLayerData);
    this.array = Utils.unpackArray(packedLayerData);

    if (this.array.length != (this.columns * this.rows))
        throw new IOException("Wrong field size");
}

From source file:org.openxdata.server.servlet.WMDownloadServlet.java

private void downloadStudies(HttpServletResponse response) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    formDownloadService.downloadStudies(dos, "", "");
    baos.flush();/*from  w w  w  .j  av a  2s .  co  m*/
    dos.flush();
    byte[] data = baos.toByteArray();
    baos.close();
    dos.close();

    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    PrintWriter out = response.getWriter();
    out.println("<StudyList>");

    try {
        @SuppressWarnings("unused")
        byte size = dis.readByte(); //reads the size of the studies

        while (true) {
            String value = "<study id=\"" + dis.readInt() + "\" name=\"" + dis.readUTF() + "\"/>";
            out.println(value);
        }
    } catch (EOFException exe) {
        //exe.printStackTrace();
    }
    out.println("</StudyList>");
    out.flush();
    dis.close();
}

From source file:org.hyperic.hq.agent.client.AgentConnection.java

/**
 * Get the result of command execution from the remote command handler.
 *
 * @param inStreamPair The pair which was returned from the associated
 *                     sendCommandHeaders invocation.
 *
 * @return an AgentRemoteValue object, as returned from the Agent.
 *
 * @throws AgentRemoteException indicating an error invoking the method.
 * @throws AgentConnectionException indicating a failure to communicate
 *                                  with the agent.
 *//*w ww.jav a2  s .  c o m*/

public AgentRemoteValue getCommandResult(AgentStreamPair inStreamPair)
        throws AgentRemoteException, AgentConnectionException {
    SocketStreamPair streamPair = (SocketStreamPair) inStreamPair;
    // Get the response
    try {
        DataInputStream inputStream;
        int isException;

        inputStream = new DataInputStream(streamPair.getInputStream());
        isException = inputStream.readInt();
        if (isException == 1) {
            String exceptionMsg = inputStream.readUTF();

            throw new AgentRemoteException(exceptionMsg);
        } else {
            AgentRemoteValue result;

            result = AgentRemoteValue.fromStream(inputStream);
            return result;
        }
    } catch (EOFException exc) {
        throw new AgentConnectionException("EOF received from Agent");
    } catch (IOException exc) {
        throw new AgentConnectionException("Error reading result: " + exc.getMessage(), exc);
    } finally {
        close(streamPair);
    }
}

From source file:BugTracker.java

private void loadBugs() {
    // Load bugs from a file.
    DataInputStream in = null;

    try {// w  w w .j a v a 2s.  c  om
        File file = new File("bugs.dat");
        if (!file.exists())
            return;
        in = new DataInputStream(new FileInputStream(file));

        while (true) {
            String id = in.readUTF();
            String summary = in.readUTF();
            String assignedTo = in.readUTF();
            boolean solved = in.readBoolean();

            TableItem item = new TableItem(table, SWT.NULL);
            item.setImage(bugIcon);
            item.setText(new String[] { id, summary, assignedTo, solved ? "Yes" : "No" });
        }

    } catch (IOException ioe) {
        // Ignore.

    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:io.dacopancm.socketdcm.net.StreamSocket.java

public String getStreamFile() {
    String list = "false";
    try {/*from w  w  w  . java  2  s  .co  m*/

        if (ConectType.GET_STREAM.name().equalsIgnoreCase(method)) {
            logger.log(Level.INFO, "get stream socket call");
            sock = new Socket(ip, port);

            DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
            DataInputStream dIn = new DataInputStream(sock.getInputStream());

            dOut.writeUTF(ConectType.STREAM.name());//send stream type
            dOut.writeUTF("uncompressed");//send comprimido o no

            dOut.writeUTF(ConectType.GET_STREAM.toString()); //send type
            dOut.writeUTF(streamid);
            dOut.flush(); // Send off the data

            String rtspId = dIn.readUTF();
            dOut.close();
            logger.log(Level.INFO, "resp get stream file: {0}", rtspId);
            list = rtspId;

        }
    } catch (IOException ex) {
        HelperUtil.showErrorB("No se pudo establecer conexin");
        logger.log(Level.INFO, "get stream file error no connect:{0}", ex.getMessage());
        try {
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e) {
        }

    }
    return list;

}