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.chiorichan.http.HttpResponseWrapper.java

public void sendMultipart(byte[] bytesToWrite) throws IOException {
    if (request.method() == HttpMethod.HEAD)
        throw new IllegalStateException("You can't start MULTIPART mode on a HEAD Request.");

    if (stage != HttpResponseStage.MULTIPART) {
        stage = HttpResponseStage.MULTIPART;
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

        HttpHeaders h = response.headers();
        try {//from w  ww. ja v a  2  s . co  m
            request.getSession().save();
        } catch (SessionException e) {
            e.printStackTrace();
        }

        for (HttpCookie c : request.getCookies())
            if (c.needsUpdating())
                h.add("Set-Cookie", c.toHeaderValue());

        if (h.get("Server") == null)
            h.add("Server", Versioning.getProduct() + " Version " + Versioning.getVersion());

        h.add("Access-Control-Allow-Origin",
                request.getLocation().getConfig().getString("site.web-allowed-origin", "*"));
        h.add("Connection", "close");
        h.add("Cache-Control", "no-cache");
        h.add("Cache-Control", "private");
        h.add("Pragma", "no-cache");
        h.set("Content-Type", "multipart/x-mixed-replace; boundary=--cwsframe");

        // if ( isKeepAlive( request ) )
        {
            // response.headers().set( CONNECTION, HttpHeaders.Values.KEEP_ALIVE );
        }

        request.getChannel().write(response);
    } else {
        StringBuilder sb = new StringBuilder();

        sb.append("--cwsframe\r\n");
        sb.append("Content-Type: " + httpContentType + "\r\n");
        sb.append("Content-Length: " + bytesToWrite.length + "\r\n\r\n");

        ByteArrayOutputStream ba = new ByteArrayOutputStream();

        ba.write(sb.toString().getBytes(encoding));
        ba.write(bytesToWrite);
        ba.flush();

        ChannelFuture sendFuture = request.getChannel().write(
                new ChunkedStream(new ByteArrayInputStream(ba.toByteArray())),
                request.getChannel().newProgressivePromise());

        ba.close();

        sendFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationComplete(ChannelProgressiveFuture future) throws Exception {
                NetworkManager.getLogger().info("Transfer complete.");
            }

            @Override
            public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
                if (total < 0)
                    NetworkManager.getLogger().info("Transfer progress: " + progress);
                else
                    NetworkManager.getLogger().info("Transfer progress: " + progress + " / " + total);
            }
        });
    }
}

From source file:com.wso2mobile.mam.packageExtractor.ZipFileReading.java

public String readiOSManifestFile(String filePath, String name) {
    String plist = "";
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {/*from w w  w. j av  a2s.  co  m*/
        File file = new File(filePath);
        ZipInputStream stream = new ZipInputStream(new FileInputStream(file));
        try {
            ZipEntry entry;
            while ((entry = stream.getNextEntry()) != null) {
                if (entry.getName().equals("Payload/" + name + ".app/Info.plist")) {
                    InputStream is = stream;

                    int nRead;
                    byte[] data = new byte[16384];

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

                    buffer.flush();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stream.close();
        }
        NSDictionary rootDict = (NSDictionary) BinaryPropertyListParser.parse(buffer.toByteArray());
        JSONObject obj = new JSONObject();
        obj.put("version", rootDict.objectForKey("CFBundleVersion").toString());
        obj.put("name", rootDict.objectForKey("CFBundleName").toString());
        obj.put("package", rootDict.objectForKey("CFBundleIdentifier").toString());
        plist = obj.toJSONString();
    } catch (Exception e) {
        plist = "Exception occured " + e;
        e.printStackTrace();
    }
    return plist;
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Reads the data of a HTTP response entity*/
public byte[] readEntityData(HttpResponse httpResponse) throws Exception {
    if (httpResponse == null) {
        return (null);
    }/*from w ww. j a  v a 2s.c  o m*/
    if (httpResponse.getEntity() == null) {
        return (null);
    }
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    httpResponse.getEntity().writeTo(outStream);
    outStream.flush();
    outStream.close();
    return (outStream.toByteArray());
}

From source file:eionet.util.Util.java

/**
 * Opens a URL and fetches the content. If there is an error, then the
 * exception message is returned.//  w  w  w.j  a  va2 s . c  o  m
 *
 * @param url - the URL
 * @return the content
 */
public static String getUrlContent(String url) {

    int i;
    byte[] buf = new byte[1024];
    InputStream in = null;
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        URL _url = new URL(url);
        HttpURLConnection httpConn = (HttpURLConnection) _url.openConnection();

        in = _url.openStream();
        while ((i = in.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, i);
        }
        out.flush();
    } catch (IOException e) {
        return e.toString().trim();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
        }
    }

    return out.toString().trim();
}

From source file:org.apache.carbondata.core.util.CarbonUtil.java

/**
 * Below method will be used to convert the thrift object to byte array.
 *///from  w w w.j av a 2 s .co  m
public static byte[] getByteArray(TBase t) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    byte[] thriftByteArray = null;
    TProtocol binaryOut = new TCompactProtocol(new TIOStreamTransport(stream));
    try {
        t.write(binaryOut);
        stream.flush();
        thriftByteArray = stream.toByteArray();
    } catch (TException | IOException e) {
        closeStreams(stream);
    } finally {
        closeStreams(stream);
    }
    return thriftByteArray;
}

From source file:io.selendroid.android.impl.AbstractDevice.java

public byte[] takeScreenshot() throws AndroidDeviceException {
    if (device == null) {
        throw new AndroidDeviceException("Device not accessible via ddmlib.");
    }//  w  w w  .  j a  v a2  s.co  m
    RawImage rawImage;
    try {
        rawImage = device.getScreenshot();
    } catch (IOException ioe) {
        throw new AndroidDeviceException("Unable to get frame buffer: " + ioe.getMessage());
    } catch (TimeoutException e) {
        e.printStackTrace();
        throw new AndroidDeviceException(e.getMessage());
    } catch (AdbCommandRejectedException e) {
        e.printStackTrace();
        throw new AndroidDeviceException(e.getMessage());
    }

    // device/adb not available?
    if (rawImage == null)
        return null;

    BufferedImage image = new BufferedImage(rawImage.width, rawImage.height, BufferedImage.TYPE_INT_ARGB);

    int index = 0;
    int IndexInc = rawImage.bpp >> 3;
    for (int y = 0; y < rawImage.height; y++) {
        for (int x = 0; x < rawImage.width; x++) {
            int value = rawImage.getARGB(index);
            index += IndexInc;
            image.setRGB(x, y, value);
        }
    }
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    try {
        if (!ImageIO.write(image, "png", stream)) {
            throw new IOException("Failed to find png writer");
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new AndroidDeviceException(e.getMessage());
    }
    byte[] raw = null;
    try {
        stream.flush();
        raw = stream.toByteArray();
        stream.close();
    } catch (IOException e) {
        throw new RuntimeException("I/O Error while capturing screenshot: " + e.getMessage());
    } finally {
        Closeable closeable = (Closeable) stream;
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }

    return raw;
}

From source file:org.apache.cocoon.components.language.programming.java.EclipseJavaCompiler.java

public boolean compile() throws IOException {
    final String targetClassName = makeClassName(sourceFile);
    final ClassLoader classLoader = ClassUtils.getClassLoader();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    class CompilationUnit implements ICompilationUnit {

        String className;//  w  w  w . j  ava  2s  .co  m
        String sourceFile;

        CompilationUnit(String sourceFile, String className) {
            this.className = className;
            this.sourceFile = sourceFile;
        }

        public char[] getFileName() {
            return className.toCharArray();
        }

        public char[] getContents() {
            char[] result = null;
            FileReader fr = null;
            try {
                fr = new FileReader(sourceFile);
                Reader reader = new BufferedReader(fr);
                if (reader != null) {
                    char[] chars = new char[8192];
                    StringBuffer buf = new StringBuffer();
                    int count;
                    while ((count = reader.read(chars, 0, chars.length)) > 0) {
                        buf.append(chars, 0, count);
                    }
                    result = new char[buf.length()];
                    buf.getChars(0, result.length, result, 0);
                }
            } catch (IOException e) {
                handleError(className, -1, -1, e.getMessage());
            }
            return result;
        }

        public char[] getMainTypeName() {
            int dot = className.lastIndexOf('.');
            if (dot > 0) {
                return className.substring(dot + 1).toCharArray();
            }
            return className.toCharArray();
        }

        public char[][] getPackageName() {
            StringTokenizer izer = new StringTokenizer(className, ".");
            char[][] result = new char[izer.countTokens() - 1][];
            for (int i = 0; i < result.length; i++) {
                String tok = izer.nextToken();
                result[i] = tok.toCharArray();
            }
            return result;
        }
    }

    final INameEnvironment env = new INameEnvironment() {

        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            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(char[] typeName, char[][] packageName) {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < packageName.length; i++) {
                if (i > 0) {
                    result.append(".");
                }
                result.append(packageName[i]);
            }
            result.append(".");
            result.append(typeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(String className) {

            try {
                if (className.equals(targetClassName)) {
                    ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
                    return new NameEnvironmentAnswer(compilationUnit);
                }
                String resourceName = className.replace('.', '/') + ".class";
                InputStream is = classLoader.getResourceAsStream(resourceName);
                if (is != null) {
                    byte[] classBytes;
                    byte[] buf = new byte[8192];
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
                    int count;
                    while ((count = is.read(buf, 0, buf.length)) > 0) {
                        baos.write(buf, 0, count);
                    }
                    baos.flush();
                    classBytes = baos.toByteArray();
                    char[] fileName = className.toCharArray();
                    ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader);
                }
            } catch (IOException exc) {
                handleError(className, -1, -1, exc.getMessage());
            } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
                handleError(className, -1, -1, exc.getMessage());
            }
            return null;
        }

        private boolean isPackage(String result) {
            if (result.equals(targetClassName)) {
                return false;
            }
            String resourceName = result.replace('.', '/') + ".class";
            InputStream is = classLoader.getResourceAsStream(resourceName);
            return is == null;
        }

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

        public void cleanup() {
            // EMPTY
        }
    };
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final Map settings = new HashMap(9);
    settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
    settings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE);
    if (sourceEncoding != null) {
        settings.put(CompilerOptions.OPTION_Encoding, sourceEncoding);
    }
    if (debug) {
        settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
    }
    // Set the sourceCodeVersion
    switch (this.compilerComplianceLevel) {
    case 150:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
        break;
    case 140:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
        break;
    default:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
    }
    // Set the target platform
    switch (SystemUtils.JAVA_VERSION_INT) {
    case 150:
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
        break;
    case 140:
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
        break;
    default:
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
    }
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    final ICompilerRequestor requestor = new ICompilerRequestor() {
        public void acceptResult(CompilationResult result) {
            try {
                if (result.hasErrors()) {
                    IProblem[] errors = result.getErrors();
                    for (int i = 0; i < errors.length; i++) {
                        IProblem error = errors[i];
                        String name = new String(errors[i].getOriginatingFileName());
                        handleError(name, error.getSourceLineNumber(), -1, error.getMessage());
                    }
                } else {
                    ClassFile[] classFiles = result.getClassFiles();
                    for (int i = 0; i < classFiles.length; i++) {
                        ClassFile classFile = classFiles[i];
                        char[][] compoundName = classFile.getCompoundName();
                        StringBuffer className = new StringBuffer();
                        for (int j = 0; j < compoundName.length; j++) {
                            if (j > 0) {
                                className.append(".");
                            }
                            className.append(compoundName[j]);
                        }
                        byte[] bytes = classFile.getBytes();
                        String outFile = destDir + "/" + className.toString().replace('.', '/') + ".class";
                        FileOutputStream fout = new FileOutputStream(outFile);
                        BufferedOutputStream bos = new BufferedOutputStream(fout);
                        bos.write(bytes);
                        bos.close();
                    }
                }
            } catch (IOException exc) {
                exc.printStackTrace();
            }
        }
    };
    ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        String className = classNames[i];
        compilationUnits[i] = new CompilationUnit(fileNames[i], className);
    }
    Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory);
    compiler.compile(compilationUnits);
    return errors.size() == 0;
}

From source file:com.parse.f8.view.SignInActivity.java

private byte[] inputStreamToBytes(InputStream is) throws IOException {

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int nRead;/*from  w  w w . j  a  v a  2s.c  om*/
    byte[] data = new byte[1048576];

    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }
    //      for (int len; (len = is.read(data)) != -1;) {
    //      buffer.write(data, 0, len);
    buffer.flush();

    return buffer.toByteArray();
}

From source file:de.sandmage.opportunisticmail.crypto.OpenPGP.java

public String getEncryptedMessage(byte[] data) {
    Security.addProvider(new BouncyCastleProvider());

    try {// w  w  w . java2  s  .  co m

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        OutputStream out = new ArmoredOutputStream(baos);
        byte[] compressedData = compressFile(data, CompressionAlgorithmTags.ZIP);
        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_128).setWithIntegrityPacket(true)
                        .setSecureRandom(new SecureRandom()).setProvider("BC"));

        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(this.publicKey).setProvider("BC"));
        OutputStream cOut = encGen.open(out, compressedData.length);
        cOut.write(compressedData);
        cOut.close();
        out.close();
        baos.flush();
        return new String(baos.toByteArray());
    } catch (PGPException | IOException e) {
        e.printStackTrace();
    }
    return null;
}

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

/**
 * Takes all requests objects and writes its serialized data to a byte array
 * for further posting to the RPG./*from   w  w w. ja  va  2s  .  c o  m*/
 * 
 * @param requests A list of requests to serialize.
 * @param reqIds
 * @return The serialized requests with RPG headers. Returns NULL id list of requests is NULL.
 */
private byte[] prepareRPGRequests(List<Request> requests, List<Integer> reqIds) {
    if (null == requests) {
        return null;
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        for (Request request : requests) {
            request.writeToOutputStream(baos, true);
            request.setActive(true);
            reqIds.add(request.getRequestId());
        }
        baos.flush();
    } catch (IOException ioe) {
        LogUtils.logE("HttpConnectionThread.prepareRPGRequests() Failed writing to BAOS", ioe);
    } finally {
        try {
            baos.close();
        } catch (IOException ioe) {
            LogUtils.logE("HttpConnectionThread.prepareRPGRequests() Failed closing BAOS", ioe);
        }
    }
    byte[] reqData = baos.toByteArray();

    return reqData;
}