List of usage examples for java.io ByteArrayOutputStream size
public synchronized int size()
From source file:org.omegat.filters.TestFilterBase.java
public static void compareBinary(File f1, File f2) throws Exception { ByteArrayOutputStream d1 = new ByteArrayOutputStream(); FileUtils.copyFile(f1, d1);/* w ww . j a va 2 s . com*/ ByteArrayOutputStream d2 = new ByteArrayOutputStream(); FileUtils.copyFile(f2, d2); assertEquals(d1.size(), d2.size()); byte[] a1 = d1.toByteArray(); byte[] a2 = d2.toByteArray(); for (int i = 0; i < d1.size(); i++) { assertEquals(a1[i], a2[i]); } }
From source file:StringUtilities.java
/** * Parses digest-challenge string, extracting each token and value(s). Each token * is a directive.//from w ww . j a v a 2 s.co m * * @param buf A non-null digest-challenge string. * @throws UnsupportedEncodingException * @throws SaslException if the String cannot be parsed according to RFC 2831 */ public static HashMap<String, String> parseDirectives(byte[] buf) throws SaslException { HashMap<String, String> map = new HashMap<String, String>(); boolean gettingKey = true; boolean gettingQuotedValue = false; boolean expectSeparator = false; byte bch; ByteArrayOutputStream key = new ByteArrayOutputStream(10); ByteArrayOutputStream value = new ByteArrayOutputStream(10); int i = skipLws(buf, 0); while (i < buf.length) { bch = buf[i]; if (gettingKey) { if (bch == ',') { if (key.size() != 0) { throw new SaslException("Directive key contains a ',':" + key); } // Empty element, skip separator and lws i = skipLws(buf, i + 1); } else if (bch == '=') { if (key.size() == 0) { throw new SaslException("Empty directive key"); } gettingKey = false; // Termination of key i = skipLws(buf, i + 1); // Skip to next non whitespace // Check whether value is quoted if (i < buf.length) { if (buf[i] == '"') { gettingQuotedValue = true; ++i; // Skip quote } } else { throw new SaslException("Valueless directive found: " + key.toString()); } } else if (isLws(bch)) { // LWS that occurs after key i = skipLws(buf, i + 1); // Expecting '=' if (i < buf.length) { if (buf[i] != '=') { throw new SaslException("'=' expected after key: " + key.toString()); } } else { throw new SaslException("'=' expected after key: " + key.toString()); } } else { key.write(bch); // Append to key ++i; // Advance } } else if (gettingQuotedValue) { // Getting a quoted value if (bch == '\\') { // quoted-pair = "\" CHAR ==> CHAR ++i; // Skip escape if (i < buf.length) { value.write(buf[i]); ++i; // Advance } else { // Trailing escape in a quoted value throw new SaslException("Unmatched quote found for directive: " + key.toString() + " with value: " + value.toString()); } } else if (bch == '"') { // closing quote ++i; // Skip closing quote gettingQuotedValue = false; expectSeparator = true; } else { value.write(bch); ++i; // Advance } } else if (isLws(bch) || bch == ',') { // Value terminated extractDirective(map, key.toString(), value.toString()); key.reset(); value.reset(); gettingKey = true; gettingQuotedValue = expectSeparator = false; i = skipLws(buf, i + 1); // Skip separator and LWS } else if (expectSeparator) { throw new SaslException( "Expecting comma or linear whitespace after quoted string: \"" + value.toString() + "\""); } else { value.write(bch); // Unquoted value ++i; // Advance } } if (gettingQuotedValue) { throw new SaslException( "Unmatched quote found for directive: " + key.toString() + " with value: " + value.toString()); } // Get last pair if (key.size() > 0) { extractDirective(map, key.toString(), value.toString()); } return map; }
From source file:com.googlecode.jtiger.modules.ecside.util.ExtremeUtils.java
public static int sessionSize(HttpSession session) { int total = 0; try {/*ww w.j a v a 2 s . c o m*/ java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos); Enumeration enumeration = session.getAttributeNames(); while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); Object obj = session.getAttribute(name); oos.writeObject(obj); int size = baos.size(); total += size; logger.debug("The session name: " + name + " and the size is: " + size); } logger.debug("Total session size is: " + total); } catch (Exception e) { logger.error("Could not get the session size - " + ExceptionUtils.formatStackTrace(e)); } return total; }
From source file:Main.java
public static Bitmap loadImageFromUrl(String url) { ByteArrayOutputStream out = null; Bitmap bitmap = null;//from w w w . j a v a 2 s.c o m int BUFFER_SIZE = 1024 * 8; try { BufferedInputStream in = new BufferedInputStream(new URL(url).openStream(), BUFFER_SIZE); out = new ByteArrayOutputStream(BUFFER_SIZE); int length = 0; byte[] tem = new byte[BUFFER_SIZE]; length = in.read(tem); while (length != -1) { out.write(tem, 0, length); out.flush(); length = in.read(tem); } in.close(); if (out.toByteArray().length != 0) { bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size()); } else { out.close(); return null; } out.close(); } catch (OutOfMemoryError e) { out.reset(); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inSampleSize = 2; opts.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size(), opts); return bitmap; } catch (Exception e) { return bitmap; } return bitmap; }
From source file:com.feilong.commons.core.lang.ObjectUtil.java
/** * ?./*from ww w. ja v a 2s .c om*/ * * @param serializable * the object * @return the int * @throws IOException * Signals that an I/O exception has occurred. * @see ByteArrayOutputStream#size() * @since 1.0.7 */ //XXX ?check,? public static int size(Object serializable) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(serializable); objectOutputStream.close(); return byteArrayOutputStream.size(); }
From source file:com.beetle.framework.util.ObjectUtil.java
/** * ???// ww w .ja v a 2 s . c o m * * @param obj * @return */ public final static int sizeOf(Object obj) { ByteArrayOutputStream bao = null; ObjectOutputStream oos; try { bao = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bao); oos.writeObject(obj); oos.flush(); oos.close(); return bao.size(); } catch (Exception e) { e.printStackTrace(); return 0; } finally { try { if (bao != null) { bao.close(); bao = null; } } catch (IOException e) { } } }
From source file:dotplugin.GraphViz.java
/** * Bare bones API for launching dot. Command line options are passed to * Graphviz as specified in the options parameter. The location for dot is * obtained from the user preferences.//ww w .j a v a 2s.c o m * * @param options * command line options for dot * @return a non-zero integer if errors happened * @throws IOException */ public static IStatus runDot(String... options) { // IPath dotFullPath = activator.getDotLocation(); IPath dotFullPath = Pref.getDotLocation(); StringBuffer b = new StringBuffer(dotFullPath.toString()); for (String o : options) { b.append(" "); b.append(o); } LogUtils.logInfo("Start " + b.toString(), null); if (dotFullPath == null || dotFullPath.isEmpty()) return new Status(IStatus.ERROR, Activator.ID, "dot.exe/dot not found in PATH. Please install it from graphviz.org, update the PATH or specify the absolute path in the preferences."); if (!dotFullPath.toFile().isFile()) return new Status(IStatus.ERROR, Activator.ID, "Could not find Graphviz dot at \"" + dotFullPath + "\""); List<String> cmd = new ArrayList<String>(); cmd.add(dotFullPath.toOSString()); // insert user custom options /* String commandLineExtension = Activator.getInstance() .getCommandLineExtension(); if (commandLineExtension != null) { String[] tokens = commandLineExtension.split(" "); cmd.addAll(Arrays.asList(tokens)); } */ cmd.addAll(Arrays.asList(options)); ByteArrayOutputStream errorOutput = new ByteArrayOutputStream(); try { final ProcessController controller = new ProcessController(6000, cmd.toArray(new String[cmd.size()]), null, dotFullPath.removeLastSegments(1).toFile()); controller.forwardErrorOutput(errorOutput); controller.forwardOutput(System.out); controller.forwardInput(System.in); int exitCode = controller.execute(); System.err.println("runDot:" + exitCode + " size:" + errorOutput.size()); // if (exitCode != 0) { // for (String o:options) { // System.err.println(o); // } // System.err.println(dotFullPath.toString()); // return new Status(IStatus.WARNING, Activator.ID, // "Graphviz exit code: " + exitCode + "." // + createContentMessage(errorOutput)); // } if (errorOutput.size() > 0) return new Status(IStatus.WARNING, Activator.ID, createContentMessage(errorOutput)); return Status.OK_STATUS; } catch (ProcessController.TimeOutException e) { return new Status(IStatus.ERROR, Activator.ID, "Graphviz process did not finish in a timely way." + createContentMessage(errorOutput)); } catch (InterruptedException e) { return new Status(IStatus.ERROR, Activator.ID, "Unexpected exception executing Graphviz." + createContentMessage(errorOutput), e); } catch (IOException e) { return new Status(IStatus.ERROR, Activator.ID, "Unexpected exception executing Graphviz." + createContentMessage(errorOutput), e); } }
From source file:org.eclipse.che.api.factory.server.FactoryService.java
/** * Creates factory image from input stream. * InputStream should be closed manually. * * @param is/* w w w.j av a2 s . c om*/ * input stream with image data * @param mediaType * media type of image * @param name * image name * @return factory image, if {@param is} has no content then empty factory image will be returned * @throws BadRequestException * when factory image exceeded maximum size * @throws ServerException * when any server errors occurs */ public static FactoryImage createImage(InputStream is, String mediaType, String name) throws BadRequestException, ServerException { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int read; while ((read = is.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, read); if (out.size() > 1024 * 1024) { throw new BadRequestException("Maximum upload size exceeded."); } } if (out.size() == 0) { return new FactoryImage(); } out.flush(); return new FactoryImage(out.toByteArray(), mediaType, name); } catch (IOException ioEx) { throw new ServerException(ioEx.getLocalizedMessage()); } }
From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java
private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri, String postBody, StoredFile storedFile) { Log.d("Performing multipart request to %s", uri); ApptentiveHttpResponse ret = new ApptentiveHttpResponse(); if (storedFile == null) { Log.e("StoredFile is null. Unable to send."); return ret; }/* ww w .j a v a 2s . c o m*/ int bytesRead; int bufferSize = 4096; byte[] buffer; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = UUID.randomUUID().toString(); HttpURLConnection connection; DataOutputStream os = null; InputStream is = null; try { is = context.openFileInput(storedFile.getLocalFilePath()); // Set up the request. URL url = new URL(uri); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT); connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); connection.setRequestProperty("Authorization", "OAuth " + oauthToken); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("X-API-Version", API_VERSION); connection.setRequestProperty("User-Agent", getUserAgentString()); StringBuilder requestText = new StringBuilder(); // Write form data requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd); requestText.append("Content-Type: text/plain").append(lineEnd); requestText.append(lineEnd); requestText.append(postBody); requestText.append(lineEnd); // Write file attributes. requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"", storedFile.getFileName())).append(lineEnd); requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd); requestText.append(lineEnd); Log.d("Post body: " + requestText); // Open an output stream. os = new DataOutputStream(connection.getOutputStream()); // Write the text so far. os.writeBytes(requestText.toString()); try { // Write the actual file. buffer = new byte[bufferSize]; while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) { os.write(buffer, 0, bytesRead); } } catch (IOException e) { Log.d("Error writing file bytes to HTTP connection.", e); ret.setBadPayload(true); throw e; } os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); os.close(); ret.setCode(connection.getResponseCode()); ret.setReason(connection.getResponseMessage()); // TODO: These streams may not be ready to read now. Put this in a new thread. // Read the normal response. InputStream nis = null; ByteArrayOutputStream nbaos = null; try { Log.d("Sending file: " + storedFile.getLocalFilePath()); nis = connection.getInputStream(); nbaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) { nbaos.write(eBuf, 0, eRead); } ret.setContent(nbaos.toString()); } catch (IOException e) { Log.w("Can't read return stream.", e); } finally { Util.ensureClosed(nis); Util.ensureClosed(nbaos); } // Read the error response. InputStream eis = null; ByteArrayOutputStream ebaos = null; try { eis = connection.getErrorStream(); ebaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) { ebaos.write(eBuf, 0, eRead); } if (ebaos.size() > 0) { ret.setContent(ebaos.toString()); } } catch (IOException e) { Log.w("Can't read error stream.", e); } finally { Util.ensureClosed(eis); Util.ensureClosed(ebaos); } Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + ""); Log.v(ret.getContent()); } catch (FileNotFoundException e) { Log.e("Error getting file to upload.", e); } catch (MalformedURLException e) { Log.e("Error constructing url for file upload.", e); } catch (SocketTimeoutException e) { Log.w("Timeout communicating with server."); } catch (IOException e) { Log.e("Error executing file upload.", e); } finally { Util.ensureClosed(is); Util.ensureClosed(os); } return ret; }
From source file:com.abstratt.graphviz.GraphViz.java
/** * Bare bones API for launching dot. Command line options are passed to * Graphviz as specified in the options parameter. The location for dot is * obtained from the user preferences.//from w ww . ja va 2 s. c o m * * @param options * command line options for dot * @return a non-zero integer if errors happened * @throws IOException */ public static IStatus runDot(String... options) { IPath dotFullPath = GraphVizActivator.getInstance().getDotLocation(); if (dotFullPath == null || dotFullPath.isEmpty()) return new Status(IStatus.ERROR, GraphVizActivator.ID, "dot.exe/dot not found in PATH. Please install it from graphviz.org, update the PATH or specify the absolute path in the preferences."); if (!dotFullPath.toFile().isFile()) return new Status(IStatus.ERROR, GraphVizActivator.ID, "Could not find Graphviz dot at \"" + dotFullPath + "\""); List<String> cmd = new ArrayList<String>(); cmd.add(dotFullPath.toOSString()); // insert user custom options String commandLineExtension = GraphVizActivator.getInstance().getCommandLineExtension(); if (commandLineExtension != null) { String[] tokens = commandLineExtension.split(" "); cmd.addAll(Arrays.asList(tokens)); } cmd.addAll(Arrays.asList(options)); ByteArrayOutputStream errorOutput = new ByteArrayOutputStream(); try { final ProcessController controller = new ProcessController(60000, cmd.toArray(new String[cmd.size()]), null, dotFullPath.removeLastSegments(1).toFile()); controller.forwardErrorOutput(errorOutput); controller.forwardOutput(System.out); controller.forwardInput(System.in); int exitCode = controller.execute(); if (exitCode != 0) return new Status(IStatus.WARNING, GraphVizActivator.ID, "Graphviz exit code: " + exitCode + "." + createContentMessage(errorOutput)); if (errorOutput.size() > 0) return new Status(IStatus.WARNING, GraphVizActivator.ID, createContentMessage(errorOutput)); return Status.OK_STATUS; } catch (TimeOutException e) { return new Status(IStatus.ERROR, GraphVizActivator.ID, "Graphviz process did not finish in a timely way." + createContentMessage(errorOutput)); } catch (InterruptedException e) { return new Status(IStatus.ERROR, GraphVizActivator.ID, "Unexpected exception executing Graphviz." + createContentMessage(errorOutput), e); } catch (IOException e) { return new Status(IStatus.ERROR, GraphVizActivator.ID, "Unexpected exception executing Graphviz." + createContentMessage(errorOutput), e); } }