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:org.eclipse.lyo.oslc.am.resource.ResourceService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isFileUpload = ServletFileUpload.isMultipartContent(request);
    String contentType = request.getContentType();

    if (!isFileUpload && (RioStore.rdfFormatFromContentType(contentType) == null)) {
        throw new RioServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }//from w  ww . ja v  a 2s.c o  m

    InputStream content = request.getInputStream();

    if (isFileUpload) {
        // being uploaded from a web page
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);

            // find the first (and only) file resource in the post
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    // this is a form field, maybe we can accept a title or descr?
                } else {
                    content = item.getInputStream();
                    contentType = item.getContentType();
                }
            }

        } catch (Exception e) {
            throw new RioServiceException(e);
        }
    }

    RioStore store = this.getStore();
    if (RioStore.rdfFormatFromContentType(contentType) != null) {
        try {
            String resUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(resUri);
            List<RioStatement> statements = store.parse(resUri, content, contentType);
            resource.addStatements(statements);
            String userUri = getUserUri(request.getRemoteUser());

            // if it parsed, then add it to the store.
            store.update(resource, userUri);

            // now get it back, to find 
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }
    } else if (IAmConstants.CT_APP_X_VND_MSPPT.equals(contentType) || isFileUpload) {
        try {

            ByteArrayInputStream bais = isToBais(content);

            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(uri);
            resource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
            resource.addRdfType(IAmConstants.RIO_AM_PPT_DECK);
            String id = resource.getIdentifier();
            String deckTitle = "PPT Deck " + id;
            resource.setTitle(deckTitle);
            resource.setDescription("A Power Point Deck");
            String sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());

            store.storeBinaryResource(bais, id);
            bais.reset();

            SlideShow ppt = new SlideShow(bais);
            Dimension pgsize = ppt.getPageSize();

            Slide[] slide = ppt.getSlides();
            for (int i = 0; i < slide.length; i++) {
                String slideTitle = extractTitle(slide[i]);
                String slideUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
                Resource slideResource = new Resource(slideUri);
                slideResource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
                slideResource.addRdfType(IAmConstants.RIO_AM_PPT_SLIDE);
                String slideId = slideResource.getIdentifier();
                slideResource.setTitle(slideTitle);
                sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + slideId;
                slideResource.setSource(sourceUri);
                slideResource.setSourceContentType(IConstants.CT_IMAGE_PNG);
                store.update(slideResource, userUri);

                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide[i].draw(graphics);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                javax.imageio.ImageIO.write(img, "png", out);
                ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray());
                store.storeBinaryResource(is, slideId);
                out.close();
                is.close();
                try {
                    RioValue v = new RioValue(RioValueType.URI, slideResource.getUri());
                    resource.appendToSeq(IConstants.RIO_NAMESPACE + "slides", v);
                } catch (UnrecognizedValueTypeException e) {
                    // log this?  don't want to throw away everything, since this should never happen
                }
            }

            store.update(resource, userUri);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }

    } else {
        // must be a binary or unknown format, treat as black box
        // normally a service provider will understand this and parse it appropriately
        // however this server will accept any blank box resource

        try {
            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(uri);
            String id = resource.getIdentifier();
            resource.setTitle("Resource " + id);
            resource.setDescription("A binary resource");
            String sourceUri = getBaseUrl() + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());
            store.update(resource, userUri);

            store.storeBinaryResource(content, id);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }
    }
}

From source file:de.javakaffee.web.msm.serializer.javolution.AaltoTranscoderTest.java

private StandardSession javaRoundtrip(final StandardSession session,
        final MemcachedBackupSessionManager manager) throws IOException, ClassNotFoundException {

    final long start1 = System.nanoTime();
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(bos);
    session.writeObjectData(oos);/*from w ww .  ja va  2 s  .c  o m*/
    oos.close();
    bos.close();
    System.out.println("java-ser took " + (System.nanoTime() - start1) / 1000);

    final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    final ObjectInputStream ois = new ObjectInputStream(bis);
    final StandardSession readSession = manager.createEmptySession();
    readSession.readObjectData(ois);
    ois.close();
    bis.close();

    return readSession;
}

From source file:es.jamisoft.comun.utils.compression.Jar.java

private void metaInf() {
    byte[] buf = "Manifest-Version: 1.0\r\nX-COMMENT: www.jamisoft.es - Jose Antonio Jamilena Daza".getBytes();
    ByteArrayInputStream manifest = new ByteArrayInputStream(buf);
    String asDir = "/META-INF/";
    try {/*from  ww w  .  j  a v a  2 s .c  o  m*/
        String lsRutaAbs = "/META-INF/manifest.mf";
        //String lsRutaRelat = lsRutaAbs.substring(isDirectorioRelativoComp.length(), lsRutaAbs.length());
        String lsRutaRelat = lsRutaAbs;
        JarArchiveEntry entry = new JarArchiveEntry(lsRutaRelat);

        sout.putArchiveEntry(entry);

        byte buffer[] = new byte[2048];
        int liLeido = -1;
        int numCaracteresLeidos = 0;

        while ((liLeido = manifest.read(buffer, 0, 2048)) != -1) {
            sout.write(buffer, 0, liLeido);
        }

        sout.flush();
        sout.closeArchiveEntry();
        manifest.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ee.sk.digidoc.SignedDoc.java

/**
 * Reads X509 certificate from a data stream
 * @param data input data in Base64 form
 * @return X509Certificate object/*from  w w  w  . j  a v a 2 s  .  c  om*/
 * @throws EFormException for all errors
 */
public static X509Certificate readCertificate(byte[] data) throws DigiDocException {
    X509Certificate cert = null;
    try {
        ByteArrayInputStream certStream = new ByteArrayInputStream(data);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(certStream);
        certStream.close();
    } catch (Exception ex) {
        m_logger.error("Error reading certificate: " + ex);
        //DigiDocException.handleException(ex, DigiDocException.ERR_READ_CERT);
        return null;
    }
    return cert;
}

From source file:org.apache.lens.driver.hive.TestRemoteHiveDriver.java

/**
 * Read context./* w  w  w  .java 2  s  . co  m*/
 *
 * @param bytes  the bytes
 * @param driver the driver
 * @return the query context
 * @throws IOException            Signals that an I/O exception has occurred.
 * @throws ClassNotFoundException the class not found exception
 */
private QueryContext readContext(byte[] bytes, LensDriver driver) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream in = new ObjectInputStream(bais);
    QueryContext ctx;
    try {
        ctx = (QueryContext) in.readObject();
        ctx.setConf(queryConf);
        boolean driverAvailable = in.readBoolean();
        if (driverAvailable) {
            String driverQualifiedName = in.readUTF();
            ctx.setSelectedDriver(driver);
        }
    } finally {
        in.close();
        bais.close();
    }
    return ctx;
}

From source file:org.apache.solr.search.CursorMark.java

/**
 * Parses the serialized version of a CursorMark from a client 
 * (which must conform to the existing sortSpec) and populates this object.
 *
 * @see #getSerializedTotem/*w  w  w  .j a va2s .c o m*/
 */
public void parseSerializedTotem(final String serialized) {
    if (CURSOR_MARK_START.equals(serialized)) {
        values = null;
        return;
    }
    final SortField[] sortFields = sortSpec.getSort().getSort();
    final List<SchemaField> schemaFields = sortSpec.getSchemaFields();

    List<Object> pieces = null;
    try {
        final byte[] rawData = Base64.base64ToByteArray(serialized);
        ByteArrayInputStream in = new ByteArrayInputStream(rawData);
        try {
            pieces = (List<Object>) codec.unmarshal(in);
            boolean b = false;
            for (Object o : pieces) {
                if (o instanceof BytesRefBuilder || o instanceof BytesRef || o instanceof String) {
                    b = true;
                    break;
                }
            }
            if (b) {
                in.reset();
                pieces = (List<Object>) codec.unmarshal(in);
            }
        } finally {
            in.close();
        }
    } catch (Exception ex) {
        throw new SolrException(ErrorCode.BAD_REQUEST,
                "Unable to parse '" + CURSOR_MARK_PARAM + "' after totem: " + "value must either be '"
                        + CURSOR_MARK_START + "' or the " + "'" + CURSOR_MARK_NEXT
                        + "' returned by a previous search: " + serialized,
                ex);
    }
    assert null != pieces : "pieces wasn't parsed?";

    if (sortFields.length != pieces.size()) {
        throw new SolrException(ErrorCode.BAD_REQUEST,
                CURSOR_MARK_PARAM + " does not work with current sort (wrong size): " + serialized);
    }

    this.values = new ArrayList<>(sortFields.length);

    final BytesRef tmpBytes = new BytesRef();
    for (int i = 0; i < sortFields.length; i++) {

        SortField curSort = sortFields[i];
        SchemaField curField = schemaFields.get(i);
        Object rawValue = pieces.get(i);

        if (null != curField) {
            FieldType curType = curField.getType();
            rawValue = curType.unmarshalSortValue(rawValue);
        }

        this.values.add(rawValue);
    }
}

From source file:com.haulmont.cuba.core.app.FoldersServiceBean.java

@Override
public Folder importFolder(Folder parentFolder, byte[] bytes) throws IOException {
    if (!security.isEntityOpPermitted(Folder.class, EntityOp.CREATE)) {
        throw new AccessDeniedException(PermissionType.ENTITY_OP, Folder.class.getSimpleName());
    }/*from ww  w  .j  a  va2  s  .c  o m*/

    Folder folder = null;
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    ZipArchiveInputStream archiveReader;
    archiveReader = new ZipArchiveInputStream(byteArrayInputStream);
    ZipArchiveEntry archiveEntry;

    while (((archiveEntry = archiveReader.getNextZipEntry()) != null) && (folder == null)) {
        if (archiveEntry.getName().equals("folder.xml")) {
            String xml = new String(IOUtils.toByteArray(archiveReader), StandardCharsets.UTF_8);
            folder = (Folder) createXStream().fromXML(xml);
        }
    }

    byteArrayInputStream.close();

    if (folder != null) {
        checkImportPermissions(folder);
        folder.setParent(parentFolder);
        Transaction tx = persistence.createTransaction();
        try {
            EntityManager em = persistence.getEntityManager();
            em.setSoftDeletion(false);
            Folder existingFolder = em.find(Folder.class, folder.getId());
            if (existingFolder != null) {
                checkImportPermissions(existingFolder);
                folder.setVersion(existingFolder.getVersion());
                folder.setCreateTs(existingFolder.getCreateTs());
                folder.setCreatedBy(existingFolder.getCreatedBy());
            } else {
                User user = userSessionSource.getUserSession().getUser();
                folder.setCreatedBy(user.getLoginLowerCase());
                folder.setCreateTs(timeSource.currentTimestamp());
                folder.setUpdatedBy(null);
                folder.setUpdateTs(null);
                folder.setVersion(0);
            }

            em.merge(folder);
            tx.commit();
        } finally {
            tx.end();
        }
    }
    return folder;
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Loads the store from the repository and stores it locally
 * /*from   w  ww.j a  va2s .c o m*/
 * @throws ResourceException
 */
public void loadStoreFromRepo() throws ResourceException {
    JsonValue keystoreValue = readFromRepo("security/" + resourceName);
    String keystoreString = keystoreValue.get("storeString").asString();
    byte[] keystoreBytes = Base64.decode(keystoreString.getBytes());
    ByteArrayInputStream bais = new ByteArrayInputStream(keystoreBytes);
    try {
        KeyStore keystore = null;
        try {
            keystore = KeyStore.getInstance(store.getType());
            keystore.load(bais, store.getPassword().toCharArray());
        } finally {
            bais.close();
        }
        store.setStore(keystore);
    } catch (Exception e) {
        // Note this may catch NPE from Base64.decode returning null if keyStoreString
        // is null or not a base64-encoded string
        throw new InternalServerErrorException("Error creating keystore from store bytes", e);
    }
}

From source file:org.dasein.cloud.ibm.sce.SCEMethod.java

public @Nonnull Document parseResponse(@Nonnull String responseBody, boolean withWireLogging)
        throws CloudException, InternalException {
    Logger wire = (withWireLogging ? SCE.getLogger(SCEMethod.class, "wire") : null);

    try {/*from   w ww  .  j  a  v  a 2  s  .c om*/
        if (wire != null && wire.isDebugEnabled()) {
            String[] lines = responseBody.split("\n");

            if (lines.length < 1) {
                lines = new String[] { responseBody };
            }
            for (String l : lines) {
                wire.debug(l);
            }
            wire.debug("");
        }
        ByteArrayInputStream bas = new ByteArrayInputStream(responseBody.getBytes());

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = factory.newDocumentBuilder();
        Document doc = parser.parse(bas);

        bas.close();
        return doc;
    } catch (IOException e) {
        throw new CloudException(e);
    } catch (ParserConfigurationException e) {
        throw new CloudException(e);
    } catch (SAXException e) {
        throw new CloudException(e);
    }
}

From source file:com.netflix.zeno.examples.BasicSerializationExample.java

public FastBlobStateEngine deserializeLatestData(byte snapshot[], byte delta[]) {
    /// now we are on the client.  We need to create a state engine, and again
    /// tell it about our data model.
    FastBlobStateEngine stateEngine = new FastBlobStateEngine(new ExampleSerializerFactory());

    /// we need to create a FastBlobReader, which is responsible for reading
    /// serialized blobs.
    FastBlobReader reader = new FastBlobReader(stateEngine);

    /// get a stream from the snapshot file location
    ByteArrayInputStream snapshotStream = new ByteArrayInputStream(snapshot);
    /// get a stream from the delta file location
    ByteArrayInputStream deltaStream = new ByteArrayInputStream(delta);

    try {//  w  w  w  . ja v  a  2  s .c  o m
        /// first read the snapshot
        reader.readSnapshot(snapshotStream);
        /// then apply the delta
        reader.readDelta(deltaStream);
    } catch (IOException e) {
        /// either of these methods throws an exception if the FastBlobReader
        /// is unable to read from the provided stream.
    } finally {
        /// it is your responsibility to close the streams.  The FastBlobReader will not do this.
        try {
            snapshotStream.close();
            deltaStream.close();
        } catch (IOException ignore) {
        }
    }

    return stateEngine;
}