List of usage examples for java.io ByteArrayOutputStream reset
public synchronized void reset()
From source file:NetUtils.java
/** * Encode a path as required by the URL specificatin (<a href="http://www.ietf.org/rfc/rfc1738.txt"> * RFC 1738</a>). This differs from <code>java.net.URLEncoder.encode()</code> which encodes according * to the <code>x-www-form-urlencoded</code> MIME format. * * @param path the path to encode/*w ww . j av a2 s.c o m*/ * @return the encoded path */ public static String encodePath(String path) { // stolen from org.apache.catalina.servlets.DefaultServlet ;) /** * Note: This code portion is very similar to URLEncoder.encode. * Unfortunately, there is no way to specify to the URLEncoder which * characters should be encoded. Here, ' ' should be encoded as "%20" * and '/' shouldn't be encoded. */ int maxBytesPerChar = 10; StringBuffer rewrittenPath = new StringBuffer(path.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar); OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(buf, "UTF8"); } catch (Exception e) { e.printStackTrace(); writer = new OutputStreamWriter(buf); } for (int i = 0; i < path.length(); i++) { int c = (int) path.charAt(i); if (safeCharacters.get(c)) { rewrittenPath.append((char) c); } else { // convert to external encoding before hex conversion try { writer.write(c); writer.flush(); } catch (IOException e) { buf.reset(); continue; } byte[] ba = buf.toByteArray(); for (int j = 0; j < ba.length; j++) { // Converting each byte in the buffer byte toEncode = ba[j]; rewrittenPath.append('%'); int low = (int) (toEncode & 0x0f); int high = (int) ((toEncode & 0xf0) >> 4); rewrittenPath.append(hexadecimal[high]); rewrittenPath.append(hexadecimal[low]); } buf.reset(); } } return rewrittenPath.toString(); }
From source file:processing.app.linux.Platform.java
@Override public Map<String, Object> resolveDeviceAttachedTo(String serial, Map<String, TargetPackage> packages, String devicesListOutput) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Executor executor = new ExternalProcessExecutor(baos); try {//from ww w . java2 s . c o m CommandLine toDevicePath = CommandLine.parse("udevadm info -q path -n " + serial); executor.execute(toDevicePath); String devicePath = new String(baos.toByteArray()); baos.reset(); CommandLine commandLine = CommandLine.parse("udevadm info --query=property -p " + devicePath); executor.execute(commandLine); String vidPid = new UDevAdmParser().extractVIDAndPID(new String(baos.toByteArray())); if (vidPid == null) { return super.resolveDeviceAttachedTo(serial, packages, devicesListOutput); } return super.resolveDeviceByVendorIdProductId(packages, vidPid); } catch (IOException e) { return super.resolveDeviceAttachedTo(serial, packages, devicesListOutput); } }
From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDInlinedImage.java
/** * This will take the inlined image information and create a java.awt.Image from * it.//from w ww .java2s . com * * @param colorSpaces The ColorSpace dictionary from the current resources, if any. * * @return The image that this object represents. * * @throws IOException If there is an error creating the image. */ public BufferedImage createImage(Map colorSpaces) throws IOException { /* * This was the previous implementation, not sure which is better right now. * byte[] transparentColors = new byte[]{(byte)0xFF,(byte)0xFF}; byte[] colors=new byte[]{0, (byte)0xFF}; IndexColorModel colorModel = new IndexColorModel( 1, 2, colors, colors, colors, transparentColors ); BufferedImage image = new BufferedImage( params.getWidth(), params.getHeight(), BufferedImage.TYPE_BYTE_BINARY, colorModel ); DataBufferByte buffer = new DataBufferByte( getImageData(), 1 ); WritableRaster raster = Raster.createPackedRaster( buffer, params.getWidth(), params.getHeight(), params.getBitsPerComponent(), new Point(0,0) ); image.setData( raster ); return image; */ //verify again pci32.pdf before changing below PDColorSpace pcs = params.getColorSpace(colorSpaces); ColorModel colorModel; if (pcs != null) { colorModel = pcs.createColorModel(params.getBitsPerComponent()); } else { byte[] transparentColors = new byte[] { (byte) 0xFF, (byte) 0xFF }; byte[] colors = new byte[] { 0, (byte) 0xFF }; colorModel = new IndexColorModel(1, 2, colors, colors, colors, transparentColors); } boolean invert = false; // maybe a decode array is defined COSBase dictObj = params.getDictionary().getDictionaryObject(COSName.DECODE, COSName.D); if (dictObj != null && dictObj instanceof COSArray) { COSArray decode = (COSArray) dictObj; if (decode.getInt(0) == 1) { if (params.getBitsPerComponent() == 1) { // [1.0, 0.0] -> invert the "color" values invert = true; } else { //TODO implement decode array for BPC > 1 LOG.warn("decode array is not implemented for BPC > 1"); } } } List filters = params.getFilters(); byte[] finalData; if (filters == null || filters.isEmpty()) { finalData = getImageData(); } else { ByteArrayInputStream in = new ByteArrayInputStream(getImageData()); ByteArrayOutputStream out = new ByteArrayOutputStream(getImageData().length); FilterManager filterManager = new FilterManager(); for (int i = 0; i < filters.size(); i++) { out.reset(); Filter filter = filterManager.getFilter((String) filters.get(i)); filter.decode(in, out, params.getDictionary(), i); in = new ByteArrayInputStream(out.toByteArray()); } finalData = out.toByteArray(); } WritableRaster raster = colorModel.createCompatibleWritableRaster(params.getWidth(), params.getHeight()); /* Raster.createPackedRaster( buffer, params.getWidth(), params.getHeight(), params.getBitsPerComponent(), new Point(0,0) ); */ DataBuffer rasterBuffer = raster.getDataBuffer(); if (rasterBuffer instanceof DataBufferByte) { DataBufferByte byteBuffer = (DataBufferByte) rasterBuffer; byte[] data = byteBuffer.getData(); System.arraycopy(finalData, 0, data, 0, data.length); if (invert) { invertBitmap(data); } } else if (rasterBuffer instanceof DataBufferInt) { DataBufferInt byteBuffer = (DataBufferInt) rasterBuffer; int[] data = byteBuffer.getData(); for (int i = 0; i < finalData.length; i++) { data[i] = (finalData[i] + 256) % 256; if (invert) { data[i] = (~data[i] & 0xFF); } } } BufferedImage image = new BufferedImage(colorModel, raster, false, null); image.setData(raster); return image; }
From source file:com.vrs.qrw100s.NetworkReader.java
@Override public void run() { Thread.currentThread().setName("Network Reader"); HttpResponse res;//from w w w .ja va 2s . com DefaultHttpClient httpclient = new DefaultHttpClient(); HttpParams httpParams = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 10 * 1000); Log.d(TAG, "1. Sending http request"); try { res = httpclient.execute(new HttpGet(URI.create(myURL))); Log.d(TAG, "2. Request finished, status = " + res.getStatusLine().getStatusCode()); if (res.getStatusLine().getStatusCode() == 401) { return; } DataInputStream bis = new DataInputStream(res.getEntity().getContent()); ByteArrayOutputStream jpgOut = new ByteArrayOutputStream(10000); int prev = 0; int cur; while ((cur = bis.read()) >= 0 && _runThread) { if (prev == 0xFF && cur == 0xD8) { // reset the output stream if (!skipFrame) { jpgOut.reset(); jpgOut.write((byte) prev); } } if (!skipFrame) { if (jpgOut != null) { jpgOut.write((byte) cur); } } if (prev == 0xFF && cur == 0xD9) { if (!skipFrame) { synchronized (curFrame) { curFrame = jpgOut.toByteArray(); } skipFrame = true; Message threadMessage = mainHandler.obtainMessage(); threadMessage.obj = curFrame; mainHandler.sendMessage(threadMessage); } else { if (skipNum < frameDecrement) { skipNum++; } else { skipNum = 0; skipFrame = false; } } } prev = cur; } } catch (ClientProtocolException e) { Log.d(TAG, "Request failed-ClientProtocolException", e); } catch (IOException e) { Log.d(TAG, "Request failed-IOException", e); } }
From source file:org.openstatic.http.HttpResponse.java
/** Set the entire response body to the contents of an InputStream which will be read until EOF into memory and then relayed */ public void setBufferedData(InputStream is, String contentType) { try {/*from w w w . ja v a 2 s . co m*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); int inputByte; while ((inputByte = is.read()) > -1) { baos.write(inputByte); } is.close(); this.data = new ByteArrayInputStream(baos.toByteArray()); this.dataLength = baos.size(); baos.reset(); this.contentType = contentType; } catch (Exception e) { this.responseCode = "404 Not Found"; } }
From source file:at.medevit.elexis.ehc.core.internal.EhcCoreServiceImpl.java
@Override public InputStream getXdmAsStream(ClinicalDocument document) throws Exception { ConvenienceCommunication conCom = new ConvenienceCommunication(); ByteArrayOutputStream outputStream = null; // write document and create an InputStream outputStream = new ByteArrayOutputStream(); CDAUtil.save(document, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); outputStream.reset(); // write XDM and create an InputStream DocumentMetadata metaData = conCom.addDocument(DocumentDescriptor.CDA_R2, inputStream); metaData.setPatient(getPatient(document)); conCom.createXdmContents(outputStream); return new ByteArrayInputStream(outputStream.toByteArray()); }
From source file:org.apereo.portal.portlet.container.cache.LimitingTeeOutputStreamTest.java
@Test public void testContentExceedsClearBuffer() throws IOException { final byte[] content = "<p>Simple content</p>".getBytes(); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); LimitingTeeOutputStream stream = new LimitingTeeOutputStream(content.length - 1, NullOutputStream.NULL_OUTPUT_STREAM, byteStream, new Function<LimitingTeeOutputStream, Object>() { @Override//w w w .ja v a2 s . c o m public Object apply(LimitingTeeOutputStream input) { byteStream.reset(); return null; } }); // write the first few chars stream.write(content, 0, 5); // verify content successfully buffered assertFalse(stream.isLimitReached()); final byte[] subContent = Arrays.copyOf(content, 5); assertArrayEquals(subContent, byteStream.toByteArray()); // now write the remainder stream.write(content, 5, content.length); assertTrue(stream.isLimitReached()); assertArrayEquals(new byte[0], byteStream.toByteArray()); // try to write more and see no results stream.write("a".getBytes()); assertArrayEquals(new byte[0], byteStream.toByteArray()); }
From source file:com.intel.chimera.stream.AbstractCryptoStreamTest.java
private void doByteBufferWrite(String cipherClass, ByteArrayOutputStream baos, boolean withChannel) throws Exception { baos.reset(); CryptoOutputStream out = getCryptoOutputStream(baos, getCipher(cipherClass), defaultBufferSize, iv, withChannel);//from w w w . j a va2s. c o m ByteBuffer buf = ByteBuffer.allocateDirect(dataLen / 2); buf.put(data, 0, dataLen / 2); buf.flip(); int n1 = out.write(buf); buf.clear(); buf.put(data, n1, dataLen / 3); buf.flip(); int n2 = out.write(buf); buf.clear(); buf.put(data, n1 + n2, dataLen - n1 - n2); buf.flip(); int n3 = out.write(buf); Assert.assertEquals(dataLen, n1 + n2 + n3); out.flush(); InputStream in = getCryptoInputStream(new ByteArrayInputStream(encData), getCipher(cipherClass), defaultBufferSize, iv, withChannel); buf = ByteBuffer.allocate(dataLen + 100); byteBufferReadCheck(in, buf, 0); in.close(); }
From source file:org.wso2.carbon.mediation.templates.services.EndpointTemplateEditorAdmin.java
private void addDynamicEndpointTemplate(String key, OMElement endpointTemplateEl) throws AxisFault { ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.reset(); try {//from www . j a v a 2 s.c o m XMLPrettyPrinter.prettify(endpointTemplateEl, stream); } catch (Exception e) { handleException("Unable to pretty print configuration", e); } 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)) { handleException("Resource is already exists"); } Resource resource = registry.newResource(); resource.setMediaType(WSO2_ENDPOINT_TEMPLATE_MEDIA_TYPE); resource.setContent(new String(stream.toByteArray()).trim()); registry.put(key, resource); } catch (RegistryException e) { handleException("WSO2 Registry Exception", e); } }
From source file:ByteBuffer.java
public synchronized byte[] getBytes() { ByteArrayOutputStream baos = null; byte[] bArr = null; try {// ww w. jav a2 s .c om baos = new ByteArrayOutputStream(); for (int i = 0; i < bufferQueue.size(); i++) { bArr = bufferQueue.get(i); baos.write(bArr); } bArr = baos.toByteArray(); } catch (Exception e) { bArr = null; } finally { try { baos.reset(); baos.close(); } catch (Exception e) { } baos = null; } return bArr; }