Example usage for java.io ByteArrayOutputStream close

List of usage examples for java.io ByteArrayOutputStream close

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayOutputStream has no effect.

Usage

From source file:org.ubicompforall.cityexplorer.CityExplorer.java

/***
 * Ping Google//from  w w  w .  j a va2 s.c  o m
 * Start a browser if the page contains a (log-in) "redirect="
 */
public static boolean pingConnection(Activity context, String url) {
    boolean urlAvailable = false;
    if (ensureConnected(context)) {
        showProgressDialog(context);
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpResponse response = httpclient.execute(new HttpGet(url));
            StatusLine statusLine = response.getStatusLine();
            debug(2, "statusLine is " + statusLine);

            // HTTP status is OK even if not logged in to NTNU
            //Toast.makeText( context, "Status-line is "+statusLine, Toast.LENGTH_LONG).show();
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                String responseString = out.toString();
                if (responseString.contains("redirect=")) { // Connection to url should be checked.
                    debug(2, "Redirect detected for url: " + url);
                    //Toast.makeText( context, "Mismatched url: "+url, Toast.LENGTH_LONG).show();
                } else {
                    urlAvailable = true;
                } // if redirect page, else probably OK
            } else {//if status OK, else: Closes the connection on failure
                response.getEntity().getContent().close();
            } //if httpStatus OK, else close

            //Start browser to log in
            if (!urlAvailable) {
                //throw new IOException( statusLine.getReasonPhrase() );

                //String activity = Thread.currentThread().getStackTrace()[3].getClassName();
                Toast.makeText(context, "Web access needed! Are you logged in?", Toast.LENGTH_LONG).show();
                //Uri uri = Uri.parse( url +"#"+ context.getClass().getCanonicalName() );
                Uri uri = Uri.parse(url + "?activity=" + context.getClass().getCanonicalName());
                debug(0, "Pinging magic url: " + uri);
                debug(0, " Need the web for uri: " + uri);
                context.startActivityForResult(new Intent(Intent.ACTION_VIEW, uri), REQUEST_KILL_BROWSER);
                //urlAvailable=true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) { // Caused by bad url for example, missing http:// etc. Can still use cached maps...
            urlAvailable = false;
            debug(0, "Missing http:// in " + url + " ?");
        } catch (IOException e) { // e.g. UnknownHostException // try downloading db's from the Web, catch (and print) exceptions
            e.printStackTrace();
            urlAvailable = false;
        }
    } // if not already loaded once before
    return urlAvailable;
}

From source file:net.vexelon.bgrates.Utils.java

/**
 * Move a file stored in the cache to the internal storage of the specified context
 * @param context/*from  w  w  w. ja  v a2 s.c o  m*/
 * @param cacheFile
 * @param internalStorageName
 */
public static boolean moveCacheFile(Context context, File cacheFile, String internalStorageName) {

    boolean ret = false;
    FileInputStream fis = null;
    FileOutputStream fos = null;

    try {
        fis = new FileInputStream(cacheFile);

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

        fos = context.openFileOutput(internalStorageName, Context.MODE_PRIVATE);
        baos.writeTo(fos);
        fos.close();

        // delete cache
        cacheFile.delete();

        ret = true;
    } catch (Exception e) {
        //Log.e(TAG, "Error saving previous rates!");
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {
        }
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
    }

    return ret;
}

From source file:Main.java

public static byte[] decompress(byte[] compressedBuffer) {
    Inflater inflater = new Inflater();
    inflater.setInput(compressedBuffer);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(compressedBuffer.length);
    try {//from  w ww . ja va  2s  . co  m
        byte[] buffer = new byte[1024];
        while (!inflater.finished()) {
            int count = inflater.inflate(buffer);
            outputStream.write(buffer, 0, count);
        }
        byte[] output = outputStream.toByteArray();
        return output;
    } catch (DataFormatException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            inflater.end();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:Main.java

/**
 * Convert serializable object to bytes.
 *
 * @param object object//from  w  w w . jav  a  2  s  .  c om
 * @return bytes array
 */
public static byte[] toBytes(Object object) {
    byte[] result = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = null;
    try {
        out = new ObjectOutputStream(bos);
        out.writeObject(object);
        result = bos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
            }
        }
        if (bos != null) {
            try {
                bos.close();
            } catch (Exception e) {
            }
        }
    }
    return result;
}

From source file:Main.java

public static byte[] readNetWorkInputStream(InputStream in) {
    ByteArrayOutputStream os = null;
    try {//from w ww  . j  av a  2  s . c  o  m
        os = new ByteArrayOutputStream();

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

        in.close();
        in = null;

        return os.toByteArray();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (null != os) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            os = null;
        }
    }
    return null;
}

From source file:Main.java

public static byte[] serialize(Object o) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = null;//from  ww w.  j  a  v a  2 s  .co  m
    byte[] bytes = null;
    try {
        out = new ObjectOutputStream(bos);
        out.writeObject(o);
        bytes = bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
            // ignore close exception
        }
        try {
            bos.close();
        } catch (IOException ex) {
            // ignore close exception
        }
    }
    return bytes;
}

From source file:com.aaasec.sigserv.cscommon.DocTypeIdentifier.java

/**
 * Guess the document format and return an appropriate document type string
 *
 * @param is An InputStream holding the document
 * @return "xml" if the document is an XML document or "pdf" if the document
 * is a PDF document, or else an error message.
 *//*from   w w  w .  j ava  2 s. c om*/
public static SigDocumentType getDocType(InputStream is) {
    InputStream input = null;

    try {
        input = new BufferedInputStream(is);
        input.mark(5);
        byte[] preamble = new byte[5];
        int read = 0;
        try {
            read = input.read(preamble);
            input.reset();
        } catch (IOException ex) {
            return SigDocumentType.Unknown;
        }
        if (read < 5) {
            return SigDocumentType.Unknown;
        }
        String preambleString = new String(preamble);
        byte[] xmlPreable = new byte[] { '<', '?', 'x', 'm', 'l' };
        byte[] xmlUtf8 = new byte[] { -17, -69, -65, '<', '?' };
        if (Arrays.equals(preamble, xmlPreable) || Arrays.equals(preamble, xmlUtf8)) {
            return SigDocumentType.XML;
        } else if (preambleString.equals("%PDF-")) {
            return SigDocumentType.PDF;
        } else if (preamble[0] == 'P' && preamble[1] == 'K') {
            ZipInputStream asics = new ZipInputStream(new BufferedInputStream(is));
            ByteArrayOutputStream datafile = null;
            ByteArrayOutputStream signatures = null;
            ZipEntry entry;
            try {
                while ((entry = asics.getNextEntry()) != null) {
                    if (entry.getName().equals("META-INF/signatures.p7s")) {
                        signatures = new ByteArrayOutputStream();
                        IOUtils.copy(asics, signatures);
                        signatures.close();
                    } else if (entry.getName().equalsIgnoreCase("META-INF/signatures.p7s")) {
                        /* Wrong case */
                        // asics;Non ETSI compliant
                        return SigDocumentType.Unknown;
                    } else if (entry.getName().indexOf("/") == -1) {
                        if (datafile == null) {
                            datafile = new ByteArrayOutputStream();
                            IOUtils.copy(asics, datafile);
                            datafile.close();
                        } else {
                            //                              // asics;ASiC-S profile support only one data file
                            return SigDocumentType.Unknown;
                        }
                    }
                }
            } catch (Exception ex) {
                // null;Invalid ASiC-S
                return SigDocumentType.Unknown;
            }
            if (datafile == null || signatures == null) {
                // asics;ASiC-S profile support only one data file with CAdES signature
                return SigDocumentType.Unknown;
            }
            // asics/cades
            return SigDocumentType.Unknown;

        } else if (preambleString.getBytes()[0] == 0x30) {
            // cades;
            return SigDocumentType.Unknown;
        } else {
            // null;Document format not recognized/handled
            return SigDocumentType.Unknown;
        }
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.taobao.tair.etc.TranscoderUtil.java

public static byte[] compress(byte[] in) {
    if (in == null) {
        throw new NullPointerException("Can't compress null");
    }/*w w w  .  ja va2s.c  o m*/

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    GZIPOutputStream gz = null;

    try {
        gz = new GZIPOutputStream(bos);
        gz.write(in);
    } catch (IOException e) {
        throw new RuntimeException("IO exception compressing data", e);
    } finally {
        try {
            gz.close();
            bos.close();
        } catch (Exception e) {
            // should not happen
        }
    }

    byte[] rv = bos.toByteArray();

    if (log.isInfoEnabled()) {
        log.info("compressed value, size from [" + in.length + "] to [" + rv.length + "]");
    }

    return rv;
}

From source file:Main.java

public static byte[] getBodyBytes(String ip, String port, byte[] key, byte[] ips)
        throws NumberFormatException, IOException {

    String[] ipArr = ip.split("\\.");
    byte[] ipByte = new byte[4];
    ipByte[0] = (byte) (Integer.parseInt(ipArr[0]) & 0xFF);
    ipByte[1] = (byte) (Integer.parseInt(ipArr[1]) & 0xFF);
    ipByte[2] = (byte) (Integer.parseInt(ipArr[2]) & 0xFF);
    ipByte[3] = (byte) (Integer.parseInt(ipArr[3]) & 0xFF);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    dos.write(ipByte);/*  w  w w .  j a v  a 2 s . c  o m*/
    if (!isNum(port))
        throw new NumberFormatException("port is not number...");
    byte[] portByte = short2bytes(Integer.parseInt(port));
    dos.write(portByte);
    //        dos.writeByte(key.getBytes().length);
    dos.write(key);
    if (ips != null && ips.length > 0 && dos != null) {
        dos.write(ips);
    }
    byte[] bs = baos.toByteArray();
    baos.close();
    dos.close();

    return bs;
}

From source file:bencoding.securely.Converters.java

public static String serializeObjectToString(Object object) throws Exception {

    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(arrayOutputStream);
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(gzipOutputStream);

    objectOutputStream.writeObject(object);

    objectOutputStream.flush();// ww w . j a  v a  2 s  .c o m
    objectOutputStream.close();
    gzipOutputStream.close();
    arrayOutputStream.close();

    String objectString = new String(Base64.encodeToString(arrayOutputStream.toByteArray(), Base64.DEFAULT));

    return objectString;
}