Example usage for java.io ByteArrayInputStream read

List of usage examples for java.io ByteArrayInputStream read

Introduction

In this page you can find the example usage for java.io ByteArrayInputStream read.

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads some number of bytes from the input stream and stores them into the buffer array b.

Usage

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

@Override
public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) {/*from   www.j a v  a2s.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:org.fao.geonet.arcgis.ArcSDEApiConnection.java

@Override
public Map<String, String> retrieveMetadata(AtomicBoolean cancelMonitor, String arcSDEVersion)
        throws Exception {
    Log.info(ARCSDE_LOG_MODULE_NAME, "Start retrieve metadata");
    Map<String, String> results = new HashMap<>();
    try {//from  www. j  a  va  2 s .c o  m
        ArcSDEVersionFactory arcSDEVersionFactory = new ArcSDEVersionFactory();
        String metadataTable = arcSDEVersionFactory.getTableName(arcSDEVersion);
        String columnName = arcSDEVersionFactory.getMetadataColumnName(arcSDEVersion);

        // query table containing XML metadata
        SeSqlConstruct sqlConstruct = new SeSqlConstruct();
        String[] tables = { metadataTable };
        sqlConstruct.setTables(tables);
        String[] propertyNames = { columnName, "uuid" };
        SeQuery query = new SeQuery(seConnection);
        query.prepareQuery(propertyNames, sqlConstruct);
        query.execute();

        // it is not documented in the ArcSDE API how you know there are no more rows to fetch!
        // I'm assuming: query.fetch returns null (empiric tests indicate this assumption is correct).
        boolean allRowsFetched = false;
        while (!allRowsFetched) {
            if (cancelMonitor.get()) {
                return Collections.emptyMap();
            }
            SeRow row = query.fetch();

            if (row != null) {
                if (row.getObject(0) != null) {
                    Log.info(ARCSDE_LOG_MODULE_NAME, "Retrieving row metadata");

                    SeColumnDefinition colDef = row.getColumnDef(0);

                    String document = "";

                    if (colDef.getType() == SeColumnDefinition.TYPE_BLOB
                            || colDef.getType() == SeColumnDefinition.TYPE_CLOB) {
                        ByteArrayInputStream bytes = row.getBlob(0);
                        byte[] buff = new byte[bytes.available()];
                        bytes.read(buff);
                        document = new String(buff, Constants.ENCODING);

                    } else if (colDef.getType() == SeColumnDefinition.TYPE_XML) {
                        SeXmlDoc xmlDoc = row.getXml(0);
                        document = xmlDoc.getText();
                    } else if (colDef.getType() == SeColumnDefinition.TYPE_STRING) {
                        document = row.getString(0);
                    }

                    if (StringUtils.isNotEmpty(document)) {
                        String uuid = row.getString(1);
                        results.put(uuid, document);
                    }
                } else {
                    Log.info(ARCSDE_LOG_MODULE_NAME, "Ignoring row without metadata");
                }
            } else {
                allRowsFetched = true;
            }
        }
        query.close();
        Log.info(ARCSDE_LOG_MODULE_NAME,
                "Finished retrieving metadata, found: #" + results.size() + " metadata records");
        return results;
    } catch (SeException x) {
        SeError error = x.getSeError();
        String description = error.getExtError() + " " + error.getExtErrMsg() + " " + error.getErrDesc();
        Log.error(ARCSDE_LOG_MODULE_NAME,
                "Error retrieving the metadata from " + "ArcSDE connection (via API):" + description, x);
        throw new Exception(x);
    }
}

From source file:org.tridas.io.formats.lipd.LiPDFile.java

/**
 * An alternative to the normal saveToString() as this is a binary format
 * /*www  .  jav  a 2s  . c o  m*/
 * @param os
 * @throws IOException
 * @throws WriteException
 */
public void saveToDisk(OutputStream os) throws IOException, WriteException {

    // Create a buffer for reading the files
    byte[] buf = new byte[1024];

    // Create the ZIP file
    ZipOutputStream out = new ZipOutputStream(os);

    // Compress the files

    // Create JSON File
    out.putNextEntry(new ZipEntry("LiPD.jsonld"));
    String json = getJSONFileString();
    ByteArrayInputStream in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
    // Transfer bytes from the file to the ZIP file
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    // Complete the entry
    out.closeEntry();
    in.close();

    // Create CSV File
    out.putNextEntry(new ZipEntry("lipd-data.csv"));
    String[] matrix = flipMatrix();
    String data = "";

    // Remove header
    for (int i = 1; i < matrix.length; i++) {
        data += matrix[i] + "\n";
    }
    in = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
    // Transfer bytes from the file to the ZIP file
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    // Complete the entry
    out.closeEntry();
    in.close();

    // Complete the ZIP file
    out.close();

}

From source file:org.unitedinternet.cosmo.dao.hibernate.HibernateTestHelper.java

/**
 * Verify input stream.//from   w ww .j a  v a 2s  . co m
 * @param is1 The input stream.
 * @param content The content.
 * @throws Exception - if something is wrong this exception is thrown.
 */
public void verifyInputStream(InputStream is1, byte[] content) throws Exception {
    byte[] buf1 = new byte[4096];
    byte[] buf2 = new byte[4096];

    ByteArrayInputStream is2 = new ByteArrayInputStream(content);

    int read1 = is1.read(buf1);
    int read2 = is2.read(buf2);
    while (read1 > 0 || read2 > 0) {
        Assert.assertEquals(read1, read2);

        for (int i = 0; i < read1; i++) {
            Assert.assertEquals(buf1[i], buf2[i]);
        }

        read1 = is1.read(buf1);
        read2 = is2.read(buf2);
    }
}

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 ww .  ja  v  a2 s .c  om*/
 * @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:org.apache.abdera.test.client.util.MultipartRelatedRequestEntityTest.java

License:asdf

public void testMultipartEncoding() throws Exception {
    InputStream input = this.getClass().getResourceAsStream("info.png");
    int BUFF_SIZE = 1024;

    byte[] line = new byte[BUFF_SIZE];
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while (input.read(line) != -1) {
        output.write(line);//from w ww .  ja va 2  s  . co m
    }

    Base64 base64 = new Base64();
    byte[] encoded = base64.encode(output.toByteArray());
    ByteArrayInputStream bi = new ByteArrayInputStream(base64.decode(encoded));

    File f = new File("info-out.png");
    if (f.exists())
        f.delete();
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);

    int end;
    while ((end = bi.read(line)) != -1) {
        fo.write(line, 0, end);
    }

    fo.flush();
    fo.close();
}

From source file:edu.jhuapl.graphs.controller.GraphController.java

public static String zipGraphs(List<GraphObject> graphs, String tempDir, String userId) throws GraphException {
    if (graphs != null && graphs.size() > 0) {
        byte[] byteBuffer = new byte[1024];
        String zipFileName = getUniqueId(userId) + ".zip";

        try {/*w w w . ja  v a 2 s  .  c  o m*/
            File zipFile = new File(tempDir, zipFileName);
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
            boolean hasGraphs = false;

            for (GraphObject graph : graphs) {
                if (graph != null) {
                    byte[] renderedGraph = graph.getRenderedGraph().getData();
                    ByteArrayInputStream in = new ByteArrayInputStream(renderedGraph);
                    int len;

                    zos.putNextEntry(new ZipEntry(graph.getImageFileName()));

                    while ((len = in.read(byteBuffer)) > 0) {
                        zos.write(byteBuffer, 0, len);
                    }

                    in.close();
                    zos.closeEntry();
                    hasGraphs = true;
                }
            }

            zos.close();

            if (hasGraphs) {
                return zipFileName;
            } else {
                return null;
            }
        } catch (IOException e) {
            throw new GraphException("Could not write zip", e);
        }
    }

    return null;
}

From source file:org.apache.abdera2.test.client.MultipartRelatedEntityTest.java

License:asdf

public void testMultipartEncoding() throws Exception {
    InputStream input = this.getClass().getResourceAsStream("info.png");
    int BUFF_SIZE = 1024;

    byte[] line = new byte[BUFF_SIZE];
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while (input.read(line) != -1)
        output.write(line);/*from   w w w . j a v a  2 s.  co  m*/
    input.close();

    Base64 base64 = new Base64();
    byte[] encoded = base64.encode(output.toByteArray());
    ByteArrayInputStream bi = new ByteArrayInputStream(base64.decode(encoded));

    File f = new File("info-out.png");
    if (f.exists())
        f.delete();
    if (f.createNewFile()) {
        FileOutputStream fo = new FileOutputStream(f);
        int end;
        while ((end = bi.read(line)) != -1)
            fo.write(line, 0, end);
        fo.flush();
        fo.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 w  w  .  j av  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();
}

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;//from  www  .j  av  a  2s  .c om
    }

    // 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();

}