Example usage for java.io ByteArrayInputStream close

List of usage examples for java.io ByteArrayInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayInputStream has no effect.

Usage

From source file:com.quigley.zabbixj.agent.active.ActiveThread.java

private JSONObject getResponse(byte[] responseBytes) throws Exception {
    byte[] sizeBuffer = new byte[8];
    int index = 0;
    for (int i = 12; i > 4; i--) {
        sizeBuffer[index++] = responseBytes[i];
    }/*from   w  w  w. j  av a  2s . c  om*/
    ByteArrayInputStream bais = new ByteArrayInputStream(sizeBuffer);
    DataInputStream dis = new DataInputStream(bais);
    long size = dis.readLong();
    dis.close();
    bais.close();

    byte[] jsonBuffer = new byte[responseBytes.length - 13];
    if (jsonBuffer.length != size) {
        throw new ZabbixException("Reported and actual buffer sizes differ!");
    }

    index = 0;
    for (int i = 13; i < responseBytes.length; i++) {
        jsonBuffer[index++] = responseBytes[i];
    }

    JSONObject response = new JSONObject(new String(jsonBuffer));

    return response;
}

From source file:com.taobao.metamorphosis.utils.codec.impl.JavaDeserializer.java

/**
 * @see com.taobao.notify.codec.Deserializer#decodeObject(byte[])
 *//* w  w  w .  j  av  a 2s . c o m*/
@Override
public Object decodeObject(final byte[] objContent) throws IOException {
    Object obj = null;
    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    try {
        bais = new ByteArrayInputStream(objContent);
        ois = new ObjectInputStream(bais);
        obj = ois.readObject();
    } catch (final IOException ex) {
        throw ex;
    } catch (final ClassNotFoundException ex) {
        this.logger.warn("Failed to decode object.", ex);
    } finally {
        if (ois != null) {
            try {
                ois.close();
                bais.close();
            } catch (final IOException ex) {
                this.logger.error("Failed to close stream.", ex);
            }
        }
    }
    return obj;
}

From source file:com.moez.QKSMS.mmssms.Transaction.java

private static Uri createPartImage(Context context, String id, byte[] imageBytes, String mimeType)
        throws Exception {
    ContentValues mmsPartValue = new ContentValues();
    mmsPartValue.put("mid", id);
    mmsPartValue.put("ct", mimeType);
    mmsPartValue.put("cid", "<" + System.currentTimeMillis() + ">");
    Uri partUri = Uri.parse("content://mms/" + id + "/part");
    Uri res = context.getContentResolver().insert(partUri, mmsPartValue);

    // Add data to part
    OutputStream os = context.getContentResolver().openOutputStream(res);
    ByteArrayInputStream is = new ByteArrayInputStream(imageBytes);
    byte[] buffer = new byte[256];

    for (int len = 0; (len = is.read(buffer)) != -1;) {
        os.write(buffer, 0, len);//from   w w  w.  j  a  v  a  2  s . co m
    }

    os.close();
    is.close();

    return res;
}

From source file:org.cloudgraph.state.ProtoSequenceGenerator.java

private StateModelProto.StateModel.Builder fromBytes(byte[] content) {
    ByteArrayInputStream bais = new ByteArrayInputStream(content);
    try {/*from   ww w  . j a  va  2 s. c  o  m*/
        StateModelProto.StateModel.Builder result = StateModelProto.StateModel.newBuilder();
        result.mergeDelimitedFrom(bais);
        return result;
    } catch (IOException e) {
        throw new StateException(e);
    } finally {
        try {
            bais.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.taobao.metamorphosis.utils.codec.impl.Hessian1Deserializer.java

/**
 * @see com.taobao.notify.codec.Deserializer#decodeObject(byte[])
 *//*www  .jav  a2  s  . com*/
@Override
public Object decodeObject(final byte[] in) throws IOException {
    Object obj = null;
    ByteArrayInputStream bais = null;
    HessianInput input = null;
    try {
        bais = new ByteArrayInputStream(in);
        input = new HessianInput(bais);
        input.startReply();
        obj = input.readObject();
        input.completeReply();
    } catch (final IOException ex) {
        throw ex;
    } catch (final Throwable e) {
        this.logger.error("Failed to decode object.", e);
    } finally {
        if (input != null) {
            try {
                bais.close();
            } catch (final IOException ex) {
                this.logger.error("Failed to close stream.", ex);
            }
        }
    }
    return obj;
}

From source file:org.openfaces.component.table.impl.TableDataModel.java

private static boolean checkSerializableEqualsAndHashcode(Object rowKey) {
    if (!(rowKey instanceof Serializable))
        return false;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Object deserializedRowKey;//from www. j  a  v  a 2  s .c o m
    try {
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(rowKey);
        oos.close();
        byte[] serializedObject = baos.toByteArray();
        ByteArrayInputStream bais = new ByteArrayInputStream(serializedObject);
        ObjectInputStream ois = new ObjectInputStream(bais);
        deserializedRowKey = ois.readObject();
        bais.close();
    } catch (IOException e) {
        throw new RuntimeException(
                "The rowData or rowKey object is marked as Serializable, but can't be serialized: "
                        + rowKey.getClass().getName()
                        + " ; check that all object's fields are also Serializable",
                e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    boolean equalsValid = deserializedRowKey.equals(rowKey);
    boolean hashCodeValid = deserializedRowKey.hashCode() == rowKey.hashCode();
    boolean result = equalsValid && hashCodeValid;
    return result;
}

From source file:org.jenkinsci.plugins.exportparams.serializer.JSONSerializer.java

/**
 * Gets serialized string with properties format.
 * @inheritDoc/* w  ww .  j  a va  2 s  . co m*/
 *
 * @param env the env.
 * @return serialized string.
 */
public String serialize(EnvVars env) {
    Collection<Parameter> params = new ArrayList<Parameter>();
    for (String key : env.keySet()) {
        Parameter param = new Parameter();
        param.key = key;
        param.value = env.get(key);
        params.add(param);
    }
    JSON json = net.sf.json.JSONSerializer.toJSON(params);
    String buf = null;
    if (json != null) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        OutputStreamWriter osw;
        try {
            osw = new OutputStreamWriter(os, CharEncoding.UTF_8);
        } catch (UnsupportedEncodingException ueex) {
            osw = new OutputStreamWriter(os);
        }

        try {
            json.write(osw);
            osw.flush();
            ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
            InputStreamReader reader = new InputStreamReader(is, CharEncoding.UTF_8);
            StringBuilder builder = new StringBuilder();

            char[] charBuf = new char[1024];
            int numRead;

            while (0 <= (numRead = reader.read(charBuf))) {
                builder.append(charBuf, 0, numRead);
            }
            buf = builder.toString();
            is.close();

        } catch (Exception ex) {
            buf = null;
        } finally {
            try {
                os.close();
            } catch (Exception ex) {
                os = null;
            }
        }
    }
    return buf;
}

From source file:org.hdiv.util.EncodingUtil.java

/**
 * Decodes Base64 alphabet characters of the string <code>s</code>, decrypts
 * this string and finally decompresses it.
 * //from  ww w .  jav  a2s.  co m
 * @param s data to decrypt
 * @return decoded data
 * @throws HDIVException if there is an error decoding object <code>data</code>
 * @see org.apache.commons.codec.binary.Base64#decode(byte[])
 * @see org.apache.commons.codec.net.URLCodec#decode(byte[])
 * @see java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream)
 */
public Object decode64Cipher(String s) {

    try {
        Base64 base64Codec = new Base64();
        // Decodes string s containing characters in the Base64 alphabet.
        byte[] encryptedData = base64Codec.decode(s.getBytes(ZIP_CHARSET));

        // Decodes an array of URL safe 7-bit characters into an array of
        // original bytes. Escaped characters are converted back to their
        // original representation.
        byte[] encodedData = URLCodec.decodeUrl(encryptedData);

        byte[] data = this.session.getDecryptCipher().decrypt(encodedData);

        ByteArrayInputStream decodedStream = new ByteArrayInputStream(data);
        InputStream unzippedStream = new GZIPInputStream(decodedStream);
        ObjectInputStream ois = new ObjectInputStream(unzippedStream);
        Object obj = ois.readObject();

        ois.close();
        unzippedStream.close();
        decodedStream.close();
        return obj;

    } catch (Exception e) {
        throw new HDIVException(HDIVErrorCodes.HDIV_PARAMETER_INCORRECT_VALUE);
    }
}

From source file:org.apache.kylin.dict.DictionaryManager.java

void save(DictionaryInfo dict) throws IOException {
    ResourceStore store = MetadataManager.getInstance(config).getStore();
    String path = dict.getResourcePath();
    logger.info("Saving dictionary at " + path);

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(buf);
    DictionaryInfoSerializer.FULL_SERIALIZER.serialize(dict, dout);
    dout.close();/*from  w  ww .  j  a va  2  s.  c o  m*/
    buf.close();

    ByteArrayInputStream inputStream = new ByteArrayInputStream(buf.toByteArray());
    store.putResource(path, inputStream, System.currentTimeMillis());
    inputStream.close();
}