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 void write(byte[] b, int off, int len) 

Source Link

Document

Write the bytes to byte array.

Usage

From source file:com.eucalyptus.auth.euare.ldap.LicParserTest.java

private static String readInputAsString(InputStream in) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[512];
    int nRead = 0;
    while ((nRead = in.read(buf)) >= 0) {
        baos.write(buf, 0, nRead);
    }/*from  ww  w  .  j  ava 2  s  .com*/

    return new String(baos.toByteArray(), "UTF-8");
}

From source file:com.eucalyptus.auth.policy.PolicyParserTest.java

private static String readInputAsString(InputStream in) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[512];
    int nRead = 0;
    while ((nRead = in.read(buf)) >= 0) {
        baos.write(buf, 0, nRead);
    }/*from   w w w . ja  va 2s  . c om*/

    String string = new String(baos.toByteArray(), "UTF-8");
    baos.close();
    return string;
}

From source file:com.couchbase.lite.syncgateway.GzippedAttachmentTest.java

private static byte[] getBytesFromInputStream(InputStream is) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024 * 8];
    int len = 0;// ww  w  . j a  va 2s  .  c om
    try {
        while ((len = is.read(buffer)) > 0) {
            os.write(buffer, 0, len);
        }
        os.flush();
    } catch (IOException e) {
        Log.e(Log.TAG, "is.read(buffer) or os.flush() error", e);
        return null;
    }
    return os.toByteArray();
}

From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java

/**
 *
 * @param httpParam/*from   w ww  . j  av a  2 s  . c  om*/
 * @return
 */
public static SimpleHttpResult httpRequest(SimpleHttpParam httpParam) {
    String url = httpParam.getUrl();
    Map<String, Object> parameters = httpParam.getParameters();
    String sMethod = httpParam.getMethod();
    String charSet = httpParam.getCharSet();
    boolean sslVerify = httpParam.isSslVerify();
    int maxResultSize = httpParam.getMaxResultSize();
    Map<String, Object> headers = httpParam.getHeaders();
    int readTimeout = httpParam.getReadTimeout();
    int connectTimeout = httpParam.getConnectTimeout();
    boolean ignoreContentIfUnsuccess = httpParam.isIgnoreContentIfUnsuccess();
    boolean hostnameVerify = httpParam.isHostnameVerify();
    TrustKeyStore trustKeyStore = httpParam.getTrustKeyStore();
    ClientKeyStore clientKeyStore = httpParam.getClientKeyStore();

    if (url == null || url.trim().length() == 0) {
        throw new IllegalArgumentException("invalid url : " + url);
    }
    if (maxResultSize <= 0) {
        throw new IllegalArgumentException("maxResultSize must be positive : " + maxResultSize);
    }
    Charset.forName(charSet);
    HttpURLConnection urlConn = null;
    URL destURL = null;

    String baseUrl = url.trim();
    if (!baseUrl.toLowerCase().startsWith(HTTPS_PREFIX) && !baseUrl.toLowerCase().startsWith(HTTP_PREFIX)) {
        baseUrl = HTTP_PREFIX + baseUrl;
    }

    String method = null;
    if (sMethod != null) {
        method = sMethod.toUpperCase();
    }
    if (method == null || !(method.equals(HTTP_METHOD_POST) || method.equals(HTTP_METHOD_GET))) {
        throw new IllegalArgumentException("invalid http method : " + method);
    }

    int index = baseUrl.indexOf("?");
    if (index > 0) {
        baseUrl = urlEncode(baseUrl, charSet);
    } else if (index == 0) {
        throw new IllegalArgumentException("invalid url : " + url);
    }

    String queryString = mapToQueryString(parameters, charSet);
    String targetUrl = "";
    if (method.equals(HTTP_METHOD_POST)) {
        targetUrl = baseUrl;
    } else {
        if (index > 0) {
            targetUrl = baseUrl + "&" + queryString;
        } else {
            targetUrl = baseUrl + "?" + queryString;
        }
    }
    try {
        destURL = new URL(targetUrl);
        urlConn = (HttpURLConnection) destURL.openConnection();

        setSSLSocketFactory(urlConn, sslVerify, hostnameVerify, trustKeyStore, clientKeyStore);

        boolean hasContentType = false;
        boolean hasUserAgent = false;
        for (String key : headers.keySet()) {
            if ("Content-Type".equalsIgnoreCase(key)) {
                hasContentType = true;
            }
            if ("user-agent".equalsIgnoreCase(key)) {
                hasUserAgent = true;
            }
        }
        if (!hasContentType) {
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=" + charSet);
        }
        if (!hasUserAgent) {
            headers.put("user-agent", "PlatSystem");
        }

        if (headers != null && !headers.isEmpty()) {
            for (Entry<String, Object> entry : headers.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                List<String> values = makeStringList(value);
                for (String v : values) {
                    urlConn.addRequestProperty(key, v);
                }
            }
        }
        urlConn.setDoOutput(true);
        urlConn.setDoInput(true);
        urlConn.setAllowUserInteraction(false);
        urlConn.setUseCaches(false);
        urlConn.setRequestMethod(method);
        urlConn.setConnectTimeout(connectTimeout);
        urlConn.setReadTimeout(readTimeout);

        if (method.equals(HTTP_METHOD_POST)) {
            String postData = queryString.length() == 0 ? httpParam.getPostData() : queryString;
            if (postData != null && postData.trim().length() > 0) {
                OutputStream os = urlConn.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, charSet);
                osw.write(postData);
                osw.flush();
                osw.close();
            }
        }

        int responseCode = urlConn.getResponseCode();
        Map<String, List<String>> responseHeaders = urlConn.getHeaderFields();
        String contentType = urlConn.getContentType();

        SimpleHttpResult result = new SimpleHttpResult(responseCode);
        result.setHeaders(responseHeaders);
        result.setContentType(contentType);

        if (responseCode != 200 && ignoreContentIfUnsuccess) {
            return result;
        }

        InputStream is = urlConn.getInputStream();
        byte[] temp = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int readBytes = is.read(temp);
        while (readBytes > 0) {
            baos.write(temp, 0, readBytes);
            readBytes = is.read(temp);
        }
        String resultString = new String(baos.toByteArray(), charSet); //new String(buffer.array(), charSet);
        baos.close();
        result.setContent(resultString);
        return result;
    } catch (Exception e) {
        logger.warn("connection error : " + e.getMessage());
        return new SimpleHttpResult(e);
    } finally {
        if (urlConn != null) {
            urlConn.disconnect();
        }
    }
}

From source file:io.warp10.continuum.gts.GTSDecoder.java

public static GTSDecoder fromBlock(byte[] block, byte[] key) throws IOException {

    if (block.length < 6) {
        throw new IOException("Invalid block.");
    }//from  www  .  j  a v  a2  s.c  om

    ByteBuffer buffer = ByteBuffer.wrap(block);

    //
    // Extract size
    //

    buffer.order(ByteOrder.BIG_ENDIAN);
    int size = buffer.getInt();

    // Check size

    if (block.length != size) {
        throw new IOException("Invalid block size, expected " + size + ", block is " + block.length);
    }

    // Extract compression

    byte comp = buffer.get();

    boolean compress = false;

    if (0 == comp) {
        compress = false;
    } else if (1 == comp) {
        compress = true;
    } else {
        throw new IOException("Invalid compression flag");
    }

    // Extract base timestamp

    long base = Varint.decodeSignedLong(buffer);

    InputStream in;

    ByteArrayInputStream bain = new ByteArrayInputStream(block, buffer.position(), buffer.remaining());

    if (compress) {
        in = new GZIPInputStream(bain);
    } else {
        in = bain;
    }

    byte[] buf = new byte[1024];

    ByteArrayOutputStream out = new ByteArrayOutputStream(buffer.remaining());

    while (true) {
        int len = in.read(buf);

        if (len <= 0) {
            break;
        }
        out.write(buf, 0, len);
    }

    GTSDecoder decoder = new GTSDecoder(base, key, ByteBuffer.wrap(out.toByteArray()));

    return decoder;
}

From source file:inti.core.codec.direct.DirectByteCodec.java

@Override
public byte[] decode(InputStream input) throws Exception {
    ByteArrayOutputStream output = outputs.get();
    byte[] transferBuffer = transferBuffers.get();
    int read;/*  w  w  w .  ja v  a 2 s  .  c  o  m*/

    output.reset();
    while (input.available() > 0 && (read = input.read(transferBuffer)) != -1) {
        output.write(transferBuffer, 0, read);
    }

    return output.toByteArray();
}

From source file:gsn.wrappers.GPSGenerator.java

public boolean initialize() {
    AddressBean addressBean = getActiveAddressBean();
    if (addressBean.getPredicateValue("rate") != null) {
        samplingRate = ParamParser.getInteger(addressBean.getPredicateValue("rate"), DEFAULT_SAMPLING_RATE);
        if (samplingRate <= 0) {
            logger.warn(//from  www . ja v a  2s . c  o  m
                    "The specified >sampling-rate< parameter for the >MemoryMonitoringWrapper< should be a positive number.\nGSN uses the default rate ("
                            + DEFAULT_SAMPLING_RATE + "ms ).");
            samplingRate = DEFAULT_SAMPLING_RATE;
        }
    }
    if (addressBean.getPredicateValue("picture") != null) {
        String picture = addressBean.getPredicateValue("picture");
        File pictureF = new File(picture);
        if (!pictureF.isFile() || !pictureF.canRead()) {
            logger.warn("The GPSGenerator can't access the specified picture file. Initialization failed.");
            return false;
        }
        try {
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(pictureF));
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4 * 1024];
            while (fis.available() > 0)
                outputStream.write(buffer, 0, fis.read(buffer));
            fis.close();
            this.picture = outputStream.toByteArray();
            outputStream.close();
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage(), e);
            return false;
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            return false;
        }
    } else {
        logger.warn("The >picture< parameter is missing from the GPSGenerator wrapper.");
        return false;
    }
    ArrayList<DataField> output = new ArrayList<DataField>();
    for (int i = 0; i < FIELD_NAMES.length; i++)
        output.add(new DataField(FIELD_NAMES[i], FIELD_TYPES_STRING[i], FIELD_DESCRIPTION[i]));
    outputStrcture = output.toArray(new DataField[] {});
    return true;
}

From source file:com.geocent.owf.openlayers.handler.KmzHandler.java

@Override
public String handleContent(HttpServletResponse response, InputStream responseStream) throws IOException {
    ZipInputStream zis = new ZipInputStream(responseStream);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];

    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        if (ze.getName().endsWith("kml")) {
            int len;
            while ((len = zis.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }/*from   w  ww .  ja va2s. com*/

            response.setContentType(ContentTypes.KML.getContentType());
            return new String(baos.toByteArray(), Charset.defaultCharset());
        }

        ze = zis.getNextEntry();
    }

    throw new IOException("Missing KML file entry.");
}

From source file:imc.jettyserver.servlets.Log4jInit.java

private void convertLogFile(File srcConfig, File destConfig, File logDir) {

    // Step 1 read config file into memory
    String srcDoc = "not initialized";
    try {//from www .ja  va2  s .c o m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileInputStream is = new FileInputStream(srcConfig);

        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0) {
            baos.write(buf, 0, len);
        }

        is.close();
        baos.close();
        srcDoc = new String(baos.toByteArray());
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    // Step 2 ; substitute Patterns
    String destDoc = srcDoc.replaceAll("loggerdir", logDir.getAbsolutePath().replaceAll("\\\\", "/"));

    // Step 3 ; write back to file
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(destDoc.getBytes());
        FileOutputStream fos = new FileOutputStream(destConfig);
        byte[] buf = new byte[1024];
        int len;
        while ((len = bais.read(buf)) > 0) {
            fos.write(buf, 0, len);
        }
        fos.close();
        bais.close();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.cgxlib.xq.rebind.JsniBundleGenerator.java

private String inputStreamToString(InputStream in) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    byte[] buffer = new byte[4096];
    int read = in.read(buffer);
    while (read != -1) {
        bytes.write(buffer, 0, read);
        read = in.read(buffer);/*from   w  ww .  jav  a 2s .  c o m*/
    }
    in.close();
    return bytes.toString();
}