List of usage examples for java.io ByteArrayOutputStream reset
public synchronized void reset()
From source file:org.apache.hadoop.hdfs.server.namenode.MockFSInputStream.java
public void testWriteTo() throws IOException, InterruptedException { FSInputStream fsin = new MockFSInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); // new int[]{s_1, c_1, s_2, c_2, ..., s_n, c_n} means to test // reading c_i bytes starting at s_i int[] pairs = new int[] { 0, 10000, 50, 100, 50, 6000, 1000, 2000, 0, 1, 0, 0, 5000, 0, }; assertTrue("Pairs array must be even", pairs.length % 2 == 0); for (int i = 0; i < pairs.length; i += 2) { StreamFile.writeTo(fsin, os, pairs[i], pairs[i + 1]); assertArrayEquals("Reading " + pairs[i + 1] + " bytes from offset " + pairs[i], getOutputArray(pairs[i], pairs[i + 1]), os.toByteArray()); os.reset(); }//from w w w. j a va 2 s . c o m }
From source file:org.dragonet.net.inf.mcpe.PENetworkClient.java
private synchronized void sendAllACK() { if (this.queueACK.isEmpty()) { return;//from www.ja v a 2 s . co m } int[] ackSeqs = ArrayUtils.toPrimitive(this.queueACK.toArray(new Integer[0])); Arrays.sort(ackSeqs); this.queueACK.clear(); ByteArrayOutputStream allRecBos = new ByteArrayOutputStream(); PEBinaryWriter allRecWriter = new PEBinaryWriter(allRecBos); try { int count = ackSeqs.length; int records = 0; if (count > 0) { int pointer = 1; int start = ackSeqs[0]; int last = ackSeqs[0]; ByteArrayOutputStream recBos = new ByteArrayOutputStream(); PEBinaryWriter recWriter; while (pointer < count) { int current = ackSeqs[pointer++]; int diff = current - last; if (diff == 1) { last = current; } else if (diff > 1) { //Forget about duplicated packets (bad queues?) recBos.reset(); recWriter = new PEBinaryWriter(recBos); if (start == last) { recWriter.writeByte((byte) 0x01); recWriter.writeTriad(start); start = last = current; } else { recWriter.writeByte((byte) 0x00); recWriter.writeTriad(start); recWriter.writeTriad(last); start = last = current; } records++; } } if (start == last) { allRecWriter.writeByte((byte) 0x01); allRecWriter.writeTriad(start); } else { allRecWriter.writeByte((byte) 0x00); allRecWriter.writeTriad(start); allRecWriter.writeTriad(last); } records++; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); PEBinaryWriter writer = new PEBinaryWriter(bos); writer.writeByte((byte) 0xC0); writer.writeShort((short) (records & 0xFFFF)); writer.write(allRecBos.toByteArray()); handler.send(bos.toByteArray(), this.remoteAddress); } catch (IOException e) { } }
From source file:org.dragonet.net.inf.mcpe.PENetworkClient.java
private synchronized void sendAllNACK() { if (this.queueNACK.isEmpty()) { return;//from w w w .j a v a2s . c o m } int[] ackSeqs = ArrayUtils.toPrimitive(this.queueNACK.toArray(new Integer[0])); Arrays.sort(ackSeqs); this.queueNACK.clear(); ByteArrayOutputStream allRecBos = new ByteArrayOutputStream(); PEBinaryWriter allRecWriter = new PEBinaryWriter(allRecBos); try { int count = ackSeqs.length; int records = 0; if (count > 0) { int pointer = 1; int start = ackSeqs[0]; int last = ackSeqs[0]; ByteArrayOutputStream recBos = new ByteArrayOutputStream(); PEBinaryWriter recWriter; while (pointer < count) { int current = ackSeqs[pointer++]; int diff = current - last; if (diff == 1) { last = current; } else if (diff > 1) { //Forget about duplicated packets (bad queues?) recBos.reset(); recWriter = new PEBinaryWriter(recBos); if (start == last) { recWriter.writeByte((byte) 0x01); recWriter.writeTriad(start); start = last = current; } else { recWriter.writeByte((byte) 0x00); recWriter.writeTriad(start); recWriter.writeTriad(last); start = last = current; } records++; } } if (start == last) { allRecWriter.writeByte((byte) 0x01); allRecWriter.writeTriad(start); } else { allRecWriter.writeByte((byte) 0x00); allRecWriter.writeTriad(start); allRecWriter.writeTriad(last); } records++; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); PEBinaryWriter writer = new PEBinaryWriter(bos); writer.writeByte((byte) 0xA0); writer.writeShort((short) (records & 0xFFFF)); writer.write(allRecBos.toByteArray()); handler.send(bos.toByteArray(), this.remoteAddress); } catch (IOException e) { } }
From source file:org.silverpeas.migration.jcr.service.SimpleDocumentServiceTest.java
/** * Test of getBinaryContent method, of class DocumentRepository. *//*from www . j a v a 2s.co m*/ @Test public void testGetBinaryContent() throws Exception { new JcrSimpleDocumentServiceTest() { @Override public void run() throws Exception { String foreignId = "node18"; SimpleDocument document = createAttachmentForTest(defaultDocumentBuilder(foreignId).setOrder(10), defaultENContentBuilder(), "This is a test"); ByteArrayOutputStream bibaryContent = new ByteArrayOutputStream(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "en"); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("This is a test")); bibaryContent.reset(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "en", 1, 2); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("hi")); bibaryContent.reset(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "en", 1, 50); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("his is a test")); bibaryContent.reset(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "en", -10, 50); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("This is a test")); bibaryContent.reset(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "fr"); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("")); updateAttachmentForTest(document, "fr", "Ceci est un test"); bibaryContent.reset(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "en"); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("This is a test")); bibaryContent.reset(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "fr"); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("Ceci est un test")); updateAttachmentForTest(document, "en", "A"); updateAttachmentForTest(document, "fr", "B"); bibaryContent.reset(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "en"); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("A")); bibaryContent.reset(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "en", 1, 4); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("")); bibaryContent.reset(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "fr"); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("B")); bibaryContent.reset(); getSimpleDocumentService().getBinaryContent(bibaryContent, document.getPk(), "fr", 1, 2); assertThat(bibaryContent.toString(Charsets.UTF_8.name()), is("")); } }.execute(); }
From source file:org.kuali.ole.module.purap.document.web.struts.PrintAction.java
@Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //get parameters String poDocNumber = request.getParameter("poDocNumber"); Integer vendorQuoteId = new Integer(request.getParameter("vendorQuoteId")); if (StringUtils.isEmpty(poDocNumber) || StringUtils.isEmpty(poDocNumber)) { throw new RuntimeException(); }/*from w w w .j av a2 s .com*/ // doc service - get this doc PurchaseOrderDocument po = (PurchaseOrderDocument) SpringContext.getBean(DocumentService.class) .getByDocumentHeaderId(poDocNumber); DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class) .getDocumentAuthorizer(po); if (!documentAuthorizer.canInitiate(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER, GlobalVariables.getUserSession().getPerson())) { throw new DocumentInitiationException(OLEKeyConstants.AUTHORIZATION_ERROR_DOCUMENT, new String[] { GlobalVariables.getUserSession().getPerson().getPrincipalName(), "print", "Purchase Order" }); } // get the vendor quote PurchaseOrderVendorQuote poVendorQuote = null; for (PurchaseOrderVendorQuote vendorQuote : po.getPurchaseOrderVendorQuotes()) { if (vendorQuote.getPurchaseOrderVendorQuoteIdentifier().equals(vendorQuoteId)) { poVendorQuote = vendorQuote; break; } } if (poVendorQuote == null) { throw new RuntimeException(); } ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); poVendorQuote.setTransmitPrintDisplayed(false); try { StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_"); sbFilename.append(po.getPurapDocumentIdentifier()); sbFilename.append("_"); sbFilename.append(System.currentTimeMillis()); sbFilename.append(".pdf"); // call the print service boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po, poVendorQuote, baosPDF); if (!success) { poVendorQuote.setTransmitPrintDisplayed(true); if (baosPDF != null) { baosPDF.reset(); } return mapping.findForward(OLEConstants.MAPPING_BASIC); } response.setHeader("Cache-Control", "max-age=30"); response.setContentType("application/pdf"); StringBuffer sbContentDispValue = new StringBuffer(); // sbContentDispValue.append("inline"); sbContentDispValue.append("attachment"); sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); response.setContentLength(baosPDF.size()); ServletOutputStream sos; sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); } finally { if (baosPDF != null) { baosPDF.reset(); } } return null; }
From source file:org.kuali.kfs.module.purap.document.web.struts.PrintAction.java
@Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //get parameters String poDocNumber = request.getParameter("poDocNumber"); Integer vendorQuoteId = new Integer(request.getParameter("vendorQuoteId")); if (StringUtils.isEmpty(poDocNumber) || StringUtils.isEmpty(poDocNumber)) { throw new RuntimeException(); }//ww w . j a v a2 s. c o m // doc service - get this doc PurchaseOrderDocument po = (PurchaseOrderDocument) SpringContext.getBean(DocumentService.class) .getByDocumentHeaderId(poDocNumber); DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class) .getDocumentAuthorizer(po); if (!(documentAuthorizer.canInitiate(KFSConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER, GlobalVariables.getUserSession().getPerson()) || documentAuthorizer.canInitiate( KFSConstants.FinancialDocumentTypeCodes.CONTRACT_MANAGER_ASSIGNMENT, GlobalVariables.getUserSession().getPerson()))) { throw new DocumentInitiationException(KFSKeyConstants.AUTHORIZATION_ERROR_DOCUMENT, new String[] { GlobalVariables.getUserSession().getPerson().getPrincipalName(), "print", "Purchase Order" }); } // get the vendor quote PurchaseOrderVendorQuote poVendorQuote = null; for (PurchaseOrderVendorQuote vendorQuote : po.getPurchaseOrderVendorQuotes()) { if (vendorQuote.getPurchaseOrderVendorQuoteIdentifier().equals(vendorQuoteId)) { poVendorQuote = vendorQuote; break; } } if (poVendorQuote == null) { throw new RuntimeException(); } ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); poVendorQuote.setTransmitPrintDisplayed(false); try { StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_"); sbFilename.append(po.getPurapDocumentIdentifier()); sbFilename.append("_"); sbFilename.append(System.currentTimeMillis()); sbFilename.append(".pdf"); // call the print service boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po, poVendorQuote, baosPDF); if (!success) { poVendorQuote.setTransmitPrintDisplayed(true); if (baosPDF != null) { baosPDF.reset(); } return mapping.findForward(KFSConstants.MAPPING_BASIC); } response.setHeader("Cache-Control", "max-age=30"); response.setContentType("application/pdf"); StringBuffer sbContentDispValue = new StringBuffer(); // sbContentDispValue.append("inline"); sbContentDispValue.append("attachment"); sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); response.setContentLength(baosPDF.size()); ServletOutputStream sos; sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); } finally { if (baosPDF != null) { baosPDF.reset(); } } return null; }
From source file:lvge.com.myapp.modules.shop_management.NotAuthenticationFragment.java
private String saveBitmap(String name, Bitmap bitmap) throws IOException { File sd = Environment.getExternalStorageDirectory(); boolean can_write = sd.canWrite(); // Bitmap bitm = convertViewToBitMap(sale_consultant_two_iamgeview); String strPath = Environment.getExternalStorageDirectory().toString() + "/save"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); if (baos.toByteArray().length / 1024 > 500) { int option = 90; while (baos.toByteArray().length / 1024 > 500) { baos.reset(); bitmap.compress(Bitmap.CompressFormat.PNG, option, baos); option -= 10;/* w ww . j a va2 s . c o m*/ } ByteArrayInputStream isbm = new ByteArrayInputStream(baos.toByteArray()); bitmap = BitmapFactory.decodeStream(isbm, null, null); isbm.close(); } baos.close(); try { File desDir = new File(strPath); if (!desDir.exists()) { desDir.mkdir(); } File imageFile = new File(strPath + "/" + name + ".PNG"); if (imageFile.exists()) { imageFile.delete(); } imageFile.createNewFile(); FileOutputStream fos = new FileOutputStream(imageFile); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return strPath + "/" + name + ".PNG"; }
From source file:org.wso2.carbon.endpoint.service.EndpointAdmin.java
/** * Add an endpoint to the Synapse registry * * @param key of the dynamic endpoint * @param epConfiguration endpoint configuration * @throws EndpointAdminException in case of an error */// www . j av a 2s . c om public boolean addDynamicEndpoint(String key, String epConfiguration) throws EndpointAdminException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.reset(); String originalKey = key; try { org.wso2.carbon.registry.core.Registry registry; if (key.startsWith("conf:")) { registry = getConfigSystemRegistry(); key = key.replace("conf:", ""); } else { registry = getGovernanceRegistry(); key = key.replace("gov:", ""); } if (!registry.resourceExists(key)) { try { OMElement endpointElement = AXIOMUtil.stringToOM(epConfiguration); OMFactory fac = OMAbstractFactory.getOMFactory(); String name = originalKey.replace(":", "/"); endpointElement.addAttribute(fac.createOMAttribute("name", fac.createOMNamespace(XMLConfigConstants.NULL_NAMESPACE, ""), name)); XMLPrettyPrinter.prettify(endpointElement, stream); } catch (Exception e) { handleFault("Unable to pretty print configuration", e); } epConfiguration = new String(stream.toByteArray()).trim(); Resource resource = registry.newResource(); resource.setMediaType(WSO2_ENDPOINT_MEDIA_TYPE); resource.setContent(epConfiguration); registry.put(key, resource); } else { log.warn("Resource is already exists"); return false; } } catch (RegistryException e) { handleFault("WSO2 Registry Exception", e); return false; } return true; }
From source file:org.apache.accumulo.test.merkle.cli.GenerateHashes.java
public void run(final Connector conn, final String inputTableName, final String outputTableName, final String digestName, int numThreads, final boolean iteratorPushdown, final Collection<Range> ranges) throws TableNotFoundException, AccumuloSecurityException, AccumuloException, NoSuchAlgorithmException { if (!conn.tableOperations().exists(outputTableName)) { throw new IllegalArgumentException(outputTableName + " does not exist, please create it"); }//from w w w . j a va 2 s .c om ExecutorService svc = Executors.newFixedThreadPool(numThreads); final BatchWriter bw = conn.createBatchWriter(outputTableName, new BatchWriterConfig()); try { for (final Range range : ranges) { final MessageDigest digest = getDigestAlgorithm(digestName); svc.execute(new Runnable() { @Override public void run() { Scanner s; try { s = conn.createScanner(inputTableName, Authorizations.EMPTY); } catch (Exception e) { log.error("Could not get scanner for " + inputTableName, e); throw new RuntimeException(e); } s.setRange(range); Value v = null; Mutation m = null; if (iteratorPushdown) { IteratorSetting cfg = new IteratorSetting(50, DigestIterator.class); cfg.addOption(DigestIterator.HASH_NAME_KEY, digestName); s.addScanIterator(cfg); // The scanner should only ever return us one Key-Value, otherwise this approach won't work Entry<Key, Value> entry = Iterables.getOnlyElement(s); v = entry.getValue(); m = RangeSerialization.toMutation(range, v); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (Entry<Key, Value> entry : s) { DataOutputStream out = new DataOutputStream(baos); try { entry.getKey().write(out); entry.getValue().write(out); } catch (Exception e) { log.error("Error writing {}", entry, e); throw new RuntimeException(e); } digest.update(baos.toByteArray()); baos.reset(); } v = new Value(digest.digest()); m = RangeSerialization.toMutation(range, v); } // Log some progress log.info("{} computed digest for {} of {}", Thread.currentThread().getName(), range, Hex.encodeHexString(v.get())); try { bw.addMutation(m); } catch (MutationsRejectedException e) { log.error("Could not write mutation", e); throw new RuntimeException(e); } } }); } svc.shutdown(); // Wait indefinitely for the scans to complete while (!svc.isTerminated()) { try { Thread.sleep(1000); } catch (InterruptedException e) { log.error("Interrupted while waiting for executor service to gracefully complete. Exiting now"); svc.shutdownNow(); return; } } } finally { // We can only safely close this when we're exiting or we've completely all tasks bw.close(); } }
From source file:org.apache.fop.fonts.type1.Type1SubsetFile.java
/** * Creates a new subset from the given type 1 font input stream * @param sbfont The font object containing information such as the * characters from which to create the subset * @param subsetSubroutines This option will force the subset to include all * subroutines./*from w w w .j a va2 s .c o m*/ * @return Returns the subset as a byte array * @throws IOException */ private byte[] createSubset(SingleByteFont sbfont, boolean subsetSubroutines) throws IOException { this.subsetSubroutines = subsetSubroutines; InputStream in = new ByteArrayInputStream(fullFont); //Initialise resources used for the font creation this.sbfont = sbfont; PFBParser pfbParser = new PFBParser(); PFBData pfbData = pfbParser.parsePFB(in); PostscriptParser psParser = new PostscriptParser(); charNames = new ArrayList<String>(); //Parse the header section of the font if (headerSection == null) { headerSection = psParser.parse(pfbData.getHeaderSegment()); } //Read the encoding section PSElement encoding = getElement("/Encoding", headerSection); if (encoding.getFoundUnexpected()) { //Fully embed the font as we're unable to interpret postscript on arrays return new byte[0]; } List<String> subsetEncodingEntries = readEncoding(encoding); //Decode the main section in preparation for parsing byte[] decoded = BinaryCoder.decodeBytes(pfbData.getEncryptedSegment(), 55665, 4); //Initialise the resources used to hold the subset data uniqueSubs = new LinkedHashMap<Integer, byte[]>(); subsetCharStrings = new HashMap<String, byte[]>(); //Parse the encoded main font section for elements if (mainSection == null) { mainSection = psParser.parse(decoded); } //Process and write the main section PSElement charStrings = getElement("/CharStrings", mainSection); boolean result = readMainSection(mainSection, decoded, subsetEncodingEntries, charStrings); if (!result) { /* This check handles the case where a font uses a postscript method to return a * subroutine index. As there is currently no java postscript interpreter and writing * one would be very difficult it prevents us from handling this eventuality. The way * this issue is being handled is to restart the subset process and include all * subroutines. */ uniqueSubs.clear(); subsetCharStrings.clear(); charNames.clear(); return createSubset(sbfont, false); } //Write header section ByteArrayOutputStream boasHeader = writeHeader(pfbData, encoding); ByteArrayOutputStream boasMain = writeMainSection(decoded, mainSection, charStrings); byte[] mainSectionBytes = boasMain.toByteArray(); mainSectionBytes = BinaryCoder.encodeBytes(mainSectionBytes, 55665, 4); boasMain.reset(); boasMain.write(mainSectionBytes); ByteArrayOutputStream baosTrailer = new ByteArrayOutputStream(); baosTrailer.write(pfbData.getTrailerSegment(), 0, pfbData.getTrailerSegment().length); return stitchFont(boasHeader, boasMain, baosTrailer); }