Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:gov.ca.cwds.rest.util.jni.CmsPKCompressor.java

/**
 * Decompress (inflate) raw bytes of a PK-compressed document.
 * /*from   w  w  w  .j a  v  a  2 s.  c o  m*/
 * @param bytes raw bytes of PK-compressed document.
 * @return byte array of decompressed document
 * @throws IOException If an I/O error occurs
 */
public byte[] decompressBytes(byte[] bytes) throws IOException {
    if (bytes == null) {
        throw new IOException("REQUIRED: bytes to decompress cannot be null");
    }

    final ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    final InputStream iis = new InflateInputStream(bis, true);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(DEFAULT_OUTPUT_SIZE);

    IOUtils.copy(iis, bos);
    iis.close();
    bis.close();
    bos.flush();
    bos.close();

    final byte[] retval = bos.toByteArray();
    LOGGER.debug("CmsPKCompressor.decompress(byte[]): retval len={}", retval.length);
    return retval;
}

From source file:org.appverse.web.framework.backend.frontfacade.gxt.controllers.FileUploadController.java

/**
 * //  w w  w.  j  a v  a2 s.c  o m
------WebKitFormBoundaryx2lXibtD2G3Y2Qkz
Content-Disposition: form-data; name="file"; filename="iphone100x100.png"
Content-Type: image/png
        
        
------WebKitFormBoundaryx2lXibtD2G3Y2Qkz
Content-Disposition: form-data; name="hiddenFileName"
        
iphone100x100.png
------WebKitFormBoundaryx2lXibtD2G3Y2Qkz
Content-Disposition: form-data; name="hiddenMediaCategory"
        
2
------WebKitFormBoundaryx2lXibtD2G3Y2Qkz
Content-Disposition: form-data; name="maxFileSize"
        
14745600000
------WebKitFormBoundaryx2lXibtD2G3Y2Qkz--    */

@POST
@Path("{servicemethodname}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void handleFormUpload(@PathParam("servicemethodname") String servicemethodname,
        @FormDataParam("file") InputStream stream, @FormDataParam("hiddenFileName") String hiddenFileName,
        @FormDataParam("hiddenMediaCategory") String hiddenMediaCategory,
        @FormDataParam("maxFileSize") String maxSize, @Context HttpServletRequest request,
        @Context HttpServletResponse response) throws Exception {

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("hiddenFileName", hiddenFileName);
    parameters.put("hiddenMediaCategory", hiddenMediaCategory);
    parameters.put("maxFileSize", maxSize);

    SecurityHelper.checkXSRFToken(request);

    serviceName.set(servicemethodname.substring(0, servicemethodname.lastIndexOf(".")));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int read = 0;
    byte[] bytes = new byte[1024];

    while ((read = stream.read(bytes)) != -1) {
        baos.write(bytes, 0, read);
    }
    baos.flush();
    baos.close();

    if (baos != null && baos.size() > 0) {
        processCall(response, baos.toByteArray(), parameters);
    } else {
        throw new Exception("The file is empty");
    }
}

From source file:org.apache.stratos.keystore.mgt.KeyStoreGenerator.java

/**
 * Persist the keystore in the gov.registry
 *
 * @param keyStore created Keystore of the tenant
 * @param PKCertificate pub. key of the tenant
 * @throws KeyStoreMgtException Exception when storing the keystore in the registry
 *///from w ww  .ja  va  2 s. c  o m
private void persistKeyStore(KeyStore keyStore, X509Certificate PKCertificate) throws KeyStoreMgtException {
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        keyStore.store(outputStream, password.toCharArray());
        outputStream.flush();
        outputStream.close();

        String keyStoreName = generateKSNameFromDomainName();
        // Use the keystore using the keystore admin
        KeyStoreAdmin keystoreAdmin = new KeyStoreAdmin(tenantId, govRegistry);
        keystoreAdmin.addKeyStore(outputStream.toByteArray(), keyStoreName, password, " ", "JKS", password);

        //Create the pub. key resource
        Resource pubKeyResource = govRegistry.newResource();
        pubKeyResource.setContent(PKCertificate.getEncoded());
        pubKeyResource.addProperty(SecurityConstants.PROP_TENANT_PUB_KEY_FILE_NAME_APPENDER,
                generatePubKeyFileNameAppender());

        govRegistry.put(RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE, pubKeyResource);

        //associate the public key with the keystore
        govRegistry.addAssociation(RegistryResources.SecurityManagement.KEY_STORES + "/" + keyStoreName,
                RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE,
                SecurityConstants.ASSOCIATION_TENANT_KS_PUB_KEY);

    } catch (RegistryException e) {
        String msg = "Error when writing the keystore/pub.cert to registry";
        log.error(msg, e);
        throw new KeyStoreMgtException(msg, e);
    } catch (Exception e) {
        String msg = "Error when processing keystore/pub. cert to be stored in registry";
        log.error(msg, e);
        throw new KeyStoreMgtException(msg, e);
    }
}

From source file:com.impetus.client.crud.datatypes.ByteDataTest.java

/**
 * On insert image in cassandra blob object
 * //from  ww w.j  a  v a2 s  .c om
 * @throws Exception
 *             the exception
 */
@Test
public void onInsertBlobImageCassandra() throws Exception {

    PersonCassandra personWithKey = new PersonCassandra();
    personWithKey.setPersonId("111");

    BufferedImage originalImage = ImageIO.read(new File("src/test/resources/nature.jpg"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(originalImage, "jpg", baos);
    baos.flush();
    byte[] imageInByte = baos.toByteArray();

    baos.close();

    personWithKey.setA(imageInByte);
    em.persist(personWithKey);

    em.clear();

    String qry = "Select p from PersonCassandra p where p.personId = 111";
    Query q = em.createQuery(qry);
    List<PersonCassandra> persons = q.getResultList();
    PersonCassandra person = persons.get(0);

    InputStream in = new ByteArrayInputStream(person.getA());
    BufferedImage bImageFromConvert = ImageIO.read(in);

    ImageIO.write(bImageFromConvert, "jpg", new File("src/test/resources/nature-test.jpg"));

    Assert.assertNotNull(person.getA());
    Assert.assertEquals(new File("src/test/resources/nature.jpg").getTotalSpace(),
            new File("src/test/resources/nature-test.jpg").getTotalSpace());
    Assert.assertEquals(String.valueOf(Hex.encodeHex((byte[]) imageInByte)),
            String.valueOf(Hex.encodeHex((byte[]) person.getA())));

}

From source file:eionet.gdem.utils.xml.XmlSerialization.java

@Override
public ByteArrayInputStream serializeToInStream() throws XmlException {
    ByteArrayInputStream byteInputStream = null;
    try {/*from   w  ww  . j  a v a 2s  . c o  m*/
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        xmlSerializer.setOutputByteStream(byteOutputStream);
        xmlSerializer.serialize(ctx.getDocument());
        byteInputStream = new ByteArrayInputStream(byteOutputStream.toByteArray());
        byteOutputStream.flush();
        byteOutputStream.close();
    } catch (IOException ioe) {
        throw new XmlException("Error occurred while serializing XML document . Reason: " + ioe.getMessage());
    } finally {
    }
    return byteInputStream;
}

From source file:com.k42b3.kadabra.handler.Ssh.java

public byte[] getContent(String path) throws Exception {
    logger.info(basePath + "/" + path);

    InputStream is = channel.get(basePath + "/" + path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[1024];
    int len;//  w  w w. j  a v  a 2  s.  co  m

    len = is.read(buf);

    while (len != -1) {
        baos.write(buf, 0, len);

        len = is.read(buf);
    }

    baos.flush();
    baos.close();

    return baos.toByteArray();
}

From source file:com.cubusmail.server.mail.security.MailPasswordEncryptor.java

public String decryptPassword(byte[] encryptedPassword) {

    Cipher cipher;/*from   w  w w.j av  a  2 s. com*/
    try {
        log.debug("decrypt...");
        cipher = Cipher.getInstance(this.algorithm);
        cipher.init(Cipher.DECRYPT_MODE, this.keyPair.getPrivate());

        CipherInputStream cis = new CipherInputStream(new ByteArrayInputStream(encryptedPassword), cipher);
        ByteArrayOutputStream baosDecryptedData = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int len = 0;
        while ((len = cis.read(buffer)) > 0) {
            baosDecryptedData.write(buffer, 0, len);
        }
        baosDecryptedData.flush();
        cis.close();

        log.debug("...finish");

        return new String(baosDecryptedData.toByteArray());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.htmlhifive.tools.jslint.configure.JSLintConfig.java

/**
 * ??.jslint???.//  w  ww  .  j  ava  2 s. c o  m
 */
void store() {

    Properties properties = new Properties();
    properties.setProperty(KEY_JSLINT_PATH, configBean.getJsLintPath());
    properties.setProperty(KEY_OPTION_PATH, configBean.getOptionFilePath());
    properties.setProperty(KEY_USE_OTHER_PROJECT, Boolean.toString(configBean.isUseOtherProject()));
    properties.setProperty(KEY_OTHER_PROJECT_PATH, configBean.getOtherProjectPath());
    properties.setProperty(KEY_INTERNAL_LIBRARY_LIST, StringUtils.join(configBean.getInternalLibPaths(), ','));
    properties.setProperty(KEY_EXTERNAL_LIBRARY_LIST, StringUtils.join(configBean.getExternalLibPaths(), ','));
    // properties.setProperty(KEY_LIBRARY_LIST,
    // StringUtils.join(configBean.getLibList(), ","));
    // properties.setProperty(KEY_USE_FILTER,
    // Boolean.toString(configBean.isUseFilter()));
    FilterBean[] beans = configBean.getFilterBeans();
    for (int i = 0; i < beans.length; i++) {
        properties.setProperty(KEY_FILTER_REGEX + i, beans[i].toString());
    }
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    InputStream input = null;
    try {
        properties.store(output, "");
        output.flush();
        input = new ByteArrayInputStream(output.toByteArray());
        configProp.refreshLocal(IResource.DEPTH_ZERO, null);

        if (configProp.exists()) {
            configProp.setContents(input, false, false, null);
        } else {
            configProp.create(input, false, null);
        }
    } catch (CoreException e) {
        logger.put(Messages.EM0100, e);
    } catch (IOException e) {
        logger.put(Messages.EM0100, e);
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
    }
}

From source file:de.thm.arsnova.ImageUtils.java

/**
 * Gets the bytestream of an image url.//  w ww  .  j a  v  a 2 s .  c  o m
 * s
 * @param  imageUrl The image url as a {@link String}
 * @return The <code>byte[]</code> of the image on success, otherwise <code>null</code>.
 */
public byte[] convertImageToByteArray(final String imageUrl, final String extension) {

    try {
        final URL url = new URL(imageUrl);
        final BufferedImage image = ImageIO.read(url);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageIO.write(image, extension, baos);

        baos.flush();
        baos.close();
        return baos.toByteArray();

    } catch (final MalformedURLException e) {
        LOGGER.error(e.getLocalizedMessage());
    } catch (final IOException e) {
        LOGGER.error(e.getLocalizedMessage());
    }

    return null;
}

From source file:de.kartheininger.markerclustering.AbstractMapActivity.java

protected ArrayList<String[]> readJson() {
    ArrayList<String[]> data = new ArrayList<String[]>();

    BufferedInputStream inputStream = new BufferedInputStream(
            getResources().openRawResource(R.raw.annotationlocationsjson), IO_BUFFER_SIZE);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {// w ww.  j  a  va 2  s.  c  o  m
        copy(inputStream, outputStream);
        outputStream.flush();
    } catch (IOException e) {
        Log.e(TAG, "Could not load json from resources ");
    } finally {
        closeStream(inputStream);
    }

    try {
        // Parse the data into jsonobject to get original data in form of json.
        // You could also use some library like gson for mapping json to objects
        JSONObject jObject = new JSONObject(outputStream.toString());
        JSONArray jArray = jObject.getJSONArray(Constants.kAnnotationsKey);

        String number, postcode, city, name, lon, lat, street;

        for (int i = 0; i < jArray.length(); i++) {
            JSONObject jsonTmp = jArray.getJSONObject(i);
            number = jsonTmp.getString(Constants.kNumberKey);
            postcode = jsonTmp.getString(Constants.kPostcodeKey);
            city = jsonTmp.getString(Constants.kCityKey);
            name = jsonTmp.getString(Constants.kNameKey);
            lat = jsonTmp.getString(Constants.kLatitudeKey);
            lon = jsonTmp.getString(Constants.kLongitudeKey);
            street = jsonTmp.getString(Constants.kStreetKey);
            data.add(new String[] { number, postcode, city, name, lon, lat, street });
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        closeStream(outputStream);
    }
    return data;
}