List of usage examples for java.io ByteArrayInputStream close
public void close() throws IOException
From source file:org.hdiv.util.EncodingUtil.java
/** * Decodes Base64 alphabet characters of the string <code>s</code> and * decompresses it.// w ww. java 2 s. c om * * @param s data to decode * @return decoded <code>s</code> string * @throws HDIVException if there is an error decoding object <code>data</code> * @see org.apache.commons.codec.binary.Base64#decode(byte[]) * @see org.apache.commons.codec.net.URLCodec#decode(byte[]) * @see java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream) */ public Object decode64(String s) { try { Base64 base64Codec = new Base64(); // Decodes string s containing characters in the Base64 alphabet. byte[] encryptedData = base64Codec.decode(s.getBytes(ZIP_CHARSET)); // Decodes an array of URL safe 7-bit characters into an array of // original bytes. Escaped characters are converted back to their // original representation. byte[] encodedData = URLCodec.decodeUrl(encryptedData); ByteArrayInputStream decodedStream = new ByteArrayInputStream(encodedData); InputStream unzippedStream = new GZIPInputStream(decodedStream); ObjectInputStream ois = new ObjectInputStream(unzippedStream); Object obj = ois.readObject(); ois.close(); unzippedStream.close(); decodedStream.close(); return obj; } catch (Exception e) { throw new HDIVException(HDIVErrorCodes.HDIV_PARAMETER_INCORRECT_VALUE); } }
From source file:ome.model.utests.PermissionsTest.java
private Permissions deserialize(byte[] stream) throws Exception { ByteArrayInputStream bais; ObjectInputStream ois;/* ww w. ja v a2s .c om*/ bais = new ByteArrayInputStream(stream); ois = new ObjectInputStream(bais); Permissions p = (Permissions) ois.readObject(); ois.close(); bais.close(); return p; }
From source file:com.adaptris.security.StdOutput.java
/** * Split this encrypted payload into it's constituent parts. * // w w w. jav a2s . c om * @see #readEncryptedMesage(byte[]) * @throws IOException if we can't read the message * @throws Base64Exception if the message is not correctly encoded */ private void split() throws IOException { ByteArrayInputStream byteStream = new ByteArrayInputStream(Base64.decodeBase64(message)); DataInputStream in = new DataInputStream(byteStream); setSessionVector(read(in)); setSessionKey(read(in)); setEncryptedData(read(in)); setSignature(read(in)); in.close(); byteStream.close(); }
From source file:cpcc.vvrte.services.js.JavascriptWorker.java
/** * {@inheritDoc}// w ww . j a va 2 s .c o m */ @Override public void run() { String name = Thread.currentThread().getName(); Thread.currentThread().setName("Virtual Vehicle: " + vehicle.getName() + " (" + vehicle.getId() + ")"); HibernateSessionManager sessionManager = serviceResources.getService(HibernateSessionManager.class); applicationState = null; changeState(sessionManager, VirtualVehicleState.RUNNING); if (snapshot == null && script == null) { changeState(sessionManager, VirtualVehicleState.DEFECTIVE); sessionManager.commit(); serviceResources.getService(PerthreadManager.class).cleanup(); return; } Context cx = Context.enter(); cx.setOptimizationLevel(-1); ScriptableObject scope = cx.initStandardObjects(); try { cx.setClassShutter(new SandboxClassShutter(Collections.emptySet(), allowedClassesRegex)); scope.defineFunctionProperties(VvRteFunctions.FUNCTIONS, VvRteFunctions.class, ScriptableObject.DONTENUM); Object resultObj; if (snapshot == null) { Script compiledScript = cx.compileString(script, "<vehicle>", 1, null); resultObj = cx.executeScriptWithContinuations(compiledScript, scope); } else { ByteArrayInputStream bais = new ByteArrayInputStream(snapshot); ScriptableInputStream sis = new ScriptableInputStream(bais, scope); Scriptable globalScope = (Scriptable) sis.readObject(); Object c = sis.readObject(); sis.close(); bais.close(); resultObj = cx.resumeContinuation(c, globalScope, Boolean.TRUE); } logger.info("Result obj: " + Context.toString(resultObj)); result = Context.toString(resultObj); changeState(sessionManager, VirtualVehicleState.FINISHED); } catch (ContinuationPending cp) { logger.info("Application State " + cp.getApplicationState()); applicationState = (ApplicationState) cp.getApplicationState(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ScriptableOutputStream sos = new ScriptableOutputStream(baos, scope); sos.excludeStandardObjectNames(); sos.writeObject(scope); sos.writeObject(cp.getContinuation()); sos.close(); baos.close(); snapshot = baos.toByteArray(); if (applicationState.isTask()) { changeState(sessionManager, VirtualVehicleState.TASK_COMPLETION_AWAITED); } else { changeState(sessionManager, VirtualVehicleState.INTERRUPTED); } logger.info("snapshot is " + snapshot.length + " bytes long."); } catch (IOException e) { logger.error("Defective: VV=" + vehicle.getName() + " (" + vehicle.getId() + " / " + vehicle.getUuid() + ")", e); result = ExceptionFormatter.toString(e); snapshot = null; changeState(sessionManager, VirtualVehicleState.DEFECTIVE); } } catch (RhinoException e) { logger.error( "Defective: VV=" + vehicle.getName() + " (" + vehicle.getId() + " / " + vehicle.getUuid() + ")", e); result = e.getMessage() + ", line=" + (e.lineNumber() - scriptStartLine) + ":" + e.columnNumber() + ", source='" + e.lineSource() + "'"; changeState(sessionManager, VirtualVehicleState.DEFECTIVE); } catch (ClassNotFoundException | IOException | NoSuchMethodError e) { logger.error( "Defective: VV=" + vehicle.getName() + " (" + vehicle.getId() + " / " + vehicle.getUuid() + ")", e); result = ExceptionFormatter.toString(e); changeState(sessionManager, VirtualVehicleState.DEFECTIVE); } finally { Context.exit(); sessionManager.commit(); serviceResources.getService(PerthreadManager.class).cleanup(); Thread.currentThread().setName(name); } }
From source file:org.apache.hama.bsp.message.compress.SnappyCompressor.java
/** * Decompresses a BSPCompressedBundle and returns the corresponding * BSPMessageBundle./*from ww w . j a v a 2s . c om*/ * * @param compMsgBundle * @return */ @Override public byte[] decompress(byte[] compressedBytes) { ByteArrayInputStream bis = null; SnappyInputStream sis = null; DataInputStream dis = null; byte[] bytes = null; try { bis = new ByteArrayInputStream(compressedBytes); sis = new SnappyInputStream(bis); dis = new DataInputStream(sis); bytes = IOUtils.toByteArray(dis); } catch (IOException ioe) { LOG.error("Unable to decompress.", ioe); } finally { try { dis.close(); sis.close(); bis.close(); } catch (IOException e) { LOG.warn("Failed to close decompression streams.", e); } } return bytes; }
From source file:org.bonitasoft.console.common.server.utils.FormsResourcesUtils.java
private static void unzipContentToFolder(final byte[] zipContent, final File targetFolder) throws IOException { ByteArrayInputStream is = null; ZipInputStream zis = null;/* w w w . ja va2 s.co m*/ FileOutputStream out = null; try { is = new ByteArrayInputStream(zipContent); zis = new ZipInputStream(is); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { final String entryName = entry.getName(); if (entryName.endsWith(".jar")) { final File file = new File(targetFolder, entryName); if (file.exists()) { file.delete(); } file.createNewFile(); out = new FileOutputStream(file); int len = 0; final byte[] buffer = new byte[1024]; while ((len = zis.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); } } } finally { if (is != null) { is.close(); } if (zis != null) { zis.close(); } if (out != null) { out.close(); } } }
From source file:com.inmobi.grill.driver.hive.TestRemoteHiveDriver.java
@Test public void testHiveDriverPersistence() throws Exception { System.out.println("@@@@ start_persistence_test"); HiveConf driverConf = new HiveConf(remoteConf, TestRemoteHiveDriver.class); driverConf.setLong(HiveDriver.GRILL_CONNECTION_EXPIRY_DELAY, 10000); final HiveDriver oldDriver = new HiveDriver(); oldDriver.configure(driverConf);/*from w ww .j a va 2s . co m*/ driverConf.setBoolean(GrillConfConstants.GRILL_ADD_INSERT_OVEWRITE, false); driverConf.setBoolean(GrillConfConstants.GRILL_PERSISTENT_RESULT_SET, false); QueryContext ctx = new QueryContext("USE " + TestRemoteHiveDriver.class.getSimpleName(), null, driverConf); oldDriver.execute(ctx); Assert.assertEquals(0, oldDriver.getHiveHandleSize()); String tableName = "test_hive_driver_persistence"; // Create some ops with a driver String createTable = "CREATE TABLE IF NOT EXISTS " + tableName + "(ID STRING)"; ctx = new QueryContext(createTable, null, driverConf); oldDriver.execute(ctx); // Load some data into the table String dataLoad = "LOAD DATA LOCAL INPATH '" + TEST_DATA_FILE + "' OVERWRITE INTO TABLE " + tableName; ctx = new QueryContext(dataLoad, null, driverConf); oldDriver.execute(ctx); driverConf.setBoolean(GrillConfConstants.GRILL_ADD_INSERT_OVEWRITE, true); driverConf.setBoolean(GrillConfConstants.GRILL_PERSISTENT_RESULT_SET, true); // Fire two queries QueryContext ctx1 = new QueryContext("SELECT * FROM " + tableName, null, driverConf); oldDriver.executeAsync(ctx1); QueryContext ctx2 = new QueryContext("SELECT ID FROM " + tableName, null, driverConf); oldDriver.executeAsync(ctx2); Assert.assertEquals(2, oldDriver.getHiveHandleSize()); byte[] ctx1bytes = persistContext(ctx1); byte[] ctx2bytes = persistContext(ctx2); // Write driver to stream ByteArrayOutputStream driverBytes = new ByteArrayOutputStream(); try { oldDriver.writeExternal(new ObjectOutputStream(driverBytes)); } finally { driverBytes.close(); } // Create another driver from the stream ByteArrayInputStream driverInput = new ByteArrayInputStream(driverBytes.toByteArray()); HiveDriver newDriver = new HiveDriver(); newDriver.readExternal(new ObjectInputStream(driverInput)); newDriver.configure(driverConf); driverInput.close(); ctx1 = readContext(ctx1bytes, newDriver); ctx2 = readContext(ctx2bytes, newDriver); Assert.assertEquals(2, newDriver.getHiveHandleSize()); validateExecuteAsync(ctx1, DriverQueryState.SUCCESSFUL, true, GrillConfConstants.GRILL_RESULT_SET_PARENT_DIR_DEFAULT, false, newDriver); validateExecuteAsync(ctx2, DriverQueryState.SUCCESSFUL, true, GrillConfConstants.GRILL_RESULT_SET_PARENT_DIR_DEFAULT, false, newDriver); }
From source file:org.paxle.tools.ieporter.cm.impl.ConfigurationIEPorter.java
public Map<String, Dictionary<String, Object>> importConfigurations(File file) throws Exception { BufferedInputStream input = null; Map<String, Dictionary<String, Object>> configs = new HashMap<String, Dictionary<String, Object>>(); try {//w ww . j ava 2 s . co m input = new BufferedInputStream(new FileInputStream(file), 5); // pre-read data to detect file type byte[] test = new byte[5]; input.mark(5); input.read(test); input.reset(); if (new String(test, "UTF-8").equals("<?xml")) { // XML Document found Document doc = this.readXMLDocument(file); Map<String, Dictionary<String, Object>> config = this.importConfigurations(doc); configs.putAll(config); } else if (new String(test, 0, 2).equals("PK")) { // open zip file final ZipInputStream zis = new ZipInputStream(input); // loop through entries ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { // skip directories if (ze.isDirectory()) continue; // read data into memory long size = ze.getSize(); ByteArrayOutputStream bout = (size < 0) ? new ByteArrayOutputStream() : new ByteArrayOutputStream((int) size); IOUtils.copy(zis, bout); bout.close(); // read XML ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); Document doc = this.readXMLStream(bin); bin.close(); // parser configuration Map<String, Dictionary<String, Object>> config = this.importConfigurations(doc); configs.putAll(config); } zis.close(); } else { // Unknown file throw new IllegalArgumentException("Unknown file type"); } } finally { if (input != null) try { input.close(); } catch (Exception e) { /* ignore this */} } return configs; }
From source file:org.apache.axis2.context.externalize.SafeObjectInputStream.java
/** * Reads the object using the same format that was written. * // w w w . j a va 2s . c om * EXPECTED FORMATS * boolean=false * return null Object * * * boolean=true * boolean=true * return Object read from inputStream * * * boolean=true * boolean=false * int=nuber of bytes * bytes * return Object read from bytes * * @return Object or null * @throws IOException * @throws ClassNotFoundException */ private Object readObjectOverride() throws IOException, ClassNotFoundException { boolean isActive = in.readBoolean(); if (!isActive) { if (isDebug) { log.debug("Read object=null"); } return null; } Object obj = null; boolean isObjectForm = in.readBoolean(); if (isObjectForm) { // Read the object directly if (isDebug) { log.debug(" reading using object form"); } obj = in.readObject(); } else { if (isDebug) { log.debug(" reading using byte form"); } // Get the byte stream ByteArrayInputStream bais = getByteStream(in); // Now get the real object ObjectInputStream tempOIS = createObjectInputStream(bais); obj = tempOIS.readObject(); tempOIS.close(); bais.close(); } if (isDebug) { log.debug("Read object=" + valueName(obj)); } return obj; }
From source file:jade.core.messaging.FileMessageStorage.java
public synchronized void loadAll(LoadListener ll) throws IOException { // Notify the listener that the load process started ll.loadStarted(""); // Scan all its valid subdirectories. File[] subdirs = baseDir.listFiles(new FileFilter() { public boolean accept(File f) { return f.isDirectory() && f.getName().startsWith(RECEIVER_PREFIX); }//from w w w. j a va 2 s.c om }); for (int i = 0; i < subdirs.length; i++) { File subdir = subdirs[i]; // Scan all its valid files. File[] files = subdir.listFiles(new FileFilter() { public boolean accept(File f) { return !f.isDirectory() && f.getName().startsWith(MESSAGE_PREFIX); } }); for (int j = 0; j < files.length; j++) { File toRead = files[j]; // Read the file content BufferedReader in = new BufferedReader(new FileReader(toRead)); // Read the number of copies String strHowMany = in.readLine(); long howMany = 1; try { howMany = Long.parseLong(strHowMany); } catch (NumberFormatException nfe) { // Do nothing; the default value will be used } try { // NL (23/01/04) GenericMessage are now stored using Java serialization String encodedMsg = in.readLine(); // String.getBytes is, in general, an irreversible operation. However, in this case, because // the content was previously encoded Base64, we can expect that we will have only valid Base64 chars. ByteArrayInputStream istream = new ByteArrayInputStream( Base64.decodeBase64(encodedMsg.getBytes("US-ASCII"))); ObjectInputStream p = new ObjectInputStream(istream); GenericMessage message = (GenericMessage) p.readObject(); istream.close(); // Use an ACL codec to read in the receiver AID StringACLCodec codec = new StringACLCodec(in, null); // Read the receiver AID AID receiver = codec.decodeAID(); // Notify the listener that a new item was loaded for (int k = 0; k < howMany; k++) { ll.itemLoaded(toRead.getName(), message, receiver); } } catch (ACLCodec.CodecException ce) { System.err.println("Error reading file " + toRead.getName() + " [" + ce.getMessage() + "]"); } catch (ClassNotFoundException cnfe) { System.err.println("Error reading file " + toRead.getName() + " [" + cnfe.getMessage() + "]"); } finally { in.close(); } } } // Notify the listener that the load process ended ll.loadEnded(""); }