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:it.govpay.web.rs.dars.anagrafica.tributi.TipiTributoHandler.java

@Override
public TipoTributo creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaEntry " + this.titoloServizio;
    TipoTributo entry = null;/*from   w w w . j  ava 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();

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

        String tipoContabilitaId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".tipoContabilita.id");
        String tipocontabilitaS = jsonObject.getString(tipoContabilitaId);
        jsonObject.remove(tipoContabilitaId);
        jsonConfig.setRootClass(TipoTributo.class);
        entry = (TipoTributo) JSONObject.toBean(jsonObject, jsonConfig);

        TipoContabilta tipoContabilita = TipoContabilta.toEnum(tipocontabilitaS);
        entry.setTipoContabilitaDefault(tipoContabilita);

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

From source file:no.simule.actions.QueryListener.java

private void resourceModel(String name) {
    if (cd == null) {
        try {//w  w  w .  ja  v  a2  s  . c o  m
            model = getClass().getClassLoader().getResourceAsStream(name);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = model.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();

            model = new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray()));

            InputStream model2 = new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray()));

            load(model2, name);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:com.google.android.dialer.provider.DialerProvider.java

private String executeHttpRequest(Uri uri) throws IOException {
    String charset = null;/*  w w  w .  j  a  v a2s  .c o m*/

    if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
        Log.v("DialerProvider", "executeHttpRequest(" + uri + ")");
    }

    try {
        URLConnection conn = new URL(uri.toString()).openConnection();
        conn.setRequestProperty("User-Agent", mUserAgent);

        InputStream inputStream = conn.getInputStream();
        charset = getCharsetFromContentType(conn.getContentType());

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte[] buf = new byte[1000];
        while (true) {
            int len = inputStream.read(buf);
            if (len <= 0) {
                break;
            }
            outputStream.write(buf, 0, len);
        }

        inputStream.close();
        outputStream.flush();

        return new String(outputStream.toByteArray(), charset);
    } catch (UnsupportedEncodingException e) {
        Log.w("DialerProvider", "Invalid charset: " + charset, e);
    } catch (IOException e) {
        // TODO: Didn't find anything that goes here in byte-code
    }

    // TODO: Is this appropriate?
    return null;
}

From source file:no.simule.actions.QueryListener.java

public void loadModel() {
    resetAll();/*from  ww w.  j a  v  a  2s  .co  m*/
    try {
        if (diagram != null) {
            model = diagram.getInputStream();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = model.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();

            model = new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray()));

            InputStream model2 = new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray()));

            load(model2, diagram != null ? diagram.getSubmittedFileName() : "");
            // CodeGenration code = new CodeGenration();
            // code.genrateClass(cd.getClasses());

        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Model Not Selected", ""));
        }

    } catch (Exception e) {

        e.printStackTrace();
    }

}

From source file:au.com.gaiaresources.bdrs.controller.theme.ThemeControllerTest.java

private byte[] createTestImage() throws IOException {
    BufferedImage img = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2 = (Graphics2D) img.getGraphics();
    Random rand = new Random();
    g2.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));
    g2.fillRect(0, 0, img.getWidth(), img.getHeight());

    ByteArrayOutputStream baos = new ByteArrayOutputStream(img.getWidth() * img.getHeight());
    ImageIO.write(img, "png", baos);
    baos.flush();
    byte[] rawBytes = baos.toByteArray();
    baos.close();/*from   w w w .  jav a  2 s .  com*/

    return rawBytes;
}

From source file:com.vodafone360.people.service.transport.http.photouploadmanager.PhotoUploadManager.java

/**
 * Printing the response.//from w w w .  ja  v  a2  s .  c o  m
 * @param response inoput.
 * @return integer.
 */
final int print(final HttpResponse response) {
    byte[] ret = null;
    int respCode = response.getStatusLine().getStatusCode();
    try {
        HttpEntity entity = response.getEntity();
        if (null != entity) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            InputStream is = entity.getContent();
            if (null != is) {
                int nextByte = 0;
                while ((nextByte = is.read()) != -1) {
                    baos.write(nextByte);
                }
                baos.flush();
                ret = baos.toByteArray();
                baos.close();
                baos = null;
            }
            entity.consumeContent();
        }
        if (Settings.ENABLED_TRANSPORT_TRACE) {
            int length = 0;
            if (ret != null) {
                length = ret.length;
            }
            Log.v("HttpContentUpload-handleApiResponse()", "\n \n \n" + "Response with length " + length
                    + " bytes received " + "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
                    + (length == 0 ? "" : HessianUtils.getInHessian(new ByteArrayInputStream(ret), false)));

        }
    } catch (IOException e) {
        Log.v("HttpContentUpload Exception", "e" + e);
    }

    return respCode;
}

From source file:org.apache.nutch.tools.CommonCrawlDataDumper.java

private byte[] serializeCBORData(String jsonData) {
    CBORFactory factory = new CBORFactory();

    CBORGenerator generator = null;
    ByteArrayOutputStream stream = null;

    try {/*from ww w  .  j  a v a  2 s.  c  om*/
        stream = new ByteArrayOutputStream();
        generator = factory.createGenerator(stream);
        // Writes CBOR tag
        writeMagicHeader(generator);
        generator.writeString(jsonData);
        generator.flush();
        stream.flush();

        return stream.toByteArray();

    } catch (Exception e) {
        LOG.warn("CBOR encoding failed: " + e.getMessage());
    } finally {
        try {
            generator.close();
            stream.close();
        } catch (IOException e) {
            // nothing to do
        }
    }

    return null;
}

From source file:org.apache.sentry.tests.e2e.solr.AbstractSolrSentryTestBase.java

/**
 * Make a raw http request to specific cluster node.  Node is of the format
 * host:port/context, i.e. "localhost:8983/solr"
 */// www .  jav  a 2s . co  m
protected String makeHttpRequest(CloudSolrServer server, String node, String httpMethod, String path,
        byte[] content, String contentType) throws Exception {
    HttpClient httpClient = server.getLbServer().getHttpClient();
    URI uri = new URI("http://" + node + path);
    HttpRequestBase method = null;
    if ("GET".equals(httpMethod)) {
        method = new HttpGet(uri);
    } else if ("HEAD".equals(httpMethod)) {
        method = new HttpHead(uri);
    } else if ("POST".equals(httpMethod)) {
        method = new HttpPost(uri);
    } else if ("PUT".equals(httpMethod)) {
        method = new HttpPut(uri);
    } else {
        throw new IOException("Unsupported method: " + method);
    }

    if (method instanceof HttpEntityEnclosingRequestBase) {
        HttpEntityEnclosingRequestBase entityEnclosing = (HttpEntityEnclosingRequestBase) method;
        ByteArrayEntity entityRequest = new ByteArrayEntity(content);
        entityRequest.setContentType(contentType);
        entityEnclosing.setEntity(entityRequest);
    }

    HttpEntity httpEntity = null;
    boolean success = false;
    String retValue = "";
    try {
        final HttpResponse response = httpClient.execute(method);
        int httpStatus = response.getStatusLine().getStatusCode();
        httpEntity = response.getEntity();

        if (httpEntity != null) {
            InputStream is = httpEntity.getContent();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                IOUtils.copyLarge(is, os);
                os.flush();
            } finally {
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(is);
            }
            retValue = os.toString();
        }
        success = true;
    } finally {
        if (!success) {
            EntityUtils.consumeQuietly(httpEntity);
            method.abort();
        }
    }
    return retValue;
}

From source file:it.cnr.icar.eric.server.common.Utility.java

/**
 *     Get bytes array from InputStream//from w  ww.j  a  va 2s .  c o m
 */
public byte[] getBytesFromInputStream(InputStream is) throws IOException {
    java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();

    while (true) {
        byte[] buffer = new byte[100];
        int noOfBytes = is.read(buffer);

        if (noOfBytes == -1) {
            break;
        } else {
            bos.write(buffer, 0, noOfBytes);
        }
    }

    bos.flush();
    bos.close();

    return bos.toByteArray();
}

From source file:com.vodafone360.people.service.transport.http.HttpConnectionThread.java

/**
 * Handles the synchronous responses for the authentication calls which go
 * against the API directly by adding it to the queue and checking if the
 * response code was a HTTP 200. TODO: this should be refactored into a
 * AuthenticationManager class./*from w w  w.ja v a  2s  .  com*/
 * 
 * @param response The response to add to the decoder.
 * @param reqIds The request IDs the response is to be decoded for.
 * @throws Exception Thrown if the status line could not be read or the
 *             response is null.
 */
public void handleApiResponse(HttpResponse response, List<Integer> reqIds) throws Exception {
    byte[] ret = null;
    if (null != response) {
        if (null != response.getStatusLine()) {
            int respCode = response.getStatusLine().getStatusCode();
            logI("RpgHttpConnectionThread.handleApiResponse()", "HTTP Got response status: " + respCode);
            switch (respCode) {
            case HttpStatus.SC_OK:
            case HttpStatus.SC_CONTINUE:
            case HttpStatus.SC_CREATED:
            case HttpStatus.SC_ACCEPTED:
            case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
            case HttpStatus.SC_NO_CONTENT:
            case HttpStatus.SC_RESET_CONTENT:
            case HttpStatus.SC_PARTIAL_CONTENT:
            case HttpStatus.SC_MULTI_STATUS:
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    InputStream is = entity.getContent();
                    if (null != is) {
                        int nextByte = 0;
                        while ((nextByte = is.read()) != -1) {
                            baos.write(nextByte);
                        }
                        baos.flush();
                        ret = baos.toByteArray();
                        baos.close();
                        baos = null;
                    }
                    entity.consumeContent();
                }

                if (Settings.ENABLED_TRANSPORT_TRACE) {
                    int length = 0;
                    if (ret != null) {
                        length = ret.length;
                    }
                    HttpConnectionThread.logI("ResponseReader.handleApiResponse()",
                            "\n \n \n" + "Response with length " + length + " bytes received "
                                    + "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" + (length == 0 ? ""
                                            : HessianUtils.getInHessian(new ByteArrayInputStream(ret), false)));

                }
                addToDecoder(ret, reqIds);
                break;
            default:
                addErrorToResponseQueue(reqIds);
            }
        } else {
            throw new Exception("Status line of response was null.");
        }
    } else {
        throw new Exception("Response was null.");
    }
}