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.compiere.model.MMediaServer.java

/**
 *    (Re-)Deploy all media//ww w . j  a  va2 s  .  c  om
 *    @param media array of media to deploy
 *    @return true if deployed
 */
public boolean deploy(MMedia[] media) {
    // Check whether the host is our example localhost, we will not deploy locally, but this is no error
    if (this.getIP_Address().equals("127.0.0.1") || this.getName().equals("localhost")) {
        log.warning("You have not defined your own server, we will not really deploy to localhost!");
        return true;
    }

    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(getIP_Address());
        if (ftp.login(getUserName(), getPassword()))
            log.info("Connected to " + getIP_Address() + " as " + getUserName());
        else {
            log.warning("Could NOT connect to " + getIP_Address() + " as " + getUserName());
            return false;
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "Could NOT connect to " + getIP_Address() + " as " + getUserName(), e);
        return false;
    }

    boolean success = true;
    String cmd = null;
    //   List the files in the directory
    try {
        cmd = "cwd";
        ftp.changeWorkingDirectory(getFolder());
        //
        cmd = "list";
        String[] fileNames = ftp.listNames();
        log.log(Level.FINE, "Number of files in " + getFolder() + ": " + fileNames.length);

        /*
        FTPFile[] files = ftp.listFiles();
        log.config("Number of files in " + getFolder() + ": " + files.length);
        for (int i = 0; i < files.length; i++)
           log.fine(files[i].getTimestamp() + " \t" + files[i].getName());*/
        //
        cmd = "bin";
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        //
        for (int i = 0; i < media.length; i++) {
            if (!media[i].isSummary()) {
                log.log(Level.INFO, " Deploying Media Item:" + media[i].get_ID() + media[i].getExtension());
                MImage thisImage = media[i].getImage();

                // Open the file and output streams
                byte[] buffer = thisImage.getData();
                ByteArrayInputStream is = new ByteArrayInputStream(buffer);

                String fileName = media[i].get_ID() + media[i].getExtension();
                cmd = "put " + fileName;
                ftp.storeFile(fileName, is);
                is.close();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING, cmd, e);
        success = false;
    }
    //   Logout from the FTP Server and disconnect
    try {
        cmd = "logout";
        ftp.logout();
        cmd = "disconnect";
        ftp.disconnect();
    } catch (Exception e) {
        log.log(Level.WARNING, cmd, e);
    }
    ftp = null;
    return success;
}

From source file:IntergrationTest.OCSPIntegrationTest.java

private X509Certificate getX509Certificate(byte[] bcert) throws CertificateException, IOException {
    if (bcert == null)
        return null;
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(bcert);
    X509Certificate x509cert = (X509Certificate) cf.generateCertificate(bais);
    bais.close();
    return x509cert;
}

From source file:com.ikon.ws.endpoint.DocumentService.java

@WebMethod
public Document create(@WebParam(name = "token") String token, @WebParam(name = "doc") Document doc,
        @WebParam(name = "content") byte[] content)
        throws IOException, UnsupportedMimeTypeException, FileSizeExceededException, UserQuotaExceededException,
        VirusDetectedException, ItemExistsException, PathNotFoundException, AccessDeniedException,
        RepositoryException, DatabaseException, ExtensionException, AutomationException {
    log.debug("create({})", doc);
    DocumentModule dm = ModuleManager.getDocumentModule();
    ByteArrayInputStream bais = new ByteArrayInputStream(content);
    Document newDocument = dm.create(token, doc, bais);
    bais.close();
    log.debug("create: {}", newDocument);
    return newDocument;
}

From source file:com.openkm.ws.endpoint.OKMDocument.java

@WebMethod
public Document create(@WebParam(name = "token") String token, @WebParam(name = "doc") Document doc,
        @WebParam(name = "content") byte[] content)
        throws IOException, UnsupportedMimeTypeException, FileSizeExceededException, UserQuotaExceededException,
        VirusDetectedException, ItemExistsException, PathNotFoundException, AccessDeniedException,
        RepositoryException, DatabaseException, ExtensionException {
    log.debug("create({})", doc);
    DocumentModule dm = ModuleManager.getDocumentModule();
    ByteArrayInputStream bais = new ByteArrayInputStream(content);
    Document newDocument = dm.create(token, doc, bais);
    bais.close();
    log.debug("create: {}", newDocument);
    return newDocument;
}

From source file:eionet.gdem.web.struts.stylesheet.GetStylesheetAction.java

@Override
public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) {/*ww w. j a v a 2s.  c om*/

    ActionMessages errors = new ActionMessages();
    String metaXSLFolder = Properties.metaXSLFolder;
    String tableDefURL = Properties.ddURL;
    DynaValidatorForm loginForm = (DynaValidatorForm) actionForm;
    String id = (String) loginForm.get("id");
    String convId = (String) loginForm.get("conv");

    try {
        ConversionDto conv = Conversion.getConversionById(convId);
        String format = metaXSLFolder + File.separatorChar + conv.getStylesheet();
        String url = tableDefURL + "/GetTableDef?id=" + id;
        ByteArrayInputStream byteIn = XslGenerator.convertXML(url, format);
        int bufLen = 0;
        byte[] buf = new byte[1024];

        // byteIn.re

        response.setContentType("text/xml");
        while ((bufLen = byteIn.read(buf)) != -1) {
            response.getOutputStream().write(buf, 0, bufLen);
        }

        byteIn.close();
        return null;

    } catch (Exception ge) {
        LOGGER.error("Error getting stylesheet", ge);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("label.stylesheet.error.generation"));
        // request.getSession().setAttribute("dcm.errors", errors);
        request.setAttribute("dcm.errors", errors);
        return actionMapping.findForward("fail");
    }

    // return null;

}

From source file:eu.planets_project.pp.plato.util.Downloader.java

/**
 * Starts a client side download. All information provided by parameters.
 *
 * @param file data file contains//from w w w  . j  a  v a 2  s .com
 * @param fileName name of the file (e.g. report.pdf)
 * @param contentType mime type of the content to be downloaded
 */
public void download(byte[] file, String fileName, String contentType) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext context = facesContext.getExternalContext();

    HttpServletResponse response = (HttpServletResponse) context.getResponse();
    response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
    response.setContentLength((int) file.length);
    response.setContentType(contentType);

    try {
        ByteArrayInputStream in = new ByteArrayInputStream(file);
        OutputStream out = response.getOutputStream();

        // Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        out.flush();
        out.close();
        facesContext.responseComplete();
    } catch (IOException ex) {
        log.error("Error in downloadFile: " + ex.getMessage());
        FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "Download couldn't be executed");
        ex.printStackTrace();
    }
}

From source file:com.google.code.ssm.transcoders.JsonTranscoder.java

@Override
public Object decode(final CachedObject data) {
    if ((data.getFlags() & JSON_SERIALIZED) == 0) {
        LOGGER.warn("Cannot decode cached data {} using json transcoder", data);
        throw new RuntimeException("Cannot decode cached data using json transcoder");
    }/*from   www  .  j a  v  a 2s .c  o m*/

    ByteArrayInputStream bais = new ByteArrayInputStream(data.getData());

    try {
        return mapper.readValue(bais, Holder.class).getValue();
    } catch (IOException e) {
        LOGGER.warn(String.format("Error deserializing cached data %s", data.toString()), e);
        throw new RuntimeException(e);
    } finally {
        try {
            bais.close();
        } catch (IOException e) {
            LOGGER.warn("Error while closing stream", e);
        }
    }
}

From source file:ch.rgw.tools.StringTool.java

static private Object StringToObject(final String s) {
    String sx = s.substring(1);/* ww  w  .j  a v a  2 s .c o  m*/
    char pref = s.charAt(0);
    switch (pref) {
    case 'A':
        return sx;
    case 'B':
        return (new Integer(Integer.parseInt(sx)));
    case 'Z':
        byte[] b = dePrintable(sx);
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(b);
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object ret = ois.readObject();
            ois.close();
            bais.close();
            return ret;
        } catch (Exception ex) {
            ExHandler.handle(ex);
            return null;
        }
    }
    return null;
}

From source file:net.big_oh.common.web.servlets.mime.MimeServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger.info(getServletConfig().getServletName() + " invoked.  Requested mime resource: "
            + req.getParameter(REQUESTED_RESOURCE_NAME));

    // Get the name of the requested resource
    String requestedResourceName = req.getParameter(REQUESTED_RESOURCE_NAME);

    if (requestedResourceName == null || requestedResourceName.equals("")) {
        logger.error("Called " + getServletConfig().getServletName() + " without providing a parameter for '"
                + REQUESTED_RESOURCE_NAME + "'");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;/* www. j ava 2 s.c  o  m*/
    }

    // Ensure that the user is allowed to access the requested resource
    if (!isCanUserAccessRequestedResource(requestedResourceName, req.getSession(true))) {
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Get a byte array representation of the resource to be returned in the
    // response
    byte[] resourceBytes = getMimeResourceBytes(requestedResourceName);

    if (resourceBytes == null || resourceBytes.length == 0) {
        logger.error("No resource found under the name \"" + requestedResourceName + "\"");
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Set content length for the response
    resp.setContentLength(resourceBytes.length);

    // Get the MIME type for the resource
    String mimeType = getMimeType(requestedResourceName);

    if (mimeType == null || mimeType.equals("")) {
        logger.error("Failed to get MIME type for the requested resource.");
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Set the content type for the response
    resp.setContentType(mimeType);

    // Control the HTTP caching of the response
    // This setting controls how frequently the cached resource is
    // revalidated (which is not necessarily the same as reloaded)
    resp.setHeader("Cache-Control", "max-age=" + getMaxAgeInSeconds(requestedResourceName));

    // Use streams to return the requested resource
    ByteArrayInputStream in = new ByteArrayInputStream(resourceBytes);
    OutputStream out = resp.getOutputStream();

    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }

    in.close();
    out.close();

}

From source file:org.carlspring.strongbox.artifact.generator.NugetPackageGenerator.java

private void addNugetNuspecFile(Nuspec nuspec, ZipOutputStream zos) throws IOException, JAXBException {
    ZipEntry ze = new ZipEntry(nuspec.getId() + ".nuspec");
    zos.putNextEntry(ze);/*from   w  ww  . j  a  v  a 2 s . c  o  m*/

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    nuspec.saveTo(baos);

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

    byte[] buffer = new byte[4096];
    int len;
    while ((len = bais.read(buffer)) > 0) {
        zos.write(buffer, 0, len);
    }

    bais.close();
    zos.closeEntry();
}