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.mondora.chargify.controller.HttpsXmlChargify.java

protected HttpEntity marshal(Object object) {
    log.debug("marshal() object:{}", object);
    try {//from  w  ww  .jav a  2  s.  c o m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        synchronized (marshaller) {
            marshaller.marshal(object, baos);
        }
        baos.flush();
        ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
        entity.setContentType(APP_XML);
        if (log.isTraceEnabled()) {
            log.trace("marshal() raw HttpsXmlChargify request:{}", new String(baos.toByteArray()));
        }
        log.debug("marshal() returning entity:{}", entity);
        return entity;
    } catch (JAXBException e) {
        log.error("marshal() caught exception", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        log.error("marshal() caught exception", e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.taverna.scufl2.wfdesc.TestConvertToWfdesc.java

private void help(String argName) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream outBuf = new PrintStream(out);

    ByteArrayOutputStream err = new ByteArrayOutputStream();
    PrintStream errBuf = new PrintStream(err);

    try {//w  w  w .j a v a  2s.  c  om
        System.setOut(outBuf);
        System.setErr(errBuf);
        ConvertToWfdesc.main(new String[] { argName });
    } finally {
        restoreStd();
    }
    out.flush();
    out.close();
    err.flush();
    err.close();

    assertEquals(0, err.size());
    String help = out.toString("utf-8");
    //      System.out.println(help);
    assertTrue(help.contains("scufl2-to-wfdesc"));
    assertTrue(help.contains("\nIf no arguments are given"));
}

From source file:de.thm.arsnova.ImageUtils.java

/**
 * Gets the bytestream of an image url.//from   w w  w  .j  a  v a2  s .  co m
 *
 * @param  imageUrl The image url as a {@link String}
 * @return The <code>byte[]</code> of the image on success, otherwise <code>null</code>.
 */
public byte[] convertFileToByteArray(final String imageUrl) {

    try {
        final URL url = new URL(imageUrl);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        final InputStream is = url.openStream();
        final byte[] byteChunk = new byte[CHUNK_SIZE];
        int n;

        while ((n = is.read(byteChunk)) > 0) {
            baos.write(byteChunk, 0, n);
        }

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

        return baos.toByteArray();

    } catch (final MalformedURLException e) {
        LOGGER.error(e.getLocalizedMessage());
    } catch (final IOException e) {
        LOGGER.error(e.getLocalizedMessage());
    }

    return null;
}

From source file:com.yoctopuce.YoctoAPI.YCallbackHub.java

private void loadCallbackCache(InputStream in) throws YAPI_Exception, IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int nRead;/* w w w .  jav  a2s  .com*/
    byte[] data = new byte[16384];

    while ((nRead = in.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }
    buffer.flush();
    String data_str = buffer.toString(_yctx._defaultEncoding);

    if (data_str.length() == 0) {
        String errmsg = "RegisterHub(callback) used without posting YoctoAPI data";
        _output("\n!YoctoAPI:" + errmsg + "\n");
        _callbackCache = null;
        throw new YAPI_Exception(YAPI.IO_ERROR, errmsg);
    } else {
        try {
            _callbackCache = new JSONObject(data_str);
        } catch (JSONException ex) {
            String errmsg = "invalid data:[\n" + ex.toString() + data_str + "\n]";
            _output("\n!YoctoAPI:" + errmsg + "\n");
            _callbackCache = null;
            throw new YAPI_Exception(YAPI.IO_ERROR, errmsg);
        }
        if (!_http_params.getPass().equals("")) {
            MessageDigest mdigest;
            try {
                mdigest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException ex) {
                throw new YAPI_Exception(YAPI.NOT_SUPPORTED, "No MD5 provider");
            }

            // callback data signed, verify signature
            if (!_callbackCache.has("sign")) {
                String errmsg = "missing signature from incoming YoctoHub (callback password required)";
                _output("\n!YoctoAPI:" + errmsg + "\n");
                _callbackCache = null;
                throw new YAPI_Exception(YAPI.UNAUTHORIZED, errmsg);
            }
            String sign = _callbackCache.optString("sign");
            String pass = _http_params.getPass();
            String salt;
            if (pass.length() == 32) {
                salt = pass.toLowerCase();
            } else {
                mdigest.reset();
                mdigest.update(pass.getBytes(_yctx._deviceCharset));
                byte[] md5pass = mdigest.digest();
                salt = YAPIContext._bytesToHexStr(md5pass, 0, md5pass.length);
            }

            data_str = data_str.replace(sign, salt);
            mdigest.reset();
            mdigest.update(data_str.getBytes(_yctx._deviceCharset));
            byte[] md5 = mdigest.digest();
            String check = YAPIContext._bytesToHexStr(md5, 0, md5.length);
            if (!check.equals(sign)) {
                String errmsg = "invalid signature from incoming YoctoHub (invalid callback password)";
                _output("\n!YoctoAPI:" + errmsg + "\n");
                _callbackCache = null;
                throw new YAPI_Exception(YAPI.UNAUTHORIZED, errmsg);
            }
        }
    }
}

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

/**
 * Make a raw http request to specific cluster node.  Node is of the format
 * host:port/context, i.e. "localhost:8983/solr"
 *///from w  ww .j a va2 s . c  om
protected String makeHttpRequest(CloudSolrClient client, String node, String httpMethod, String path,
        byte[] content, String contentType, int expectedStatusCode) throws Exception {
    HttpClient httpClient = client.getLbClient().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);
        httpEntity = response.getEntity();

        assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode());

        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:nz.geek.caffe.jmeter.CrLfTcpClient.java

/**
 * Reads data until the defined EOL byte is reached. If there is no EOL byte
 * defined, then reads until the end of the stream is reached.
 *//* w w  w .  j  a v  a2 s.  co m*/
@Override
public String read(final InputStream is) throws ReadException {

    final ByteArrayOutputStream w = new ByteArrayOutputStream();

    try {

        int count = 0;
        int read = 0;
        int last = -1;

        while (true) {
            read = is.read();

            if (count > 0 && read == '\n' && last == '\r') {
                break;
            }

            w.write(read);

            count++;

            last = read;

        }

        w.flush();

        if (LOG.isDebugEnabled()) {
            LOG.debug("Read: " + w.size() + "\n" + w.toString());
        }

        // cut off last trailing \r
        byte[] assembledData = new byte[count - 1];
        System.arraycopy(w.toByteArray(), 0, assembledData, 0, count - 1);

        return new String(assembledData, this.charset);
    } catch (final IOException e) {
        throw new ReadException("", e, w.toString());
    }
}

From source file:org.opentestsystem.authoring.testauth.rest.FileGroupController.java

/******************************** Grid FS Endpoints ********************************/
@RequestMapping(value = "/fileGroup/gridFsFile/{fileGridId}")
@Secured({ "ROLE_Result Upload Read" })
public ResponseEntity<byte[]> getGridFsFile(@PathVariable final String fileGridId) {
    final ByteArrayOutputStream ret = new ByteArrayOutputStream();
    HttpHeaders responseHeaders;//  w  ww  .j  ava  2s. c  om

    try {
        final GridFSDBFile grid = this.fileGroupService.getGridFsFile(fileGridId);
        grid.writeTo(ret);
        responseHeaders = buildResponseHeaders(ret.toByteArray().length, grid.getFilename(),
                grid.getContentType());

        ret.flush();
    } catch (final IOException e) {
        throw new LocalizedException("document.file.notfound", new String[] { fileGridId }, e);
    }
    return new ResponseEntity<byte[]>(ret.toByteArray(), responseHeaders, HttpStatus.OK);
}

From source file:org.alfresco.extension.countersign.service.ScriptCounterSignService.java

/**
 * Validates a single signature, passed in as a nodeRef String
 * //from w  w w  .  ja  va2  s.co m
 * @param nodeRef
 * @return {signatureValid:[validity],hashValid:[validity]}
 */
public JSONObject validateSignature(String nodeRef) {
    // get the node, make sure it exists
    NodeService ns = serviceRegistry.getNodeService();
    ContentService cs = serviceRegistry.getContentService();
    NodeRef sigNode = new NodeRef(nodeRef);
    boolean signatureValid = false;
    boolean hashValid = false;

    if (ns.exists(sigNode)) {
        try {
            // get the doc has from the time of the sig and the sig itself
            String docHash = String.valueOf(ns.getProperty(sigNode, CounterSignSignatureModel.PROP_DOCHASH));
            ContentReader sigReader = cs.getReader(sigNode, ContentModel.PROP_CONTENT);
            InputStream sigStream = sigReader.getContentInputStream();

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

            // get the signing user's public key
            String person = String
                    .valueOf(ns.getProperty(sigNode, CounterSignSignatureModel.PROP_EXTERNALSIGNER));
            SignatureProvider prov = signatureProviderFactory.getSignatureProvider(person);

            // validate the sig using the public key
            signatureValid = prov.validateSignature(baos.toByteArray(), docHash.getBytes());

            // get the document associated with this sig, and compute the hash
            NodeRef signedDoc = ns.getParentAssocs(sigNode).get(0).getParentRef();
            ContentReader docReader = cs.getReader(signedDoc, ContentModel.PROP_CONTENT);
            String contentHash = new String(prov.computeHash(docReader.getContentInputStream()));
            if (docHash.equals(contentHash)) {
                hashValid = true;
            } else {
                signatureValid = false;
            }
        } catch (IOException ioex) {
            throw new AlfrescoRuntimeException("IOException reading signature: " + ioex.getMessage());
        }
    } else {
        throw new AlfrescoRuntimeException("Node: " + nodeRef + " does not exist");
    }

    // create the JSONObject to return
    JSONObject valid = new JSONObject();
    valid.put(signatureValidName, signatureValid);
    valid.put(hashValidName, hashValid);

    return valid;
}

From source file:io.stallion.contentPublishing.UploadRequestProcessor.java

public void createResized(U uploaded, BufferedImage image, String orgPath, int targetHeight, int targetWidth,
        String postfix, Scalr.Mode scalrMode) throws IOException {
    String imageFormat = uploaded.getExtension();

    BufferedImage scaledImg = Scalr.resize(image, Scalr.Method.QUALITY, scalrMode, targetWidth, targetHeight,
            Scalr.OP_ANTIALIAS);//from www  . ja  va 2  s  .  c  o  m
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int height = scaledImg.getHeight();
    int width = scaledImg.getWidth();
    ImageIO.write(scaledImg, imageFormat, baos);
    baos.flush();
    byte[] scaledImageInByte = baos.toByteArray();
    baos.close();

    String relativePath = FilenameUtils.removeExtension(uploaded.getCloudKey());
    if (!"org".equals(postfix)) {
        relativePath = relativePath + "." + postfix;
    }
    relativePath = relativePath + "." + uploaded.getExtension();
    String thumbnailPath = this.uploadsFolder + relativePath;
    Log.info("Write all byptes to {0}", thumbnailPath);
    FileUtils.writeAllBytes(scaledImageInByte, new File(thumbnailPath));
    Long sizeBytes = new File(thumbnailPath).length();
    //String url = "{cdnUrl}/st-publisher/files/view/" + uploaded.getSecret() + "/" + uploaded.getId() + "/" + postfix + "?ts=" + DateUtils.mils();
    String url = makeRawUrlForFile(uploaded, postfix);
    if (postfix.equals("thumb")) {
        uploaded.setThumbCloudKey(relativePath);
        uploaded.setThumbRawUrl(url);
        uploaded.setThumbHeight(height);
        uploaded.setThumbWidth(width);
    } else if (postfix.equals("small")) {
        uploaded.setSmallCloudKey(relativePath);
        uploaded.setSmallRawUrl(url);
        uploaded.setSmallHeight(height);
        uploaded.setSmallWidth(width);
    } else if (postfix.equals("medium")) {
        uploaded.setMediumCloudKey(relativePath);
        uploaded.setMediumRawUrl(url);
        uploaded.setMediumHeight(height);
        uploaded.setMediumWidth(width);
    } else if (postfix.equals("org")) {
        uploaded.setCloudKey(relativePath);
        uploaded.setRawUrl(url);
        uploaded.setSizeBytes(sizeBytes);
        uploaded.setHeight(height);
        uploaded.setWidth(width);
    }

    //return scaledImageInByte;
}

From source file:com.xpandit.fusionplugin.pentaho.content.FusionApi.java

@POST
@Path("/uploadFile")
@Consumes("multipart/form-data")
@Produces(MimeTypes.JSON)/*from w ww.  j  a v a2  s  . c o m*/
public String store(@FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("path") String path)
        throws JSONException {

    String fileName = checkRelativePathSanity(fileDetail.getFileName()),
            savePath = checkRelativePathSanity(path);
    ByteArrayOutputStream oStream = new ByteArrayOutputStream();
    byte[] contents;
    try {
        IOUtils.copy(uploadedInputStream, oStream);
        oStream.flush();
        contents = oStream.toByteArray();
        oStream.close();
    } catch (IOException e) {
        logger.error(e);
        return buildResponseJson(false, DEFAULT_STORE_ERROR_MESSAGE);
    }

    if (fileName == null) {
        logger.error("parameter fileName must not be null");
        return buildResponseJson(false, DEFAULT_STORE_ERROR_MESSAGE);
    }
    if (!fileName.endsWith(".zip")) {
        logger.error("parameter fileName must be zip file");
        return buildResponseJson(false, "You are only allowed to upload zip files");
    }
    if (savePath == null) {
        logger.error("parameter path must not be null");
        return buildResponseJson(false, DEFAULT_STORE_ERROR_MESSAGE);
    }
    if (contents == null) {
        logger.error("File content must not be null");
        return buildResponseJson(false, DEFAULT_STORE_ERROR_MESSAGE);
    }

    FusionPluginSettings fps = new FusionPluginSettings();
    String basePath = fps.getBasePath() + DEFAULT_STORE_UPLOAD_FOLDER;
    String fullPath = FilenameUtils.normalize(savePath + "/" + fileName);
    if (fileExists(checkRelativePathSanity(fullPath), basePath)) {
        return buildResponseJson(false, "File " + fileName + " already exists!");
    }

    File f;

    if (checkRelativePathSanity(fullPath).startsWith(File.separator)) {
        f = new File(basePath + checkRelativePathSanity(fullPath));
    } else {
        f = new File(basePath + File.separator + checkRelativePathSanity(fullPath));
    }

    FileOutputStream fos;

    try {
        fos = new FileOutputStream(f, false);
        fos.write(contents);
        fos.flush();
        fos.close();
        return buildResponseJson(true, "File " + fileName + " Saved!");
    } catch (FileNotFoundException fnfe) {
        logger.error("Unable to create file. Check permissions on folder " + fullPath, fnfe);
        return buildResponseJson(false, "File " + fileName + " not Saved!");
    } catch (IOException ioe) {
        logger.error("Error caught while writing file", ioe);
        return buildResponseJson(false, "File " + fileName + " not Saved!");
    }
}