Example usage for java.io DataInputStream readFully

List of usage examples for java.io DataInputStream readFully

Introduction

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

Prototype

public final void readFully(byte b[]) throws IOException 

Source Link

Document

See the general contract of the readFully method of DataInput .

Usage

From source file:org.kei.android.phone.cellhistory.towers.request.OpenCellIdRequestEntity.java

@Override
public int decode(final String url, final HttpConnection connection, final int timeout) throws Exception {
    int ret = OK;
    final GetMethod getMethod = new GetMethod(url);
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    // socket timeout (connection timeout already set in HttpClient)
    getMethod.getParams().setSoTimeout(timeout);
    final int resCode = getMethod.execute(new HttpState(), connection);
    final InputStream response = getMethod.getResponseBodyAsStream();
    final DataInputStream dis = new DataInputStream(response);
    if (resCode == HttpStatus.SC_OK) {
        final int av = dis.available();
        final byte[] json = new byte[av];
        dis.readFully(json);
        final String sjson = new String(json);
        final String ljson = sjson.toLowerCase(Locale.US);
        if (ljson.indexOf("err") == -1) {
            final JSONObject object = new JSONObject(sjson);
            String lat, lng;// www  .j  a v a 2s. co m
            lat = object.getString("lat");
            lng = object.getString("lon");
            ti.setCellLatitude(Double.parseDouble(lat));
            ti.setCellLongitude(Double.parseDouble(lng));
        } else if (ljson.indexOf("not found") != -1)
            ret = NOT_FOUND;
        else
            ret = EXCEPTION;
    } else if (resCode == HttpStatus.SC_NOT_FOUND)
        ret = NOT_FOUND;
    else if (resCode == HttpStatus.SC_INTERNAL_SERVER_ERROR)
        ret = BAD_REQUEST;
    else
        ret = EXCEPTION;
    getMethod.releaseConnection();
    return ret;
}

From source file:ImageLoaderMIDlet.java

public Image loadImage(String url) throws IOException {
    HttpConnection hpc = null;//from w ww  .  j  a  v  a  2s.  c  o  m
    DataInputStream dis = null;
    try {
        hpc = (HttpConnection) Connector.open(url);
        int length = (int) hpc.getLength();
        byte[] data = new byte[length];
        dis = new DataInputStream(hpc.openInputStream());
        dis.readFully(data);
        return Image.createImage(data, 0, data.length);
    } finally {
        if (hpc != null)
            hpc.close();
        if (dis != null)
            dis.close();
    }
}

From source file:org.apache.hadoop.security.Credentials.java

/**
 * Convenience method for reading a token storage file directly from a 
 * datainputstream/* ww w.  j av  a2s.  c  om*/
 */
public void readTokenStorageStream(DataInputStream in) throws IOException {
    byte[] magic = new byte[TOKEN_STORAGE_MAGIC.length];
    in.readFully(magic);
    if (!Arrays.equals(magic, TOKEN_STORAGE_MAGIC)) {
        throw new IOException("Bad header found in token storage.");
    }
    byte version = in.readByte();
    if (version != TOKEN_STORAGE_VERSION) {
        throw new IOException("Unknown version " + version + " in token storage.");
    }
    readFields(in);
}

From source file:org.apache.wink.itest.standard.JAXRSDataSourceTest.java

/**
 * Tests posting to a DataSource entity parameter.
 * /*w w w .j a  v  a 2  s. c o m*/
 * @throws HttpException
 * @throws IOException
 */
public void testPostDataSource() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PostMethod postMethod = new PostMethod(getBaseURI() + "/providers/standard/datasource");
    byte[] barr = new byte[1000];
    Random r = new Random();
    r.nextBytes(barr);
    postMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "text/plain"));
    postMethod.addRequestHeader("Accept", "text/plain");
    try {
        client.executeMethod(postMethod);

        assertEquals(200, postMethod.getStatusCode());
        InputStream is = postMethod.getResponseBodyAsStream();

        byte[] receivedBArr = new byte[1000];
        DataInputStream dis = new DataInputStream(is);
        dis.readFully(receivedBArr);

        int checkEOF = dis.read();
        assertEquals(-1, checkEOF);
        for (int c = 0; c < barr.length; ++c) {
            assertEquals(barr[c], receivedBArr[c]);
        }
        assertEquals("text/plain", postMethod.getResponseHeader("Content-Type").getValue());
        assertNull(
                (postMethod.getResponseHeader("Content-Length") == null) ? ""
                        : postMethod.getResponseHeader("Content-Length").getValue(),
                postMethod.getResponseHeader("Content-Length"));
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:com.zimbra.cs.octosync.PatchInputStream.java

private InputStream nextInputStream() throws IOException, ServiceException {
    if (!patchReader.hasMoreRecordInfos()) {
        return null;
    }//  w  w w.ja  va  2 s.  c o m

    PatchReader.RecordInfo ri = patchReader.getNextRecordInfo();

    InputStream nextStream = null;

    if (ri.type == PatchReader.RecordType.DATA) {

        log.debug("Patch data, length: " + ri.length);
        nextStream = patchReader.popData();

    } else if (ri.type == PatchReader.RecordType.REF) {

        PatchRef patchRef = patchReader.popRef();
        log.debug("Patch reference " + patchRef);

        if (patchRef.length > MAX_REF_LENGTH) {
            throw new InvalidPatchReferenceException(
                    "referenced data too large: " + patchRef.length + " > " + MAX_REF_LENGTH);
        }

        if (manifest != null) {
            int[] actualRef = blobAccess.getActualReference(patchRef.fileId, patchRef.fileVersion);
            manifest.addReference(actualRef[0], actualRef[1], patchRef.length);
        }

        try {
            InputStream blobIs = blobAccess.getBlobInputStream(patchRef.fileId, patchRef.fileVersion);

            blobIs.skip(patchRef.offset);

            byte[] chunkBuf = new byte[patchRef.length];

            DataInputStream dis = new DataInputStream(blobIs);
            dis.readFully(chunkBuf);
            dis.close();

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(chunkBuf);
            byte[] calcHash = md.digest();

            if (!Arrays.equals(patchRef.hashKey, calcHash)) {
                throw new InvalidPatchReferenceException("refrenced data hash mismatch, actual hash: "
                        + new String(Hex.encodeHex(calcHash)) + "; " + patchRef);
            }

            nextStream = new ByteArrayInputStream(chunkBuf);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            assert false : "SHA-256 must be supported";
        }
    } else {
        assert false : "Invalid record type: " + ri.type;
    }

    assert nextStream != null : "Stream returned here must be non-null";
    return nextStream;
}

From source file:org.apache.wink.itest.standard.JAXRSDataSourceTest.java

/**
 * Tests receiving a DataSource with any media type.
 * //from   w  w w  . jav a2 s  .  com
 * @throws HttpException
 * @throws IOException
 */
public void testWithRequestAcceptHeaderWillReturnRequestedContentType() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(getBaseURI() + "/providers/standard/datasource");
    byte[] barr = new byte[1000];
    Random r = new Random();
    r.nextBytes(barr);
    putMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "any/type"));
    try {
        client.executeMethod(putMethod);
        assertEquals(204, putMethod.getStatusCode());
    } finally {
        putMethod.releaseConnection();
    }

    GetMethod getMethod = new GetMethod(getBaseURI() + "/providers/standard/datasource");
    getMethod.addRequestHeader("Accept", "mytype/subtype");
    try {
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        InputStream is = getMethod.getResponseBodyAsStream();

        byte[] receivedBArr = new byte[1000];
        DataInputStream dis = new DataInputStream(is);
        dis.readFully(receivedBArr);

        int checkEOF = dis.read();
        assertEquals(-1, checkEOF);
        for (int c = 0; c < barr.length; ++c) {
            assertEquals(barr[c], receivedBArr[c]);
        }
        assertEquals("mytype/subtype", getMethod.getResponseHeader("Content-Type").getValue());
        assertNull(
                (getMethod.getResponseHeader("Content-Length") == null) ? ""
                        : getMethod.getResponseHeader("Content-Length").getValue(),
                getMethod.getResponseHeader("Content-Length"));
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.apache.wink.itest.standard.JAXRSDataSourceTest.java

/**
 * Tests putting and then getting a DataSource entity.
 * /*from www. j  a v a2 s  . co m*/
 * @throws HttpException
 * @throws IOException
 */
public void testPutDataSource() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(getBaseURI() + "/providers/standard/datasource");
    byte[] barr = new byte[1000];
    Random r = new Random();
    r.nextBytes(barr);
    putMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "bytes/array"));
    try {
        client.executeMethod(putMethod);
        assertEquals(204, putMethod.getStatusCode());
    } finally {
        putMethod.releaseConnection();
    }

    GetMethod getMethod = new GetMethod(getBaseURI() + "/providers/standard/datasource");
    try {
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        InputStream is = getMethod.getResponseBodyAsStream();

        byte[] receivedBArr = new byte[1000];
        DataInputStream dis = new DataInputStream(is);
        dis.readFully(receivedBArr);

        int checkEOF = dis.read();
        assertEquals(-1, checkEOF);
        for (int c = 0; c < barr.length; ++c) {
            assertEquals(barr[c], receivedBArr[c]);
        }

        String contentType = (getMethod.getResponseHeader("Content-Type") == null) ? null
                : getMethod.getResponseHeader("Content-Type").getValue();
        assertNotNull(contentType, contentType);
        assertNull(
                (getMethod.getResponseHeader("Content-Length") == null) ? ""
                        : getMethod.getResponseHeader("Content-Length").getValue(),
                getMethod.getResponseHeader("Content-Length"));
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.esupportail.papercut.services.PayBoxService.java

public void setDerPayboxPublicKeyFile(String derPayboxPublicKeyFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    org.springframework.core.io.Resource derPayboxPublicKeyRessource = new ClassPathResource(
            derPayboxPublicKeyFile);/*from   w  w  w.  j a v  a  2  s.co  m*/
    InputStream fis = derPayboxPublicKeyRessource.getInputStream();
    DataInputStream dis = new DataInputStream(fis);
    byte[] pubKeyBytes = new byte[fis.available()];
    dis.readFully(pubKeyBytes);
    fis.close();
    dis.close();
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKeyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    this.payboxPublicKey = kf.generatePublic(x509EncodedKeySpec);
}

From source file:com.facebook.infrastructure.db.CommitLogHeader.java

public CommitLogHeader deserialize(DataInputStream dis) throws IOException {
    int size = dis.readInt();
    byte[] bitFlags = new byte[size];
    dis.readFully(bitFlags);

    int[] position = new int[size];
    for (int i = 0; i < size; ++i) {
        position[i] = dis.readInt();/* www.  j  a  v  a2 s .c  o m*/
    }

    return new CommitLogHeader(bitFlags, position);
}

From source file:org.carbondata.processing.globalsurrogategenerator.LevelGlobalSurrogateGeneratorThread.java

public static Map<String, Integer> readLevelFileAndUpdateCache(CarbonFile memberFile) throws IOException {
    DataInputStream inputStream = null;
    Map<String, Integer> localMemberMap = new HashMap<String, Integer>(
            CarbonCommonConstants.DEFAULT_COLLECTION_SIZE);

    try {//from  w  w  w .j a v a 2  s .  co m
        inputStream = FileFactory.getDataInputStream(memberFile.getPath(),
                FileFactory.getFileType(memberFile.getPath()));

        long currentPosition = 4;
        long size = memberFile.getSize() - 4;

        boolean enableEncoding = Boolean.valueOf(
                CarbonProperties.getInstance().getProperty(CarbonCommonConstants.ENABLE_BASE64_ENCODING,
                        CarbonCommonConstants.ENABLE_BASE64_ENCODING_DEFAULT));
        int surrogateValue = inputStream.readInt();
        while (currentPosition < size) {
            int len = inputStream.readInt();
            currentPosition += 4;
            byte[] rowBytes = new byte[len];

            inputStream.readFully(rowBytes);
            currentPosition += len;
            String decodedValue = null;

            if (enableEncoding) {
                decodedValue = new String(Base64.decodeBase64(rowBytes), Charset.defaultCharset());
            } else {
                decodedValue = new String(rowBytes, Charset.defaultCharset());
            }
            localMemberMap.put(decodedValue, surrogateValue);
            surrogateValue++;
        }

    } catch (Exception e) {
        LOGGER.error(e, e.getMessage());
        CarbonUtil.closeStreams(inputStream);
    } finally {
        CarbonUtil.closeStreams(inputStream);
    }
    return localMemberMap;
}