Search in sources :

Example 61 with ByteArrayOutputStream

use of org.apache.commons.io.output.ByteArrayOutputStream in project cassandra by apache.

the class MultiResultLoggerTest method delegatesPrintlnToAdditionalPrintStreams.

@Test
public void delegatesPrintlnToAdditionalPrintStreams() throws Exception {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PrintStream additionalPrintStream = new PrintStream(output, true);
    MultiResultLogger underTest = new MultiResultLogger(new PrintStream(NOOP));
    underTest.addStream(additionalPrintStream);
    underTest.println();
    assertEquals("\n", output.toString());
}
Also used : PrintStream(java.io.PrintStream) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) Test(org.junit.Test)

Example 62 with ByteArrayOutputStream

use of org.apache.commons.io.output.ByteArrayOutputStream in project hudson-2.x by hudson.

the class UsageStatistics method getStatData.

/**
     * Gets the encrypted usage stat data to be sent to the Hudson server.
     */
public String getStatData() throws IOException {
    Hudson h = Hudson.getInstance();
    JSONObject o = new JSONObject();
    o.put("stat", 1);
    o.put("install", Util.getDigestOf(h.getSecretKey()));
    o.put("version", Hudson.VERSION);
    List<JSONObject> nodes = new ArrayList<JSONObject>();
    for (Computer c : h.getComputers()) {
        JSONObject n = new JSONObject();
        if (c.getNode() == h) {
            n.put("master", true);
            n.put("jvm-vendor", System.getProperty("java.vm.vendor"));
            n.put("jvm-version", System.getProperty("java.version"));
        }
        n.put("executors", c.getNumExecutors());
        DescriptorImpl descriptor = h.getDescriptorByType(DescriptorImpl.class);
        n.put("os", descriptor.get(c));
        nodes.add(n);
    }
    o.put("nodes", nodes);
    List<JSONObject> plugins = new ArrayList<JSONObject>();
    for (PluginWrapper pw : h.getPluginManager().getPlugins()) {
        if (!pw.isActive()) {
            // treat disabled plugins as if they are uninstalled
            continue;
        }
        JSONObject p = new JSONObject();
        p.put("name", pw.getShortName());
        p.put("version", pw.getVersion());
        plugins.add(p);
    }
    o.put("plugins", plugins);
    JSONObject jobs = new JSONObject();
    List<TopLevelItem> items = h.getItems();
    for (TopLevelItemDescriptor d : Items.all()) {
        int cnt = 0;
        for (TopLevelItem item : items) {
            if (item.getDescriptor() == d) {
                cnt++;
            }
        }
        jobs.put(d.getJsonSafeClassName(), cnt);
    }
    o.put("jobs", jobs);
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // json -> UTF-8 encode -> gzip -> encrypt -> base64 -> string
        OutputStreamWriter w = new OutputStreamWriter(new GZIPOutputStream(new CombinedCipherOutputStream(baos, getCipher(), "AES")), "UTF-8");
        o.write(w);
        w.close();
        return new String(Base64.encode(baos.toByteArray()));
    } catch (GeneralSecurityException e) {
        // impossible
        throw new Error(e);
    }
}
Also used : DescriptorImpl(hudson.node_monitors.ArchitectureMonitor.DescriptorImpl) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) JSONObject(net.sf.json.JSONObject) GZIPOutputStream(java.util.zip.GZIPOutputStream) PluginWrapper(hudson.PluginWrapper) OutputStreamWriter(java.io.OutputStreamWriter)

Example 63 with ByteArrayOutputStream

use of org.apache.commons.io.output.ByteArrayOutputStream in project voldemort by voldemort.

the class GetResponseSender method sendResponse.

/**
     * Sends a multipart response. Each body part represents a versioned value
     * of the given key.
     *
     * @throws IOException
     * @throws MessagingException
     */
@Override
public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception {
    /*
         * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.
         * However when writing to the outputStream we only send the multiPart object and not the entire
         * mimeMessage. This is intentional.
         *
         * In the earlier version of this code we used to create a multiPart object and just send that multiPart
         * across the wire.
         *
         * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates
         * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated
         * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the
         * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()
         * on the body part. It's this updateHeaders call that transfers the content type from the
         * DataHandler to the part's MIME Content-Type header.
         *
         * To make sure that the Content-Type headers are being updated (without changing too much code), we decided
         * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.
         * This is to make sure multiPart's headers are updated accurately.
         */
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    MimeMultipart multiPart = new MimeMultipart();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    String base64Key = RestUtils.encodeVoldemortKey(key.get());
    String contentLocationKey = "/" + this.storeName + "/" + base64Key;
    for (Versioned<byte[]> versionedValue : versionedValues) {
        byte[] responseValue = versionedValue.getValue();
        VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
        String eTag = RestUtils.getSerializedVectorClock(vectorClock);
        numVectorClockEntries += vectorClock.getVersionMap().size();
        // Create the individual body part for each versioned value of the
        // requested key
        MimeBodyPart body = new MimeBodyPart();
        try {
            // Add the right headers
            body.addHeader(CONTENT_TYPE, "application/octet-stream");
            body.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
            body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);
            body.setContent(responseValue, "application/octet-stream");
            body.addHeader(RestMessageHeaders.CONTENT_LENGTH, Integer.toString(responseValue.length));
            multiPart.addBodyPart(body);
        } catch (MessagingException me) {
            logger.error("Exception while constructing body part", me);
            outputStream.close();
            throw me;
        }
    }
    message.setContent(multiPart);
    message.saveChanges();
    try {
        multiPart.writeTo(outputStream);
    } catch (Exception e) {
        logger.error("Exception while writing multipart to output stream", e);
        outputStream.close();
        throw e;
    }
    ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
    responseContent.writeBytes(outputStream.toByteArray());
    // Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    // Set the right headers
    response.setHeader(CONTENT_TYPE, "multipart/binary");
    response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
    response.setHeader(CONTENT_LOCATION, contentLocationKey);
    // Copy the data into the payload
    response.setContent(responseContent);
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
    // Write the response to the Netty Channel
    if (logger.isDebugEnabled()) {
        String keyStr = RestUtils.getKeyHexString(this.key);
        debugLog("GET", this.storeName, keyStr, startTimeInMs, System.currentTimeMillis(), numVectorClockEntries);
    }
    this.messageEvent.getChannel().write(response);
    if (performanceStats != null && isFromLocalZone) {
        recordStats(performanceStats, startTimeInMs, Tracked.GET);
    }
    outputStream.close();
}
Also used : MessagingException(javax.mail.MessagingException) VectorClock(voldemort.versioning.VectorClock) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) Properties(java.util.Properties) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 64 with ByteArrayOutputStream

use of org.apache.commons.io.output.ByteArrayOutputStream in project async-http-client by AsyncHttpClient.

the class NtlmTest method testGenerateType3MsgThworsExceptionWhenType2IndicatorNotPresent.

@Test(expectedExceptions = NtlmEngineException.class)
public void testGenerateType3MsgThworsExceptionWhenType2IndicatorNotPresent() throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    buf.write("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
    buf.write(0);
    // type 2 indicator
    buf.write(3);
    buf.write(0);
    buf.write(0);
    buf.write(0);
    buf.write("challenge".getBytes());
    NtlmEngine engine = new NtlmEngine();
    engine.generateType3Msg("username", "password", "localhost", "workstation", Base64.encode(buf.toByteArray()));
    buf.close();
    fail("An NtlmEngineException must have occurred as type 2 indicator is incorrect");
}
Also used : ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Example 65 with ByteArrayOutputStream

use of org.apache.commons.io.output.ByteArrayOutputStream in project async-http-client by AsyncHttpClient.

the class NtlmTest method testGenerateType3Msg.

@Test
public void testGenerateType3Msg() throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    buf.write("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
    buf.write(0);
    // type 2 indicator
    buf.write(2);
    buf.write(0);
    buf.write(0);
    buf.write(0);
    // we want to write a Long
    buf.write(longToBytes(0L));
    // flags
    // unicode support indicator
    buf.write(1);
    buf.write(0);
    buf.write(0);
    buf.write(0);
    // challenge
    buf.write(longToBytes(1L));
    NtlmEngine engine = new NtlmEngine();
    String type3Msg = engine.generateType3Msg("username", "password", "localhost", "workstation", Base64.encode(buf.toByteArray()));
    buf.close();
    assertEquals(type3Msg, "TlRMTVNTUAADAAAAGAAYAEgAAAAYABgAYAAAABIAEgB4AAAAEAAQAIoAAAAWABYAmgAAAAAAAACwAAAAAQAAAgUBKAoAAAAP1g6lqqN1HZ0wSSxeQ5riQkyh7/UexwVlCPQm0SHU2vsDQm2wM6NbT2zPonPzLJL0TABPAEMAQQBMAEgATwBTAFQAdQBzAGUAcgBuAGEAbQBlAFcATwBSAEsAUwBUAEEAVABJAE8ATgA=", "Incorrect type3 message generated");
}
Also used : ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Aggregations

ByteArrayOutputStream (org.apache.commons.io.output.ByteArrayOutputStream)92 Test (org.junit.Test)36 DataOutputStream (java.io.DataOutputStream)15 IOException (java.io.IOException)14 HashSet (java.util.HashSet)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 ArrayList (java.util.ArrayList)12 Configuration (org.apache.hadoop.conf.Configuration)12 PrintStream (java.io.PrintStream)10 SparkConf (org.apache.spark.SparkConf)10 Edge (uk.gov.gchq.gaffer.data.element.Edge)10 Element (uk.gov.gchq.gaffer.data.element.Element)10 Entity (uk.gov.gchq.gaffer.data.element.Entity)10 Graph (uk.gov.gchq.gaffer.graph.Graph)10 User (uk.gov.gchq.gaffer.user.User)10 File (java.io.File)9 HashMap (java.util.HashMap)8 InputStream (java.io.InputStream)7 OutputStream (java.io.OutputStream)6 JavaSparkContext (org.apache.spark.api.java.JavaSparkContext)6