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:com.online.restful.UsersSrv.java

@GET
@Produces("application/json")
@Path("/loadImg")
public StreamingOutput loadImg(InputStream requestBodyStream, @Context UriInfo uriInfo) throws IOException {

    String imgId = uriInfo.getQueryParameters().get("imgId").get(0);
    Session session = this.getSessionFactory().openSession();

    try {//from  www. ja v  a2 s .co  m

        session.beginTransaction();

        Image img = (Image) session.load(Image.class, Long.parseLong(imgId));

        BufferedImage originalImage;

        InputStream in = new ByteArrayInputStream(img.getImage());
        originalImage = ImageIO.read(in);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageIO.write(originalImage, "jpg", baos);
        baos.flush();
        final byte[] imageInByte = baos.toByteArray();
        baos.close();

        session.getTransaction().commit();
        session.close();
        return new StreamingOutput() {

            public void write(OutputStream output) throws IOException, WebApplicationException {
                byte[] out = imageInByte;
                output.write(out);
            }
        };
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        session.close();
    }
    return null;

}

From source file:it.govpay.web.rs.dars.anagrafica.tributi.TributiHandler.java

@Override
public Tributo creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaEntry " + this.titoloServizio;
    Tributo entry = null;//from   w  w  w  .j  a  va 2s. 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 jsonObject = JSONObject.fromObject(baos.toString());

        String tipoContabilitaId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".tipoContabilita.id");
        String codContabilitaId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".codContabilita.id");
        String codificaTributoInIuvId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".codificaTributoInIuv.id");

        String tipocontabilitaS = jsonObject.getString(tipoContabilitaId);
        jsonObject.remove(tipoContabilitaId);

        String codContabilitaS = jsonObject.getString(codContabilitaId);
        jsonObject.remove(codContabilitaId);

        String codificaTributoInIuvS = jsonObject.getString(codificaTributoInIuvId);
        jsonObject.remove(codificaTributoInIuvId);

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

        TipiTributoBD tributiBD = new TipiTributoBD(bd);
        TipoTributo t = tributiBD.getTipoTributo(entry.getIdTipoTributo());
        entry.setCodTributo(t.getCodTributo());
        entry.setDescrizione(t.getDescrizione());

        // imposto i valori custom solo se sono valorizzati correttamente. 
        if (StringUtils.isNotEmpty(tipocontabilitaS) && !tipocontabilitaS.endsWith("_p")) {
            TipoContabilta tipoContabilita = TipoContabilta.toEnum(tipocontabilitaS);
            entry.setTipoContabilitaCustom(tipoContabilita);
        }

        if (StringUtils.isNotBlank(codContabilitaS)) {
            entry.setCodContabilitaCustom(codContabilitaS);
        }

        if (StringUtils.isNotBlank(codificaTributoInIuvS)) {
            entry.setCodTributoIuvCustom(codificaTributoInIuvS);
        }

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

From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java

@Override
public String encryptData(final SecureToken data) {
    if (data == null || StringUtils.isBlank(data.getData())) {
        throw new IllegalArgumentException("missing token");
    }//ww w  .j a  v a2s .c  o  m
    try {
        final SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM);
        final int[] paddingSizes = computePaddingLengths(random);

        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
        dataOutputStream.write(generatePadding(paddingSizes[0], random));
        dataOutputStream.writeUTF(data.getData());
        dataOutputStream.writeUTF(createChecksum(data.getData()));
        dataOutputStream.writeLong(data.getTimeStamp());
        dataOutputStream.write(generatePadding(paddingSizes[1], random));

        dataOutputStream.flush();
        final byte[] unsignedDataBytes = byteArrayOutputStream.toByteArray();

        final byte[] md5SigBytes = generateSignature(unsignedDataBytes, 0, unsignedDataBytes.length,
                signatureKeyBytes);
        byteArrayOutputStream.write(md5SigBytes);
        byteArrayOutputStream.flush();

        final byte[] signedDataBytes = byteArrayOutputStream.toByteArray();

        return encrypt(signedDataBytes, encryptionKeyBytes, random);
    } catch (final IOException e) {
        LOG.error("Could not encrypt", e);
        throw new SystemException(e.toString(), e);
    } catch (final GeneralSecurityException e) {
        LOG.error("Could not encrypt", e);
        throw new SystemException(e.toString(), e);
    }
}

From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Function to resize image/*from   w w w .j  av  a2 s.  c om*/
 * @param inputImageRaw input image in byte array
 * @return return resized image in byte array
 * @throws IllegalArgumentException Illegal argument exception
 * @throws IOException IO exception
 * @throws NUllPointerException null pointer exception
 */
private byte[] resizeImage(byte[] inputImageRaw)
        throws IllegalArgumentException, IOException, NullPointerException {

    BufferedImage img = ImageIO.read(new ByteArrayInputStream(inputImageRaw));
    BufferedImage newImg = Scalr.resize(img, Mode.AUTOMATIC, 300, 300);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(newImg, "png", baos);
    baos.flush();
    byte[] output = baos.toByteArray();
    baos.close();
    return output;

}

From source file:microsoft.exchange.webservices.data.autodiscover.request.AutodiscoverRequest.java

/**
 * Executes this instance.//from  ww  w .j  ava  2  s  . com
 *
 * @return the autodiscover response
 * @throws Exception the exception
 */
protected AutodiscoverResponse internalExecute() throws Exception {
    this.validate();
    HttpWebRequest request = null;
    try {
        request = this.service.prepareHttpWebRequestForUrl(this.url);
        this.service.traceHttpRequestHeaders(TraceFlags.AutodiscoverRequestHttpHeaders, request);

        boolean needSignature = this.getService().getCredentials() != null
                && this.getService().getCredentials().isNeedSignature();
        boolean needTrace = this.getService().isTraceEnabledFor(TraceFlags.AutodiscoverRequest);

        OutputStream urlOutStream = request.getOutputStream();
        // OutputStreamWriter out = new OutputStreamWriter(request
        // .getOutputStream());

        ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
        EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.getService(), memoryStream);
        writer.setRequireWSSecurityUtilityNamespace(needSignature);
        this.writeSoapRequest(this.url, writer);

        if (needSignature) {
            this.service.getCredentials().sign(memoryStream);
        }

        if (needTrace) {
            memoryStream.flush();
            this.service.traceXml(TraceFlags.AutodiscoverRequest, memoryStream);
        }
        memoryStream.writeTo(urlOutStream);
        urlOutStream.flush();
        urlOutStream.close();
        memoryStream.close();
        // out.write(memoryStream.toString());
        // out.close();
        request.executeRequest();
        request.getResponseCode();
        if (AutodiscoverRequest.isRedirectionResponse(request)) {
            AutodiscoverResponse response = this.createRedirectionResponse(request);
            if (response != null) {
                return response;
            } else {
                throw new ServiceRemoteException("The service returned an invalid redirection response.");
            }
        }

        memoryStream = new ByteArrayOutputStream();
        InputStream serviceResponseStream = request.getInputStream();

        while (true) {
            int data = serviceResponseStream.read();
            if (-1 == data) {
                break;
            } else {
                memoryStream.write(data);
            }
        }
        memoryStream.flush();
        serviceResponseStream.close();

        if (this.service.isTraceEnabled()) {
            this.service.traceResponse(request, memoryStream);
        }
        ByteArrayInputStream memoryStreamIn = new ByteArrayInputStream(memoryStream.toByteArray());
        EwsXmlReader ewsXmlReader = new EwsXmlReader(memoryStreamIn);

        // WCF may not generate an XML declaration.
        ewsXmlReader.read();
        if (ewsXmlReader.getNodeType().getNodeType() == XmlNodeType.START_DOCUMENT) {
            ewsXmlReader.readStartElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName);
        } else if ((ewsXmlReader.getNodeType().getNodeType() != XmlNodeType.START_ELEMENT)
                || (!ewsXmlReader.getLocalName().equals(XmlElementNames.SOAPEnvelopeElementName))
                || (!ewsXmlReader.getNamespaceUri().equals(EwsUtilities.getNamespaceUri(XmlNamespace.Soap)))) {
            throw new ServiceXmlDeserializationException("The Autodiscover service response was invalid.");
        }

        this.readSoapHeaders(ewsXmlReader);

        AutodiscoverResponse response = this.readSoapBody(ewsXmlReader);

        ewsXmlReader.readEndElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName);

        if (response.getErrorCode() == AutodiscoverErrorCode.NoError) {
            return response;
        } else {
            throw new AutodiscoverResponseException(response.getErrorCode(), response.getErrorMessage());
        }

    } catch (XMLStreamException ex) {
        this.service.traceMessage(TraceFlags.AutodiscoverConfiguration,
                String.format("XML parsing error: %s", ex.getMessage()));

        // Wrap exception
        throw new ServiceRequestException(String.format("The request failed. %s", ex.getMessage()), ex);
    } catch (IOException ex) {
        this.service.traceMessage(TraceFlags.AutodiscoverConfiguration,
                String.format("I/O error: %s", ex.getMessage()));

        // Wrap exception
        throw new ServiceRequestException(String.format("The request failed. %s", ex.getMessage()), ex);
    } catch (Exception ex) {
        // HttpWebRequest httpWebResponse = (HttpWebRequest)ex;

        if (null != request && request.getResponseCode() == 7) {
            if (AutodiscoverRequest.isRedirectionResponse(request)) {
                this.service.processHttpResponseHeaders(TraceFlags.AutodiscoverResponseHttpHeaders, request);

                AutodiscoverResponse response = this.createRedirectionResponse(request);
                if (response != null) {
                    return response;
                }
            } else {
                this.processWebException(ex, request);
            }
        }

        // Wrap exception if the above code block didn't throw
        throw new ServiceRequestException(String.format("The request failed. %s", ex.getMessage()), ex);
    } finally {
        try {
            if (request != null) {
                request.close();
            }
        } catch (Exception e) {
            // do nothing
        }
    }
}

From source file:microsoft.exchange.webservices.data.autodiscover.request.AutodiscoverRequest.java

/**
 * Processes the web exception.//ww  w . jav a 2 s  . c  om
 *
 * @param exception WebException
 * @param req       HttpWebRequest
 */
private void processWebException(Exception exception, HttpWebRequest req) {
    if (null != req) {
        try {
            if (500 == req.getResponseCode()) {
                if (this.service.isTraceEnabledFor(TraceFlags.AutodiscoverRequest)) {
                    ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
                    InputStream serviceResponseStream = AutodiscoverRequest.getResponseStream(req);
                    while (true) {
                        int data = serviceResponseStream.read();
                        if (-1 == data) {
                            break;
                        } else {
                            memoryStream.write(data);
                        }
                    }
                    memoryStream.flush();
                    serviceResponseStream.close();
                    this.service.traceResponse(req, memoryStream);
                    ByteArrayInputStream memoryStreamIn = new ByteArrayInputStream(memoryStream.toByteArray());
                    EwsXmlReader reader = new EwsXmlReader(memoryStreamIn);
                    this.readSoapFault(reader);
                    memoryStream.close();
                } else {
                    InputStream serviceResponseStream = AutodiscoverRequest.getResponseStream(req);
                    EwsXmlReader reader = new EwsXmlReader(serviceResponseStream);
                    SoapFaultDetails soapFaultDetails = this.readSoapFault(reader);
                    serviceResponseStream.close();

                    if (soapFaultDetails != null) {
                        throw new ServiceResponseException(new ServiceResponse(soapFaultDetails));
                    }
                }
            } else {
                this.service.processHttpErrorResponse(req, exception);
            }
        } catch (Exception e) {
            LOG.error(e);
        }
    }
}

From source file:org.asqatasun.rules.test.AbstractRuleImplementationTestCase.java

private byte[] getBinaryImage(String imgUrl) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
    URL url = null;//from w  w w  .j a  v a 2  s . c  o m
    try {
        url = new URL(imgUrl);
    } catch (MalformedURLException ex) {
        LOGGER.error(ex);
    }
    byte[] resultImageAsRawBytes = null;
    try {
        BufferedImage image = ImageIO.read(url);
        // W R I T E
        ImageIO.write(image, getImageExtension(imgUrl), baos);
        // C L O S E
        baos.flush();
        resultImageAsRawBytes = baos.toByteArray();
        baos.close();
    } catch (IOException ex) {
        LOGGER.error(ex);
    }
    return resultImageAsRawBytes;
}

From source file:com.polyvi.xface.extension.contact.XContactsExt.java

/**
 * ??????./*from  ww  w. j  a va 2 s.  c  om*/
 *
 * @param filename
 *            ?????
 * @return  byte 
 * @throws IOException
 */
private byte[] getPhotoBytes(String filename) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {
        int bytesRead = 0;
        long totalBytesRead = 0;
        byte[] data = new byte[XConstant.BUFFER_LEN * 4];
        InputStream in = getDataStreamFromUri(filename);

        while ((bytesRead = in.read(data, 0, data.length)) != -1 && totalBytesRead <= MAX_PHOTO_SIZE) {
            buffer.write(data, 0, bytesRead);
            totalBytesRead += bytesRead;
        }

        in.close();
        buffer.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        XLog.e(CLASS_NAME, e.getMessage(), e);
    } catch (IOException e) {
        e.printStackTrace();
        XLog.e(CLASS_NAME, e.getMessage(), e);
    }
    return buffer.toByteArray();
}

From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterManagedProcess.java

@Override
public void start(String userName, Boolean isUserImpersonate) {
    // start server process
    try {/*from w  w  w.  j  a v a 2  s  .c  om*/
        port = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces();
    } catch (IOException e1) {
        throw new InterpreterException(e1);
    }

    CommandLine cmdLine = CommandLine.parse(interpreterRunner);
    cmdLine.addArgument("-d", false);
    cmdLine.addArgument(interpreterDir, false);
    cmdLine.addArgument("-p", false);
    cmdLine.addArgument(Integer.toString(port), false);
    if (isUserImpersonate && !userName.equals("anonymous")) {
        cmdLine.addArgument("-u", false);
        cmdLine.addArgument(userName, false);
    }
    cmdLine.addArgument("-l", false);
    cmdLine.addArgument(localRepoDir, false);

    executor = new DefaultExecutor();

    ByteArrayOutputStream cmdOut = new ByteArrayOutputStream();
    ProcessLogOutputStream processOutput = new ProcessLogOutputStream(logger);
    processOutput.setOutputStream(cmdOut);

    executor.setStreamHandler(new PumpStreamHandler(processOutput));
    watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);

    try {
        Map procEnv = EnvironmentUtils.getProcEnvironment();
        procEnv.putAll(env);

        logger.info("Run interpreter process {}", cmdLine);
        executor.execute(cmdLine, procEnv, this);
        running = true;
    } catch (IOException e) {
        running = false;
        throw new InterpreterException(e);
    }

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() - startTime < getConnectTimeout()) {
        if (!running) {
            try {
                cmdOut.flush();
            } catch (IOException e) {
                // nothing to do
            }
            throw new InterpreterException(new String(cmdOut.toByteArray()));
        }

        try {
            if (RemoteInterpreterUtils.checkIfRemoteEndpointAccessible("localhost", port)) {
                break;
            } else {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    logger.error("Exception in RemoteInterpreterProcess while synchronized reference "
                            + "Thread.sleep", e);
                }
            }
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Remote interpreter not yet accessible at localhost:" + port);
            }
        }
    }
    processOutput.setOutputStream(null);
}

From source file:org.jboss.arquillian.ce.fabric8.F8OpenShiftAdapter.java

public String exec(Map<String, String> labels, int waitSeconds, String... input) throws Exception {
    List<Pod> pods = client.inAnyNamespace().pods().withLabels(labels).list().getItems();
    if (pods.isEmpty()) {
        throw new IllegalStateException("No such pod: " + labels);
    }/*from  w  w w . j  a  va  2 s  .  co  m*/
    Pod targetPod = pods.get(0);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    client.inNamespace(targetPod.getMetadata().getNamespace()).pods()
            .withName(targetPod.getMetadata().getName()).readingInput(System.in).writingOutput(output)
            .writingError(System.err).withTTY().usingListener(new SimpleListener()).exec(input);

    Thread.sleep(waitSeconds * 1000);

    output.flush();
    return output.toString();
}