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:org.apache.slider.common.tools.SliderUtils.java

public static InputStream getApplicationResourceInputStream(FileSystem fs, Path appPath, String entry)
        throws IOException {
    InputStream is = null;/*from w ww  .  j  a  v a 2s.  c  om*/
    FSDataInputStream appStream = null;
    try {
        appStream = fs.open(appPath);
        ZipArchiveInputStream zis = new ZipArchiveInputStream(appStream);
        ZipArchiveEntry zipEntry;
        boolean done = false;
        while (!done && (zipEntry = zis.getNextZipEntry()) != null) {
            if (entry.equals(zipEntry.getName())) {
                int size = (int) zipEntry.getSize();
                if (size != -1) {
                    log.info("Reading {} of size {}", zipEntry.getName(), zipEntry.getSize());
                    byte[] content = new byte[size];
                    int offset = 0;
                    while (offset < size) {
                        offset += zis.read(content, offset, size - offset);
                    }
                    is = new ByteArrayInputStream(content);
                } else {
                    log.debug("Size unknown. Reading {}", zipEntry.getName());
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    while (true) {
                        int byteRead = zis.read();
                        if (byteRead == -1) {
                            break;
                        }
                        baos.write(byteRead);
                    }
                    is = new ByteArrayInputStream(baos.toByteArray());
                }
                done = true;
            }
        }
    } finally {
        IOUtils.closeStream(appStream);
    }

    return is;
}

From source file:org.apache.synapse.commons.json.JsonDataSourceImpl.java

public JsonDataSourceImpl(InputStream inputStream) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    int c;/*from w ww  .  j  a v  a 2s  .  c om*/
    try {
        while (((c = inputStream.read()) != -1) && Character.isWhitespace((char) c)) {
        }
        ++length;
        if (c == '{') {
            stream.write(WRAPPER_OBJECT.getBytes());
            offset = WRAPPER_OBJECT.length();
        } else if (c == '[') {
            stream.write(WRAPPER_ARRAY.getBytes());
            isObject = false;
            offset = WRAPPER_ARRAY.length();
        } else {
            logger.error("Could not create a JSON data source from the input stream. Found '" + ((char) c)
                    + "' at the start of the input stream.");
            this.stream = EMPTY_OBJECT.getBytes();
            return;
        }
        stream.write(c);
        while (((c = inputStream.read()) != -1)) {
            stream.write(c);
            ++length;
        }
        if (isObject) {
            stream.write(END_OBJECT.getBytes());
        } else {
            stream.write(END_ARRAY.getBytes());
        }
        stream.flush();
        this.stream = stream.toByteArray();
        if (logger.isDebugEnabled()) {
            logger.debug("Built JSON Data Source from the incoming stream.");
        }
    } catch (IOException e) {
        logger.error("Could not create a JSON data source from the input stream. " + e.getLocalizedMessage());
        this.stream = EMPTY_OBJECT.getBytes();
        isObject = true;
    }
}

From source file:org.apache.synapse.commons.json.JsonUtil.java

/**
 * Returns a reader that can read from the JSON payload contained in the provided message context as a JavaScript source.<br/>
 * The reader returns the '(' character at the beginning of the stream and marks the end with the ')' character.<br/>
 * The reader returned by this method can be directly used with the JavaScript {@link javax.script.ScriptEngine#eval(java.io.Reader)} method.
 *
 * @param messageContext Axis2 Message context
 * @return {@link java.io.InputStreamReader}
 *///from w w  w.  ja  va2  s. c o  m
public static Reader newJavaScriptSourceReader(MessageContext messageContext) {
    InputStream jsonStream = jsonStream(messageContext, true);
    if (jsonStream == null) {
        logger.error(
                "#newJavaScriptSourceReader. Could not create a JavaScript source. Error>>> No JSON stream found.");
        return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        out.write('(');
        IOUtils.copy(jsonStream, out);
        out.write(')');
        out.flush();
    } catch (IOException e) {
        logger.error("#newJavaScriptSourceReader. Could not create a JavaScript source. Error>>> "
                + e.getLocalizedMessage());
        return null;
    }
    return new InputStreamReader(new ByteArrayInputStream(out.toByteArray()));
}

From source file:org.apache.xmlgraphics.image.loader.impl.ImageLoaderRawJPEG.java

/** {@inheritDoc} */
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session)
        throws ImageException, IOException {
    if (!MimeConstants.MIME_JPEG.equals(info.getMimeType())) {
        throw new IllegalArgumentException(
                "ImageInfo must be from a image with MIME type: " + MimeConstants.MIME_JPEG);
    }/*  w ww.ja  v a 2s. com*/

    ColorSpace colorSpace = null;
    boolean appeFound = false;
    int sofType = 0;
    ByteArrayOutputStream iccStream = null;

    Source src = session.needSource(info.getOriginalURI());
    ImageInputStream in = ImageUtil.needImageInputStream(src);
    JPEGFile jpeg = new JPEGFile(in);
    in.mark();
    try {
        outer: while (true) {
            int reclen;
            int segID = jpeg.readMarkerSegment();
            if (log.isTraceEnabled()) {
                log.trace("Seg Marker: " + Integer.toHexString(segID));
            }
            switch (segID) {
            case EOI:
                log.trace("EOI found. Stopping.");
                break outer;
            case SOS:
                log.trace("SOS found. Stopping early."); //TODO Not sure if this is safe
                break outer;
            case SOI:
            case NULL:
                break;
            case SOF0: //baseline
            case SOF1: //extended sequential DCT
            case SOF2: //progressive (since PDF 1.3)
            case SOFA: //progressive (since PDF 1.3)
                sofType = segID;
                if (log.isTraceEnabled()) {
                    log.trace("SOF: " + Integer.toHexString(sofType));
                }
                in.mark();
                try {
                    reclen = jpeg.readSegmentLength();
                    in.skipBytes(1); //data precision
                    in.skipBytes(2); //height
                    in.skipBytes(2); //width
                    int numComponents = in.readUnsignedByte();
                    if (numComponents == 1) {
                        colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY);
                    } else if (numComponents == 3) {
                        colorSpace = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
                    } else if (numComponents == 4) {
                        colorSpace = DeviceCMYKColorSpace.getInstance();
                    } else {
                        throw new ImageException("Unsupported ColorSpace for image " + info
                                + ". The number of components supported are 1, 3 and 4.");
                    }
                } finally {
                    in.reset();
                }
                in.skipBytes(reclen);
                break;
            case APP2: //ICC (see ICC1V42.pdf)
                in.mark();
                try {
                    reclen = jpeg.readSegmentLength();
                    // Check for ICC profile
                    byte[] iccString = new byte[11];
                    in.readFully(iccString);
                    in.skipBytes(1); //string terminator (null byte)

                    if ("ICC_PROFILE".equals(new String(iccString, "US-ASCII"))) {
                        in.skipBytes(2); //chunk sequence number and total number of chunks
                        int payloadSize = reclen - 2 - 12 - 2;
                        if (ignoreColorProfile(hints)) {
                            log.debug("Ignoring ICC profile data in JPEG");
                            in.skipBytes(payloadSize);
                        } else {
                            byte[] buf = new byte[payloadSize];
                            in.readFully(buf);
                            if (iccStream == null) {
                                if (log.isDebugEnabled()) {
                                    log.debug("JPEG has an ICC profile");
                                    DataInputStream din = new DataInputStream(new ByteArrayInputStream(buf));
                                    log.debug("Declared ICC profile size: " + din.readInt());
                                }
                                //ICC profiles can be split into several chunks
                                //so collect in a byte array output stream
                                iccStream = new ByteArrayOutputStream();
                            }
                            iccStream.write(buf);
                        }
                    }
                } finally {
                    in.reset();
                }
                in.skipBytes(reclen);
                break;
            case APPE: //Adobe-specific (see 5116.DCT_Filter.pdf)
                in.mark();
                try {
                    reclen = jpeg.readSegmentLength();
                    // Check for Adobe header
                    byte[] adobeHeader = new byte[5];
                    in.readFully(adobeHeader);

                    if ("Adobe".equals(new String(adobeHeader, "US-ASCII"))) {
                        // The reason for reading the APPE marker is that Adobe Photoshop
                        // generates CMYK JPEGs with inverted values. The correct thing
                        // to do would be to interpret the values in the marker, but for now
                        // only assume that if APPE marker is present and colorspace is CMYK,
                        // the image is inverted.
                        appeFound = true;
                    }
                } finally {
                    in.reset();
                }
                in.skipBytes(reclen);
                break;
            default:
                jpeg.skipCurrentMarkerSegment();
            }
        }
    } finally {
        in.reset();
    }

    ICC_Profile iccProfile = buildICCProfile(info, colorSpace, iccStream);
    if (iccProfile == null && colorSpace == null) {
        throw new ImageException("ColorSpace could not be identified for JPEG image " + info);
    }

    boolean invertImage = false;
    if (appeFound && colorSpace.getType() == ColorSpace.TYPE_CMYK) {
        if (log.isDebugEnabled()) {
            log.debug("JPEG has an Adobe APPE marker. Note: CMYK Image will be inverted. ("
                    + info.getOriginalURI() + ")");
        }
        invertImage = true;
    }

    ImageRawJPEG rawImage = new ImageRawJPEG(info, ImageUtil.needInputStream(src), sofType, colorSpace,
            iccProfile, invertImage);
    return rawImage;
}

From source file:org.apache.xmlgraphics.image.loader.impl.ImageLoaderRawJPEG.java

private ICC_Profile buildICCProfile(ImageInfo info, ColorSpace colorSpace, ByteArrayOutputStream iccStream)
        throws IOException, ImageException {
    if (iccStream != null && iccStream.size() > 0) {
        if (log.isDebugEnabled()) {
            log.debug("Effective ICC profile size: " + iccStream.size());
        }/*from  w ww.  j a  v a2 s.  c  o m*/
        final int alignment = 4;
        int padding = (alignment - (iccStream.size() % alignment)) % alignment;
        if (padding != 0) {
            try {
                iccStream.write(new byte[padding]);
            } catch (IOException ioe) {
                throw new IOException("Error while aligning ICC stream: " + ioe.getMessage());
            }
        }

        ICC_Profile iccProfile = null;
        try {
            iccProfile = ICC_Profile.getInstance(iccStream.toByteArray());
            if (log.isDebugEnabled()) {
                log.debug("JPEG has an ICC profile: " + iccProfile.toString());
            }
        } catch (IllegalArgumentException iae) {
            log.warn("An ICC profile is present in the JPEG file but it is invalid (" + iae.getMessage()
                    + "). The color profile will be ignored. (" + info.getOriginalURI() + ")");
            return null;
        }
        if (iccProfile.getNumComponents() != colorSpace.getNumComponents()) {
            log.warn("The number of components of the ICC profile (" + iccProfile.getNumComponents()
                    + ") doesn't match the image (" + colorSpace.getNumComponents()
                    + "). Ignoring the ICC color profile.");
            return null;
        } else {
            return iccProfile;
        }
    } else {
        return null; //no ICC profile available
    }
}

From source file:org.apache.xmlgraphics.util.io.ASCII85InputStreamTestCase.java

private byte[] getFullASCIIRange() {
    java.io.ByteArrayOutputStream baout = new java.io.ByteArrayOutputStream(256);
    for (int i = 254; i < 256; i++) {
        baout.write(i);
    }//  www  . ja  va2 s  .c  om
    return baout.toByteArray();
}

From source file:org.asynchttpclient.ntlm.NtlmTest.java

@Test(expectedExceptions = NtlmEngineException.class)
public void testGenerateType3MsgThworsExceptionWhenType2IndicatorNotPresent() throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    buf.write("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
    buf.write(0);/*ww w  . j  av a2s . c o m*/
    // 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");
}

From source file:org.asynchttpclient.ntlm.NtlmTest.java

@Test(expectedExceptions = NtlmEngineException.class)
public void testGenerateType3MsgThrowsExceptionWhenUnicodeSupportNotIndicated() throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    buf.write("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
    buf.write(0);/* w  w w.  j ava  2  s. c  o  m*/
    // type 2 indicator
    buf.write(2);
    buf.write(0);
    buf.write(0);
    buf.write(0);

    buf.write(longToBytes(1L)); // we want to write a Long

    // flags
    buf.write(0);// unicode support indicator
    buf.write(0);
    buf.write(0);
    buf.write(0);

    buf.write(longToBytes(1L));// challenge
    NtlmEngine engine = new NtlmEngine();
    engine.generateType3Msg("username", "password", "localhost", "workstation",
            Base64.encode(buf.toByteArray()));
    buf.close();
    fail("An NtlmEngineException must have occurred as unicode support is not indicated");
}

From source file:org.asynchttpclient.ntlm.NtlmTest.java

@Test
public void testGenerateType3Msg() throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    buf.write("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
    buf.write(0);// w  ww  .  j ava 2 s .  c o m
    // type 2 indicator
    buf.write(2);
    buf.write(0);
    buf.write(0);
    buf.write(0);

    buf.write(longToBytes(0L)); // we want to write a Long

    // flags
    buf.write(1);// unicode support indicator
    buf.write(0);
    buf.write(0);
    buf.write(0);

    buf.write(longToBytes(1L));// challenge
    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");
}

From source file:org.commonjava.util.partyline.BinaryFileTest.java

private void writeBinaryFile(OutputStream jos, ByteArrayOutputStream written) throws IOException {
    try {/*w ww . j a v a  2  s  . co m*/
        for (int i = 0; i < 255; i++) {
            jos.write(i);
            written.write(i);
        }
    } finally {
        IOUtils.closeQuietly(jos);
    }
}