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.karura.framework.plugins.Contacts.java

@JavascriptInterface
@SupportJavascriptInterface//from  w  ww  .  j  av a  2  s  .  com
@Description("Resolve the content URI to a base64 image.")
@Asynchronous(retVal = "Returns the base64 encoded photograph of the specified contact")
@Params({ @Param(name = "callId", description = "The method correlator between javascript and java."),
        @Param(name = "contactContentUri", description = "Content URI of the photograph which was returned by the plugin in the call to getContact API") })
public void getPhoto(final String callId, final String contactContentUri) {
    runInBackground(new Runnable() {
        public void run() {
            try {
                String decodedUri = URLDecoder.decode(contactContentUri, "UTF-8");

                ByteArrayOutputStream buffer = new ByteArrayOutputStream();

                int bytesRead = 0;
                byte[] data = new byte[8192];

                Uri uri = Uri.parse(decodedUri);

                InputStream in = getActivity().getContentResolver().openInputStream(uri);

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

                in.close();
                buffer.flush();

                String base64EncodedImage = Base64.encodeToString(buffer.toByteArray(), Base64.DEFAULT);
                resolveWithResult(callId, base64EncodedImage);

            } catch (Exception e) {
                if (BuildConfig.DEBUG) {
                    e.printStackTrace();
                }
                rejectWithCode(callId, ERR_INVALID_ARG);
            }
        }
    });
}

From source file:com.opensymphony.webwork.util.classloader.compilers.eclipse.EclipseJavaCompiler.java

public void compile(final String[] pClazzNames, final ResourceReader pReader, final ResourceStore pStore,
        final CompilationProblemHandler pProblemHandler) {

    final Map settingsMap = settings.getMap();
    final Set clazzIndex = new HashSet();
    ICompilationUnit[] compilationUnits = new ICompilationUnit[pClazzNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        final String clazzName = pClazzNames[i];
        compilationUnits[i] = new CompilationUnit(pReader, clazzName);
        clazzIndex.add(clazzName);//w w  w  .j a va 2  s. c  o m
        log.debug("compiling " + clazzName);
    }

    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final INameEnvironment nameEnvironment = new INameEnvironment() {

        public NameEnvironmentAnswer findType(final char[][] compoundTypeName) {
            final StringBuffer result = new StringBuffer();
            for (int i = 0; i < compoundTypeName.length; i++) {
                if (i != 0) {
                    result.append('.');
                }
                result.append(compoundTypeName[i]);
            }
            return findType(result.toString());
        }

        public NameEnvironmentAnswer findType(final char[] typeName, final char[][] packageName) {
            final StringBuffer result = new StringBuffer();
            for (int i = 0; i < packageName.length; i++) {
                result.append(packageName[i]);
                result.append('.');
            }
            result.append(typeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(final String clazzName) {
            byte[] clazzBytes = pStore.read(clazzName);
            if (clazzBytes != null) {
                // log.debug("loading from store " + clazzName);
                final char[] fileName = clazzName.toCharArray();
                try {
                    final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader, null);
                } catch (final ClassFormatException e) {
                    log.error("wrong class format", e);
                }
            } else {
                if (pReader.isAvailable(clazzName.replace('.', '/') + ".java")) {
                    log.debug("compile " + clazzName);
                    ICompilationUnit compilationUnit = new CompilationUnit(pReader, clazzName);
                    return new NameEnvironmentAnswer(compilationUnit, null);
                }

                final String resourceName = clazzName.replace('.', '/') + ".class";
                final InputStream is = this.getClass().getClassLoader().getResourceAsStream(resourceName);
                if (is != null) {
                    final byte[] buffer = new byte[8192];
                    final ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.length);
                    int count;
                    try {
                        while ((count = is.read(buffer, 0, buffer.length)) > 0) {
                            baos.write(buffer, 0, count);
                        }
                        baos.flush();
                        clazzBytes = baos.toByteArray();
                        final char[] fileName = clazzName.toCharArray();
                        ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
                        return new NameEnvironmentAnswer(classFileReader, null);
                    } catch (final IOException e) {
                        log.error("could not read class", e);
                    } catch (final ClassFormatException e) {
                        log.error("wrong class format", e);
                    } finally {
                        try {
                            baos.close();
                        } catch (final IOException oe) {
                            log.error("could not close output stream", oe);
                        }
                        try {
                            is.close();
                        } catch (final IOException ie) {
                            log.error("could not close input stream", ie);
                        }
                    }
                }
            }
            return null;
        }

        private boolean isPackage(final String clazzName) {
            final String resourceName = clazzName.replace('.', '/') + ".class";
            final URL resource = this.getClass().getClassLoader().getResource(resourceName);
            return resource == null;
        }

        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            final StringBuffer result = new StringBuffer();
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    if (i != 0) {
                        result.append('.');
                    }
                    result.append(parentPackageName[i]);
                }
            }
            if (Character.isUpperCase(packageName[0])) {
                return false;
            }
            if (parentPackageName != null && parentPackageName.length > 0) {
                result.append('.');
            }
            result.append(packageName);
            return isPackage(result.toString());
        }

        public void cleanup() {
        }
    };

    final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {
        public void acceptResult(CompilationResult result) {
            if (result.hasProblems()) {
                if (pProblemHandler != null) {
                    final IProblem[] problems = result.getProblems();
                    for (int i = 0; i < problems.length; i++) {
                        final IProblem problem = problems[i];
                        pProblemHandler.handle(new EclipseCompilationProblem(problem));
                    }
                }
            }
            if (!result.hasErrors()) {
                final ClassFile[] clazzFiles = result.getClassFiles();
                for (int i = 0; i < clazzFiles.length; i++) {
                    final ClassFile clazzFile = clazzFiles[i];
                    final char[][] compoundName = clazzFile.getCompoundName();
                    final StringBuffer clazzName = new StringBuffer();
                    for (int j = 0; j < compoundName.length; j++) {
                        if (j != 0) {
                            clazzName.append('.');
                        }
                        clazzName.append(compoundName[j]);
                    }
                    pStore.write(clazzName.toString(), clazzFile.getBytes());
                }
            }
        }
    };

    pProblemHandler.onStart();

    try {

        final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor,
                problemFactory);

        compiler.compile(compilationUnits);

    } finally {
        pProblemHandler.onStop();
    }
}

From source file:com.bazaarvoice.test.SubmissionTests.PhotoSubmissionTest.java

public void testPhotoSubmit4() {

    OnBazaarResponseHelper bazaarResponse = new OnBazaarResponseHelper() {
        @Override//from   w w w.ja v  a 2 s  . co m
        public void onResponseHelper(JSONObject response) throws JSONException {
            Log.e(tag, "End of photo submit transmission : END " + System.currentTimeMillis());

            Log.i(tag, "Response = \n" + response);
            assertFalse("The test returned errors! ", response.getBoolean("HasErrors"));
            assertNotNull(response.getJSONObject("Photo"));
        }
    };

    SubmissionMediaParams mediaParams = new SubmissionMediaParams(MediaParamsContentType.REVIEW_COMMENT);
    mediaParams.setUserId(
            "735688f97b74996e214f5df79bff9e8b7573657269643d393274796630666f793026646174653d3230313130353234");

    AssetManager assets = this.mContext.getAssets();

    InputStream in = null;
    ByteArrayOutputStream out = null;

    try {
        in = assets.open("RalphRocks.jpg");
        out = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }

        mediaParams.setPhoto(out.toByteArray(), "RalphRocks.jpg");

        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.e(tag, "Begin of photo submit transmission : BEGIN " + System.currentTimeMillis());
    submitMedia.postSubmission(RequestType.PHOTOS, mediaParams, bazaarResponse);
    bazaarResponse.waitForTestToFinish();
}

From source file:com.vake.message.Message.java

public byte[] encodeToBytes() {
    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    byte[] bytes = null;
    try {//from  w  w w  .  java  2s. c om
        stream.write(NumberUtils.intToBytes(sessionId));
        stream.write(NumberUtils.intToBytes(serial));
        stream.write(NumberUtils.intToBytes(contentLength));

        final byte[] contentBytes = content.getBytes();
        stream.write(contentBytes);
        final int length = contentBytes.length;
        if (length <= contentLength) {
            stream.write(new byte[contentLength - length]);
        }
        stream.flush();
        bytes = stream.toByteArray();
    } catch (Exception ex) {
        LOGGER.error("convert value to byte[] error", ex);
        return null;
    } finally {
        try {
            stream.close();
        } catch (IOException e) {
            LOGGER.error("error raised", e);
        }
    }
    return bytes;
}

From source file:edu.asu.msse.dssoni.moviedescrpitionapp.JsonRPCClientViaThread.java

private String post(URL url, Map<String, String> headers, String data) throws Exception {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            connection.addRequestProperty(entry.getKey(), entry.getValue());
        }//from   www .  j a v a2  s . co  m
    }
    connection.addRequestProperty("Accept-Encoding", "gzip");
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.connect();
    OutputStream out = null;
    try {
        out = connection.getOutputStream();
        out.write(data.getBytes());
        out.flush();
        out.close();
        int statusCode = connection.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new Exception("Unexpected status from post: " + statusCode);
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }
    String responseEncoding = connection.getHeaderField("Content-Encoding");
    responseEncoding = (responseEncoding == null ? "" : responseEncoding.trim());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    InputStream in = connection.getInputStream();
    try {
        in = connection.getInputStream();
        if ("gzip".equalsIgnoreCase(responseEncoding)) {
            in = new GZIPInputStream(in);
        }
        in = new BufferedInputStream(in);
        byte[] buff = new byte[1024];
        int n;
        while ((n = in.read(buff)) > 0) {
            bos.write(buff, 0, n);
        }
        bos.flush();
        bos.close();
    } finally {
        if (in != null) {
            in.close();
        }
    }
    android.util.Log.d(this.getClass().getSimpleName(),
            "json rpc request via http returned string " + bos.toString());
    return bos.toString();
}

From source file:business.services.PaNumberService.java

public HttpEntity<InputStreamResource> writePaNumbers(List<PathologyItem> items, Integer labNumber,
        String labRequestCode) throws Exception {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(out, PA_NUMBERS_DOWNLOAD_CHARACTER_ENCODING);
    CSVWriter csvwriter = new CSVWriter(writer, ';', '"');

    csvwriter.writeNext(FILE_HEADER);/*from  www .j a  va  2  s  .co m*/

    for (PathologyItem item : items) {
        log.info(item.getPaNumber());
        String[] toppings = { labNumber.toString(), item.getPaNumber(), "", "" };
        csvwriter.writeNext(toppings);
    }

    String filename = "panumbers_" + labRequestCode + ".csv";

    try {
        csvwriter.flush();
        writer.flush();
        out.flush();
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        csvwriter.close();
        writer.close();
        out.close();
        InputStreamResource resource = new InputStreamResource(in);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("text/csv;charset=" + PA_NUMBERS_DOWNLOAD_CHARACTER_ENCODING));
        headers.set("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        return response;
    } catch (IOException e) {
        throw new Exception(e);
    }
}

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

private void processConfigurationExportRequest(IoSession session, ConfigurationExportRequest request) {
    ConfigurationExportResponse response = new ConfigurationExportResponse(request);
    try {//w w  w. j  a  v a 2s. co m
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ConfigurationExport export = new ConfigurationExport(this.configConnection, this.runtimeConnection);
        export.export(outStream);
        outStream.flush();
        response.setData(outStream.toByteArray());
    } catch (Exception e) {
        response.setException(e);
    }
    session.write(response);
}

From source file:org.apache.karaf.decanter.collector.system.SystemCollector.java

@Override
public void run() {
    if (properties != null) {
        String karafName = System.getProperty("karaf.name");
        String hostAddress = null;
        String hostName = null;//from   www.  j  a va2 s  . c om
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (Exception e) {
            // nothing to do
        }
        Enumeration<String> keys = properties.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            try {
                if (key.startsWith("command.")) {
                    HashMap<String, Object> data = new HashMap<>();
                    String command = (String) properties.get(key);
                    LOGGER.debug("Executing {} ({})", command, key);
                    CommandLine cmdLine = CommandLine.parse(command);
                    DefaultExecutor executor = new DefaultExecutor();
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
                    executor.setStreamHandler(streamHandler);
                    data.put("timestamp", System.currentTimeMillis());
                    data.put("type", "system");
                    data.put("karafName", karafName);
                    data.put("hostAddress", hostAddress);
                    data.put("hostName", hostName);
                    executor.execute(cmdLine);
                    outputStream.flush();
                    String output = outputStream.toString();
                    if (output.endsWith("\n")) {
                        output = output.substring(0, output.length() - 1);
                    }
                    // try to convert to number
                    try {
                        if (output.contains(".")) {
                            Double value = Double.parseDouble(output);
                            data.put(key, value);
                        } else {
                            Integer value = Integer.parseInt(output);
                            data.put(key, value);
                        }
                    } catch (NumberFormatException e) {
                        data.put(key, outputStream.toString());
                    }
                    streamHandler.stop();
                    Event event = new Event("decanter/collect/system/" + key.replace(".", "_"), data);
                    eventAdmin.postEvent(event);
                    try {
                        outputStream.close();
                    } catch (Exception e) {
                        // nothing to do
                    }
                }
            } catch (Exception e) {
                LOGGER.warn("Command {} execution failed", key, e);
            }
        }
    }
}

From source file:deployer.TestUtils.java

public static ByteBuffer createSampleAppTarBall(ArtifactType type) throws IOException, ArchiveException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(8096);
    CompressorOutputStream gzs = new GzipCompressorOutputStream(bos);
    ArchiveOutputStream aos = new TarArchiveOutputStream(gzs);
    {//from  www  .j av  a2  s  .co m
        TarArchiveEntry nextEntry = new TarArchiveEntry(CONFIG_DIRECTORY + "/app.conf");
        byte[] sampleConf = SAMPLE_CONF_DATA.getBytes();
        nextEntry.setSize(sampleConf.length);
        aos.putArchiveEntry(nextEntry);
        IOUtils.write(sampleConf, aos);
        aos.closeArchiveEntry();
    }
    if (type != ArtifactType.WebApp) {
        TarArchiveEntry nextEntry = new TarArchiveEntry("bin/myApplication.jar");
        byte[] jarData = SAMPLE_JAR_DATA.getBytes();
        nextEntry.setSize(jarData.length);
        aos.putArchiveEntry(nextEntry);
        IOUtils.write(jarData, aos);
        aos.closeArchiveEntry();
    } else {
        TarArchiveEntry nextEntry = new TarArchiveEntry("deployments/ROOT.war");
        byte[] jarData = SAMPLE_JAR_DATA.getBytes();
        nextEntry.setSize(jarData.length);
        aos.putArchiveEntry(nextEntry);
        IOUtils.write(jarData, aos);
        aos.closeArchiveEntry();
    }
    aos.finish();
    gzs.close();
    bos.flush();
    return ByteBuffer.wrap(bos.toByteArray());
}

From source file:com.kkbox.toolkit.internal.api.APIRequest.java

@Override
public Void doInBackground(Object... params) {
    int readLength;
    final byte[] buffer = new byte[128];
    listener = (APIRequestListener) params[0];
    int retryTimes = 0;
    File cacheFile = null;//from w w w .j a va2s . c om
    ConnectivityManager connectivityManager = null;
    if (context != null) {
        final File cacheDir = new File(context.getCacheDir().getAbsolutePath() + File.separator + "api");
        if (!cacheDir.exists()) {
            cacheDir.mkdir();
        }
        cacheFile = new File(
                cacheDir.getAbsolutePath() + File.separator + StringUtils.getMd5Hash(url + getParams));
        connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
    }

    if (context != null && cacheTimeOut > 0 && cacheFile.exists()
            && ((System.currentTimeMillis() - cacheFile.lastModified() < cacheTimeOut)
                    || connectivityManager.getActiveNetworkInfo() == null)) {
        try {
            parseInputStream(new FileInputStream(cacheFile), cipher);
        } catch (IOException e) {
            isNetworkError = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        do {
            try {
                KKDebug.i("Connect API url " + url + getParams);
                if (postParams != null || multipartEntity != null || stringEntity != null || fileEntity != null
                        || byteArrayEntity != null || gzipStreamEntity != null
                        || (headerParams != null && postParams != null)) {
                    final HttpPost httppost = new HttpPost(url + getParams);
                    if (postParams != null) {
                        httppost.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
                    }
                    if (multipartEntity != null) {
                        httppost.setEntity(multipartEntity);
                    }
                    if (stringEntity != null) {
                        httppost.setEntity(stringEntity);
                    }
                    if (fileEntity != null) {
                        httppost.setEntity(fileEntity);
                    }
                    if (byteArrayEntity != null) {
                        httppost.setEntity(byteArrayEntity);
                    }
                    if (gzipStreamEntity != null) {
                        httppost.setHeader("Accept-Encoding", "gzip");
                        httppost.setEntity(gzipStreamEntity);
                    }
                    if (headerParams != null) {
                        for (NameValuePair header : headerParams) {
                            httppost.setHeader(header.getName(), header.getValue());
                        }
                    }
                    response = httpclient.execute(httppost);
                } else {
                    final HttpGet httpGet = new HttpGet(url + getParams);
                    if (headerParams != null) {
                        for (NameValuePair header : headerParams) {
                            httpGet.setHeader(header.getName(), header.getValue());
                        }
                    }
                    response = httpclient.execute(httpGet);
                }
                httpStatusCode = response.getStatusLine().getStatusCode();
                int httpStatusType = httpStatusCode / 100;
                switch (httpStatusType) {
                case 2:
                    is = getInputStreamFromHttpResponse();
                    isNetworkError = false;
                    break;
                case 4:
                    KKDebug.w("Get client error " + httpStatusCode + " with connection : " + url + getParams);
                    is = getInputStreamFromHttpResponse();
                    isHttpStatusError = true;
                    isNetworkError = false;
                    break;
                case 5:
                    KKDebug.w("Get server error " + httpStatusCode + " with connection : " + url + getParams);
                    is = getInputStreamFromHttpResponse();
                    isHttpStatusError = true;
                    isNetworkError = false;
                    break;
                default:
                    KKDebug.w("connection to " + url + getParams + " returns " + httpStatusCode);
                    retryTimes++;
                    isNetworkError = true;
                    SystemClock.sleep(1000);
                    break;
                }
            } catch (final SSLException e) {
                KKDebug.w("connection to " + url + getParams + " failed with " + e.getClass().getName());
                isNetworkError = true;
                errorMessage = e.getClass().getName();
                return null;
            } catch (final Exception e) {
                KKDebug.w("connection to " + url + getParams + " failed!");
                retryTimes++;
                isNetworkError = true;
                SystemClock.sleep(1000);
            }
        } while (isNetworkError && retryTimes < retryLimit);

        try {
            if (!isNetworkError && !isHttpStatusError && listener != null) {
                if (cacheTimeOut > 0) {
                    FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
                    while ((readLength = is.read(buffer, 0, buffer.length)) != -1) {
                        fileOutputStream.write(buffer, 0, readLength);
                    }
                    fileOutputStream.close();
                    parseInputStream(new FileInputStream(cacheFile), cipher);
                } else {
                    parseInputStream(is, cipher);
                }
            } else if (isHttpStatusError) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                while ((readLength = is.read(buffer, 0, buffer.length)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, readLength);
                }
                byteArrayOutputStream.flush();
                errorMessage = byteArrayOutputStream.toString();
            }
            response.getEntity().consumeContent();
        } catch (IOException e) {
            isNetworkError = true;
        } catch (Exception e) {
        }
    }
    return null;
}