List of usage examples for java.io ByteArrayOutputStream reset
public synchronized void reset()
From source file:org.eclipse.dataset.metadata.Metadata.java
@Override public IMetadata clone() { Metadata c = null;/* ww w .j a v a2 s. c o m*/ try { c = (Metadata) super.clone(); if (metadata != null) { HashMap<String, Serializable> md = new HashMap<String, Serializable>(); c.metadata = md; ByteArrayOutputStream os = new ByteArrayOutputStream(512); for (String k : metadata.keySet()) { Serializable v = metadata.get(k); if (v != null) { // TODO: Note that there is a dependency on org.apache.commons.lang that is only used for // accessing SerializationUtils. In reality, the serialize call really is just: // try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) { // out.writeObject(v); // } finally { // out.close(); // } // and deserialize is similarly simple. SerializationUtils.serialize(v, os); Serializable nv = (Serializable) SerializationUtils.deserialize(os.toByteArray()); os.reset(); md.put(k, nv); } else { md.put(k, null); } } } c.shapes = new HashMap<String, int[]>(1); for (Entry<String, int[]> e : shapes.entrySet()) { int[] s = e.getValue(); c.shapes.put(e.getKey(), s == null ? null : s.clone()); } } catch (CloneNotSupportedException e) { // Allowed for some objects not to be cloned. } catch (Throwable e) { if (e instanceof ClassNotFoundException) { // Fix to http://jira.diamond.ac.uk/browse/SCI-1644 // Happens when cloning meta data with GridPreferences } if (e instanceof RuntimeException) { throw (RuntimeException) e; } } return c; }
From source file:org.apache.jackrabbit.core.query.lucene.SQL2IndexingAggregateTest.java
/** * simple index aggregation from jcr:content to nt:file * //from w ww. j av a 2s . c om * The aggregation hierarchy is defined in * src/test/repository/workspaces/indexing-test/indexing-configuration.xml * */ public void testNtFileAggregate() throws Exception { String sqlBase = "SELECT * FROM [nt:file] as f" + " WHERE ISCHILDNODE([" + testRoot + "])"; String sqlCat = sqlBase + " AND CONTAINS (f.*, 'cat')"; String sqlDog = sqlBase + " AND CONTAINS (f.*, 'dog')"; ByteArrayOutputStream out = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(out, "UTF-8"); writer.write("the quick brown fox jumps over the lazy dog."); writer.flush(); Node file = testRootNode.addNode("myFile", "nt:file"); Node resource = file.addNode("jcr:content", "nt:resource"); resource.setProperty("jcr:lastModified", Calendar.getInstance()); resource.setProperty("jcr:encoding", "UTF-8"); resource.setProperty("jcr:mimeType", "text/plain"); resource.setProperty("jcr:data", session.getValueFactory().createBinary(new ByteArrayInputStream(out.toByteArray()))); testRootNode.getSession().save(); executeSQL2Query(sqlDog, new Node[] { file }); // update jcr:data out.reset(); writer.write("the quick brown fox jumps over the lazy cat."); writer.flush(); resource.setProperty("jcr:data", session.getValueFactory().createBinary(new ByteArrayInputStream(out.toByteArray()))); testRootNode.getSession().save(); executeSQL2Query(sqlDog, new Node[] {}); executeSQL2Query(sqlCat, new Node[] { file }); // replace jcr:content with unstructured resource.remove(); Node unstrContent = file.addNode("jcr:content", "nt:unstructured"); Node foo = unstrContent.addNode("foo"); foo.setProperty("text", "the quick brown fox jumps over the lazy dog."); testRootNode.getSession().save(); executeSQL2Query(sqlDog, new Node[] { file }); executeSQL2Query(sqlCat, new Node[] {}); // remove foo foo.remove(); testRootNode.getSession().save(); executeSQL2Query(sqlDog, new Node[] {}); executeSQL2Query(sqlCat, new Node[] {}); // replace jcr:content again with resource unstrContent.remove(); resource = file.addNode("jcr:content", "nt:resource"); resource.setProperty("jcr:lastModified", Calendar.getInstance()); resource.setProperty("jcr:encoding", "UTF-8"); resource.setProperty("jcr:mimeType", "text/plain"); resource.setProperty("jcr:data", session.getValueFactory().createBinary(new ByteArrayInputStream(out.toByteArray()))); testRootNode.getSession().save(); executeSQL2Query(sqlDog, new Node[] {}); executeSQL2Query(sqlCat, new Node[] { file }); }
From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java
/** * Tests that the PurchaseOrderService would print purchase order quote requests list pdf. * * @throws Exception/*w ww.j a v a 2s . c o m*/ */ public void testPrintPurchaseOrderQuoteRequestsListPDF() throws Exception { PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS .createPurchaseOrderDocument(); po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN); po.refreshNonUpdateableReferences(); po.prepareForSave(); AccountingDocumentTestUtils.saveDocument(po, docService); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { DateTimeService dtService = SpringContext.getBean(DateTimeService.class); poService.printPurchaseOrderQuoteRequestsListPDF(po.getDocumentNumber(), baosPDF); assertTrue(baosPDF.size() > 0); } catch (ValidationException e) { LOG.warn("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber()); } finally { if (baosPDF != null) { baosPDF.reset(); } } }
From source file:org.dhatim.archive.Archive.java
/** * Add the entries from the supplied {@link ZipInputStream} to this archive instance. * @param zipStream The zip stream./* w w w .j ava 2 s. co m*/ * @return This archive instance. * @throws IOException Error reading zip stream. */ public Archive addEntries(ZipInputStream zipStream) throws IOException { AssertArgument.isNotNull(zipStream, "zipStream"); try { ZipEntry zipEntry = zipStream.getNextEntry(); ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); byte[] byteReadBuffer = new byte[512]; int byteReadCount; while (zipEntry != null) { if (zipEntry.isDirectory()) { addEntry(zipEntry.getName(), (byte[]) null); } else { while ((byteReadCount = zipStream.read(byteReadBuffer)) != -1) { outByteStream.write(byteReadBuffer, 0, byteReadCount); } addEntry(zipEntry.getName(), outByteStream.toByteArray()); outByteStream.reset(); } zipEntry = zipStream.getNextEntry(); } } finally { try { zipStream.close(); } catch (IOException e) { logger.debug("Unexpected error closing EDI Mapping Model Zip stream.", e); } } return this; }
From source file:org.apache.any23.Any23Test.java
@Test public void testExtractionParametersWithNestingDisabled() throws IOException, ExtractionException, TripleHandlerException { final int EXPECTED_TRIPLES = 19; Any23 runner = new Any23(); DocumentSource source = getDocumentSourceFromResource("/microformats/nested-microformats-a1.html", "http://www.test.com"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); CountingTripleHandler cth1 = new CountingTripleHandler(); RDFXMLWriter ctw1 = new RDFXMLWriter(baos); CompositeTripleHandler compositeTH1 = new CompositeTripleHandler(); compositeTH1.addChild(cth1);/*from w ww . ja va 2 s . c o m*/ compositeTH1.addChild(ctw1); runner.extract(new ExtractionParameters(DefaultConfiguration.singleton(), ValidationMode.None, true), source, compositeTH1); compositeTH1.close(); logger.debug("Out1: " + baos.toString()); Assert.assertEquals("Unexpected number of triples.", EXPECTED_TRIPLES + 3, cth1.getCount()); baos.reset(); CountingTripleHandler cth2 = new CountingTripleHandler(); NTriplesWriter ctw2 = new NTriplesWriter(baos); CompositeTripleHandler compositeTH2 = new CompositeTripleHandler(); compositeTH2.addChild(cth2); compositeTH2.addChild(ctw2); runner.extract( new ExtractionParameters(DefaultConfiguration.singleton(), ValidationMode.ValidateAndFix, false), source, compositeTH2); compositeTH2.close(); logger.debug("Out2: " + baos.toString()); Assert.assertEquals("Unexpected number of triples.", EXPECTED_TRIPLES, cth2.getCount()); }
From source file:com.amalto.core.delegator.IItemCtrlDelegator.java
public ArrayList<String> getItems(DataClusterPOJOPK dataClusterPOJOPK, String conceptName, IWhereItem whereItem, int spellThreshold, String orderBy, String direction, int start, int limit, boolean totalCountOnFirstRow) throws XtentisException { isExistDataCluster(dataClusterPOJOPK); Server server = ServerContext.INSTANCE.get(); StorageAdmin storageAdmin = server.getStorageAdmin(); String dataContainerName = dataClusterPOJOPK.getUniqueId(); Storage storage = storageAdmin.get(dataContainerName, storageAdmin.getType(dataContainerName)); MetadataRepository repository = storage.getMetadataRepository(); ComplexTypeMetadata type = repository.getComplexType(conceptName); if (type == null) { throw new IllegalArgumentException("Type '" + conceptName + "' does not exist in data cluster '" //$NON-NLS-1$ //$NON-NLS-2$ + dataContainerName + "'."); //$NON-NLS-1$ }// www.ja va 2 s .c om UserQueryBuilder qb = UserQueryBuilder.from(type); // Condition and paging qb.where(UserQueryHelper.buildCondition(qb, whereItem, repository)); qb.start(start < 0 ? 0 : start); // UI can send negative start index qb.limit(limit); // Order by if (orderBy != null) { String orderByFieldName = StringUtils.substringAfter(orderBy, "/"); //$NON-NLS-1$ List<TypedExpression> fields = UserQueryHelper.getFields(type, orderByFieldName); if (fields == null) { throw new IllegalArgumentException("Field '" + orderBy + "' does not exist."); //$NON-NLS-1$ //$NON-NLS-2$ } OrderBy.Direction queryDirection; if ("ascending".equals(direction) //$NON-NLS-1$ || "NUMBER:ascending".equals(direction) //$NON-NLS-1$ || "ASC".equals(direction)) { //$NON-NLS-1$ queryDirection = OrderBy.Direction.ASC; } else { queryDirection = OrderBy.Direction.DESC; } for (TypedExpression typedExpression : fields) { qb.orderBy(typedExpression, queryDirection); } } // Get records ArrayList<String> resultsAsString = new ArrayList<String>(); StorageResults results; try { storage.begin(); if (totalCountOnFirstRow) { results = storage.fetch(qb.getSelect()); resultsAsString.add("<totalCount>" + results.getCount() + "</totalCount>"); //$NON-NLS-1$ //$NON-NLS-2$ } results = storage.fetch(qb.getSelect()); DataRecordWriter writer = new DataRecordXmlWriter(type); writer.setSecurityDelegator(SecuredStorage.getDelegator()); ByteArrayOutputStream output = new ByteArrayOutputStream(); for (DataRecord result : results) { try { if (totalCountOnFirstRow) { output.write("<result>".getBytes()); //$NON-NLS-1$ } writer.write(result, output); if (totalCountOnFirstRow) { output.write("</result>".getBytes()); //$NON-NLS-1$ } } catch (IOException e) { throw new XtentisException(e); } String document = new String(output.toByteArray()); resultsAsString.add(document); output.reset(); } storage.commit(); } catch (Exception e) { storage.rollback(); throw new XtentisException(e); } return resultsAsString; }
From source file:com.datatorrent.lib.io.HttpInputOperator.java
@Override public void run() { while (super.isActive()) { try {/*w ww . j a v a 2 s . c o m*/ ClientResponse response = resource.header("x-stream", "rockon").accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); LOG.debug("Opening stream: " + resource); // media type check, if any, should be configuration based //if (!MediaType.APPLICATION_JSON_TYPE.equals(response.getType())) { // LOG.error("Unexpected response type " + response.getType()); // response.close(); //} else { InputStream is = response.getEntity(java.io.InputStream.class); while (true) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bytes = new byte[255]; int bytesRead; while ((bytesRead = is.read(bytes)) != -1) { LOG.debug("read {} bytes", bytesRead); bos.write(bytes, 0, bytesRead); if (is.available() == 0 && bos.size() > 0) { // give chance to process what we have before blocking on read break; } } if (processBytes(bos.toByteArray())) { LOG.debug("End of chunked input stream."); response.close(); break; } if (bytesRead == -1) { LOG.error("Unexpected end of chunked input stream"); response.close(); break; } bos.reset(); } //} } catch (Exception e) { LOG.error("Error reading from " + resource.getURI(), e); } try { Thread.sleep(500); } catch (InterruptedException e) { LOG.info("Exiting IO loop {}.", e.toString()); break; } } }
From source file:org.apache.any23.Any23Test.java
@Test public void testExtractionParameters() throws IOException, ExtractionException, TripleHandlerException { final int EXPECTED_TRIPLES = 6; Any23 runner = new Any23(); DocumentSource source = getDocumentSourceFromResource( "/org/apache/any23/validator/missing-og-namespace.html", "http://www.test.com"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); CountingTripleHandler cth1 = new CountingTripleHandler(); NTriplesWriter ctw1 = new NTriplesWriter(baos); CompositeTripleHandler compositeTH1 = new CompositeTripleHandler(); compositeTH1.addChild(cth1);//from w w w . ja va2 s.co m compositeTH1.addChild(ctw1); try { runner.extract(new ExtractionParameters(DefaultConfiguration.singleton(), ValidationMode.None), source, compositeTH1); } finally { compositeTH1.close(); } logger.info(baos.toString()); Assert.assertEquals("Unexpected number of triples.", EXPECTED_TRIPLES, cth1.getCount()); baos.reset(); CountingTripleHandler cth2 = new CountingTripleHandler(); NTriplesWriter ctw2 = new NTriplesWriter(baos); CompositeTripleHandler compositeTH2 = new CompositeTripleHandler(); compositeTH2.addChild(cth2); compositeTH2.addChild(ctw2); runner.extract(new ExtractionParameters(DefaultConfiguration.singleton(), ValidationMode.ValidateAndFix), source, compositeTH2); logger.debug(baos.toString()); Assert.assertEquals("Unexpected number of triples.", EXPECTED_TRIPLES + 5, cth2.getCount()); }
From source file:com.ge.predix.solsvc.blobstore.bootstrap.BlobstoreClientImpl.java
/** * Adds a new Blob to the binded bucket in the Object Store * * @param obj S3Object to be added//from w w w. jav a 2s. co m */ @Override public String saveBlob(S3Object obj) { if (obj == null) { this.log.error("put(): Empty file provided"); //$NON-NLS-1$ throw new RuntimeException("File is null"); //$NON-NLS-1$ } List<PartETag> partETags = new ArrayList<>(); String bucket = this.blobstoreConfig.getBucketName(); InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucket, obj.getKey()); InitiateMultipartUploadResult initResponse = this.s3Client.initiateMultipartUpload(initRequest); try (InputStream is = obj.getObjectContent();) { int i = 1; int currentPartSize = 0; ByteArrayOutputStream tempBuffer = new ByteArrayOutputStream(); int byteValue; while ((byteValue = is.read()) != -1) { tempBuffer.write(byteValue); currentPartSize = tempBuffer.size(); if (currentPartSize == (50 * 1024 * 1024)) //make this a const { byte[] b = tempBuffer.toByteArray(); ByteArrayInputStream byteStream = new ByteArrayInputStream(b); UploadPartRequest uploadPartRequest = new UploadPartRequest().withBucketName(bucket) .withKey(obj.getKey()).withUploadId(initResponse.getUploadId()).withPartNumber(i++) .withInputStream(byteStream).withPartSize(currentPartSize); partETags.add(this.s3Client.uploadPart(uploadPartRequest).getPartETag()); tempBuffer.reset(); } } this.log.info("currentPartSize: " + currentPartSize); //$NON-NLS-1$ ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(currentPartSize); if (this.enableSSE) { objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); } obj.setObjectMetadata(objectMetadata); if (i == 1 && currentPartSize < (5 * 1024 * 1024)) // make this a const { this.s3Client.abortMultipartUpload( new AbortMultipartUploadRequest(bucket, obj.getKey(), initResponse.getUploadId())); byte[] b = tempBuffer.toByteArray(); ByteArrayInputStream byteStream = new ByteArrayInputStream(b); objectMetadata.setContentType(getContentType(b)); if (this.enableSSE) { objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); } obj.setObjectMetadata(objectMetadata); PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, obj.getKey(), byteStream, obj.getObjectMetadata()); this.s3Client.putObject(putObjectRequest); ObjectMetadata meta = this.s3Client.getObjectMetadata(bucket, obj.getKey()); Map<String, Object> headers = meta.getRawMetadata(); for (Map.Entry<String, Object> entry : headers.entrySet()) { this.log.info("Object Metadata -- " + entry.getKey() + ": " + entry.getValue().toString()); //$NON-NLS-1$ //$NON-NLS-2$ } return initResponse.getUploadId(); } if (currentPartSize > 0 && currentPartSize <= (50 * 1024 * 1024)) // make this a const { byte[] b = tempBuffer.toByteArray(); ByteArrayInputStream byteStream = new ByteArrayInputStream(b); this.log.info("currentPartSize: " + currentPartSize); //$NON-NLS-1$ this.log.info("byteArray: " + b); //$NON-NLS-1$ UploadPartRequest uploadPartRequest = new UploadPartRequest().withBucketName(bucket) .withKey(obj.getKey()).withUploadId(initResponse.getUploadId()).withPartNumber(i) .withInputStream(byteStream).withPartSize(currentPartSize); partETags.add(this.s3Client.uploadPart(uploadPartRequest).getPartETag()); } CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest() .withBucketName(bucket).withPartETags(partETags).withUploadId(initResponse.getUploadId()) .withKey(obj.getKey()); this.s3Client.completeMultipartUpload(completeMultipartUploadRequest); return initResponse.getUploadId(); } catch (Exception e) { this.log.error("put(): Exception occurred in put(): " + e.getMessage()); //$NON-NLS-1$ this.s3Client.abortMultipartUpload( new AbortMultipartUploadRequest(bucket, obj.getKey(), initResponse.getUploadId())); throw new RuntimeException("put(): Exception occurred in put(): ", e); //$NON-NLS-1$ } }
From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java
/** * Tests that the PurchaseOrderService would print purchase order quote pdf. * * @throws Exception//from w w w .j a v a2s. c o m */ public void testPrintPurchaseOrderQuotePDF() throws Exception { PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS .createPurchaseOrderDocument(); po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN); po.refreshNonUpdateableReferences(); po.prepareForSave(); AccountingDocumentTestUtils.saveDocument(po, docService); PurchaseOrderVendorQuote vendorQuote = PurchaseOrderVendorQuoteFixture.BASIC_VENDOR_QUOTE_1 .createPurchaseOrderVendorQuote(); vendorQuote.setDocumentNumber(po.getDocumentNumber()); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { poService.printPurchaseOrderQuotePDF(po, vendorQuote, baosPDF); assertTrue(baosPDF.size() > 0); LOG.error("Attn From testPrintPurchaseOrderQuotePDF"); LOG.error("baosPDF.size is : " + baosPDF.size()); LOG.error("----------------------------------------"); } catch (Exception e) { LOG.warn("Caught ValidationException while trying to print PO quote pdf with doc id " + po.getDocumentNumber()); } finally { if (baosPDF != null) { baosPDF.reset(); } } }