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:com.sshtools.common.automate.RemoteIdentification.java

/**
 *
 *
 * @param sftp//  w  w w .  j  a  v a 2 s .  co m
 * @param serverId
 * @param system
 * @param username
 * @param keys
 * @param authorizationFile
 * @param mode
 *
 * @return
 *
 * @throws RemoteIdentificationException
 */
public boolean configureUserAccess(final SftpClient sftp, final String serverId, String system, String username,
        List keys, String authorizationFile, int mode) throws RemoteIdentificationException {
    try {

        if (sftp.isClosed()) {
            throw new RemoteIdentificationException("SFTP connection must be open");
        }

        if (authorizationFile == null) {
            throw new RemoteIdentificationException("authorization file cannot be null");
        }

        if ((mode != ADD_AUTHORIZEDKEY) && (mode != REMOVE_AUTHORIZEDKEY)) {
            throw new RemoteIdentificationException(
                    "Invalid configuration mode specifed in call to configureUserAccess");
        }

        AuthorizedKeys authorizedKeys;
        authorizationFile.replace('\\', '/');

        final String directory = ((authorizationFile.lastIndexOf("/") > 0)
                ? authorizationFile.substring(0, authorizationFile.lastIndexOf("/") + 1)
                : "");

        try {
            // Remove the old backup - ignore the error
            try {
                sftp.rm(authorizationFile + ".bak");
            } catch (IOException ex) {
            }

            // Change the current authorization file to the backup
            sftp.rename(authorizationFile, authorizationFile + ".bak");
            log.info("Opening existing authorized keys file from " + authorizationFile + ".bak");

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            sftp.get(authorizationFile + ".bak", out);

            byte[] backup = out.toByteArray();
            out.close();

            // Obtain the current authoized keys settings
            log.info("Parsing authorized keys file");
            authorizedKeys = AuthorizedKeys.parse(backup, serverId, system, new AuthorizedKeysFileLoader() {
                public byte[] loadFile(String filename) throws IOException {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    sftp.get(directory + filename, out);
                    out.close();

                    return out.toByteArray();
                }
            });
        } catch (IOException ioe) {
            // Could not open so create a new file
            authorizedKeys = new AuthorizedKeys();
        } catch (RemoteIdentificationException rie) {
            throw new RemoteIdentificationException("Open3SP cannot identify the remote host.\n"
                    + "Please email support@open3sp.org with specifying 'remote identification' in the subject and supplying the server type and the follwing data '"
                    + serverId + "'");
        }

        log.info("Updating authorized keys file");

        // Check the existing keys and add any that are not present
        SshPublicKey pk;

        for (Iterator x = keys.iterator(); x.hasNext();) {
            pk = (SshPublicKey) x.next();

            if (!authorizedKeys.containsKey(pk) && (mode == ADD_AUTHORIZEDKEY)) {
                authorizedKeys.addKey(username, pk);
            } else if (authorizedKeys.containsKey(pk) && (mode == REMOVE_AUTHORIZEDKEY)) {
                authorizedKeys.removeKey(pk);
            }
        }

        // Verfiy that the directory exists?
        log.info("Verifying directory " + directory);
        int umask = sftp.umask(0022);
        sftp.mkdirs(directory);

        // Output the new file
        log.info("Writing new authorized keys file to " + authorizationFile);

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        // Output the authorization file to a ByteArrayOutputStream
        out.write(AuthorizedKeys.create(authorizedKeys, serverId, system, new AuthorizedKeysFileSaver() {
            public void saveFile(String filename, byte[] filedata) throws IOException {
                //SftpFile file = null;
                ByteArrayInputStream in = null;

                try {
                    in = new ByteArrayInputStream(filedata);
                    sftp.put(in, directory + filename);
                } catch (IOException ex) {
                    log.info("Error writing public key file to server" + filename, ex);
                } finally {
                    if (in != null) {
                        in.close();
                    }
                }
            }
        }));
        out.close();

        // Copy the new authorisation file to the server
        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

        sftp.umask(0133);
        sftp.put(in, authorizationFile);

        sftp.umask(umask);

        return true;
    } catch (IOException ioe) {
        throw new RemoteIdentificationException(ioe.getMessage());
    } catch (RemoteIdentificationException rie) {
        throw new RemoteIdentificationException("SSHTools cannot identify the remote host.\n"
                + "Please email support@sshtools.com specifying 'remote identification' in the subject, supplying the server type and the following data: '"
                + serverId + "'");
    }
}

From source file:com.octo.captcha.engine.bufferedengine.buffer.DiskCaptchaBuffer.java

/**
 * Gets an entry from the Disk Store.//from www. ja  v  a2 s. co m
 *
 * @return The element
 */
protected synchronized Collection remove(int number, Locale locale) throws IOException {
    if (!isInitalized)
        return new ArrayList(0);
    DiskElement diskElement = null;
    int index = 0;
    boolean diskEmpty = false;

    Collection collection = new UnboundedFifoBuffer();

    //if no locale
    if (!diskElements.containsKey(locale)) {
        return collection;
    }

    try {
        while (!diskEmpty && index < number) {

            // Check if the element is on disk
            try {
                diskElement = (DiskElement) ((LinkedList) diskElements.get(locale)).removeFirst();

                // Load the element
                randomAccessFile.seek(diskElement.position);
                byte[] buffer = new byte[diskElement.payloadSize];
                randomAccessFile.readFully(buffer);
                ByteArrayInputStream instr = new ByteArrayInputStream(buffer);
                ObjectInputStream objstr = new ObjectInputStream(instr);

                collection.add(objstr.readObject());
                instr.close();
                objstr.close();

                freeBlock(diskElement);
                index++;
            } catch (NoSuchElementException e) {
                diskEmpty = true;
                log.debug("disk is empty for locale : " + locale.toString());
            }
        }
    } catch (Exception e) {
        log.error("Error while reading on disk ", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("removed  " + collection.size() + " from disk buffer with locale " + locale.toString());
    }
    return collection;
}

From source file:ch.admin.hermes.etl.load.cmis.AlfrescoCMISClient.java

/**
 * Laedt eine Datei von http://www.hermes.admin.ch in Alfresco hoch.
 * @param parentId Parent Id/*from www .ja  va 2  s.  c  o  m*/
 * @param name Name
 * @param properties Eigenschaften
 * @param localname Lokaler Name wenn Datei oder URL wenn von http://www.hermes.admin.ch
 * @return neu erstelles Dokument
 * @throws Exception Allgemeiner I/O Fehler
 */
private Document postFile(String parentId, String name, HashMap<String, Object> properties, URL url)
        throws IOException, URISyntaxException {
    Folder parent = (Folder) session.getObject(parentId, session.getDefaultContext());

    // Dokument von http://www.hermes.admin.ch holen
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (url != null) {
        HttpGet req = new HttpGet(url.toURI());
        req.addHeader("Accept", "application/json;odata=verbose;charset=utf-8");
        req.addHeader("Content-Type", "application/octet-stream");

        HttpResponse resp = client.execute(req);
        checkError(resp, url.toString());

        byte buf[] = new byte[128 * 32768];
        InputStream inp = resp.getEntity().getContent();
        for (int length; (length = inp.read(buf, 0, buf.length)) > 0;)
            out.write(buf, 0, length);
        out.close();

        EntityUtils.consume(resp.getEntity());
    }
    String mimeType = mimeTypesMap.getContentType(url.getFile());
    if (properties == null)
        properties = new HashMap<String, Object>();

    properties.put("cmis:name", name);
    // This works because we are using the OpenCMIS extension for Alfresco
    properties.put("cmis:objectTypeId", "cmis:document,P:cm:titled");

    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    ContentStream contentStream = new ContentStreamImpl(name, BigInteger.valueOf(out.size()), mimeType, in);
    properties.put(PropertyIds.CONTENT_STREAM_FILE_NAME, name);
    properties.put(PropertyIds.CONTENT_STREAM_LENGTH, out.size());
    properties.put(PropertyIds.CONTENT_STREAM_MIME_TYPE, mimeType);

    Document doc = parent.createDocument(properties, contentStream, VersioningState.MAJOR);
    in.close();
    return (doc);
}

From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java

public boolean parseAndPersistResult(InputStreamReader inputStreamReader, String contentType)
        throws IOException {
    String resultString = parseMultipartEncodedFile(inputStreamReader, contentType, "filename");
    SAXParserFactory factory = SAXParserFactory.newInstance();
    OpenRosaResultsHandler handler = new OpenRosaResultsHandler();
    try {/*w w  w  .  j  av  a2 s  . co m*/
        ByteArrayInputStream streamToParse = new ByteArrayInputStream(resultString.getBytes());
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(streamToParse, handler);
        streamToParse.close();
    } catch (Throwable err) {
        err.printStackTrace();
    }
    String resultId = handler.getResultId();
    String deviceId = handler.getDeviceId();
    String surveyId = handler.getSurveyId();
    if (resultId == null || deviceId == null || surveyId == null) {
        return false;
    } else {
        return persistResult(resultString, surveyId, resultId, deviceId);
    }
}

From source file:org.eclipse.lyo.samples.sharepoint.adapter.ResourceService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("entered do Post for /resource");
    boolean isFileUpload = ServletFileUpload.isMultipartContent(request);
    String contentType = request.getContentType();

    if (!isFileUpload && !IConstants.CT_RDF_XML.equals(contentType)) {
        throw new ShareServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }/*from ww w . ja v a 2 s . 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 ShareServiceException(e);
        }
    }

    ShareStore store = this.getStore();
    if (ShareStore.rdfFormatFromContentType(contentType) != null) {
        try {
            String resUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            SharepointResource resource = new SharepointResource(resUri);
            List<ShareStatement> 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 (ShareServerException e) {
            throw new ShareServiceException(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);
            SharepointResource resource = new SharepointResource(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);
                SharepointResource slideResource = new SharepointResource(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 {
                    ShareValue v = new ShareValue(ShareValueType.URI, slideResource.getUri());
                    resource.appendToSeq(IConstants.SHARE_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 (ShareServerException e) {
            throw new ShareServiceException(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);
            SharepointResource resource = new SharepointResource(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 (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }
    }
}

From source file:org.mrgeo.vector.mrsvector.VectorTile.java

public static VectorTile fromProtobuf(final byte[] buffer, int offset, int length) throws IOException {
    final ByteArrayInputStream stream = new ByteArrayInputStream(buffer, offset, length);
    try {/*from ww w. jav a 2s  . c om*/
        return fromProtobuf(stream);
    } finally {
        stream.close();
    }
}

From source file:org.openmrs.web.servlet.ComplexObsServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from ww w .j a  v a  2 s.c  o m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String obsId = request.getParameter("obsId");
    String view = request.getParameter("view");
    String download = request.getParameter("download");

    HttpSession session = request.getSession();

    if (obsId == null || obsId.length() == 0) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.null");
        return;
    }
    if (!Context.hasPrivilege(PrivilegeConstants.GET_OBS)) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                "Privilege required: " + PrivilegeConstants.GET_OBS);
        session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR,
                request.getRequestURI() + "?" + request.getQueryString());
        response.sendRedirect(request.getContextPath() + "/login.htm");
        return;
    }

    Obs complexObs = Context.getObsService().getComplexObs(Integer.valueOf(obsId), view);
    ComplexData cd = complexObs.getComplexData();
    Object data = cd.getData();

    if (null != download) {
        response.setHeader("Content-Disposition", "attachment; filename=" + cd.getTitle());
        response.setHeader("Pragma", "no-cache");
    }

    String mimeType = cd.getMimeType();

    if (null != mimeType) {
        response.setHeader("Content-Type", mimeType);
    }

    Long length = cd.getLength();
    if (length != null) {
        response.setHeader("Content-Length", String.valueOf(length));
        response.setHeader("Accept-Ranges", "bytes");
    }

    if (data instanceof byte[]) {
        ByteArrayInputStream stream = new ByteArrayInputStream((byte[]) data);
        OpenmrsUtil.copyFile(stream, response.getOutputStream());
    } else if (RenderedImage.class.isAssignableFrom(data.getClass())) {
        RenderedImage img = (RenderedImage) data;
        String[] parts = cd.getTitle().split("\\.");
        String extension = "jpg"; // default extension
        if (parts.length > 0) {
            extension = parts[parts.length - 1];
        }

        ImageIO.write(img, extension, response.getOutputStream());
    } else if (InputStream.class.isAssignableFrom(data.getClass())) {
        InputStream stream = (InputStream) data;
        OpenmrsUtil.copyFile(stream, response.getOutputStream());
        stream.close();
    } else {
        throw new ServletException(
                "Couldn't serialize complex obs data for obsId=" + obsId + " of type " + data.getClass());
    }
}

From source file:Base64.java

/**
 * Attempts to decode Base64 data and deserialize a Java
 * Object within. Returns <tt>null</tt> if there was an error.
 *
 * @param encodedObject The Base64 data to decode
 * @return The decoded and deserialized object
 * @since 1.5/* w w  w. j  a  v  a  2 s. c  om*/
 */
public static Object decodeToObject(String encodedObject) {
    // Decode and gunzip if necessary
    byte[] objBytes = decode(encodedObject);

    java.io.ByteArrayInputStream bais = null;
    java.io.ObjectInputStream ois = null;
    Object obj = null;

    try {
        bais = new java.io.ByteArrayInputStream(objBytes);
        ois = new java.io.ObjectInputStream(bais);

        obj = ois.readObject();
    } // end try
    catch (java.io.IOException e) {
        e.printStackTrace();
        obj = null;
    } // end catch
    catch (java.lang.ClassNotFoundException e) {
        e.printStackTrace();
        obj = null;
    } // end catch
    finally {
        try {
            bais.close();
        } catch (Exception e) {
        }
        try {
            ois.close();
        } catch (Exception e) {
        }
    } // end finally

    return obj;
}

From source file:com.verisign.epp.codec.signedMark.EPPEncodedSignedMark.java

/**
 * Creates an <code>EPPEncodedSignedMark</code> that is initialized by
 * decoding the input <code>byte[]</code>.
 * /*from w  w  w  .  ja v  a2s . c o  m*/
 * @param aEncodedSignedMarkArray
 *        <code>byte[]</code> to decode the attribute values
 * @throws EPPDecodeException
 *         Error decoding the input <code>byte[]</code>.
 */
public EPPEncodedSignedMark(byte[] aEncodedSignedMarkArray) throws EPPDecodeException {
    cat.debug("EPPSignedMark(byte[]): enter");

    byte[] signedMarkXML = null;
    Element elm;
    ByteArrayInputStream is = null;
    try {
        is = new ByteArrayInputStream(aEncodedSignedMarkArray);
        DocumentBuilder parser = new EPPSchemaCachingParser();
        Document doc = parser.parse(is);
        elm = doc.getDocumentElement();
        String base64SignedMark = EPPUtil.getTextContent(elm);
        signedMarkXML = Base64.decodeBase64(base64SignedMark);
    } catch (Exception ex) {
        throw new EPPDecodeException("Error decoding signed mark array: " + ex);
    } finally {
        if (is != null) {
            try {
                is.close();
                is = null;
            } catch (IOException e) {
            }
        }
    }

    super.decode(signedMarkXML);

    cat.debug("EPPSignedMark.decode(byte[]): exit");
}

From source file:org.s23m.cell.serialization.serializer.FileSystemSerializer.java

public String decompressSerializationContent(final byte[] compressedContent) throws IOException {
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(compressedContent);
    final BufferedInputStream bufInputStream = new BufferedInputStream(new GZIPInputStream(inputStream));
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    String decompressedContent;//from  www  .  j a v  a  2 s  .c  om
    final int bufferSize = 1024;
    final byte[] buf = new byte[bufferSize];
    int len;
    while ((len = bufInputStream.read(buf)) > 0) {
        outputStream.write(buf, 0, len);
    }
    decompressedContent = outputStream.toString(CONTENT_ENCODING);
    inputStream.close();
    bufInputStream.close();
    outputStream.close();
    return decompressedContent;
}