Java Code Examples for java.io.ObjectInputStream
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/.
Source file: DefaultHttpCacheEntrySerializer.java

public HttpCacheEntry readFrom(InputStream is) throws IOException { ObjectInputStream ois=new ObjectInputStream(is); try { return (HttpCacheEntry)ois.readObject(); } catch ( ClassNotFoundException ex) { throw new HttpCacheEntrySerializationException("Class not found: " + ex.getMessage(),ex); } finally { ois.close(); } }
Example 2
From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/utils/.
Source file: SerializationUtils.java

@SuppressWarnings("unchecked") public static <T extends Serializable>T deserializeFromBytes(byte[] serializedObject){ try { ByteArrayInputStream bais=new ByteArrayInputStream(serializedObject); ObjectInputStream ois=new ObjectInputStream(bais); return (T)ois.readObject(); } catch ( IOException e) { throw new IllegalStateException(e); } catch ( ClassNotFoundException e) { throw new IllegalStateException(e); } }
Example 3
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/mysql/util/.
Source file: Util.java

/** * Given a ResultSet and an index into the columns of that ResultSet, read binary data from the column which represents a serialized object, and re-create the object. * @param resultSet the ResultSet to use. * @param index an index into the ResultSet. * @return the object if it can be de-serialized * @throws Exception if an error occurs */ public static Object readObject(java.sql.ResultSet resultSet,int index) throws Exception { ObjectInputStream objIn=new ObjectInputStream(resultSet.getBinaryStream(index)); Object obj=objIn.readObject(); objIn.close(); return obj; }
Example 4
From project amplafi-sworddance, under directory /src/test/java/com/sworddance/taskcontrol/.
Source file: TestFutureListenerNotifier.java

private <F>F serializeDeserialize(F futureResult) throws IOException, ClassNotFoundException { ByteArrayOutputStream out=new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream=new ObjectOutputStream(out); objectOutputStream.writeObject(futureResult); objectOutputStream.close(); ByteArrayInputStream in=new ByteArrayInputStream(out.toByteArray()); ObjectInputStream objectInputStream=new ObjectInputStream(in); F f=(F)objectInputStream.readObject(); assertNotNull(f); return f; }
Example 5
From project android-async-http, under directory /src/com/loopj/android/http/.
Source file: PersistentCookieStore.java

protected Cookie decodeCookie(String cookieStr){ byte[] bytes=hexStringToByteArray(cookieStr); ByteArrayInputStream is=new ByteArrayInputStream(bytes); Cookie cookie=null; try { ObjectInputStream ois=new ObjectInputStream(is); cookie=((SerializableCookie)ois.readObject()).getCookie(); } catch ( Exception e) { e.printStackTrace(); } return cookie; }
Example 6
From project arquillian-extension-jrebel, under directory /impl/src/main/java/org/jboss/arquillian/extension/jrebel/.
Source file: Serializer.java

public static <T>T toObject(Class<T> type,byte[] objectArray){ try { ObjectInputStream outObj=new ObjectInputStream(new ByteArrayInputStream(objectArray)); Object object=outObj.readObject(); return type.cast(object); } catch ( Exception e) { throw new RuntimeException("Could not deserialize object: " + objectArray,e); } }
Example 7
From project android-vpn-server, under directory /src/com/android/server/vpn/.
Source file: VpnServiceBinder.java

private void checkSavedStates(){ try { ObjectInputStream ois=new ObjectInputStream(new FileInputStream(getStateFilePath())); mService=(VpnService<? extends VpnProfile>)ois.readObject(); mService.recover(this); ois.close(); } catch ( FileNotFoundException e) { } catch ( Throwable e) { Log.i("VpnServiceBinder","recovery error, remove states: " + e); removeStates(); } }
Example 8
From project android-vpn-settings, under directory /src/com/android/settings/vpn/.
Source file: VpnSettings.java

private VpnProfile deserialize(File profileObjectFile) throws IOException { try { ObjectInputStream ois=new ObjectInputStream(new FileInputStream(profileObjectFile)); VpnProfile p=(VpnProfile)ois.readObject(); ois.close(); return p; } catch ( ClassNotFoundException e) { Log.d(TAG,"deserialize a profile",e); return null; } }
Example 9
From project android_5, under directory /src/aarddict/android/.
Source file: DictionariesActivity.java

@SuppressWarnings("unchecked") void loadVerifyData() throws IOException, ClassNotFoundException { File verifyDir=getDir("verify",0); File verifyFile=new File(verifyDir,"verifydata"); if (verifyFile.exists()) { FileInputStream fin=new FileInputStream(verifyFile); ObjectInputStream oin=new ObjectInputStream(fin); verifyData=(Map<UUID,VerifyRecord>)oin.readObject(); } }
Example 10
From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/vpn/.
Source file: VpnSettings.java

private VpnProfile deserialize(File profileObjectFile) throws IOException { try { ObjectInputStream ois=new ObjectInputStream(new FileInputStream(profileObjectFile)); VpnProfile p=(VpnProfile)ois.readObject(); ois.close(); return p; } catch ( ClassNotFoundException e) { Log.d(TAG,"deserialize a profile",e); return null; } }
Example 11
From project android_external_libphonenumber, under directory /java/src/com/android/i18n/phonenumbers/geocoding/.
Source file: PhoneNumberOfflineGeocoder.java

private void loadMappingFileProvider(){ InputStream source=PhoneNumberOfflineGeocoder.class.getResourceAsStream(phonePrefixDataDirectory + "config"); ObjectInputStream in=null; try { in=new ObjectInputStream(source); mappingFileProvider.readExternal(in); } catch ( IOException e) { LOGGER.log(Level.WARNING,e.toString()); } finally { close(in); } }
Example 12
From project arquillian-core, under directory /protocols/jmx/src/main/java/org/jboss/arquillian/protocol/jmx/.
Source file: Serializer.java

public static <T>T toObject(Class<T> type,byte[] objectArray){ try { ObjectInputStream outObj=new ObjectInputStream(new ByteArrayInputStream(objectArray)); Object object=outObj.readObject(); return type.cast(object); } catch ( Exception e) { throw new RuntimeException("Could not deserialize object: " + objectArray,e); } }
Example 13
From project arquillian_deprecated, under directory /extensions/performance/src/main/java/org/jboss/arquillian/performance/event/.
Source file: PerformanceResultStore.java

private PerformanceSuiteResult getResultFromFile(File file){ try { FileInputStream fis=new FileInputStream(file); ObjectInputStream ois=new ObjectInputStream(fis); return (PerformanceSuiteResult)ois.readObject(); } catch ( IOException ioe) { return null; } catch ( ClassNotFoundException e) { e.printStackTrace(); return null; } }
Example 14
From project beanmill_1, under directory /src/main/java/com/traxel/lumbermill/event/.
Source file: EventListenerServer.java

/** * Creates a new SocketListener object. * @param socket DOCUMENT ME! */ public SocketListener(final Socket socket){ ObjectInputStream ois=null; this.socket=socket; try { ois=new ObjectInputStream(socket.getInputStream()); } catch ( final IOException e) { LOG.warn("could not open ObjectInputStream from socket: " + socket,e); } stream=ois; }
Example 15
From project big-data-plugin, under directory /shims/api/src/org/pentaho/hbase/shim/api/.
Source file: HBaseValueMeta.java

/** * Decode/deserialize an object from an array of bytes * @param rawEncoded the raw encoded form * @return the deserialized object */ public static Object decodeObject(byte[] rawEncoded){ try { ByteArrayInputStream bis=new ByteArrayInputStream(rawEncoded); BufferedInputStream buf=new BufferedInputStream(bis); ObjectInputStream ois=new ObjectInputStream(buf); Object result=ois.readObject(); return result; } catch ( Exception ex) { ex.printStackTrace(); } return null; }
Example 16
From project BusFollower, under directory /src/net/argilo/busfollower/.
Source file: RecentQueryList.java

@SuppressWarnings("unchecked") public static synchronized ArrayList<RecentQuery> loadRecents(Context context){ ArrayList<RecentQuery> recents; try { ObjectInputStream in=new ObjectInputStream(context.openFileInput(FILENAME)); recents=(ArrayList<RecentQuery>)in.readObject(); in.close(); } catch ( Exception e) { recents=new ArrayList<RecentQuery>(); } return recents; }
Example 17
From project cascading-avro, under directory /cascading-avro/src/test/java/com/maxpoint/cascading/avro/.
Source file: AvroSchemeTest.java

@Test public void testSerialization() throws Exception { final Schema.Parser parser=new Schema.Parser(); final Schema schema=parser.parse(getClass().getResourceAsStream("test1.avsc")); final AvroScheme expected=new AvroScheme(schema); final ByteArrayOutputStream bytes=new ByteArrayOutputStream(); ObjectOutputStream oos=new ObjectOutputStream(bytes); oos.writeObject(expected); oos.close(); final ObjectInputStream iis=new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())); final AvroScheme actual=(AvroScheme)iis.readObject(); assertEquals(expected,actual); }
Example 18
From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/util/.
Source file: SerializationUtils.java

@SuppressWarnings("unchecked") public static <T extends Serializable>T deserializeFromBytes(byte[] serializedObject){ try { ByteArrayInputStream bais=new ByteArrayInputStream(serializedObject); ObjectInputStream ois=new ObjectInputStream(bais); return (T)ois.readObject(); } catch ( IOException e) { throw new IllegalStateException(e); } catch ( ClassNotFoundException e) { throw new IllegalStateException(e); } }
Example 19
From project Cilia_1, under directory /components/tcp-adapter/src/main/java/fr/liglab/adele/cilia/tcp/.
Source file: TCPCollector.java

private Object readObject(InputStream is) throws IOException, ClassNotFoundException { byte buffer[]=new byte[4096]; byte complete[]; int bytesRead; ByteArrayOutputStream byteBuffer=new ByteArrayOutputStream(); while ((bytesRead=is.read(buffer)) > 0) { byteBuffer.write(buffer,0,bytesRead); } byteBuffer.flush(); complete=byteBuffer.toByteArray(); ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(complete)); return in.readObject(); }
Example 20
From project citrus-sample, under directory /petstore/dal/src/test/java/com/alibaba/sample/petstore/dal/dataobject/.
Source file: CartTests.java

private Cart deepClone() throws Exception { ByteArrayOutputStream baos=new ByteArrayOutputStream(); ObjectOutputStream oos=new ObjectOutputStream(baos); oos.writeObject(cart); oos.close(); ObjectInputStream ois=new ObjectInputStream(baos.toInputStream()); try { return (Cart)ois.readObject(); } finally { ois.close(); } }
Example 21
From project cogroo4, under directory /cogroo-nlp/src/main/java/org/cogroo/tools/featurizer/.
Source file: FeaturizerFactory.java

@SuppressWarnings("unchecked") public Set<String> create(InputStream in) throws IOException, InvalidFormatException { ObjectInputStream oin=null; Set<String> set=null; oin=new ObjectInputStream(new UncloseableInputStream(in)); try { set=(Set<String>)oin.readObject(); } catch ( ClassNotFoundException e) { System.err.println("could not restore serialied object"); e.printStackTrace(); } return Collections.unmodifiableSet(set); }
Example 22
From project collections-generic, under directory /src/test/org/apache/commons/collections15/comparators/.
Source file: TestReverseComparator.java

/** * Override this inherited test since Collections.reverseOrder doesn't adhere to the "soft" Comparator contract, and we've already "cannonized" the comparator returned by makeComparator. */ public void testSerializeDeserializeThenCompare() throws Exception { Comparator comp=new ReverseComparator(new ComparableComparator()); ByteArrayOutputStream buffer=new ByteArrayOutputStream(); ObjectOutputStream out=new ObjectOutputStream(buffer); out.writeObject(comp); out.close(); ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object dest=in.readObject(); in.close(); assertEquals("obj != deserialize(serialize(obj))",comp,dest); }
Example 23
public static Object read(String path) throws Exception { File f=new File(path); FileInputStream fos=new FileInputStream(f); ObjectInputStream objectInputStream=new ObjectInputStream(fos); Object readObject=objectInputStream.readObject(); objectInputStream.close(); return readObject; }
Example 24
From project commons-io, under directory /src/test/java/org/apache/commons/io/.
Source file: IOCaseTestCase.java

private IOCase serialize(IOCase value) throws Exception { ByteArrayOutputStream buf=new ByteArrayOutputStream(); ObjectOutputStream out=new ObjectOutputStream(buf); out.writeObject(value); out.flush(); out.close(); ByteArrayInputStream bufin=new ByteArrayInputStream(buf.toByteArray()); ObjectInputStream in=new ObjectInputStream(bufin); return (IOCase)in.readObject(); }
Example 25
From project commons-logging, under directory /src/test/org/apache/commons/logging/jdk14/.
Source file: DefaultConfigTestCase.java

public void testSerializable() throws Exception { ByteArrayOutputStream baos=new ByteArrayOutputStream(); ObjectOutputStream oos=new ObjectOutputStream(baos); oos.writeObject(log); oos.close(); ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois=new ObjectInputStream(bais); log=(Log)ois.readObject(); ois.close(); checkLog(); }
Example 26
From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.
Source file: IdentityApplic.java

public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException { prop=new Properties(); prop.load(new FileInputStream("ferryinpres.properties")); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Socket sock=new Socket(prop.getProperty("IDENTITY_SERVER"),Integer.parseInt(prop.getProperty("IDENTITY_PORT"))); ObjectOutputStream out=new ObjectOutputStream(sock.getOutputStream()); ObjectInputStream in=new ObjectInputStream(sock.getInputStream()); SecretKey sessionKey=keyExchange(in,out); Cipher cryptor=Cipher.getInstance("DES/ECB/PKCS5Padding"); cryptor.init(Cipher.ENCRYPT_MODE,sessionKey); Cipher decryptor=Cipher.getInstance("DES/ECB/PKCS5Padding"); decryptor.init(Cipher.DECRYPT_MODE,sessionKey); login(in,out,cryptor,decryptor); }
Example 27
From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Manager/.
Source file: StructureManager.java

public ArrayList<StructureBlock> loadStructure(String structureName){ ArrayList<StructureBlock> blockList=new ArrayList<StructureBlock>(); try { File folder=new File("plugins/16Blocks/structures"); folder.mkdirs(); File file=new File(folder,structureName + ".dat"); if (!file.exists()) return null; FileInputStream fileInputStream=new FileInputStream(file); ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream); int length=objectInputStream.readInt(); byte[] xArray=new byte[length]; byte[] yArray=new byte[length]; byte[] zArray=new byte[length]; byte[] IDArray=new byte[length]; byte[] SubIDArray=new byte[length]; xArray=(byte[])objectInputStream.readObject(); yArray=(byte[])objectInputStream.readObject(); zArray=(byte[])objectInputStream.readObject(); IDArray=(byte[])objectInputStream.readObject(); SubIDArray=(byte[])objectInputStream.readObject(); objectInputStream.close(); fileInputStream.close(); for (int i=0; i < length; i++) { blockList.add(new StructureBlock(xArray[i],yArray[i],zArray[i],IDArray[i],SubIDArray[i])); } return blockList.size() > 0 ? blockList : null; } catch ( Exception e) { e.printStackTrace(); return null; } }
Example 28
From project Absolute-Android-RSS, under directory /src/com/AA/Services/.
Source file: RssService.java

/** * Reads in data from the saved file. * @param context - Context that gives us some system access * @return - Returns the list of items that were saved; If there was problemwhen gathering this data, an empty list is returned */ @SuppressWarnings("unchecked") public static ArrayList<Article> readData(Context context){ ArrayList<Article> oldList=new ArrayList<Article>(); try { FileInputStream fileStream=context.openFileInput("articles"); ObjectInputStream reader=new ObjectInputStream(fileStream); oldList=(ArrayList<Article>)reader.readObject(); reader.close(); fileStream.close(); return oldList; } catch ( java.io.FileNotFoundException e) { return new ArrayList<Article>(); } catch ( IOException e) { Log.e("AARSS","Problem loading the file. Does it exists?",e); return new ArrayList<Article>(); } catch ( ClassNotFoundException e) { Log.e("AARSS","Problem converting data from file.",e); return new ArrayList<Article>(); } }
Example 29
From project agraph-java-client, under directory /src/test/.
Source file: RepositoryConnectionTest.java

@Test public void testStatementSerialization() throws Exception { testCon.add(bob,name,nameBob); Statement st; RepositoryResult<Statement> statements=testCon.getStatements(null,null,null,true); try { st=statements.next(); } finally { statements.close(); } ByteArrayOutputStream baos=new ByteArrayOutputStream(); ObjectOutputStream out=new ObjectOutputStream(baos); out.writeObject(st); out.close(); ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in=new ObjectInputStream(bais); Statement deserializedStatement=(Statement)in.readObject(); in.close(); assertTrue(st.equals(deserializedStatement)); assertTrue(testCon.hasStatement(st,true)); assertTrue(testCon.hasStatement(deserializedStatement,true)); }
Example 30
From project airlift, under directory /jmx-http-rpc/src/main/java/io/airlift/jmx/http/rpc/.
Source file: HttpMBeanServerRpc.java

public static Object deserialize(InputStream inputStream) throws IOException { try { return new ObjectInputStream(inputStream).readObject(); } catch ( ClassNotFoundException e) { throw new IOException(e); } }
Example 31
From project Airports, under directory /src/com/nadmm/airports/wx/.
Source file: NoaaService.java

protected Object readObject(File objFile){ Object object=null; try { ObjectInputStream in=new ObjectInputStream(new FileInputStream(objFile)); object=in.readObject(); in.close(); return object; } catch ( FileNotFoundException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } catch ( ClassNotFoundException e) { objFile.delete(); e.printStackTrace(); } return object; }
Example 32
public T read(){ FileInputStream in; try { in=new FileInputStream(this.file); ObjectInputStream inStream=new ObjectInputStream(in); @SuppressWarnings("unchecked") T result=(T)inStream.readObject(); inStream.close(); return result; } catch ( ClassNotFoundException e) { LogEx.exception(e); return null; } catch ( FileNotFoundException e1) { LogEx.warning("File " + this.file.getName() + " does not exist."); } catch ( IOException e) { LogEx.exception(e); } catch ( Exception ex) { LogEx.exception(ex); } return null; }
Example 33
From project android-client, under directory /xwiki-android-core/src/org/xwiki/android/data/fileStore/.
Source file: DocumentFaoImpSer.java

@Override public Document load(File file){ ObjectInputStream ois; Document doc=null; try { ois=new ObjectInputStream(new FileInputStream(file)); doc=((Document)ois.readObject()); } catch ( StreamCorruptedException e) { e.printStackTrace(); } catch ( FileNotFoundException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } catch ( ClassNotFoundException e) { e.printStackTrace(); } return doc; }
Example 34
From project Android-MapForgeFragment, under directory /library-common/src/com/jakewharton/android/mapsforge_fragment/.
Source file: TileMemoryCardCache.java

/** * Restores the serialized cache map if possible. * @return true if the map was restored successfully, false otherwise. */ @SuppressWarnings("unchecked") private synchronized boolean deserializeCacheMap(){ try { File file=new File(this.tempDir,SERIALIZATION_FILE_NAME); if (!file.exists()) { return false; } else if (!file.isFile()) { return false; } else if (!file.canRead()) { return false; } FileInputStream inputStream=new FileInputStream(file); ObjectInputStream objectInputStream=new ObjectInputStream(inputStream); this.map=(Map<MapGeneratorJob,File>)objectInputStream.readObject(); objectInputStream.close(); inputStream.close(); if (!file.delete()) { file.deleteOnExit(); } return true; } catch ( IOException e) { Logger.exception(e); return false; } catch ( ClassNotFoundException e) { Logger.exception(e); return false; } }
Example 35
From project android-rackspacecloud, under directory /src/com/rackspacecloud/android/.
Source file: ListAccountsActivity.java

private ArrayList<Account> readAccounts(){ FileInputStream fis; ObjectInputStream in; try { fis=openFileInput(FILENAME); in=new ObjectInputStream(fis); @SuppressWarnings("unchecked") ArrayList<Account> file=(ArrayList<Account>)in.readObject(); in.close(); return file; } catch ( FileNotFoundException e) { e.printStackTrace(); return null; } catch ( StreamCorruptedException e) { showAlert("Error","Could not load accounts."); e.printStackTrace(); } catch ( IOException e) { showAlert("Error","Could not load accounts."); e.printStackTrace(); } catch ( ClassNotFoundException e) { showAlert("Error","Could not load accounts."); e.printStackTrace(); } return null; }
Example 36
From project AndroidCommon, under directory /src/com/asksven/android/common/utils/.
Source file: DataStorage.java

public static Object fileToObject(Context context,String fileName){ FileInputStream fis; Object myRet=null; try { fis=context.openFileInput(fileName); ObjectInputStream is=new ObjectInputStream(fis); myRet=is.readObject(); is.close(); } catch ( FileNotFoundException e) { myRet=null; } catch ( IOException e) { myRet=null; } catch ( ClassNotFoundException e) { myRet=null; } return myRet; }
Example 37
From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.
Source file: SOContainer.java

public static ContainerMessage deserializeContainerMessage(byte[] bytes) throws IOException { final ByteArrayInputStream bis=new ByteArrayInputStream(bytes); final ObjectInputStream ois=new ObjectInputStream(bis); Object obj=null; try { obj=ois.readObject(); } catch ( final ClassNotFoundException e) { Log.i("SOContainer ",Messages.SOContainer_EXCEPTION_CLASS_NOT_FOUND,e); printToSystemError("deserializeContainerMessage class not found",e); return null; } catch ( final InvalidClassException e) { printToSystemError("deserializeContainerMessage invalid class",e); return null; } if (obj instanceof ContainerMessage) return (ContainerMessage)obj; printToSystemError("deserializeContainerMessage invalid container message ",new InvalidObjectException("object " + obj + " not appropriate type")); return null; }
Example 38
From project android_packages_apps_phone, under directory /src/com/android/phone/sip/.
Source file: SipProfileDb.java

private SipProfile deserialize(File profileObjectFile) throws IOException { AtomicFile atomicFile=new AtomicFile(profileObjectFile); ObjectInputStream ois=null; try { ois=new ObjectInputStream(atomicFile.openRead()); SipProfile p=(SipProfile)ois.readObject(); return p; } catch ( ClassNotFoundException e) { Log.w(TAG,"deserialize a profile: " + e); } finally { if (ois != null) ois.close(); } return null; }
Example 39
private Map<File,ModulesInfo> loadEntries(){ Map<File,ModulesInfo> result=new TreeMap<File,ModulesInfo>(); try { ObjectInputStream ois=new ObjectInputStream(new FileInputStream(cacheFile)); int size=ois.readInt(); for (int i=0; i < size; i++) { Object item=ois.readObject(); if (item instanceof ModulesInfo) { ModulesInfo info=(ModulesInfo)item; result.put(info.getPath(),info); } } ois.close(); } catch ( IOException ignore) { } catch ( ClassNotFoundException ignore) { } return result; }
Example 40
From project apollo, under directory /injector/src/main/java/com/bskyb/cg/environments/hash/.
Source file: PersistentHash.java

private synchronized void refreshFromStore(String dirname) throws IOException { FileInputStream fis; BufferedInputStream bis; Serializable messageEntry; ObjectInputStream ois; File emptyDir=new File(dirname); FilenameFilter onlyDat=new FileExtFilter(STOREFILEEXT); File[] files=emptyDir.listFiles(onlyDat); hash.clear(); for ( File file : files) { fis=new FileInputStream(file); bis=new BufferedInputStream(fis); ois=new ObjectInputStream(bis); try { messageEntry=(Serializable)ois.readObject(); } catch ( ClassNotFoundException e) { throw new IOException(e.toString()); } catch ( ClassCastException e) { throw new IOException(e.toString()); } catch ( StreamCorruptedException e) { throw new IOException(e.toString()); } try { hash.put(file.getName(),(Message)messageEntry); } catch ( ClassCastException e) { throw new IOException(e.toString()); } fis.close(); } }
Example 41
From project appengine-java-mapreduce, under directory /java/src/com/google/appengine/tools/mapreduce/impl/util/.
Source file: SerializationUtil.java

public static Object deserializeFromByteArray(byte[] bytes){ ObjectInputStream in; try { in=new ObjectInputStream(new ByteArrayInputStream(bytes)); } catch ( IOException e) { throw new RuntimeException("Deserialization error",e); } try { return in.readObject(); } catch ( IOException e) { throw new RuntimeException("Deserialization error",e); } catch ( ClassNotFoundException e) { throw new RuntimeException("Deserialization error",e); } finally { try { in.close(); } catch ( IOException e) { throw new RuntimeException("Deserialization error",e); } } }
Example 42
From project arquillian-extension-drone, under directory /drone-webdriver/src/test/java/org/jboss/arquillian/drone/webdriver/factory/remote/reusable/ftest/.
Source file: TestReusableRemoteWebDriver.java

@SuppressWarnings("unchecked") private <T>T serializeDeserialize(T object){ ByteArrayOutputStream baos=new ByteArrayOutputStream(); ObjectOutputStream out=null; try { out=new ObjectOutputStream(baos); out.writeObject(object); } catch ( IOException ex) { throw new IllegalStateException(ex); } finally { IOUtils.closeQuietly(out); } ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in=null; try { in=new ObjectInputStream(bais); return (T)object.getClass().cast(in.readObject()); } catch ( IOException ex) { throw new IllegalStateException(ex); } catch ( ClassNotFoundException ex) { throw new IllegalStateException(ex); } finally { IOUtils.closeQuietly(in); } }
Example 43
From project astyanax, under directory /src/main/java/com/netflix/astyanax/serializers/.
Source file: ObjectSerializer.java

@Override public Object fromByteBuffer(ByteBuffer bytes){ if ((bytes == null) || !bytes.hasRemaining()) { return null; } try { int l=bytes.remaining(); ByteArrayInputStream bais=new ByteArrayInputStream(bytes.array(),bytes.arrayOffset() + bytes.position(),l); ObjectInputStream ois=new ObjectInputStream(bais); Object obj=ois.readObject(); bytes.position(bytes.position() + (l - ois.available())); ois.close(); return obj; } catch ( Exception ex) { throw new SerializationException(ex); } }
Example 44
From project AudioBox.fm-JavaLib, under directory /audiobox.fm-core/src/main/java/fm/audiobox/configurations/.
Source file: Response.java

/** * Instantiates a new {@link Response} by reading a given {@link InputStream} * @param inStream the {@link InputStream} which read objects from * @return a new {@link Response} * @throws IOException the InputStream default exception */ public static Response deserialize(InputStream inStream) throws IOException { ObjectInputStream in=new ObjectInputStream(inStream); ContentFormat format=ContentFormat.values()[in.readInt()]; int status=in.readInt(); InputStream stream=null; try { stream=new ByteArrayInputStream(((String)in.readObject()).getBytes()); } catch ( ClassNotFoundException e) { log.error("An error occurred while deserializing Response",e); return null; } in.close(); return new Response(format,status,stream); }
Example 45
@Deprecated private void registerPitchAccentCollectionFeatureExtractors() throws FeatureExtractorException { try { String pad_filename=getParameter("spectral_pitch_accent_detector_collection"); PitchAccentDetectionClassifierCollection pacc; FileInputStream fis; ObjectInputStream in; fis=new FileInputStream(pad_filename); in=new ObjectInputStream(fis); Object o=in.readObject(); if (o instanceof PitchAccentDetectionClassifierCollection) { pacc=(PitchAccentDetectionClassifierCollection)o; } else { throw new FeatureExtractorException("Object read from -spectral_pitch_accent_detector_collection=" + pad_filename + " is not a valid PitchAccentDetectionClassifierCollection"); } Integer high_bark=Integer.parseInt(getOptionalParameter("high_bark","20")); for (int low=0; low < high_bark; ++low) { for (int high=low + 1; high <= high_bark; ++high) { registerFeatureExtractor(new SpectrumPADFeatureExtractor(low,high,pacc.getPitchAccentDetector(low,high),new SpectrumPADFeatureSet(low,high))); registerFeatureExtractor(new CorrectionSpectrumPADFeatureExtractor(low,high,pacc.getCorrectionClassifier(low,high),new CorrectionSpectrumPADFeatureSet(low,high))); } } } catch ( ClassNotFoundException e) { e.printStackTrace(); } catch ( FileNotFoundException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } catch ( AuToBIException e) { e.printStackTrace(); } }
Example 46
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/util/.
Source file: Serializer.java

/** * Uses default de-serialization to turn a byte array into an object. * @param data the byte array need to be converted * @return the converted object * @throws IOException io exception * @throws ClassNotFoundException class not found exception */ public static Object deserialize(final byte[] data) throws IOException, ClassNotFoundException { final ByteArrayInputStream bais=new ByteArrayInputStream(data); final BufferedInputStream bis=new BufferedInputStream(bais); final ObjectInputStream ois=new ObjectInputStream(bis); try { try { return ois.readObject(); } catch ( final IOException e) { throw e; } catch ( final ClassNotFoundException e) { throw e; } } finally { ois.close(); } }
Example 47
/** * @param context * @param filename * @return */ public static Object readObjectFromFile(Context context,String filename){ ObjectInputStream objectIn=null; Object object=null; try { FileInputStream fileIn=context.getApplicationContext().openFileInput(filename); objectIn=new ObjectInputStream(fileIn); object=objectIn.readObject(); } catch ( FileNotFoundException e) { } catch ( IOException e) { e.printStackTrace(); } catch ( ClassNotFoundException e) { e.printStackTrace(); } finally { if (objectIn != null) { try { objectIn.close(); } catch ( IOException e) { } } } return object; }
Example 48
From project baseunits, under directory /src/test/java/jp/xet/baseunits/tests/.
Source file: SerializationTester.java

/** * ????€????????????????????? * @param serializable ????€???????????????? * @throws AssertionError ????€?????????????? */ public static void assertCanBeSerialized(Object serializable){ if (Serializable.class.isInstance(serializable) == false) { fail("Object doesn't implement java.io.Serializable interface: " + serializable.getClass()); } ObjectOutputStream out=null; ObjectInputStream in=null; ByteArrayOutputStream byteArrayOut=new ByteArrayOutputStream(); ByteArrayInputStream byteArrayIn=null; try { out=new ObjectOutputStream(byteArrayOut); out.writeObject(serializable); byteArrayIn=new ByteArrayInputStream(byteArrayOut.toByteArray()); in=new ObjectInputStream(byteArrayIn); Object deserialized=in.readObject(); if (serializable.equals(deserialized) == false) { fail("Reconstituted object is expected to be equal to serialized"); } } catch ( IOException e) { fail(e.getMessage()); } catch ( ClassNotFoundException e) { fail(e.getMessage()); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } }
Example 49
public static FileCollection read(InputStream in){ FileCollection fileCollection=new FileCollection(); ObjectInputStream oin=null; try { oin=new ObjectInputStream(in); fileCollection.entries=new FileEntry[oin.readInt()]; for (int i=0; i < fileCollection.entries.length; i++) { String readLine=oin.readUTF(); fileCollection.entries[i]=FileEntry.valueOf(readLine); } return fileCollection; } catch ( IOException e) { throw new BeeException(e); } finally { try { oin.close(); } catch ( Exception ignore) { } } }
Example 50
From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.
Source file: SDFileManager.java

public String ReadFile(String fileName) throws IOException, ClassNotFoundException { ObjectInputStream ois=null; String result=null; try { File root=Environment.getExternalStorageDirectory(); File file=new File(root.getAbsolutePath(),".beintoo/" + fileName); FileInputStream fis=new FileInputStream(file); ois=new ObjectInputStream(fis); result=(String)ois.readObject(); ois.close(); } catch ( Exception e) { e.printStackTrace(); } finally { try { if (null != ois) ois.close(); } catch ( IOException ex) { } } return result; }
Example 51
From project BHT-FPA, under directory /patterns-codebeispiele/de.bht.fpa.examples.proxypattern/de.bht.fpa.examples.proxypattern.coffemachine.proxy/src/de/bht/fpa/proxypattern/coffemachine/proxy/.
Source file: CoffeMachineRemoteServiceDecorator.java

private void handleClient(final Socket client){ System.out.println(getClass().getName() + " got connection: " + client.getInetAddress()); new Thread(){ @Override public void run(){ try { ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream()); ObjectInputStream ois=new ObjectInputStream(client.getInputStream()); while (client.isConnected()) { handleCommand(ois,oos); } } catch ( Exception e) { e.printStackTrace(); } } } .start(); }
Example 52
From project BibleQuote-for-Android, under directory /src/com/BibleQuote/dal/.
Source file: CacheContext.java

@SuppressWarnings("unchecked") public synchronized <T>T loadData() throws FileAccessException { T data=null; try { FileInputStream fStr=new FileInputStream(new File(cacheDir,cacheName)); ObjectInputStream out=new ObjectInputStream(fStr); data=(T)out.readObject(); out.close(); } catch ( ClassNotFoundException e) { String message=String.format("Unexpected data format in the cache %1$s%2$s: $3$s",cacheDir,cacheName,e.getMessage()); throw new FileAccessException(message); } catch ( IOException e) { String message=String.format("Data isn't loaded from the cache %1$s%2$s: $3$s",cacheDir,cacheName,e.getMessage()); throw new FileAccessException(message); } return data; }
Example 53
From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/database/.
Source file: SerializationUtils.java

/** * Deserialize the passed byte array * @param blob * @return * @throws DeserializationException */ public static <T>T deserializeObject(byte[] blob) throws DeserializationException { try { ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(blob)); Object o=in.readObject(); return (T)o; } catch ( ClassCastException e) { throw new DeserializationException(e); } catch ( StreamCorruptedException e) { throw new DeserializationException(e); } catch ( IOException e) { throw new DeserializationException(e); } catch ( ClassNotFoundException e) { throw new DeserializationException(e); } }
Example 54
From project Carolina-Digital-Repository, under directory /services/src/main/java/edu/unc/lib/dl/cdr/services/model/.
Source file: FailedObjectHashMap.java

/** * Factory method which creates a Failed object map from the file located at filePath. If the file is not found, then a new map is returned * @param filePath * @return * @throws IOException * @throws ClassNotFoundException */ public static FailedObjectHashMap loadFailedEnhancements(String filePath,String failureLogPath) throws IOException, ClassNotFoundException { try { FileInputStream fileInputStream=new FileInputStream(filePath); ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream); Object obj=objectInputStream.readObject(); if (obj instanceof FailedObjectHashMap) { ((FailedObjectHashMap)obj).setSerializationPath(filePath); return (FailedObjectHashMap)obj; } } catch ( FileNotFoundException e) { log.info("Failed Enhancement serialization file " + filePath + " was not found, creating new map."); } catch ( InvalidClassException e) { log.warn("Unable to reload failed enhancement instance from " + filePath + ", the serial version ID did not match. Creating new map.",e); } catch ( Exception e) { log.error("Unable to reload failed enhancement instance from " + filePath + ", creating new map.",e); } FailedObjectHashMap failedObjectMap=new FailedObjectHashMap(filePath,failureLogPath); failedObjectMap.clear(); return failedObjectMap; }
Example 55
From project cascading, under directory /src/hadoop/cascading/flow/hadoop/util/.
Source file: JavaObjectSerializer.java

@Override public <T>T deserialize(byte[] bytes,Class<T> type,boolean decompress) throws IOException { if (Map.class.isAssignableFrom(type)) return (T)deserializeMap(bytes,decompress); if (List.class.isAssignableFrom(type)) { return (T)deserializeList(bytes,decompress); } ObjectInputStream in=null; try { ByteArrayInputStream byteStream=new ByteArrayInputStream(bytes); in=new ObjectInputStream(decompress ? new GZIPInputStream(byteStream) : byteStream){ @Override protected Class<?> resolveClass( ObjectStreamClass desc) throws IOException, ClassNotFoundException { try { return Class.forName(desc.getName(),false,Thread.currentThread().getContextClassLoader()); } catch ( ClassNotFoundException exception) { return super.resolveClass(desc); } } } ; return (T)in.readObject(); } catch ( ClassNotFoundException exception) { throw new FlowException("unable to deserialize data",exception); } finally { if (in != null) in.close(); } }
Example 56
From project ciel-java, under directory /bindings/src/main/java/com/asgow/ciel/references/.
Source file: CielFuture.java

@SuppressWarnings("unchecked") public T get(){ try { String filename=Ciel.RPC.getFilenameForReference(this); FileInputStream fis=new FileInputStream(filename); ObjectInputStream ois=new ObjectInputStream(fis); return (T)ois.readObject(); } catch ( ReferenceUnavailableException rue) { throw rue; } catch ( Exception e) { System.err.println("Error getting value from future."); e.printStackTrace(); throw new RuntimeException(e); } }
Example 57
From project Clotho-Core, under directory /ClothoProject/ClothoCore/src/org/clothocore/api/core/.
Source file: Collector.java

/** * I'm not sure this should really be part of the API. It is convenient, but it ends up bypassing any validation and could create duplicate part conflicts. Well, it's here now, but don't plan on putting it in plugins. * @deprecated * @param uuid * @param type * @return */ @Deprecated private static ObjBase getFromSerialized(String uuid,ObjType type){ ObjectInputStream ois=null; ObjBase out=null; try { FileInputStream fis=new FileInputStream("serials\\" + uuid + "."+ type); ois=new ObjectInputStream(fis); out=(ObjBase)ois.readObject(); ois.close(); } catch ( Exception e) { e.printStackTrace(); } if (out != null) { add(out); return out; } return null; }
Example 58
From project cometd, under directory /cometd-java/cometd-java-common/src/test/java/org/cometd/common/.
Source file: HashMapMessageTest.java

@Test public void testSerialization() throws Exception { HashMapMessage message=new HashMapMessage(); message.setChannel("/channel"); message.setClientId("clientId"); message.setId("id"); message.setSuccessful(true); message.getDataAsMap(true).put("data1","dataValue1"); message.getExt(true).put("ext1","extValue1"); ByteArrayOutputStream baos=new ByteArrayOutputStream(); ObjectOutputStream oos=new ObjectOutputStream(baos); oos.writeObject(message); oos.close(); ObjectInputStream ois=new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); HashMapMessage deserialized=(HashMapMessage)ois.readObject(); assertEquals(message,deserialized); }
Example 59
From project commons-fileupload, under directory /src/test/org/apache/commons/fileupload/.
Source file: DiskFileItemSerializeTest.java

/** * Do serialization and deserialization. */ private Object serializeDeserialize(Object target){ ByteArrayOutputStream baos=new ByteArrayOutputStream(); try { ObjectOutputStream oos=new ObjectOutputStream(baos); oos.writeObject(target); oos.flush(); oos.close(); } catch ( Exception e) { fail("Exception during serialization: " + e); } Object result=null; try { ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois=new ObjectInputStream(bais); result=ois.readObject(); bais.close(); } catch ( Exception e) { fail("Exception during deserialization: " + e); } return result; }
Example 60
From project components, under directory /bpm/src/main/java/org/switchyard/component/bpm/task/service/jbpm/.
Source file: JBPMTaskContent.java

private Object readBytes(byte[] bytes){ Object object=null; if (bytes != null && bytes.length > 0) { ByteArrayInputStream bais=new ByteArrayInputStream(bytes); ObjectInputStream ois=null; try { ois=new ObjectInputStream(bais){ @Override protected Class<?> resolveClass( ObjectStreamClass desc) throws IOException, ClassNotFoundException { Class<?> clazz=Classes.forName(desc.getName(),getClass()); return clazz != null ? clazz : super.resolveClass(desc); } } ; object=ois.readObject(); } catch ( IOException ioe) { throw new SwitchYardException(ioe); } catch ( ClassNotFoundException cnfe) { throw new SwitchYardException(cnfe); } finally { if (ois != null) { try { ois.close(); } catch ( IOException ioe) { throw new SwitchYardException(ioe); } } } } return object; }
Example 61
From project core_1, under directory /runtime/src/main/java/org/switchyard/internal/io/.
Source file: ObjectStreamSerializer.java

/** * {@inheritDoc} */ @Override public <T>T deserialize(InputStream in,Class<T> type,int bufferSize) throws IOException { in=new BufferedInputStream(in,bufferSize); try { ObjectInputStream ois=new ObjectInputStream(in); Object obj=ois.readObject(); return type.cast(obj); } catch ( ClassNotFoundException cnfe) { throw new IOException(cnfe); } finally { if (isCloseEnabled()) { in.close(); } } }
Example 62
From project core_4, under directory /impl/src/main/java/org/richfaces/util/.
Source file: Util.java

public static Object decodeObjectData(String encodedData){ byte[] objectArray=decodeBytesData(encodedData); try { ObjectInputStream in=new ObjectInputStreamImpl(new ByteArrayInputStream(objectArray)); return in.readObject(); } catch ( StreamCorruptedException e) { RESOURCE_LOGGER.error(Messages.getMessage(Messages.STREAM_CORRUPTED_ERROR),e); } catch ( IOException e) { RESOURCE_LOGGER.error(Messages.getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR),e); } catch ( ClassNotFoundException e) { RESOURCE_LOGGER.error(Messages.getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR),e); } return null; }
Example 63
From project akubra, under directory /akubra-rmi/src/main/java/org/akubraproject/rmi/remote/.
Source file: PartialBuffer.java

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { off=0; len=in.readInt(); b=new byte[len]; in.readFully(b); }
Example 64
From project android-client_1, under directory /src/org/apache/harmony/javax/security/auth/.
Source file: Subject.java

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); switch (setType) { case SET_Principal: permission=_PRINCIPALS; break; case SET_PrivCred: permission=_PRIVATE_CREDENTIALS; break; case SET_PubCred: permission=_PUBLIC_CREDENTIALS; break; default : throw new IllegalArgumentException(); } Iterator<SST> it=elements.iterator(); while (it.hasNext()) { verifyElement(it.next()); } }
Example 65
From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/.
Source file: Lesson.java

private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { name=(String)stream.readObject(); description=(String)stream.readObject(); int len=stream.readInt(); cards=new Card[len]; for (int i=0; i < len; i++) cards[i]=(Card)stream.readObject(); }
Example 66
From project android_external_guava, under directory /src/com/google/common/collect/.
Source file: ArrayListMultimap.java

private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); expectedValuesPerKey=stream.readInt(); int distinctKeys=Serialization.readCount(stream); Map<K,Collection<V>> map=Maps.newHashMapWithExpectedSize(distinctKeys); setMap(map); Serialization.populateMultimap(this,stream,distinctKeys); }
Example 67
From project Anki-Android, under directory /src/com/mindprod/common11/.
Source file: BigDate.java

/** * read back a serialized BigDate object and reconstruct the missing transient fields. readObject leaves results in this. It does not create a new object. * @param s stream to read from. * @throws IOException if can't read object * @throws ClassNotFoundException if unexpected class in the stream. */ private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { s.defaultReadObject(); try { toGregorian(); } catch ( IllegalArgumentException e) { throw new java.io.IOException("bad serialized BigDate"); } }
Example 68
From project AsmackService, under directory /src/org/apache/harmony/javax/security/auth/.
Source file: Subject.java

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); switch (setType) { case SET_Principal: permission=_PRINCIPALS; break; case SET_PrivCred: permission=_PRIVATE_CREDENTIALS; break; case SET_PubCred: permission=_PUBLIC_CREDENTIALS; break; default : throw new IllegalArgumentException(); } Iterator<SST> it=elements.iterator(); while (it.hasNext()) { verifyElement(it.next()); } }
Example 69
From project BookmarksPortlet, under directory /src/main/java/edu/wisc/my/portlets/bookmarks/domain/.
Source file: Folder.java

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); final Object comparatorInfo=in.readObject(); if (comparatorInfo instanceof Comparator) { this.childComparator=this.castComparator(comparatorInfo); } else if (comparatorInfo instanceof Class && Comparator.class.isAssignableFrom((Class)comparatorInfo)) { try { final Object instance=((Class)comparatorInfo).newInstance(); this.childComparator=this.castComparator(instance); } catch ( InstantiationException e) { this.childComparator=DefaultBookmarksComparator.DEFAULT_BOOKMARKS_COMPARATOR; } catch ( IllegalAccessException e) { this.childComparator=DefaultBookmarksComparator.DEFAULT_BOOKMARKS_COMPARATOR; } } else { this.childComparator=DefaultBookmarksComparator.DEFAULT_BOOKMARKS_COMPARATOR; } }
Example 70
From project C-Cat, under directory /util/src/main/java/gov/llnl/ontology/text/parse/.
Source file: StanfordParser.java

/** * Creates a new {@link StanfordParser} using the provided model location.If {@code loadFromJar} is {@code true}, then the path is assumed to refer to a file within the currently running jar. This {@link Parser} canreadily by used within a map reduce job by setting {@code loadFromJar} totrue and including the parser model within the map reduce jar. */ public StanfordParser(String parserModel,boolean loadFromJar){ LexicalizedParser p=null; GrammaticalStructureFactory g=null; try { InputStream inStream=(loadFromJar) ? StreamUtil.fromJar(this.getClass(),parserModel) : new FileInputStream(parserModel); p=new LexicalizedParser(new ObjectInputStream(StreamUtil.gzipInputStream(inStream))); g=p.getOp().tlpParams.treebankLanguagePack().grammaticalStructureFactory(); } catch ( Exception e) { throw new RuntimeException(e); } parser=p; gsf=g; }
Example 71
From project c3p0, under directory /src/java/com/mchange/v2/c3p0/.
Source file: DriverManagerDataSource.java

private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { short version=ois.readShort(); switch (version) { case VERSION: setUpPropertyListeners(); break; default : throw new IOException("Unsupported Serialized Version: " + version); } }
Example 72
From project capedwarf-blue, under directory /bytecode/src/main/java/org/jboss/capedwarf/bytecode/.
Source file: CursorTransformer.java

protected void transform(CtClass clazz) throws Exception { if (isAlreadyModified(clazz)) return; final ClassPool pool=clazz.getClassPool(); CtClass intClass=pool.get(int.class.getName()); CtField indexField=CtField.make("private java.util.concurrent.atomic.AtomicInteger index;",clazz); clazz.addField(indexField); CtConstructor ctor=new CtConstructor(new CtClass[]{pool.get(AtomicInteger.class.getName())},clazz); ctor.setBody("{this.index = $1;}"); clazz.addConstructor(ctor); CtMethod getIndex=new CtMethod(intClass,"getIndex",new CtClass[]{},clazz); getIndex.setModifiers(Modifier.PUBLIC); getIndex.setBody("{return index.get();}"); clazz.addMethod(getIndex); CtConstructor cloneCtor=clazz.getDeclaredConstructor(new CtClass[]{clazz}); cloneCtor.setBody("this($1.index);"); CtMethod writeObject=clazz.getDeclaredMethod("writeObject",new CtClass[]{pool.get(ObjectOutputStream.class.getName())}); writeObject.setBody("$1.writeInt(getIndex());"); CtMethod readObject=clazz.getDeclaredMethod("readObject",new CtClass[]{pool.get(ObjectInputStream.class.getName())}); readObject.setBody("index = new java.util.concurrent.atomic.AtomicInteger($1.readInt()); "); CtMethod advance=clazz.getDeclaredMethod("advance",new CtClass[]{intClass,pool.get(PreparedQuery.class.getName())}); advance.setBody("index.addAndGet($1);"); CtMethod reverse=clazz.getDeclaredMethod("reverse"); reverse.setBody("return new com.google.appengine.api.datastore.Cursor(new java.util.concurrent.atomic.AtomicInteger((-1) * getIndex()));"); CtMethod toWebSafeString=clazz.getDeclaredMethod("toWebSafeString"); toWebSafeString.setBody("return index.toString();"); CtMethod fromWebSafeString=clazz.getDeclaredMethod("fromWebSafeString",new CtClass[]{pool.get(String.class.getName())}); fromWebSafeString.setBody("return new com.google.appengine.api.datastore.Cursor(new java.util.concurrent.atomic.AtomicInteger($1 != null && $1.length() > 0 ? Integer.parseInt($1) : 0));"); CtMethod fromByteArray=clazz.getDeclaredMethod("fromByteArray",new CtClass[]{pool.get(byte[].class.getName())}); fromByteArray.setBody("return fromWebSafeString(new String($1));"); CtMethod equals=clazz.getDeclaredMethod("equals",new CtClass[]{pool.get(Object.class.getName())}); equals.setBody("return ($1 instanceof com.google.appengine.api.datastore.Cursor) && ((com.google.appengine.api.datastore.Cursor) $1).getIndex() == getIndex();"); CtMethod hashCode=clazz.getDeclaredMethod("hashCode"); hashCode.setBody("return getIndex();"); CtMethod toString=clazz.getDeclaredMethod("toString"); toString.setBody("return \"Cursor:\" + index;"); }
Example 73
From project CircDesigNA, under directory /src/org/apache/commons/math/linear/.
Source file: MatrixUtils.java

/** * Deserialize a {@link RealVector} field in a class.<p> This method is intended to be called from within a private <code>readObject</code> method (after a call to <code>ois.defaultReadObject()</code>) in a class that has a {@link RealVector} field, which should be declared <code>transient</code>.This way, the default handling does not deserialize the vector (the {@link RealVector} interface is not serializable by default) but this method doesdeserialize it specifically. </p> * @param instance instance in which the field must be set up * @param fieldName name of the field within the class (may be private and final) * @param ois stream from which the real vector should be read * @exception ClassNotFoundException if a class in the stream cannot be found * @exception IOException if object cannot be read from the stream * @see #serializeRealVector(RealVector,ObjectOutputStream) */ public static void deserializeRealVector(final Object instance,final String fieldName,final ObjectInputStream ois) throws ClassNotFoundException, IOException { try { final int n=ois.readInt(); final double[] data=new double[n]; for (int i=0; i < n; ++i) { data[i]=ois.readDouble(); } final RealVector vector=new ArrayRealVector(data,false); final java.lang.reflect.Field f=instance.getClass().getDeclaredField(fieldName); f.setAccessible(true); f.set(instance,vector); } catch ( NoSuchFieldException nsfe) { IOException ioe=new IOException(); ioe.initCause(nsfe); throw ioe; } catch ( IllegalAccessException iae) { IOException ioe=new IOException(); ioe.initCause(iae); throw ioe; } }
Example 74
From project Cloud9, under directory /src/dist/edu/umd/cloud9/util/map/.
Source file: HMapID.java

/** * Reconstitute the <tt>HMapID</tt> instance from a stream (i.e., deserialize it). */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); int numBuckets=s.readInt(); table=new Entry[numBuckets]; init(); int size=s.readInt(); for (int i=0; i < size; i++) { int key=s.readInt(); double value=s.readDouble(); putForCreate(key,value); } }
Example 75
From project com.cedarsoft.serialization, under directory /test/performance/src/test/java/com/cedarsoft/serialization/test/performance/.
Source file: XmlParserPerformance.java

public void benchSerialization() throws IOException { FileType type=new FileType("Canon Raw",new Extension(".","cr2",true),false); ByteArrayOutputStream bao=new ByteArrayOutputStream(); ObjectOutputStream out=new ObjectOutputStream(bao); out.writeObject(type); out.close(); final byte[] serialized=bao.toByteArray(); runBenchmark(new Runnable(){ @Override public void run(){ try { for (int i=0; i < MEDIUM; i++) { assertNotNull(new ObjectInputStream(new ByteArrayInputStream(serialized)).readObject()); } } catch ( Exception e) { throw new RuntimeException(e); } } } ,4); }
Example 76
From project commons-pool, under directory /src/java/org/apache/commons/pool/impl/.
Source file: CursorableLinkedList.java

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); _size=0; _modCount=0; _cursors=new ArrayList(); _head=new Listable(null,null,null); int size=in.readInt(); for (int i=0; i < size; i++) { this.add(in.readObject()); } }