Example usage for org.apache.commons.io.output ByteArrayOutputStream write

List of usage examples for org.apache.commons.io.output ByteArrayOutputStream write

Introduction

In this page you can find the example usage for org.apache.commons.io.output ByteArrayOutputStream write.

Prototype

public synchronized int write(InputStream in) throws IOException 

Source Link

Document

Writes the entire contents of the specified input stream to this byte stream.

Usage

From source file:io.warp10.continuum.DirectoryUtil.java

private static long computeHash(long k0, long k1, long timestamp, List<String> classSelectors,
        List<Map<String, String>> labelsSelectors) {
    ////  w  ww.  j av  a 2s  .  c o  m
    // Create a ByteArrayOutputStream into which the content will be dumped
    //

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Add timestamp

    try {
        baos.write(Longs.toByteArray(timestamp));

        if (null != classSelectors) {
            for (String classSelector : classSelectors) {
                baos.write(classSelector.getBytes(Charsets.UTF_8));
            }
        }

        if (null != labelsSelectors) {
            for (Map<String, String> map : labelsSelectors) {
                TreeMap<String, String> tm = new TreeMap<String, String>();
                tm.putAll(map);
                for (Entry<String, String> entry : tm.entrySet()) {
                    baos.write(entry.getKey().getBytes(Charsets.UTF_8));
                    baos.write(entry.getValue().getBytes(Charsets.UTF_8));
                }
            }
        }
    } catch (IOException ioe) {
        return 0L;
    }

    // Compute hash

    byte[] data = baos.toByteArray();

    long hash = SipHashInline.hash24(k0, k1, data, 0, data.length);

    return hash;
}

From source file:model.PayloadSegment.java

/**
 * Copy the encapsulation file to the restoration directory first, to be
 * sure that you won't touch the file in the encapsulation output directory.
 * /*from   www  . ja v  a2 s.co  m*/
 * @param encapsulatedData
 * @return altered carrier file...
 */
public static byte[] removeLeastPayloadSegment(byte[] encapsulatedData) {
    try {
        int endIndex = -1;
        for (int index = encapsulatedData.length - 1; index >= 0; index--) {
            if (PayloadSequences.isEndSequence(encapsulatedData, index)) {
                endIndex = index;
            } else if (PayloadSequences.isStartSequence(encapsulatedData, index)) {
                if (endIndex == -1) {
                    return null;
                }
                ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                byteOut.write(Arrays.copyOfRange(encapsulatedData, 0, index));
                if (endIndex + END_SEQ.length > encapsulatedData.length) {
                    byte[] afterPayload = Arrays.copyOfRange(encapsulatedData, endIndex + END_SEQ.length,
                            encapsulatedData.length - 1);
                    byteOut.write(afterPayload);
                }
                byte[] dataWithRemovedPayload = byteOut.toByteArray();
                byteOut.close();
                return dataWithRemovedPayload;
            }
        }
    } catch (IOException e) {
    }
    return null;
}

From source file:com.edduarte.argus.util.PluginLoader.java

private static Class loadPlugin(Path pluginFile) throws ClassNotFoundException, IOException {

    CustomClassLoader loader = new CustomClassLoader();

    String url = "file:" + pluginFile.toAbsolutePath().toString();
    URL myUrl = new URL(url);
    URLConnection connection = myUrl.openConnection();
    InputStream input = connection.getInputStream();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int data = input.read();

    while (data != -1) {
        buffer.write(data);
        data = input.read();/*from  ww  w.ja  va 2 s. c  o  m*/
    }

    input.close();

    byte[] classData = buffer.toByteArray();
    Class loadedClass;

    try {
        loadedClass = loader.defineClass(classData);

    } catch (NoClassDefFoundError ex) {
        loadedClass = null;
    }

    loader.clearAssertionStatus();
    loader = null;
    System.gc();

    return loadedClass;
}

From source file:ch.admin.isb.hermes5.util.ImageUtilsTest.java

private byte[] getResourceAsStream(String string) {
    InputStream resource = ImageUtilsTest.class.getResourceAsStream(string);
    assertNotNull(resource);/* w  ww .  j av  a2  s . c  o  m*/
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        byteArrayOutputStream.write(resource);
        byteArrayOutputStream.flush();
        return byteArrayOutputStream.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            byteArrayOutputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.oracle.bdglue.publisher.kafka.KafkaRegistry.java

/**
 * Serialize as appropriate to send a record to Kafka that contains information
 * pertaining to the schema version that applies to this record.
 *
 * @param record a GenericRecord// www .  j a v a  2 s.c o  m
 * @return a byte array representing the encoded Generic record + schema ID
 * @throws IOException if there is a problem with the encoding
 */
public byte[] serialize(GenericRecord record) throws IOException {

    BinaryEncoder encoder = null;
    Schema schema = record.getSchema();

    byte[] rval;

    // register the schema. 
    // TODO: determine if we need getName() or getFullName()
    int schemaId = registerSchema(schema.getName(), schema);

    // serialize the record into a byte array
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(magic_byte);
    out.write(ByteBuffer.allocate(idSize).putInt(schemaId).array());
    //DatumWriter<GenericRecord> writer = new GenericDatumWriter<GenericRecord>(schema);
    DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);

    encoder = org.apache.avro.io.EncoderFactory.get().directBinaryEncoder(out, encoder);
    writer.write(record, encoder);
    encoder.flush();
    rval = out.toByteArray();
    //out.close(); // noop in the Apache version, so not bothering

    return rval;
}

From source file:com.sunney.eweb.config.MappingFastjson2HttpMessageConverter.java

@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {
    @SuppressWarnings("resource")
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int i;/* w w w.j a  va  2  s .c o  m*/
    while ((i = inputMessage.getBody().read()) != -1) {
        baos.write(i);
    }
    return JSON.parseArray(baos.toString(), clazz);
}

From source file:com.bittorrent.mpetazzoni.client.announce.HTTPTrackerClient.java

/**
 * Build, send and process a tracker announce request.
 *
 * <p>//from w ww  .  j a  v a2s .c  om
 * This function first builds an announce request for the specified event
 * with all the required parameters. Then, the request is made to the
 * tracker and the response analyzed.
 * </p>
 *
 * <p>
 * All registered {@link AnnounceResponseListener} objects are then fired
 * with the decoded payload.
 * </p>
 *
 * @param event The announce event type (can be AnnounceEvent.NONE for
 * periodic updates).
 * @param inhibitEvents Prevent event listeners from being notified.
 */
@Override
public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents)
        throws AnnounceException {
    logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
            new Object[] { this.formatAnnounceEvent(event), this.torrent.getUploaded(),
                    this.torrent.getDownloaded(), this.torrent.getLeft() });

    URL target = null;
    try {
        HTTPAnnounceRequestMessage request = this.buildAnnounceRequest(event);
        target = request.buildAnnounceURL(this.tracker.toURL());
    } catch (MalformedURLException mue) {
        throw new AnnounceException("Invalid announce URL (" + mue.getMessage() + ")", mue);
    } catch (MessageValidationException mve) {
        throw new AnnounceException(
                "Announce request creation violated " + "expected protocol (" + mve.getMessage() + ")", mve);
    } catch (IOException ioe) {
        throw new AnnounceException("Error building announce request (" + ioe.getMessage() + ")", ioe);
    }

    HttpURLConnection conn = null;
    InputStream in = null;
    try {
        conn = (HttpURLConnection) target.openConnection();
        in = conn.getInputStream();
    } catch (IOException ioe) {
        if (conn != null) {
            in = conn.getErrorStream();
        }
    }

    // At this point if the input stream is null it means we have neither a
    // response body nor an error stream from the server. No point in going
    // any further.
    if (in == null) {
        throw new AnnounceException("No response or unreachable tracker!");
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(in);

        // Parse and handle the response
        HTTPTrackerMessage message = HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray()));
        this.handleTrackerAnnounceResponse(message, inhibitEvents);
    } catch (IOException ioe) {
        throw new AnnounceException("Error reading tracker response!", ioe);
    } catch (MessageValidationException mve) {
        throw new AnnounceException(
                "Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve);
    } finally {
        // Make sure we close everything down at the end to avoid resource
        // leaks.
        try {
            in.close();
        } catch (IOException ioe) {
            logger.warn("Problem ensuring error stream closed!", ioe);
        }

        // This means trying to close the error stream as well.
        InputStream err = conn.getErrorStream();
        if (err != null) {
            try {
                err.close();
            } catch (IOException ioe) {
                logger.warn("Problem ensuring error stream closed!", ioe);
            }
        }
    }
}

From source file:com.silverpeas.attachment.web.SharedAttachmentResource.java

@GET
@Path("zipcontent/{name}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getZipContent(@PathParam("name") String zipFileName) {
    String zipFilePath = FileRepositoryManager.getTemporaryPath() + zipFileName;
    File realFile = new File(zipFilePath);
    if (!realFile.exists() && !realFile.isFile()) {
        return Response.ok().build();
    } else {/*  w ww  .j av  a2 s  .c  om*/
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        InputStream in = null;
        try {
            in = new FileInputStream(realFile);
            output.write(in);
            return Response.ok().entity(output.toByteArray()).type(MimeTypes.SHORT_ARCHIVE_MIME_TYPE).build();
        } catch (IOException e) {
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(output);
        }
    }
}

From source file:com.silverpeas.attachment.web.AttachmentRessource.java

@GET
@Path("zipcontent/{name}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getZipContent(@PathParam("name") String zipFileName) {
    String zipFilePath = FileRepositoryManager.getTemporaryPath() + zipFileName;
    File realFile = new File(zipFilePath);
    if (!realFile.exists() && !realFile.isFile()) {
        return Response.ok().build();
    } else {// w ww  . j a  v  a2s . co m
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        InputStream in = null;
        try {
            in = new FileInputStream(realFile);
            output.write(in);
            return Response.ok().entity(output.toByteArray()).type(MimeTypes.SHORT_ARCHIVE_MIME_TYPE).build();
        } catch (IOException e) {
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(output);
        }

    }
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileX.java

@Override
protected SignerInformation extendCMSSignature(CMSSignedData signedData, SignerInformation si,
        SignatureParameters parameters, Document originalData) throws IOException {

    si = super.extendCMSSignature(signedData, si, parameters, originalData);

    ASN1ObjectIdentifier attributeId = null;
    ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

    switch (getExtendedValidationType()) {
    case 1:/*from  ww  w . j  a  v a2s  .  com*/
        attributeId = PKCSObjectIdentifiers.id_aa_ets_escTimeStamp;

        toTimestamp.write(si.getSignature());

        // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS 6.3.5,
        // NOTE 2)
        toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken)
                .getAttrType().getDEREncoded());
        toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken)
                .getAttrValues().getDEREncoded());
        break;
    case 2:
        attributeId = PKCSObjectIdentifiers.id_aa_ets_certCRLTimestamp;
        break;
    default:
        throw new IllegalStateException(
                "CAdES-X Profile: Extended validation is set but no valid type (1 or 2)");
    }

    /* Those are common to Type 1 and Type 2 */
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs)
            .getAttrType().getDEREncoded());
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs)
            .getAttrValues().getDEREncoded());
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs)
            .getAttrType().getDEREncoded());
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs)
            .getAttrValues().getDEREncoded());

    @SuppressWarnings("unchecked")
    Hashtable<ASN1ObjectIdentifier, Attribute> unsignedAttrHash = si.getUnsignedAttributes().toHashtable();
    Attribute extendedTimeStamp = getTimeStampAttribute(attributeId, getSignatureTsa(), digestAlgorithm,
            toTimestamp.toByteArray());
    unsignedAttrHash.put(attributeId, extendedTimeStamp);

    return SignerInformation.replaceUnsignedAttributes(si, new AttributeTable(unsignedAttrHash));

}