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.nih.nci.cadsr.cadsrpasswordchange.test.TestPasswordReset.java

public byte[] toBytes(InputStream in) throws Exception {
    OutputStream out = null;//from   w  w  w.j a  v a2  s .  co  m
    // Read bytes, decrypt, and write them out.
    int bufferSize = 2048;
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
    byte[] data = new byte[bufferSize];

    while ((nRead = in.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }

    buffer.flush();

    return buffer.toByteArray();
}

From source file:it.govpay.web.rs.dars.anagrafica.stazioni.StazioniHandler.java

@Override
public Stazione creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaEntry " + this.titoloServizio;
    Stazione entry = null;//  w  w  w.j  a  v a 2 s .c  om
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di scrittura
        this.darsService.checkDirittiServizioScrittura(bd, this.funzionalita);

        JsonConfig jsonConfig = new JsonConfig();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Utils.copy(is, baos);

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

        JSONObject jsonObjectStazione = JSONObject.fromObject(baos.toString());
        jsonConfig.setRootClass(Stazione.class);
        entry = (Stazione) JSONObject.toBean(jsonObjectStazione, jsonConfig);

        jsonObjectStazione = JSONObject.fromObject(baos.toString());
        jsonConfig.setRootClass(Intermediario.class);
        Intermediario intermediario = (Intermediario) JSONObject.toBean(jsonObjectStazione, jsonConfig);
        this.codIntermediario = intermediario.getCodIntermediario();

        this.log.info("Esecuzione " + methodName + " completata.");
        return entry;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:org.apache.axis2.transport.http.HTTPWorker.java

public void service(final AxisHttpRequest request, final AxisHttpResponse response,
        final MessageContext msgContext) throws HttpException, IOException {
    ConfigurationContext configurationContext = msgContext.getConfigurationContext();
    final String servicePath = configurationContext.getServiceContextPath();
    final String contextPath = (servicePath.startsWith("/") ? servicePath : "/" + servicePath) + "/";

    String uri = request.getRequestURI();
    String method = request.getMethod();
    String soapAction = HttpUtils.getSoapAction(request);
    InvocationResponse pi;//from  ww w. java 2 s .c  o  m

    if (method.equals(HTTPConstants.HEADER_GET)) {
        if (uri.equals("/favicon.ico")) {
            response.setStatus(HttpStatus.SC_MOVED_PERMANENTLY);
            response.addHeader(new BasicHeader("Location", "http://ws.apache.org/favicon.ico"));
            return;
        }
        if (!uri.startsWith(contextPath)) {
            response.setStatus(HttpStatus.SC_MOVED_PERMANENTLY);
            response.addHeader(new BasicHeader("Location", contextPath));
            return;
        }
        if (uri.endsWith("axis2/services/")) {
            String s = HTTPTransportReceiver.getServicesHTML(configurationContext);
            response.setStatus(HttpStatus.SC_OK);
            response.setContentType("text/html");
            OutputStream out = response.getOutputStream();
            out.write(EncodingUtils.getBytes(s, HTTP.ISO_8859_1));
            return;
        }
        if (uri.indexOf("?") < 0) {
            if (!uri.endsWith(contextPath)) {
                if (uri.endsWith(".xsd") || uri.endsWith(".wsdl")) {
                    HashMap services = configurationContext.getAxisConfiguration().getServices();
                    String file = uri.substring(uri.lastIndexOf("/") + 1, uri.length());
                    if ((services != null) && !services.isEmpty()) {
                        Iterator i = services.values().iterator();
                        while (i.hasNext()) {
                            AxisService service = (AxisService) i.next();
                            InputStream stream = service.getClassLoader()
                                    .getResourceAsStream("META-INF/" + file);
                            if (stream != null) {
                                OutputStream out = response.getOutputStream();
                                response.setContentType("text/xml");
                                ListingAgent.copy(stream, out);
                                out.flush();
                                out.close();
                                return;
                            }
                        }
                    }
                }
            }
        }
        if (uri.endsWith("?wsdl2")) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.length() - 6);
            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    service.printWSDL2(response.getOutputStream(), getHost(request));
                } else {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                }
                return;
            }
        }
        if (uri.endsWith("?wsdl")) {
            /**
             * service name can be hierarchical (axis2/services/foo/1.0.0/Version?wsdl) or
             * normal (axis2/services/Version?wsdl).
             */
            String[] temp = uri.split(configurationContext.getServiceContextPath() + "/");
            String serviceName = temp[1].substring(0, temp[1].length() - 5);

            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    service.printWSDL(response.getOutputStream(), getHost(request));
                } else {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                }
                return;
            }
        }
        if (uri.endsWith("?xsd")) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.length() - 4);
            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    service.printSchema(response.getOutputStream());
                } else {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                }
                return;
            }
        }
        //cater for named xsds - check for the xsd name
        if (uri.indexOf("?xsd=") > 0) {
            // fix for imported schemas
            String[] uriParts = uri.split("[?]xsd=");
            String serviceName = uri.substring(uriParts[0].lastIndexOf("/") + 1, uriParts[0].length());
            String schemaName = uri.substring(uri.lastIndexOf("=") + 1);

            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (!canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                    return;
                }
                //run the population logic just to be sure
                service.populateSchemaMappings();
                //write out the correct schema
                Map schemaTable = service.getSchemaMappingTable();
                XmlSchema schema = (XmlSchema) schemaTable.get(schemaName);
                if (schema == null) {
                    int dotIndex = schemaName.indexOf('.');
                    if (dotIndex > 0) {
                        String schemaKey = schemaName.substring(0, dotIndex);
                        schema = (XmlSchema) schemaTable.get(schemaKey);
                    }
                }
                //schema found - write it to the stream
                if (schema != null) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    schema.write(response.getOutputStream());
                    return;
                } else {
                    InputStream instream = service.getClassLoader()
                            .getResourceAsStream(DeploymentConstants.META_INF + "/" + schemaName);

                    if (instream != null) {
                        response.setStatus(HttpStatus.SC_OK);
                        response.setContentType("text/xml");
                        OutputStream outstream = response.getOutputStream();
                        boolean checkLength = true;
                        int length = Integer.MAX_VALUE;
                        int nextValue = instream.read();
                        if (checkLength)
                            length--;
                        while (-1 != nextValue && length >= 0) {
                            outstream.write(nextValue);
                            nextValue = instream.read();
                            if (checkLength)
                                length--;
                        }
                        outstream.flush();
                        return;
                    } else {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        int ret = service.printXSD(baos, schemaName);
                        if (ret > 0) {
                            baos.flush();
                            instream = new ByteArrayInputStream(baos.toByteArray());
                            response.setStatus(HttpStatus.SC_OK);
                            response.setContentType("text/xml");
                            OutputStream outstream = response.getOutputStream();
                            boolean checkLength = true;
                            int length = Integer.MAX_VALUE;
                            int nextValue = instream.read();
                            if (checkLength)
                                length--;
                            while (-1 != nextValue && length >= 0) {
                                outstream.write(nextValue);
                                nextValue = instream.read();
                                if (checkLength)
                                    length--;
                            }
                            outstream.flush();
                            return;
                        }
                        // no schema available by that name  - send 404
                        response.sendError(HttpStatus.SC_NOT_FOUND, "Schema Not Found!");
                        return;
                    }
                }
            }
        }
        if (uri.indexOf("?wsdl2=") > 0) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("?wsdl2="));
            if (processInternalWSDL(uri, configurationContext, serviceName, response, getHost(request)))
                return;
        }
        if (uri.indexOf("?wsdl=") > 0) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("?wsdl="));
            if (processInternalWSDL(uri, configurationContext, serviceName, response, getHost(request)))
                return;
        }

        String contentType = null;
        Header[] headers = request.getHeaders(HTTPConstants.HEADER_CONTENT_TYPE);
        if (headers != null && headers.length > 0) {
            contentType = headers[0].getValue();
            int index = contentType.indexOf(';');
            if (index > 0) {
                contentType = contentType.substring(0, index);
            }
        }

        // deal with GET request
        pi = RESTUtil.processURLRequest(msgContext, response.getOutputStream(), contentType);

    } else if (method.equals(HTTPConstants.HEADER_POST)) {
        // deal with POST request

        String contentType = request.getContentType();

        if (HTTPTransportUtils.isRESTRequest(contentType)) {
            pi = RESTUtil.processXMLRequest(msgContext, request.getInputStream(), response.getOutputStream(),
                    contentType);
        } else {
            String ip = (String) msgContext.getProperty(MessageContext.TRANSPORT_ADDR);
            if (ip != null) {
                uri = ip + uri;
            }
            pi = HTTPTransportUtils.processHTTPPostRequest(msgContext, request.getInputStream(),
                    response.getOutputStream(), contentType, soapAction, uri);
        }

    } else if (method.equals(HTTPConstants.HEADER_PUT)) {

        String contentType = request.getContentType();
        msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);

        pi = RESTUtil.processXMLRequest(msgContext, request.getInputStream(), response.getOutputStream(),
                contentType);

    } else if (method.equals(HTTPConstants.HEADER_DELETE)) {

        pi = RESTUtil.processURLRequest(msgContext, response.getOutputStream(), null);

    } else {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    Boolean holdResponse = (Boolean) msgContext.getProperty(RequestResponseTransport.HOLD_RESPONSE);
    if (pi.equals(InvocationResponse.SUSPEND) || (holdResponse != null && Boolean.TRUE.equals(holdResponse))) {
        try {
            ((RequestResponseTransport) msgContext.getProperty(RequestResponseTransport.TRANSPORT_CONTROL))
                    .awaitResponse();
        } catch (InterruptedException e) {
            throw new IOException("We were interrupted, so this may not function correctly:" + e.getMessage());
        }
    }

    // Finalize response
    RequestResponseTransport requestResponseTransportControl = (RequestResponseTransport) msgContext
            .getProperty(RequestResponseTransport.TRANSPORT_CONTROL);

    if (TransportUtils.isResponseWritten(msgContext)
            || ((requestResponseTransportControl != null) && requestResponseTransportControl.getStatus()
                    .equals(RequestResponseTransport.RequestResponseTransportStatus.SIGNALLED))) {
        // The response is written or signalled.  The current status is used (probably SC_OK).
    } else {
        // The response may be ack'd, mark the status as accepted.
        response.setStatus(HttpStatus.SC_ACCEPTED);
    }
}

From source file:eu.aniketos.scpm.userinterface.views.ScpmUI.java

/**
 * Read input file and transforms it into String.
 * /*from  w  w w  . j  ava  2 s.  com*/
 * @param is
 *            Input stream that contains the file.
 * @return Output String.
 */
private static String readFileAsString(InputStream is) throws java.io.IOException {

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
    byte[] data = new byte[16384];
    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }
    buffer.flush();

    is.close();
    return buffer.toString();
}

From source file:com.aimluck.eip.services.storage.impl.ALDefaultStorageHandler.java

protected int getFileSize(File file) {
    if (file == null) {
        return -1;
    }/*w w  w . j a v  a  2  s.c om*/

    FileInputStream fileInputStream = null;
    int size = -1;
    try {
        fileInputStream = new FileInputStream(file);
        BufferedInputStream input = new BufferedInputStream(fileInputStream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] b = new byte[512];
        int len = -1;
        while ((len = input.read(b)) != -1) {
            output.write(b, 0, len);
            output.flush();
        }
        input.close();
        fileInputStream.close();

        byte[] fileArray = output.toByteArray();
        size = fileArray.length;
        output.close();
    } catch (FileNotFoundException e) {
        return -1;
    } catch (IOException ioe) {
        return -1;
    }
    return size;
}

From source file:de.mendelson.comm.as2.server.AS2ServerProcessing.java

private void processStatisticExportRequest(IoSession session, StatisticExportRequest request) {
    StatisticExportResponse response = new StatisticExportResponse(request);
    StatisticExport exporter = new StatisticExport(this.configConnection, this.runtimeConnection);
    ByteArrayOutputStream outStream = null;
    try {//  w w w  .  j a  v a  2  s. co m
        outStream = new ByteArrayOutputStream();
        exporter.export(outStream, request.getStartDate(), request.getEndDate(), request.getTimestep(),
                request.getLocalStation(), request.getPartner());
        outStream.flush();
        response.setData(outStream.toByteArray());
    } catch (Throwable e) {
        response.setException(e);
    } finally {
        if (outStream != null) {
            try {
                outStream.close();
            } catch (Exception e) {
                //nop
            }
        }
    }
    //sync respond to the request
    session.write(response);
}

From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java

/**
 * Used to upload entries from networks table to OCID servers.
 *//*ww w  . j  ava 2 s.  co  m*/
private void uploadNetworks() {
    writeToLog("uploadNetworks()");

    String existingFileName = "uploadNetworks.csv";
    String data = null;

    NetworkDBIterator dbIterator = mDatabase.getNonUploadedNetworks();
    try {
        if (dbIterator.getCount() > 0) {
            //timestamp, mcc, mnc, net (network type), nen (network name)
            StringBuilder sb = new StringBuilder("timestamp,mcc,mnc,net,nen" + ((char) 0xA));

            while (dbIterator.hasNext() && uploadThreadRunning) {
                Network network = dbIterator.next();
                sb.append(network.getTimestamp()).append(",");
                sb.append(network.getMcc()).append(",");
                sb.append(network.getMnc()).append(",");
                sb.append(network.getType()).append(",");
                sb.append(network.getName());
                sb.append(((char) 0xA));
            }

            data = sb.toString();

        } else {
            writeToLog("No networks for upload.");
            return;
        }
    } finally {
        dbIterator.close();
    }

    writeToLog("uploadNetworks(): " + data);

    if (uploadThreadRunning) {

        try {
            httppost = new HttpPost(networksUrl);

            HttpResponse response = null;

            writeToLog("Upload request URL: " + httppost.getURI());

            if (uploadThreadRunning) {
                MultipartEntity mpEntity = new MultipartEntity();
                mpEntity.addPart("apikey", new StringBody(apiKey));
                mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(data.getBytes()),
                        "text/csv", existingFileName));

                ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
                // reqEntity is the MultipartEntity instance
                mpEntity.writeTo(bArrOS);
                bArrOS.flush();
                ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
                bArrOS.close();

                bArrEntity.setChunked(false);
                bArrEntity.setContentEncoding(mpEntity.getContentEncoding());
                bArrEntity.setContentType(mpEntity.getContentType());

                httppost.setEntity(bArrEntity);

                response = httpclient.execute(httppost);
                if (response == null) {
                    writeToLog("Upload: null HTTP-response");
                    throw new IllegalStateException("no HTTP-response from server");
                }

                HttpEntity resEntity = response.getEntity();

                writeToLog("Response: " + response.getStatusLine().getStatusCode() + " - "
                        + response.getStatusLine());

                if (resEntity != null) {
                    writeToLog("Response content: " + EntityUtils.toString(resEntity));
                    resEntity.consumeContent();
                }
            }

            if (uploadThreadRunning) {
                if (response == null) {
                    writeToLog(": " + "null response");

                    throw new IllegalStateException("no response");
                }
                if (response.getStatusLine() == null) {
                    writeToLog(": " + "null HTTP-status-line");

                    throw new IllegalStateException("no HTTP-status returned");
                }
                if (response.getStatusLine().getStatusCode() == 200) {
                    mDatabase.setAllNetworksUploaded();
                } else if (response.getStatusLine().getStatusCode() != 200) {
                    throw new IllegalStateException(
                            response.getStatusLine().getStatusCode() + " HTTP-status returned");
                }
            }

        } catch (Exception e) {
            // httppost cancellation throws exceptions
            if (uploadThreadRunning) {
                writeExceptionToLog(e);
            }
        }
    }
}

From source file:com.giri.target.svr.SeleniumTestRunner.java

private String toB64Text(final String text, final boolean compress) throws Exception {
    final byte[] inputbs = text.getBytes(Charset.forName("UTF-8"));

    final byte[] bytesToConvert;
    if (compress) {
        final ByteArrayOutputStream bout = new ByteArrayOutputStream();
        final Deflater d = new Deflater();
        final DeflaterOutputStream dout = new DeflaterOutputStream(bout, d);
        dout.write(inputbs);/* w  w w .jav a 2s.c o  m*/
        dout.close();
        bout.flush();
        bytesToConvert = bout.toByteArray();
    } else {
        bytesToConvert = inputbs;
    }

    final byte[] s64encBts = Base64.encodeBase64(bytesToConvert);

    return new String(s64encBts);
}

From source file:de.hybris.platform.test.MediaTest.java

private byte[] getBytes(final InputStream in) throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final byte[] buffer = new byte[1024 * 64];
    int len;/* w ww.jav a2 s  . c om*/
    while ((len = in.read(buffer)) != -1) {
        out.write(buffer, 0, len);
    }
    out.flush();
    in.close();

    return out.toByteArray();
}

From source file:it.govpay.web.rs.dars.anagrafica.operatori.OperatoriHandler.java

@Override
public Operatore creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaEntry " + this.titoloServizio;
    Operatore entry = null;/*from w ww .  j av  a  2  s  .  co m*/
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di scrittura
        this.darsService.checkDirittiServizioScrittura(bd, this.funzionalita);

        JsonConfig jsonConfig = new JsonConfig();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Utils.copy(is, baos);

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

        Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
        jsonConfig.setClassMap(classMap);

        JSONObject jsonObject = JSONObject.fromObject(baos.toString());

        jsonConfig.setRootClass(Operatore.class);
        entry = (Operatore) JSONObject.toBean(jsonObject, jsonConfig);

        this.log.info("Esecuzione " + methodName + " completata.");
        return entry;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}