List of usage examples for java.io ByteArrayOutputStream reset
public synchronized void reset()
From source file:J2MEMixedRecordEnumerationExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/*from ww w . j a va2 s .com*/ notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); byte[] outputRecord; String outputString[] = { "First Record", "Second Record", "Third Record" }; int outputInteger[] = { 15, 10, 5 }; boolean outputBoolean[] = { true, false, true }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeBoolean(outputBoolean[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); } outputStream.reset(); outputStream.close(); outputDataStream.close(); StringBuffer buffer = new StringBuffer(); byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); recordEnumeration = recordstore.enumerateRecords(null, null, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); buffer.append(inputDataStream.readUTF()); buffer.append("\n"); buffer.append(inputDataStream.readBoolean()); buffer.append("\n"); buffer.append(inputDataStream.readInt()); buffer.append("\n"); alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } inputStream.close(); recordstore.closeRecordStore(); if (RecordStore.listRecordStores() != null) { RecordStore.deleteRecordStore("myRecordStore"); recordEnumeration.destroy(); } } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } }
From source file:SearchMixedRecordDataTypeExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/*w w w. j a va 2 s . c o m*/ notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); } catch (Exception error) { alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { byte[] outputRecord; String outputString[] = { "Adam", "Bob", "Mary" }; int outputInteger[] = { 15, 10, 5 }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); outputStream.reset(); } outputStream.close(); outputDataStream.close(); } catch (Exception error) { alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { String inputString; byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); if (recordstore.getNumRecords() > 0) { filter = new Filter("Mary"); recordEnumeration = recordstore.enumerateRecords(filter, null, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); inputString = inputDataStream.readUTF() + " " + inputDataStream.readInt(); alert = new Alert("Reading", inputString, null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } inputStream.close(); } catch (Exception error) { alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { recordstore.closeRecordStore(); } catch (Exception error) { alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore("myRecordStore"); filter.filterClose(); recordEnumeration.destroy(); } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } } }
From source file:org.wso2.carbon.mediation.templates.services.TemplateEditorAdmin.java
public void addDynamicTemplate(String key, OMElement sequence) throws AxisFault { ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.reset(); try {/*from w w w .j a va2 s .c o m*/ XMLPrettyPrinter.prettify(sequence, 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_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:org.apache.hadoop.hdfs.server.namenode.MockFSInputStream.java
public void testSendPartialData() throws IOException, InterruptedException { FSInputStream in = new MockFSInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); // test if multiple ranges, then 416 {//from ww w . j av a 2 s .com List ranges = strToRanges("0-,10-300", 500); MockHttpServletResponse response = new MockHttpServletResponse(); StreamFile.sendPartialData(in, os, response, 500, ranges); assertEquals("Multiple ranges should result in a 416 error", 416, response.getStatus()); } // test if no ranges, then 416 { os.reset(); MockHttpServletResponse response = new MockHttpServletResponse(); StreamFile.sendPartialData(in, os, response, 500, null); assertEquals("No ranges should result in a 416 error", 416, response.getStatus()); } // test if invalid single range (out of bounds), then 416 { List ranges = strToRanges("600-800", 500); MockHttpServletResponse response = new MockHttpServletResponse(); StreamFile.sendPartialData(in, os, response, 500, ranges); assertEquals("Single (but invalid) range should result in a 416", 416, response.getStatus()); } // test if one (valid) range, then 206 { List ranges = strToRanges("100-300", 500); MockHttpServletResponse response = new MockHttpServletResponse(); StreamFile.sendPartialData(in, os, response, 500, ranges); assertEquals("Single (valid) range should result in a 206", 206, response.getStatus()); assertArrayEquals("Byte range from 100-300", getOutputArray(100, 201), os.toByteArray()); } }
From source file:ca.ualberta.app.activity.CreateAnswerActivity.java
/** * get the image from the imagePath and try compress the image to 64kb * /*from w ww .j ava 2s. co m*/ * @param imagePath * the imagePath * @return return true if imageString is created */ private Boolean saveImageView(String imagePath) { image = BitmapFactory.decodeFile(imagePath); ByteArrayOutputStream stream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, stream); if (stream.toByteArray().length / 1024 > 1024) { stream.reset(); image.compress(Bitmap.CompressFormat.JPEG, 50, stream); } scaleImage(SCALEIMAGESIZE, SCALEIMAGESIZE, false); imageString = compressImage(); if (imageString == null) return false; return true; }
From source file:SortMixedRecordDataTypeExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/*from w ww . j a va 2 s .c o m*/ notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); } catch (Exception error) { alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { byte[] outputRecord; String outputString[] = { "Mary", "Bob", "Adam" }; int outputInteger[] = { 15, 10, 5 }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); outputStream.reset(); } outputStream.close(); outputDataStream.close(); } catch (Exception error) { alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { String[] inputString = new String[3]; int z = 0; byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); StringBuffer buffer = new StringBuffer(); comparator = new Comparator(); recordEnumeration = recordstore.enumerateRecords(null, comparator, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); buffer.append(inputDataStream.readUTF()); buffer.append(inputDataStream.readInt()); buffer.append("\n"); inputDataStream.reset(); } alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); inputDataStream.close(); inputStream.close(); } catch (Exception error) { alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { recordstore.closeRecordStore(); } catch (Exception error) { alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore("myRecordStore"); comparator.compareClose(); recordEnumeration.destroy(); } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } } }
From source file:org.apache.hama.ipc.AsyncServer.java
/** * Setup response for the IPC Call.// w w w.ja va 2s .c o m * * @param response buffer to serialize the response into * @param call {@link Call} to which we are setting up the response * @param status {@link Status} of the IPC call * @param rv return value for the IPC Call, if the call was successful * @param errorClass error class, if the the call failed * @param error error message, if the call failed * @throws IOException */ private void setupResponse(ByteArrayOutputStream response, Call call, Status status, Writable rv, String errorClass, String error) throws IOException { response.reset(); DataOutputStream out = new DataOutputStream(response); out.writeInt(call.id); // write call id out.writeInt(status.state); // write status if (status == Status.SUCCESS) { rv.write(out); } else { WritableUtils.writeString(out, errorClass); WritableUtils.writeString(out, error); } call.setResponse(ByteBuffer.wrap(response.toByteArray())); IOUtils.closeStream(out); }
From source file:org.openxdm.xcap.client.test.error.NotUTF8Test.java
@Test public void test() throws HttpException, IOException, JAXBException, InterruptedException { // exception for response codes NotUTF8ConflictException exception = new NotUTF8ConflictException(); // create content for tests String goodDocumentContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\">" + "<list/>" + "</resource-lists>"; String badDocumentContent1 = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\">" + "<list name=\"friends\"/>" + "</resource-lists>"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); char notUTF8Char = 0xA9; String goodAttrContent = "enemies"; baos.write(goodAttrContent.getBytes("UTF8")); baos.write(notUTF8Char);//from w w w . jav a2 s. c o m byte[] badAttrContent = baos.toByteArray(); String goodElementContent = "<list xmlns=\"urn:ietf:params:xml:ns:resource-lists\"/>"; baos.reset(); baos.write("<list/>".getBytes("UTF8")); baos.write(notUTF8Char); baos.write("/>".getBytes("UTF8")); byte[] badElementContent = baos.toByteArray(); String badDocumentContent2 = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\">" + badElementContent + "</resource-lists>"; baos.reset(); baos.write(0xFE); baos.write(0xFF); String someDocumentContent3 = "<?xml version=\"1.0\" ?>" + "<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\">" + "<list name=\"friends\"/>" + "</resource-lists>"; baos.write(someDocumentContent3.getBytes("UTF8")); byte[] badDocumentContent3Bytes = baos.toByteArray(); // 1. put new document // create uri UserDocumentUriKey documentKey = new UserDocumentUriKey(appUsage.getAUID(), user, documentName); // send put request and get response Response response = client.put(documentKey, appUsage.getMimetype(), badDocumentContent1, null); // check put response assertTrue("Put response must exists", response != null); assertTrue( "Put response content must be the expected and the response code should be " + exception.getResponseStatus(), response.getCode() == exception.getResponseStatus() && response.getContent().equals(exception.getResponseContent())); // send put request and get response response = client.put(documentKey, appUsage.getMimetype(), badDocumentContent2, null); // check put response assertTrue("Put response must exists", response != null); assertTrue( "Put response content must be the expected and the response code should be " + exception.getResponseStatus(), response.getCode() == exception.getResponseStatus() && response.getContent().equals(exception.getResponseContent())); // send put request and get response response = client.put(documentKey, appUsage.getMimetype(), badDocumentContent3Bytes, null); // check put response assertTrue("Put response must exists", response != null); assertTrue( "Put response content must be the expected and the response code should be " + exception.getResponseStatus(), response.getCode() == exception.getResponseStatus() && response.getContent().equals(exception.getResponseContent())); // 2. replace document // send put request and get response response = client.put(documentKey, appUsage.getMimetype(), goodDocumentContent, null); // check put response assertTrue("Put response must exists", response != null); assertTrue("Put response code should be 201", response.getCode() == 201); // send put request and get response response = client.put(documentKey, appUsage.getMimetype(), badDocumentContent1, null); // check put response assertTrue("Put response must exists", response != null); assertTrue( "Put response content must be the expected and the response code should be " + exception.getResponseStatus(), response.getCode() == exception.getResponseStatus() && response.getContent().equals(exception.getResponseContent())); // send put request and get response response = client.put(documentKey, appUsage.getMimetype(), badDocumentContent2, null); // check put response assertTrue("Put response must exists", response != null); assertTrue( "Put response content must be the expected and the response code should be " + exception.getResponseStatus(), response.getCode() == exception.getResponseStatus() && response.getContent().equals(exception.getResponseContent())); // send put request and get response response = client.put(documentKey, appUsage.getMimetype(), badDocumentContent3Bytes, null); // check put response assertTrue("Put response must exists", response != null); assertTrue( "Put response content must be the expected and the response code should be " + exception.getResponseStatus(), response.getCode() == exception.getResponseStatus() && response.getContent().equals(exception.getResponseContent())); // 3. put new element // create uri LinkedList<ElementSelectorStep> elementSelectorSteps = new LinkedList<ElementSelectorStep>(); ElementSelectorStep step1 = new ElementSelectorStep("resource-lists"); ElementSelectorStep step2 = new ElementSelectorStepByPos("list", 2); elementSelectorSteps.add(step1); elementSelectorSteps.addLast(step2); ElementSelector elementSelector = new ElementSelector(elementSelectorSteps); UserElementUriKey elementKey = new UserElementUriKey(appUsage.getAUID(), user, documentName, elementSelector, null); // send put request and get response response = client.put(elementKey, ElementResource.MIMETYPE, badElementContent, null); // check put response assertTrue("Put response must exists", response != null); assertTrue( "Put response content must be the expected and the response code should be " + exception.getResponseStatus(), response.getCode() == exception.getResponseStatus() && response.getContent().equals(exception.getResponseContent())); // 4. replace element // send put request and get response response = client.put(elementKey, ElementResource.MIMETYPE, goodElementContent, null); // check put response assertTrue("Put response must exists", response != null); assertTrue("Put response code should be 201", response.getCode() == 201); // send put request and get response response = client.put(elementKey, ElementResource.MIMETYPE, badElementContent, null); // check put response assertTrue("Put response must exists", response != null); assertTrue( "Put response content must be the expected and the response code should be " + exception.getResponseStatus(), response.getCode() == exception.getResponseStatus() && response.getContent().equals(exception.getResponseContent())); // 5. put new attr UserAttributeUriKey attrKey = new UserAttributeUriKey(appUsage.getAUID(), user, documentName, new ElementSelector(elementSelectorSteps), new AttributeSelector("name"), null); // send put request and get response response = client.put(attrKey, AttributeResource.MIMETYPE, badAttrContent, null); // check put response assertTrue("Put response must exists", response != null); assertTrue( "Put response content must be the expected and the response code should be " + exception.getResponseStatus(), response.getCode() == exception.getResponseStatus() && response.getContent().equals(exception.getResponseContent())); // 6. replace attr // send put request and get response response = client.put(attrKey, AttributeResource.MIMETYPE, goodAttrContent, null); // check put response assertTrue("Put response must exists", response != null); assertTrue("Put response code should be 201", response.getCode() == 201); // send put request and get response response = client.put(attrKey, AttributeResource.MIMETYPE, badAttrContent, null); // check put response assertTrue("Put response must exists", response != null); assertTrue( "Put response content must be the expected and the response code should be " + exception.getResponseStatus(), response.getCode() == exception.getResponseStatus() && response.getContent().equals(exception.getResponseContent())); // clean up client.delete(documentKey, null); }
From source file:org.apache.hadoop.hbase.io.hfile.TestHFileBlockIndex.java
public void testBlockIndexChunk() throws IOException { BlockIndexChunk c = new BlockIndexChunk(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int N = 1000; int[] numSubEntriesAt = new int[N]; int numSubEntries = 0; for (int i = 0; i < N; ++i) { baos.reset(); DataOutputStream dos = new DataOutputStream(baos); c.writeNonRoot(dos);//from w ww .j a va 2s. com assertEquals(c.getNonRootSize(), dos.size()); baos.reset(); dos = new DataOutputStream(baos); c.writeRoot(dos); assertEquals(c.getRootSize(), dos.size()); byte[] k = TestHFileWriterV2.randomOrderedKey(rand, i); numSubEntries += rand.nextInt(5) + 1; keys.add(k); c.add(k, getDummyFileOffset(i), getDummyOnDiskSize(i), numSubEntries); } // Test the ability to look up the entry that contains a particular // deeper-level index block's entry ("sub-entry"), assuming a global // 0-based ordering of sub-entries. This is needed for mid-key calculation. for (int i = 0; i < N; ++i) { for (int j = i == 0 ? 0 : numSubEntriesAt[i - 1]; j < numSubEntriesAt[i]; ++j) { assertEquals(i, c.getEntryBySubEntry(j)); } } }
From source file:MixedRecordEnumerationExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/*ww w .j av a 2 s . c o m*/ notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); } catch (Exception error) { alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { byte[] outputRecord; String outputString[] = { "First Record", "Second Record", "Third Record" }; int outputInteger[] = { 15, 10, 5 }; boolean outputBoolean[] = { true, false, true }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeBoolean(outputBoolean[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); } outputStream.reset(); outputStream.close(); outputDataStream.close(); } catch (Exception error) { alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { StringBuffer buffer = new StringBuffer(); byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); recordEnumeration = recordstore.enumerateRecords(null, null, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); buffer.append(inputDataStream.readUTF()); buffer.append("\n"); buffer.append(inputDataStream.readBoolean()); buffer.append("\n"); buffer.append(inputDataStream.readInt()); buffer.append("\n"); alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } inputStream.close(); } catch (Exception error) { alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { recordstore.closeRecordStore(); } catch (Exception error) { alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore("myRecordStore"); recordEnumeration.destroy(); } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } } }