List of usage examples for java.io ByteArrayOutputStream reset
public synchronized void reset()
From source file:org.apache.fop.pdf.PDFNameTestCase.java
/** * Test outputInline() - this writes the object reference if it is a direct object (has an * object number), or writes the String representation if there is no object number. *///from ww w . j ava2 s . c o m @Test public void testOutputInline() { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); CountingOutputStream cout = new CountingOutputStream(outStream); StringBuilder textBuffer = new StringBuilder(); try { // test with no object number set. pdfName.outputInline(outStream, textBuffer); PDFDocument.flushTextBuffer(textBuffer, cout); assertEquals("/TestName", outStream.toString()); outStream.reset(); // test with object number set pdfName.setObjectNumber(1); pdfName.outputInline(outStream, textBuffer); PDFDocument.flushTextBuffer(textBuffer, cout); assertEquals("1 0 R", outStream.toString()); } catch (IOException e) { fail("IOException: " + e.getMessage()); } }
From source file:org.apache.pdfbox.filter.LZWFilter.java
/** * {@inheritDoc}//from www .ja v a 2s .co m */ @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index) throws IOException { int predictor = -1; int earlyChange = 1; COSDictionary decodeParams = getDecodeParams(parameters, index); if (decodeParams != null) { predictor = decodeParams.getInt(COSName.PREDICTOR); earlyChange = decodeParams.getInt(COSName.EARLY_CHANGE, 1); if (earlyChange != 0 && earlyChange != 1) { earlyChange = 1; } } if (predictor > 1) { @SuppressWarnings("null") int colors = Math.min(decodeParams.getInt(COSName.COLORS, 1), 32); int bitsPerPixel = decodeParams.getInt(COSName.BITS_PER_COMPONENT, 8); int columns = decodeParams.getInt(COSName.COLUMNS, 1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); doLZWDecode(encoded, baos, earlyChange); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); Predictor.decodePredictor(predictor, colors, bitsPerPixel, columns, bais, decoded); decoded.flush(); baos.reset(); bais.reset(); } else { doLZWDecode(encoded, decoded, earlyChange); } return new DecodeResult(parameters); }
From source file:inti.core.codec.base64.Base64OutputStreamPerformanceTest.java
public void writePerformance(int count, int bufferSize) throws Exception { ByteArrayOutputStream underlying = new ByteArrayOutputStream(bufferSize); byte[] data;// w w w . jav a2s .c om long start, end; Base64 b64 = new Base64(); StringBuilder message = new StringBuilder(); for (int i = 0; i < bufferSize / 10; i++) { message.append("0123456789"); } data = message.toString().getBytes(Charset.forName("utf-8")); output.reset(underlying, null); for (int i = 0; i < 10; i++) { underlying.reset(); output.write(data); output.flush(); } for (int i = 0; i < 100; i++) { Thread.sleep(10); } start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { underlying.reset(); output.write(data); output.flush(); } end = System.currentTimeMillis(); System.out.format("writePerformance(Inti) - size: %d, duration: %dms, ratio: %#.4f", bufferSize, end - start, count / ((end - start) / 1000.0)); System.out.println(); for (int i = 0; i < 10; i++) { b64.encode(data); } for (int i = 0; i < 100; i++) { Thread.sleep(10); } start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { b64.encode(data); } end = System.currentTimeMillis(); System.out.format("writePerformance(commons.codec) - size: %d, duration: %dms, ratio: %#.4f", bufferSize, end - start, count / ((end - start) / 1000.0)); System.out.println(); }
From source file:org.jenkinsci.plugins.docker.commons.tools.DockerToolInstallerTest.java
@Issue({ "JENKINS-36082", "JENKINS-32790" }) @Test/*from ww w.j av a 2 s .com*/ public void smokes() throws Exception { try { new URL("https://get.docker.com/").openStream().close(); } catch (IOException x) { Assume.assumeNoException("Cannot contact get.docker.com, perhaps test machine is not online", x); } r.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class).setInstallations( new DockerTool("latest", "", Collections.singletonList(new InstallSourceProperty( Collections.singletonList(new DockerToolInstaller("", "latest"))))), new DockerTool("1.10.0", "", Collections.singletonList(new InstallSourceProperty( Collections.singletonList(new DockerToolInstaller("", "1.10.0")))))); DumbSlave slave = r.createOnlineSlave(); FilePath toolDir = slave.getRootPath().child("tools/org.jenkinsci.plugins.docker.commons.tools.DockerTool"); FilePath exe10 = toolDir.child("1.10.0/bin/docker"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); TaskListener l = new StreamTaskListener(new TeeOutputStream(baos, System.err)); // Download 1.10.0 for first time: assertEquals(exe10.getRemote(), DockerTool.getExecutable("1.10.0", slave, l, null)); assertTrue(exe10.exists()); assertThat(baos.toString(), containsString(Messages.DockerToolInstaller_downloading_docker_client_("1.10.0"))); // Next time we do not need to download: baos.reset(); assertEquals(exe10.getRemote(), DockerTool.getExecutable("1.10.0", slave, l, null)); assertTrue(exe10.exists()); assertThat(baos.toString(), not(containsString(Messages.DockerToolInstaller_downloading_docker_client_("1.10.0")))); // Download latest for the first time: baos.reset(); FilePath exeLatest = toolDir.child("latest/bin/docker"); assertEquals(exeLatest.getRemote(), DockerTool.getExecutable("latest", slave, l, null)); assertTrue(exeLatest.exists()); assertThat(baos.toString(), containsString(Messages.DockerToolInstaller_downloading_docker_client_("latest"))); // Next time we do not need to download: baos.reset(); assertEquals(exeLatest.getRemote(), DockerTool.getExecutable("latest", slave, l, null)); assertTrue(exeLatest.exists()); assertThat(baos.toString(), not(containsString(Messages.DockerToolInstaller_downloading_docker_client_("latest")))); assertThat("we do not have any extra files in here", toolDir.list("**"), arrayContainingInAnyOrder(exe10, toolDir.child("1.10.0/.timestamp"), exeLatest, toolDir.child("latest/.timestamp"))); }
From source file:org.eclipse.dawnsci.analysis.api.metadata.Metadata.java
@Override public IMetadata clone() { Metadata c = null;/*w ww . java 2 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) { 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:J2MEWriteReadMixedDataTypesExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/*from w w w . j a va2 s. c o m*/ notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); byte[] outputRecord; String outputString = "First Record"; int outputInteger = 15; boolean outputBoolean = true; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); outputDataStream.writeUTF(outputString); outputDataStream.writeBoolean(outputBoolean); outputDataStream.writeInt(outputInteger); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); outputStream.reset(); outputStream.close(); outputDataStream.close(); String inputString = null; int inputInteger = 0; boolean inputBoolean = false; byte[] byteInputData = new byte[100]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); for (int x = 1; x <= recordstore.getNumRecords(); x++) { recordstore.getRecord(x, byteInputData, 0); inputString = inputDataStream.readUTF(); inputBoolean = inputDataStream.readBoolean(); inputInteger = inputDataStream.readInt(); inputStream.reset(); } inputStream.close(); inputDataStream.close(); alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); recordstore.closeRecordStore(); if (RecordStore.listRecordStores() != null) { RecordStore.deleteRecordStore("myRecordStore"); } } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } }
From source file:com.vmware.vhadoop.vhm.hadoop.HadoopAdaptor.java
private int executeScriptWithCopyRetryOnFailure(HadoopConnection connection, String scriptFileName, String[] scriptArgs, ByteArrayOutputStream out) { int rc = -1;//from ww w. j a v a2 s . c o m for (int i = 0; i < 2; i++) { /* ensure that we're operating with a clean output buffer */ out.reset(); rc = connection.executeScript(scriptFileName, JOB_TRACKER_DEFAULT_SCRIPT_DEST_PATH, scriptArgs, out); if (i == 0 && (rc == ERROR_COMMAND_NOT_FOUND || rc == ERROR_CATCHALL)) { _log.log(Level.INFO, scriptFileName + " not found..."); // Changed this to accommodate using jar file... // String fullLocalPath = HadoopAdaptor.class.getClassLoader().getResource(scriptFileName).getPath(); // byte[] scriptData = loadLocalScript(DEFAULT_SCRIPT_SRC_PATH + scriptFileName); // byte[] scriptData = loadLocalScript(fullLocalPath); byte[] scriptData = loadLocalScript(scriptFileName); if ((scriptData != null) && (connection.copyDataToJobTracker(scriptData, JOB_TRACKER_DEFAULT_SCRIPT_DEST_PATH, scriptFileName, true) == 0)) { continue; } } break; } return rc; }
From source file:hudson.Util.java
/** * Escapes non-ASCII characters in URL.//ww w . j a v a2 s . co m * * <p> * Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters, * such as '#'. * {@link #rawEncode(String)} should generally be used instead, though be careful to pass only * a single path component to that method (it will encode /, but this method does not). */ public static String encode(String s) { try { boolean escaped = false; StringBuilder out = new StringBuilder(s.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(); OutputStreamWriter w = new OutputStreamWriter(buf, "UTF-8"); for (int i = 0; i < s.length(); i++) { int c = (int) s.charAt(i); if (c < 128 && c != ' ') { out.append((char) c); } else { // 1 char -> UTF8 w.write(c); w.flush(); for (byte b : buf.toByteArray()) { out.append('%'); out.append(toDigit((b >> 4) & 0xF)); out.append(toDigit(b & 0xF)); } buf.reset(); escaped = true; } } return escaped ? out.toString() : s; } catch (IOException e) { throw new Error(e); // impossible } }
From source file:edu.vt.middleware.crypt.KeyStoreCliTest.java
/** * @param keyStore Keystore file./*w w w. ja v a 2s . c om*/ * @param storeType Keystore type. Uses default type if null. * @param cert Certificate file. * @param privKey Private key file. * @param keyAlg Key algorithm name. Uses default key type if null. * @param alias Alias of keypair inside keystore. * * @throws Exception On test failure. */ @Test(groups = { "cli", "keystore" }, dataProvider = "keypairdata") public void testImportExportKeyPair(final String keyStore, final String storeType, final String cert, final String privKey, final String keyAlg, final String alias) throws Exception { new File(TEST_OUTPUT_DIR).mkdir(); final PrintStream oldStdOut = System.out; final String keyStorePath = TEST_OUTPUT_DIR + keyStore; final String exportCertPath = TEST_OUTPUT_DIR + keyStore + "." + cert; final String exportKeyPath = TEST_OUTPUT_DIR + keyStore + "." + privKey; final OptionData keyStoreOption = new OptionData("keystore", keyStorePath); final OptionData storeTypeOption = storeType == null ? null : new OptionData("storetype", storeType); final OptionData storePassOption = new OptionData("storepass", "changeit"); final OptionData keyAlgOption = keyAlg == null ? null : new OptionData("keyalg", keyAlg); final OptionData aliasOption = new OptionData("alias", alias); final OptionData[] listOptions = new OptionData[] { new OptionData("list"), keyStoreOption, storeTypeOption, storePassOption, }; final OptionData[] importOptions = new OptionData[] { new OptionData("import"), keyStoreOption, storeTypeOption, storePassOption, new OptionData("cert", KEY_DIR_PATH + cert), new OptionData("key", KEY_DIR_PATH + privKey), keyAlgOption, aliasOption, }; final OptionData[] exportOptions = new OptionData[] { new OptionData("export"), keyStoreOption, storeTypeOption, storePassOption, new OptionData("cert", exportCertPath), new OptionData("key", exportKeyPath), keyAlgOption, aliasOption, }; try { final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(outStream)); logger.info( "Importing keypair into keystore with command line " + CliHelper.toCommandLine(importOptions)); KeyStoreCli.main(CliHelper.toArgs(importOptions)); AssertJUnit.assertTrue(new File(keyStorePath).exists()); // Verify imported entry is present when we list contents outStream.reset(); KeyStoreCli.main(CliHelper.toArgs(listOptions)); final String output = outStream.toString(); logger.info("Keystore listing output:\n" + output); AssertJUnit.assertTrue(output.indexOf(alias) != -1); outStream.reset(); logger.info( "Exporting keypair from keystore with command line " + CliHelper.toCommandLine(exportOptions)); KeyStoreCli.main(CliHelper.toArgs(exportOptions)); AssertJUnit.assertTrue(new File(exportCertPath).exists()); AssertJUnit.assertTrue(new File(exportKeyPath).exists()); } finally { // Restore STDOUT System.setOut(oldStdOut); } }
From source file:org.jahia.utils.migration.Migrators.java
public List<String> migrate(InputStream inputStream, OutputStream outputStream, String filePath, Version fromVersion, Version toVersion, boolean performModification) { List<String> messages = new ArrayList<String>(); for (Migration migration : migrationsConfig.getMigrations()) { if (migration.getFromVersion().equals(fromVersion) && migration.getToVersion().equals(toVersion)) { for (MigrationResource migrationResource : migration.getMigrationResources()) { Matcher resourcePatternMatcher = migrationResource.getCompiledPattern().matcher(filePath); if (resourcePatternMatcher.matches()) { // we use byte array input and output stream to be able to iterate over the contents multiple times, feeding in the result of the last iteration into the next. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { IOUtils.copyLarge(inputStream, byteArrayOutputStream); } catch (IOException e) { e.printStackTrace(); }/*from ww w. j av a2 s . c om*/ byte[] inputByteArray = byteArrayOutputStream.toByteArray(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(inputByteArray); byteArrayOutputStream.reset(); for (MigrationOperation migrationOperation : migrationResource.getOperations()) { messages.addAll(migrationOperation.execute(byteArrayInputStream, byteArrayOutputStream, filePath, performModification)); byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); byteArrayOutputStream.reset(); } try { IOUtils.copyLarge(byteArrayInputStream, outputStream); } catch (IOException e) { e.printStackTrace(); } } } } } return messages; }