List of usage examples for java.io ByteArrayOutputStream size
public synchronized int size()
From source file:com.microsoft.azure.storage.core.Utility.java
/** * Encrypts an input stream up to a given length. * Exits early if the encrypted data is longer than the abandon length. * /*from w w w . j av a 2 s . c om*/ * @param sourceStream * A <code>InputStream</code> object that represents the stream to measure. * @param targetStream * A <code>ByteArrayOutputStream</code> object that represents the stream to write the encrypted data. * @param cipher * The <code>Cipher</code> to use to encrypt the data. * @param writeLength * The number of bytes to read and encrypt from the sourceStream. * @param abandonLength * The number of bytes to read before the analysis is abandoned. Set this value to <code>-1</code> to * force the entire stream to be read. This parameter is provided to support upload thresholds. * @return * The size of the encrypted stream, or -1 if the encrypted stream would be over the abandonLength. * @throws IOException * If an I/O error occurs. */ public static long encryptStreamIfUnderThreshold(final InputStream sourceStream, final ByteArrayOutputStream targetStream, Cipher cipher, long writeLength, long abandonLength) throws IOException { if (abandonLength < 0) { abandonLength = Long.MAX_VALUE; } if (!sourceStream.markSupported()) { throw new IllegalArgumentException(SR.INPUT_STREAM_SHOULD_BE_MARKABLE); } sourceStream.mark(Constants.MAX_MARK_LENGTH); if (writeLength < 0) { writeLength = Long.MAX_VALUE; } CipherOutputStream encryptStream = new CipherOutputStream(targetStream, cipher); int count = -1; long totalEncryptedLength = targetStream.size(); final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH]; int nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength); count = sourceStream.read(retrievedBuff, 0, nextCopy); while (nextCopy > 0 && count != -1) { // Note: We are flushing the CryptoStream on every write here. This way, we don't end up encrypting more data than we intend here, if // we go over the abandonLength. encryptStream.write(retrievedBuff, 0, count); encryptStream.flush(); totalEncryptedLength = targetStream.size(); if (totalEncryptedLength > abandonLength) { // Abandon operation break; } nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength); count = sourceStream.read(retrievedBuff, 0, nextCopy); } sourceStream.reset(); sourceStream.mark(Constants.MAX_MARK_LENGTH); encryptStream.close(); totalEncryptedLength = targetStream.size(); if (totalEncryptedLength > abandonLength) { totalEncryptedLength = -1; } return totalEncryptedLength; }
From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializerTest.java
@Test public void testSerializeApplicationVersionWithLiveMarshallers() throws Exception { underTest.setArchive(false);//from w w w . j a v a 2 s .co m underTest.setMarshallerMap(liveMarshallerMap); // Set a spy on the ApplicationVersionConverter ApplicationVersionConverter applicationVersionConverter = spy(new ApplicationVersionConverter()); XStreamMarshaller xsm = (XStreamMarshaller) underTest.getMarshallerMap().get(StreamId.APPLICATION_VERSION) .getMarshaller(); XStream x = xsm.getXStream(); x.registerConverter(applicationVersionConverter, XStream.PRIORITY_VERY_HIGH); // because there is a non-spy // version of this already // registered in the configure // method ByteArrayOutputStream result = new ByteArrayOutputStream(); underTest.serialize(state, StreamId.APPLICATION_VERSION, result); verify(applicationVersionConverter, atLeastOnce()).canConvert(ApplicationVersion.class); // cant verify the marshal(...) method b/c it's final verify(applicationVersionConverter).marshalInternal(eq(applicationVersion), any(HierarchicalStreamWriter.class), any(MarshallingContext.class)); assertTrue(result.size() > 1); }
From source file:org.apache.jmeter.protocol.amf.proxy.AmfRequestHdr.java
/** * Parses a http header from a stream./*from w w w . ja v a 2s .c o m*/ * * @param in * the stream to parse. * @return array of bytes from client. */ public byte[] parse(InputStream in) throws IOException { boolean inHeaders = true; int readLength = 0; int dataLength = 0; boolean firstLine = true; ByteArrayOutputStream clientRequest = new ByteArrayOutputStream(); ByteArrayOutputStream line = new ByteArrayOutputStream(); int x; while ((inHeaders || readLength < dataLength) && ((x = in.read()) != -1)) { line.write(x); clientRequest.write(x); if (firstLine && !CharUtils.isAscii((char) x)) {// includes \n throw new IllegalArgumentException("Only ASCII supported in headers (perhaps SSL was used?)"); } if (inHeaders && (byte) x == (byte) '\n') { // $NON-NLS-1$ if (line.size() < 3) { inHeaders = false; firstLine = false; // cannot be first line either } if (firstLine) { parseFirstLine(line.toString()); firstLine = false; } else { // parse other header lines, looking for Content-Length final int contentLen = parseLine(line.toString()); if (contentLen > 0) { dataLength = contentLen; // Save the last valid content length one } } if (log.isDebugEnabled()) { log.debug("Client Request Line: " + line.toString()); } line.reset(); } else if (!inHeaders) { readLength++; } } // Keep the raw post data rawPostData = line.toByteArray(); if (log.isDebugEnabled()) { log.debug("rawPostData in default JRE encoding: " + new String(rawPostData)); // TODO - charset? log.debug("Request: " + clientRequest.toString()); } return clientRequest.toByteArray(); }
From source file:org.commoncrawl.util.CompressedURLFPList.java
public static void validateURLFPSerializationRootDomain() { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); Builder firstBuilder = new Builder(FLAG_ARCHIVE_SEGMENT_ID); TreeMultimap<Integer, URLFP> sourceMap = TreeMultimap.create(); TreeMultimap<Integer, URLFP> destMap = TreeMultimap.create(); ;/* w w w .j a v a 2s .c om*/ // top level domain with matching sub domain an two urls insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "0", 1); insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_2 + "1", 1); // top level domain with matching sub domain an two urls insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "2", 1); insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_2 + "3", 1); // top level domain with matching sub domain an two urls insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "4", 1); insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_2 + "5", 1); addMapToBuilder(firstBuilder, sourceMap); try { // flush to byte stream ... firstBuilder.flush(byteStream); // now set up to read the stream ByteArrayInputStream inputStream = new ByteArrayInputStream(byteStream.toByteArray(), 0, byteStream.size()); Reader reader = new Reader(inputStream); while (reader.hasNext()) { URLFP fp = reader.next(); destMap.put(fp.getRootDomainHash(), fp); } reader.close(); // dump both lists for (Integer rootDomain : sourceMap.keySet()) { for (URLFP urlfp : sourceMap.get(rootDomain)) { System.out.println("SourceFP Root:" + urlfp.getRootDomainHash() + " Domain:" + urlfp.getDomainHash() + " URL:" + urlfp.getUrlHash()); } } for (Integer rootDomain : destMap.keySet()) { for (URLFP urlfp : destMap.get(rootDomain)) { System.out.println("DestFP Root:" + urlfp.getRootDomainHash() + " Domain:" + urlfp.getDomainHash() + " URL:" + urlfp.getUrlHash()); } } System.out .println("Buffer Size:" + byteStream.size() + " URLCount:" + firstBuilder.getLinkMap().size()); Assert.assertTrue(sourceMap.equals(destMap)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:ffx.FFXClassLoader.java
/** * {@inheritDoc}/*from ww w.ja v a2 s .c o m*/ * * Finds and defines the given class among the extension JARs given in * constructor, then among resources. */ @Override protected Class findClass(String name) throws ClassNotFoundException { /* if (name.startsWith("com.jogamp")) { System.out.println(" Class requested:" + name); } */ if (!extensionsLoaded) { loadExtensions(); } // Build class file from its name String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; if (extensionJars != null) { for (JarFile extensionJar : extensionJars) { JarEntry jarEntry = extensionJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = extensionJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } } // If it's not an extension class, search if its an application // class that can be read from resources if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } ByteArrayOutputStream out = null; BufferedInputStream in = null; try { // Read class input content to a byte array out = new ByteArrayOutputStream(); in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8192]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } // Define class return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { throw new ClassNotFoundException("Class " + name, e); } } }
From source file:SearchlistClassLoader.java
/** * load the byte data for a class definition. * * @param name the fully-qualified class name * @return a byte[] containing the class bytecode or <i>null</i> */// w ww. j a va2s . c om protected byte[] loadClassData(ClassLoader cl, String name) { ByteArrayOutputStream barray; byte buff[]; int len; InputStream in = cl.getResourceAsStream(translate(name, ".", "/") + ".class"); if (in == null) return null; try { barray = new ByteArrayOutputStream(1024 * 16); buff = new byte[1024]; do { len = in.read(buff, 0, buff.length); if (len > 0) barray.write(buff, 0, len); } while (len >= 0); return (barray.size() > 0 ? barray.toByteArray() : null); } catch (Exception e) { return null; } }
From source file:controllers.AnyplaceMapping.java
private static Results.Status gzippedOk(final String body) throws IOException { final ByteArrayOutputStream gzip = gzip(body); response().setHeader("Content-Encoding", "gzip"); response().setHeader("Content-Length", gzip.size() + ""); return ok(gzip.toByteArray()); }
From source file:controllers.AnyplaceMapping.java
/** * Should check if Request Headers accept gzip encoding * <p>/*from w w w . j av a 2 s.c o m*/ * Creates a response with a gzipped string. Changes the content-type. */ private static Results.Status gzippedJSONOk(final String body) throws IOException { final ByteArrayOutputStream gzip = gzip(body); response().setHeader("Content-Encoding", "gzip"); response().setHeader("Content-Length", gzip.size() + ""); response().setHeader("Content-Type", "application/json"); return ok(gzip.toByteArray()); }
From source file:com.clustercontrol.http.util.GetHttpResponse.java
/** * URL??//from ww w. ja v a 2 s .c om * * @param url URL * @param timeout * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws KeyManagementException * @throws IOException * @throws ClientProtocolException */ public boolean execute(String url, String post) { Response result = new Response(); try { CloseableHttpClient client = getHttpClient(); result.url = url; if (m_authType != null && !AuthType.NONE.equals(m_authType)) { URI uri = new URI(url); Credentials credential = null; String authSchema = null; switch (m_authType) { case BASIC: credential = new UsernamePasswordCredentials(m_authUser, m_authPassword); authSchema = "basic"; break; case NTLM: credential = new NTCredentials(m_authUser, m_authPassword, null, null); authSchema = "ntlm"; break; case DIGEST: credential = new UsernamePasswordCredentials(m_authUser, m_authPassword); authSchema = "digest"; break; default: m_log.warn("Auth type is unexpected value. AuthType = " + m_authType.name()); } if (credential != null) { AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, authSchema); if (m_cledentialProvider.getCredentials(scope) == null) { m_cledentialProvider.setCredentials(scope, credential); } } } HttpRequestBase request = null; if (post != null && !post.isEmpty()) { List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); for (String ss : post.split("&")) { int index = ss.indexOf("="); if (index <= 0) { continue; } urlParameters.add(new BasicNameValuePair(ss.substring(0, index), ss.substring(index + 1))); } if (m_log.isTraceEnabled()) { m_log.trace("post1=" + post + ", post2=" + urlParameters); } HttpPost requestPost = new HttpPost(url); Charset charset = Consts.UTF_8; try { charset = Charset.forName( HinemosPropertyUtil.getHinemosPropertyStr("monitor.http.post.charset", "UTF-8")); } catch (UnsupportedCharsetException e) { m_log.warn("UnsupportedCharsetException " + e.getMessage()); } requestPost.setEntity(new UrlEncodedFormEntity(urlParameters, charset)); requestPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); request = requestPost; } else { request = new HttpGet(url); } // Execute the method. try { long start = HinemosTime.currentTimeMillis(); HttpResponse response = client.execute(request); result.responseTime = HinemosTime.currentTimeMillis() - start; result.statusCode = response.getStatusLine().getStatusCode(); // Header Header[] headers = response.getAllHeaders(); if (headers != null && headers.length > 0) { StringBuffer header = new StringBuffer(); for (int i = 0; i < headers.length; i++) { header.append((i != 0 ? "\n" : "") + headers[i]); } result.headerString = header.toString(); result.headers = Arrays.asList(headers); } if (result.statusCode == HttpStatus.SC_OK) { result.success = true; // Content-Type?text?????Body? Header header = response.getFirstHeader(HTTP.CONTENT_TYPE); boolean contentTypeFlag = false; String[] contentTypes = HinemosPropertyUtil .getHinemosPropertyStr(TARGET_CONTENT_TYPE_KEY, "text").split(","); if (header != null && header.getValue() != null) { String value = header.getValue(); for (String contentType : contentTypes) { if (value.indexOf(contentType) != -1) { contentTypeFlag = true; break; } } } if (contentTypeFlag) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (InputStream in = response.getEntity().getContent()) { byte[] buffer = new byte[BUFF_SIZE]; while (out.size() < BODY_MAX_SIZE) { int len = in.read(buffer); if (len < 0) { break; } out.write(buffer, 0, len); } } // ????HTTP ? meta ??????? // HTTP ?? // // Content-Type: text/html; charset=euc-jp // // meta ? // // <meta http-equiv="Content-Type" content="text/html; charset=euc-jp"> // <meta charset="euc-jp"> // // HTML ???meta ????? // // ???????????????? // ??????????????????? // ???????????????? // // ?????????????????? // // 1. HTTP ? Content-Type ? charset ???????? // ????????? // // 2. ????????"JISAutoDetect" ??? // ???? // // 3. ??????meta ?? // // 4. meta ?????????? // ???????? // ??????????? String charset = "JISAutoDetect"; Matcher m = chasetPattern.matcher(header.getValue()); if (m.matches()) charset = m.group(1); String content = new String(out.toByteArray(), charset); CharsetParser parser = new CharsetParser(); ParserDelegator p = new ParserDelegator(); p.parse(new StringReader(content), parser, true); if (parser.charset != null && !charset.equals(parser.charset)) { charset = parser.charset; content = new String(out.toByteArray(), charset); } result.responseBody = content; } else { result.errorMessage = MessageConstant.MESSAGE_FAIL_TO_CHECK_NOT_TEXT.getMessage(); } } else { result.errorMessage = response.getStatusLine().toString(); } } finally { request.releaseConnection(); } } catch (UnsupportedEncodingException e) { m_log.info("execute(): " + e.getMessage() + " class=" + e.getClass().getName()); result.errorMessage = "http receiving failure. (unsupported encoding)"; result.exception = e; } catch (IOException e) { m_log.info("execute(): Fatal transport error. " + e.getMessage() + " class=" + e.getClass().getName()); result.errorMessage = "http requesting failure. (I/O error : unreachable or timeout)"; result.exception = e; } catch (Exception e) { m_log.info("execute(): " + e.getMessage() + " class=" + e.getClass().getName()); result.errorMessage = "http requesting failure. " + e.getMessage() + "(" + e.getClass().getSimpleName() + ")"; result.exception = e; } m_requestResult = result; return m_requestResult.success; }
From source file:com.gst.infrastructure.reportmailingjob.service.ReportMailingJobWritePlatformServiceImpl.java
/** * generate the report output stream//from w w w.j a v a 2s .c om * * @param reportMailingJob * @param emailAttachmentFileFormat * @param reportParams * @param reportName * @param errorLog * @return the error log StringBuilder object */ private StringBuilder generateReportOutputStream(final ReportMailingJob reportMailingJob, final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat, final MultivaluedMap<String, String> reportParams, final String reportName, final StringBuilder errorLog) { try { final String reportType = this.readReportingService.getReportType(reportName); final ReportingProcessService reportingProcessService = this.reportingProcessServiceProvider .findReportingProcessService(reportType); if (reportingProcessService != null) { final Response processReport = reportingProcessService.processRequest(reportName, reportParams); final Object reponseObject = (processReport != null) ? processReport.getEntity() : null; if (reponseObject != null && reponseObject.getClass().equals(ByteArrayOutputStream.class)) { final ByteArrayOutputStream byteArrayOutputStream = ByteArrayOutputStream.class .cast(reponseObject); final String fileLocation = FileSystemContentRepository.FINERACT_BASE_DIR + File.separator + ""; final String fileNameWithoutExtension = fileLocation + File.separator + reportName; // check if file directory exists, if not create directory if (!new File(fileLocation).isDirectory()) { new File(fileLocation).mkdirs(); } if ((byteArrayOutputStream == null) || byteArrayOutputStream.size() == 0) { errorLog.append("Report processing failed, empty output stream created"); } else if ((errorLog != null && errorLog.length() == 0) && (byteArrayOutputStream.size() > 0)) { final String fileName = fileNameWithoutExtension + "." + emailAttachmentFileFormat.getValue(); // send the file to email recipients this.sendReportFileToEmailRecipients(reportMailingJob, fileName, byteArrayOutputStream, errorLog); } } else { errorLog.append("Response object entity is not equal to ByteArrayOutputStream ---------- "); } } else { errorLog.append("ReportingProcessService object is null ---------- "); } } catch (Exception e) { errorLog.append( "The ReportMailingJobWritePlatformServiceImpl.generateReportOutputStream method threw an Exception: " + e + " ---------- "); } return errorLog; }