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:CertStreamCallback.java

private static void invokeActions(String url, String params, byte[] data, Part[] parts, String accept,
        String contentType, String sessionID, String language, String method, Callback callback) {

    if (params != null && !"".equals(params)) {
        if (url.contains("?")) {
            url = url + "&" + params;
        } else {/* w ww . j  a va2  s. co  m*/
            url = url + "?" + params;
        }
    }

    if (language != null && !"".equals(language)) {
        if (url.contains("?")) {
            url = url + "&language=" + language;
        } else {
            url = url + "?language=" + language;
        }
    }

    HttpMethod httpMethod = null;

    try {
        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        httpMethod = getHttpMethod(url, method);
        if ((httpMethod instanceof PostMethod) || (httpMethod instanceof PutMethod)) {
            if (null != data)
                ((EntityEnclosingMethod) httpMethod).setRequestEntity(new ByteArrayRequestEntity(data));
            if (httpMethod instanceof PostMethod && null != parts)
                ((PostMethod) httpMethod)
                        .setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams()));
        }

        if (sessionID != null) {
            httpMethod.addRequestHeader("Cookie", "JSESSIONID=" + sessionID);
        }

        if (!(httpMethod instanceof PostMethod && null != parts)) {
            if (null != accept && !"".equals(accept))
                httpMethod.addRequestHeader("Accept", accept);
            if (null != contentType && !"".equals(contentType))
                httpMethod.addRequestHeader("Content-Type", contentType);
        }

        int statusCode = httpClient.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            throw ActionException.create(ClientMessages.CON_ERROR1, httpMethod.getStatusLine());
        }

        contentType = null != httpMethod.getResponseHeader("Content-Type")
                ? httpMethod.getResponseHeader("Content-Type").getValue()
                : accept;

        InputStream o = httpMethod.getResponseBodyAsStream();
        if (callback != null) {
            callback.execute(o, contentType, sessionID);
        }

    } catch (Exception e) {
        String result = BizClientUtils.doError(e, contentType);
        ByteArrayInputStream in = null;
        try {
            in = new ByteArrayInputStream(result.getBytes("UTF-8"));
            if (callback != null) {
                callback.execute(in, contentType, null);
            }

        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1.getMessage() + "", e1);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    } finally {
        // 
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:net.brtly.monkeyboard.api.plugin.Bundle.java

/**
 * Factory method that creates a Bundle by deserializing a byte array
 * produced by {@link #toByteArray(Bundle)}
 * /*from w  w w. j  a v  a  2  s . co m*/
 * @param b
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static Bundle fromByteArray(byte[] b) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    ObjectInput in = null;
    try {
        in = new ObjectInputStream(bis);
        return (Bundle) in.readObject();
    } finally {
        bis.close();
        in.close();
    }
}

From source file:cn.sharesdk.analysis.net.NetworkHelper.java

public static String Base64Gzip(String str) {
    ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    String result = null;//from  w ww. j av a  2 s . c  om
    // gzip
    GZIPOutputStream gos;
    try {
        gos = new GZIPOutputStream(baos);
        int count;
        byte data[] = new byte[1024];
        while ((count = bais.read(data, 0, 1024)) != -1) {
            gos.write(data, 0, count);
        }
        gos.finish();
        gos.close();

        byte[] output = baos.toByteArray();
        baos.flush();
        baos.close();
        bais.close();

        result = Base64.encodeToString(output, Base64.NO_WRAP);

    } catch (IOException e) {
        e.printStackTrace();
        Ln.e("NetworkHelper", "Base64Gzip == >>", e);
    }

    //Ln.i("after base64gizp", result);
    return result;
}

From source file:Main.java

/**
 * Compress a String to a zip file that has only one entry like zipName
 * The name shouldn't have .zip//from  w w  w. ja  va 2 s  .  c o m
 * 
 * @param content
 * @param fName
 * @throws IOException 
 */
public static void zipAContentAsFileName(String fName, String content, String charset) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(content.getBytes(charset));
    BufferedInputStream bis = new BufferedInputStream(bais);

    File f = new File(fName);
    File parentFile = f.getParentFile();
    if (!parentFile.exists()) {
        parentFile.mkdirs();
    }
    ZipOutputStream zf = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f + ".zip")));

    ZipEntry entry = new ZipEntry(f.getName());
    zf.putNextEntry(entry);
    byte[] barr = new byte[8192];
    int len = 0;
    while ((len = bis.read(barr)) != -1) {
        zf.write(barr, 0, len);
    }
    zf.flush();
    zf.close();
    bis.close();
    bais.close();
}

From source file:com.runwaysdk.controller.ErrorUtility.java

private static String decompress(String message) {
    try {/*  w  w w.  ja  va2  s .  c  o  m*/
        byte[] bytes = Base64.decode(message);

        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        BufferedInputStream bufis = new BufferedInputStream(new GZIPInputStream(bis));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = bufis.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        String retval = bos.toString();
        bis.close();
        bufis.close();
        bos.close();
        return retval;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.mrgeo.data.raster.RasterWritable.java

public static RasterWritable toWritable(final Raster raster, final Writable payload) throws IOException {
    final byte[] pixels = rasterToBytes(raster);
    final ByteArrayInputStream bis = new ByteArrayInputStream(pixels);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    writeHeader(raster, baos);/*from w ww  .  jav  a2 s .c o  m*/
    IOUtils.copyBytes(bis, baos, pixels.length, false);

    if (payload != null) {
        writePayload(payload, baos);
    }
    bis.close();
    baos.close();
    return new RasterWritable(baos.toByteArray());
}

From source file:org.apache.carbondata.hadoop.util.ObjectSerializationUtil.java

/**
 * Converts Base64 string to object.//  w  ww  .ja va2  s . c o  m
 *
 * @param objectString serialized object in string format
 * @return Object after convert string to object
 * @throws IOException
 */
public static Object convertStringToObject(String objectString) throws IOException {
    if (objectString == null) {
        return null;
    }

    byte[] bytes = Base64.decodeBase64(objectString.getBytes(CarbonCommonConstants.DEFAULT_CHARSET));

    ByteArrayInputStream bais = null;
    GZIPInputStream gis = null;
    ObjectInputStream ois = null;

    try {
        bais = new ByteArrayInputStream(bytes);
        gis = new GZIPInputStream(bais);
        ois = new ObjectInputStream(gis);
        return ois.readObject();
    } catch (ClassNotFoundException e) {
        throw new IOException("Could not read object", e);
    } finally {
        try {
            if (ois != null) {
                ois.close();
            }
            if (gis != null) {
                gis.close();
            }
            if (bais != null) {
                bais.close();
            }
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}

From source file:fr.paris.lutece.plugins.document.modules.solr.indexer.SolrDocIndexer.java

/**
 * GEt the content to index//w w  w . j a  va2s . c om
 * @param document The document
 * @param item The SolR item
 * @return The content
 */
private static String getContentToIndex(Document document, SolrItem item) {
    StringBuilder sbContentToIndex = new StringBuilder();
    sbContentToIndex.append(document.getTitle());
    sbContentToIndex.append(" ");

    for (DocumentAttribute attribute : document.getAttributes()) {
        if (attribute.isSearchable()) {
            if (!attribute.isBinary()) {
                if (PARAMETER_TYPE_GEOLOC.equalsIgnoreCase(attribute.getCodeAttributeType())) {
                    // Geojson attribute, put the address as text if it exists
                    String address = null;
                    GeolocItem geolocItem = null;
                    try {
                        geolocItem = GeolocItem.fromJSON(attribute.getTextValue());
                    } catch (IOException e) {
                        AppLogService.error("SolrDocumentIndexer, error parsing JSON" + e);
                    }
                    if (geolocItem != null && geolocItem.getAddress() != null) {
                        sbContentToIndex.append(geolocItem.getAddress());
                    }
                } else {
                    // Text attributes
                    sbContentToIndex.append(attribute.getTextValue());
                }
                sbContentToIndex.append(" ");

                //Dynamic Field

                if (PARAMETER_TYPE_NUMERICTEXT.equalsIgnoreCase(attribute.getCodeAttributeType())) {
                    Long nI = StringUtils.isNotEmpty(attribute.getTextValue())
                            && StringUtils.isNumeric(attribute.getTextValue().trim())
                                    ? Long.valueOf(attribute.getTextValue().trim())
                                    : 0;
                    item.addDynamicField(attribute.getCode(), nI);
                } else if (PARAMETER_TYPE_GEOLOC.equalsIgnoreCase(attribute.getCodeAttributeType())) {
                    item.addDynamicFieldGeoloc(attribute.getCode(), attribute.getTextValue(),
                            document.getCodeDocumentType());
                } else
                    item.addDynamicField(attribute.getCode(), attribute.getTextValue());
            } else {
                // Binary file attribute
                // Gets indexer depending on the ContentType (ie: "application/pdf" should use a PDF indexer)
                IFileIndexerFactory _factoryIndexer = (IFileIndexerFactory) SpringContextService
                        .getBean(IFileIndexerFactory.BEAN_FILE_INDEXER_FACTORY);
                IFileIndexer indexer = _factoryIndexer.getIndexer(attribute.getValueContentType());

                if (indexer != null) {
                    try {
                        ByteArrayInputStream bais = new ByteArrayInputStream(attribute.getBinaryValue());
                        sbContentToIndex.append(indexer.getContentToIndex(bais));
                        sbContentToIndex.append(" ");
                        bais.close();
                    } catch (IOException e) {
                        AppLogService.error(e.getMessage(), e);
                    }
                } else {
                    AppLogService.debug("No indexer found. Url to this data will be given instead");

                    String strName = attribute.getCode() + "_" + attribute.getCodeAttributeType() + "_url";
                    UrlItem url = new UrlItem(SolrIndexerService.getBaseUrl());
                    url.addParameter(PARAMETER_DOCUMENT_ID, document.getId());
                    url.addParameter(PARAMETER_ATTRIBUTE_ID, attribute.getId());
                    item.addDynamicField(strName, url.getUrl());
                }
            }
        }
    }

    // Index Metadata
    if (document.getXmlMetadata() != null) {
        sbContentToIndex.append(document.getXmlMetadata());
    }

    return sbContentToIndex.toString();
}

From source file:com.clustercontrol.plugin.impl.AsyncTask.java

/**
 * ??XMLSerializable???// ww  w .  j  a v  a 2  s . com
 * @param xml ??XML
 * @return Serializable
 * @throws IOException
 */
public static Serializable decodeXML(String xml) throws IOException {
    ByteArrayInputStream bais = null;
    XMLDecoder dec = null;
    Serializable obj = null;

    try {
        bais = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        dec = new XMLDecoder(bais);
        obj = (Serializable) dec.readObject();
    } catch (UnsupportedEncodingException e) {
        log.warn(e);
    } finally {
        if (dec != null) {
            dec.close();
        }
        if (bais != null) {
            bais.close();
        }
    }

    return obj;
}

From source file:com.rathravane.drumlin.util.JsonBodyReader.java

/**
 * read the bytes for objects. If the bytes contain a single JSON object and the path is
 * not null, the objects are loaded from the value named by path rather than the top-level
 * object./*w ww  . j a v  a  2 s  . co  m*/
 *  
 * @param bytes
 * @param path
 * @return a list of 0 or more JSON objects
 * @throws IOException
 * @throws JSONException
 */
public static List<JSONObject> readBodyForObjects(final byte[] bytes, String path)
        throws IOException, JSONException {
    final LinkedList<JSONObject> result = new LinkedList<JSONObject>();

    // determine the first token in the stream to decide if we're reading a single
    // object or an array.
    boolean isSingleObject = false;
    {
        final ByteArrayInputStream s = new ByteArrayInputStream(bytes);
        final JSONTokener t = new JSONTokener(s);

        char c = t.next();
        while (Character.isWhitespace(c))
            c = t.next();

        switch (c) {
        case '{':
            isSingleObject = true;
            break;
        case '[':
            isSingleObject = false;
            break;
        default:
            throw new JSONException("Expected an object or an array of objects.");
        }
        s.close();
    }

    if (isSingleObject) {
        final String jsonStream = new String(bytes, utf8);
        final JSONObject o = new JSONObject(jsonStream);

        if (path != null) {
            final Object oo = o.opt(path);
            if (oo instanceof JSONObject) {
                result.add((JSONObject) oo);
            } else if (oo instanceof JSONArray) {
                result.addAll(readArrayForObjects((JSONArray) oo));
            } else {
                throw new JSONException("Couldn't read object at path [" + path + "].");
            }
        } else {
            result.add(o);
        }
    } else {
        final String jsonStream = new String(bytes);
        final JSONArray a = new JSONArray(jsonStream);
        result.addAll(readArrayForObjects(a));
    }

    return result;
}