List of usage examples for java.io ByteArrayOutputStream reset
public synchronized void reset()
From source file:edu.vt.middleware.crypt.signature.SignatureCliTest.java
/** * @param partialLine Partial command line. * @param pubKey Public key file./*from ww w .j a v a 2 s. c o m*/ * @param privKey Private key file. * * @throws Exception On test failure. */ @Test(groups = { "cli", "signature" }, dataProvider = "testdata") public void testSignatureCli(final String partialLine, final String pubKey, final String privKey) throws Exception { final String pubKeyPath = KEY_DIR_PATH + pubKey; final String privKeyPath = KEY_DIR_PATH + privKey; final PrintStream oldStdOut = System.out; try { final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(outStream)); // Compute signature and verify it String fullLine = partialLine + " -sign " + " -key " + privKeyPath + " -in " + TEST_PLAINTEXT; logger.info("Testing signature CLI sign operation with command line:\n\t" + fullLine); SignatureCli.main(CliHelper.splitArgs(fullLine)); final String sig = outStream.toString(); Assert.assertTrue(sig.length() > 0); // Write signature out to file for use in verify step new File(TEST_OUTPUT_DIR).mkdir(); final File sigFile = new File(TEST_OUTPUT_DIR + "sig.out"); final BufferedOutputStream sigOs = new BufferedOutputStream(new FileOutputStream(sigFile)); try { sigOs.write(outStream.toByteArray()); } finally { sigOs.close(); } outStream.reset(); // Verify signature fullLine = partialLine + " -verify " + sigFile + " -key " + pubKeyPath + " -in " + TEST_PLAINTEXT; logger.info("Testing signature CLI verify operation with command " + "line:\n\t" + fullLine); SignatureCli.main(CliHelper.splitArgs(fullLine)); final String result = outStream.toString(); AssertJUnit.assertTrue(result.indexOf("SUCCESS") != -1); } catch (Exception e) { e.printStackTrace(); } finally { // Restore STDOUT System.setOut(oldStdOut); } }
From source file:com.amalto.core.delegator.IItemCtrlDelegator.java
public ArrayList<String> viewSearch(DataClusterPOJOPK dataClusterPOJOPK, ViewPOJOPK viewPOJOPK, IWhereItem whereItem, String orderBy, String direction, int start, int limit) throws XtentisException { try {//from ww w. j a va 2 s . c om ViewPOJO view = getViewPOJO(viewPOJOPK); whereItem = Util.fixWebConditions(whereItem, getLocalUser().getUserXML()); // Create an ItemWhere which combines the search and and view wheres ArrayList<IWhereItem> conditions = view.getWhereConditions().getList(); // fix conditions: value of condition do not generate xquery. Util.fixConditions(conditions); // Set User Property conditions. if (Util.isContainUserProperty(conditions)) { Util.updateUserPropertyCondition(conditions, getLocalUser().getUserXML()); } IWhereItem fullWhere = getFullWhereCondition(whereItem, conditions); // Add Filters from the Roles ILocalUser user = getLocalUser(); HashSet<String> roleNames = user.getRoles(); String objectType = "View"; //$NON-NLS-1$ ArrayList<IWhereItem> roleWhereConditions = new ArrayList<IWhereItem>(); for (String roleName : roleNames) { if (SecurityConfig.isSecurityPermission(roleName)) { continue; } // load Role RolePOJO role = ObjectPOJO.load(RolePOJO.class, new RolePOJOPK(roleName)); // get Specifications for the View Object RoleSpecification specification = role.getRoleSpecifications().get(objectType); if (specification != null) { if (!specification.isAdmin()) { Set<String> regexIds = specification.getInstances().keySet(); for (String regexId : regexIds) { if (viewPOJOPK.getIds()[0].matches(regexId)) { HashSet<String> parameters = specification.getInstances().get(regexId) .getParameters(); for (String marshaledWhereCondition : parameters) { if (marshaledWhereCondition == null || marshaledWhereCondition.trim().length() == 0) { continue; } WhereCondition whereCondition = RoleWhereCondition .parse(marshaledWhereCondition).toWhereCondition(); String conditionValue = whereCondition.getRightValueOrPath(); if ((conditionValue != null && conditionValue.length() > 0) || WhereCondition.EMPTY_NULL.equals(whereCondition.getOperator())) { roleWhereConditions.add(whereCondition); } } } } } } } // add collected additional conditions if (roleWhereConditions.size() > 0) { // Set User Property conditions. if (Util.isContainUserProperty(roleWhereConditions)) { Util.updateUserPropertyCondition(roleWhereConditions, getLocalUser().getUserXML()); } IWhereItem normalizedRolesConditions = normalizeConditions(roleWhereConditions); if (fullWhere == null) { fullWhere = normalizedRolesConditions; } else { WhereAnd wAnd = new WhereAnd(); wAnd.add(fullWhere); wAnd.add(normalizedRolesConditions); fullWhere = wAnd; } } // Find revision id for type String typeName = view.getSearchableBusinessElements().getList().get(0).split("/")[0]; //$NON-NLS-1$ // Try to get storage for revision Server server = ServerContext.INSTANCE.get(); String dataModelName = dataClusterPOJOPK.getUniqueId(); StorageAdmin storageAdmin = server.getStorageAdmin(); Storage storage = storageAdmin.get(dataModelName, storageAdmin.getType(dataModelName)); MetadataRepository repository = storage.getMetadataRepository(); boolean isStaging = storage.getType() == StorageType.STAGING; // Build query (from 'main' type) ComplexTypeMetadata type = repository.getComplexType(typeName); if (type == null) { throw new IllegalArgumentException( "Type '" + typeName + "' does not exist in data cluster '" + dataModelName //$NON-NLS-1$ //$NON-NLS-2$ + "'."); //$NON-NLS-1$ } UserQueryBuilder qb = UserQueryBuilder.from(type); // Select fields ArrayListHolder<String> viewableBusinessElements = view.getViewableBusinessElements(); for (String viewableBusinessElement : viewableBusinessElements.getList()) { String viewableTypeName = StringUtils.substringBefore(viewableBusinessElement, "/"); //$NON-NLS-1$ String viewablePath = StringUtils.substringAfter(viewableBusinessElement, "/"); //$NON-NLS-1$ if (viewablePath.isEmpty()) { throw new IllegalArgumentException("View element '" + viewableBusinessElement //$NON-NLS-1$ + "' is invalid: no path to element."); //$NON-NLS-1$ } ComplexTypeMetadata viewableType = repository.getComplexType(viewableTypeName); List<TypedExpression> fields = UserQueryHelper.getFields(viewableType, viewablePath); for (TypedExpression field : fields) { if (isNeedToAddExplicitly(isStaging, field)) { qb.select(field); } } } qb.select(repository.getComplexType(typeName), "../../taskId"); //$NON-NLS-1$ if (isStaging) { qb.select(repository.getComplexType(typeName), "$staging_status$"); //$NON-NLS-1$ qb.select(repository.getComplexType(typeName), "$staging_error$"); //$NON-NLS-1$ qb.select(repository.getComplexType(typeName), "$staging_source$"); //$NON-NLS-1$ } // Condition and paging qb.where(UserQueryHelper.buildCondition(qb, fullWhere, repository)); qb.start(start < 0 ? 0 : start); // UI can send negative start index qb.limit(limit); // Order by if (orderBy != null) { ComplexTypeMetadata orderByType = repository .getComplexType(StringUtils.substringBefore(orderBy, "/")); //$NON-NLS-1$ String orderByFieldName = StringUtils.substringAfter(orderBy, "/"); //$NON-NLS-1$ List<TypedExpression> fields = UserQueryHelper.getFields(orderByType, orderByFieldName); 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 field : fields) { qb.orderBy(field, queryDirection); } } // Get records ArrayList<String> resultsAsString = new ArrayList<String>(); try { storage.begin(); StorageResults results = storage.fetch(qb.getSelect()); resultsAsString.add("<totalCount>" + results.getCount() + "</totalCount>"); //$NON-NLS-1$ //$NON-NLS-2$ DataRecordWriter writer = new ViewSearchResultsWriter(); ByteArrayOutputStream output = new ByteArrayOutputStream(); for (DataRecord result : results) { try { writer.write(result, output); } catch (IOException e) { throw new XmlServerException(e); } String document = new String(output.toByteArray(), Charset.forName("UTF-8")); //$NON-NLS-1$ resultsAsString.add(document); output.reset(); } storage.commit(); } catch (Exception e) { storage.rollback(); throw new XmlServerException(e); } return resultsAsString; } catch (XtentisException e) { throw (e); } catch (Exception e) { String err = "Unable to single search: " + ": " + e.getClass().getName() + ": " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + e.getLocalizedMessage(); LOGGER.error(err, e); throw new XtentisException(err, e); } }
From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java
public final void testPurchaseOrderRetransmit() throws Exception { // Create and save a minimally-populated basic PO document for each test. PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS .createPurchaseOrderDocument(); po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN); po.refreshNonUpdateableReferences(); po.prepareForSave();/*from ww w . ja v a2s. c om*/ AccountingDocumentTestUtils.saveDocument(po, docService); PurchaseOrderDocument poRetrans = null; try { poRetrans = poService.createAndSavePotentialChangeDocument(po.getDocumentNumber(), PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT, PurchaseOrderStatuses.APPDOC_PENDING_RETRANSMIT); po = poService.getPurchaseOrderByDocumentNumber(po.getDocumentNumber()); } catch (ValidationException ve) { fail("Validation errors creating PO retransmit document: " + dumpMessageMapErrors()); } assertMatchRetransmit(po, poRetrans); ((PurchaseOrderItem) poRetrans.getItem(0)).setItemSelectedForRetransmitIndicator(true); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { poService.retransmitPurchaseOrderPDF(poRetrans, baosPDF); assertTrue(baosPDF.size() > 0); } catch (ValidationException e) { fail("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber() + "\n" + dumpMessageMapErrors()); } finally { if (baosPDF != null) { baosPDF.reset(); } } }
From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java
public final void testPurchaseOrderPrint() throws Exception { PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS .createPurchaseOrderDocument(); po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN); po.refreshNonUpdateableReferences(); po.prepareForSave();/*from w w w .java2s .com*/ AccountingDocumentTestUtils.saveDocument(po, docService); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { poService.performPrintPurchaseOrderPDFOnly(po.getDocumentNumber(), baosPDF); assertTrue(baosPDF.size() > 0); } catch (ValidationException e) { fail("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber() + "\n" + dumpMessageMapErrors()); } finally { if (baosPDF != null) { baosPDF.reset(); } } }
From source file:IntSort.java
public void writeStream(String[] sData, boolean[] bData, int[] iData) { try {//from w w w .ja v a2s. c o m // Write data into an internal byte array ByteArrayOutputStream strmBytes = new ByteArrayOutputStream(); // Write Java data types into the above byte array DataOutputStream strmDataType = new DataOutputStream(strmBytes); byte[] record; for (int i = 0; i < sData.length; i++) { // Write Java data types strmDataType.writeUTF(sData[i]); strmDataType.writeBoolean(bData[i]); strmDataType.writeInt(iData[i]); // Clear any buffered data strmDataType.flush(); // Get stream data into byte array and write record record = strmBytes.toByteArray(); rs.addRecord(record, 0, record.length); // Toss any data in the internal array so writes // starts at beginning (of the internal array) strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } }
From source file:com.datatorrent.lib.io.HttpJsonChunksInputOperator.java
@Override public void processResponse(ClientResponse response) throws IOException { 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; }// www. j a v a2 s.c om } try { if (processBytes(bos.toByteArray())) { LOG.debug("End of chunked input stream."); response.close(); break; } } catch (JSONException ex) { LOG.error("Caught JSON error:", ex); } if (bytesRead == -1) { LOG.error("Unexpected end of chunked input stream"); response.close(); break; } bos.reset(); } }
From source file:com.yk.notification.util.BitmapUtil.java
/** * ?// w ww. j a v a 2 s . c om * * @param image * ?Bitmap * @return ?Bitmap */ public static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// ?100???baos int options = 100; while (baos.toByteArray().length / 1024 > 100) { // ??100kb, baos.reset();// ?baos?baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);// options%??baos options -= 10;// ??10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// ??baosByteArrayInputStream Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// ByteArrayInputStream?? return bitmap; }
From source file:com.ge.predix.sample.blobstore.repository.BlobstoreService.java
/** * Adds a new Blob to the binded bucket in the Object Store * * @param obj S3Object to be added//from w w w .ja v a 2s. c o m * @throws Exception */ public void put(S3Object obj) throws Exception { if (obj == null) { log.error("put(): Empty file provided"); throw new Exception("File is null"); } InputStream is = obj.getObjectContent(); List<PartETag> partETags = new ArrayList<>(); InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucket, obj.getKey()); InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest); try { 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(s3Client.uploadPart(uploadPartRequest).getPartETag()); tempBuffer.reset(); } } log.info("currentPartSize: " + currentPartSize); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(currentPartSize); obj.setObjectMetadata(objectMetadata); if (i == 1 && currentPartSize < (5 * 1024 * 1024)) // make this a const { s3Client.abortMultipartUpload( new AbortMultipartUploadRequest(bucket, obj.getKey(), initResponse.getUploadId())); byte[] b = tempBuffer.toByteArray(); ByteArrayInputStream byteStream = new ByteArrayInputStream(b); PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, obj.getKey(), byteStream, obj.getObjectMetadata()); s3Client.putObject(putObjectRequest); return; } if (currentPartSize > 0 && currentPartSize <= (50 * 1024 * 1024)) // make this a const { byte[] b = tempBuffer.toByteArray(); ByteArrayInputStream byteStream = new ByteArrayInputStream(b); log.info("currentPartSize: " + currentPartSize); log.info("byteArray: " + b); UploadPartRequest uploadPartRequest = new UploadPartRequest().withBucketName(bucket) .withKey(obj.getKey()).withUploadId(initResponse.getUploadId()).withPartNumber(i) .withInputStream(byteStream).withPartSize(currentPartSize); partETags.add(s3Client.uploadPart(uploadPartRequest).getPartETag()); } } catch (Exception e) { log.error("put(): Exception occurred in put(): " + e.getMessage()); s3Client.abortMultipartUpload( new AbortMultipartUploadRequest(bucket, obj.getKey(), initResponse.getUploadId())); throw e; } CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest() .withBucketName(bucket).withPartETags(partETags).withUploadId(initResponse.getUploadId()) .withKey(obj.getKey()); s3Client.completeMultipartUpload(completeMultipartUploadRequest); }
From source file:org.apache.hadoop.hbase.mapreduce.TestRowCounter.java
/** * test main method. Import should print help and call System.exit *//*from ww w . j av a2 s.c om*/ @Test public void testImportMain() throws Exception { PrintStream oldPrintStream = System.err; SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSecurityManager newSecurityManager = new LauncherSecurityManager(); System.setSecurityManager(newSecurityManager); ByteArrayOutputStream data = new ByteArrayOutputStream(); String[] args = {}; System.setErr(new PrintStream(data)); try { System.setErr(new PrintStream(data)); try { RowCounter.main(args); fail("should be SecurityException"); } catch (SecurityException e) { assertEquals(-1, newSecurityManager.getExitCode()); assertTrue(data.toString().contains("Wrong number of parameters:")); assertTrue(data.toString() .contains("Usage: RowCounter [options] <tablename> [--range=[startKey],[endKey]] " + "[<column1> <column2>...]")); assertTrue(data.toString().contains("-Dhbase.client.scanner.caching=100")); assertTrue(data.toString().contains("-Dmapreduce.map.speculative=false")); } data.reset(); try { args = new String[2]; args[0] = "table"; args[1] = "--range=1"; RowCounter.main(args); fail("should be SecurityException"); } catch (SecurityException e) { assertEquals(-1, newSecurityManager.getExitCode()); assertTrue(data.toString().contains( "Please specify range in such format as \"--range=a,b\" or, with only one boundary," + " \"--range=,b\" or \"--range=a,\"")); assertTrue(data.toString() .contains("Usage: RowCounter [options] <tablename> [--range=[startKey],[endKey]] " + "[<column1> <column2>...]")); } } finally { System.setErr(oldPrintStream); System.setSecurityManager(SECURITY_MANAGER); } }
From source file:org.apache.hadoop.hive.cli.TestCliDriverMethods.java
public void testRun() throws Exception { // clean history String historyDirectory = System.getProperty("user.home"); if ((new File(historyDirectory)).exists()) { File historyFile = new File(historyDirectory + File.separator + ".hivehistory"); historyFile.delete();// w w w. j a v a2 s.co m } HiveConf configuration = new HiveConf(); configuration.setBoolVar(ConfVars.HIVE_SESSION_HISTORY_ENABLED, true); PrintStream oldOut = System.out; ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(dataOut)); PrintStream oldErr = System.err; ByteArrayOutputStream dataErr = new ByteArrayOutputStream(); System.setErr(new PrintStream(dataErr)); CliSessionState ss = new CliSessionState(configuration); CliSessionState.start(ss); String[] args = {}; try { new FakeCliDriver().run(args); assertTrue(dataOut.toString(), dataOut.toString().contains("test message")); assertTrue(dataErr.toString(), dataErr.toString().contains("Hive history file=")); assertTrue(dataErr.toString(), dataErr.toString().contains("File: fakeFile is not a file.")); dataOut.reset(); dataErr.reset(); } finally { System.setOut(oldOut); System.setErr(oldErr); } }