static void serTest(Map s, int size) throws Exception { if (!(s instanceof Serializable)) return; System.out.print("Serialize : "); for (int i = 0; i < size; i++) { s.put(new Integer(i), Boolean.TRUE); } long startTime = System.currentTimeMillis(); FileOutputStream fs = new FileOutputStream("MapCheck.dat"); ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fs)); out.writeObject(s); out.close(); FileInputStream is = new FileInputStream("MapCheck.dat"); ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(is)); Map m = (Map) in.readObject(); long endTime = System.currentTimeMillis(); long time = endTime - startTime; System.out.print(time + "ms"); if (s instanceof IdentityHashMap) return; reallyAssert(s.equals(m)); }
/** * Copy method. Return an exact copy of this column. A deep copy is attempted, but if it fails a * new column will be created, initialized with the same data as this column. * * @return A new Column with a copy of the contents of this column. */ public Column copy() { LongColumn newCol; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); byte buf[] = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(buf); ObjectInputStream ois = new ObjectInputStream(bais); newCol = (LongColumn) ois.readObject(); ois.close(); return newCol; } catch (Exception e) { // newCol = new LongColumn(getNumRows()); long[] newVals = new long[getNumRows()]; for (int i = 0; i < getNumRows(); i++) // newCol.setLong(internal[i], i); newVals[i] = getLong(i); boolean[] miss = new boolean[internal.length]; boolean[] em = new boolean[internal.length]; for (int i = 0; i < internal.length; i++) { miss[i] = missing[i]; em[i] = empty[i]; } newCol = new LongColumn(newVals, miss, em, getLabel(), getComment()); return newCol; } }
private void load(InputStream is) throws IOException, ClassNotFoundException, CoreException { // try to read the file version number. Pre 2.0 versions had no number int version = is.read(); if (version == KEYRING_FILE_VERSION) { // read the authorization data CipherInputStream cis = new CipherInputStream(is, password); ObjectInputStream ois = new ObjectInputStream(cis); try { authorizationInfo = (Hashtable) ois.readObject(); protectionSpace = (Hashtable) ois.readObject(); } finally { ois.close(); } } else { // the format has changed, just log a warning InternalPlatform.getDefault() .log( new Status( IStatus.WARNING, Platform.PI_RUNTIME, Platform.FAILED_READ_METADATA, Messages.meta_authFormatChanged, null)); // close the stream and save a new file in the correct format try { is.close(); } catch (IOException e) { // ignore failure to close } needsSaving = true; save(); } }
public static TaggedDictionary loadFrom(File f) throws Exception { FileInputStream fi = null; BufferedInputStream bi = null; ObjectInputStream oin = null; TaggedDictionary result = null; try { fi = new FileInputStream(f); bi = new BufferedInputStream(fi, 1000000); oin = new ObjectInputStream(bi); result = new TaggedDictionary(); result.readFrom(oin); } finally { try { oin.close(); } catch (Exception exx) { } try { bi.close(); } catch (Exception exx) { } try { fi.close(); } catch (Exception exx) { } } return result; }
public static WordClass[] loadWordClassesFrom(File f) throws Exception { FileInputStream fi = null; BufferedInputStream bi = null; ObjectInputStream oin = null; WordClass result[]; try { fi = new FileInputStream(f); bi = new BufferedInputStream(fi, 1000000); oin = new ObjectInputStream(bi); result = (WordClass[]) oin.readObject(); } finally { try { oin.close(); } catch (Exception exx) { } try { bi.close(); } catch (Exception exx) { } try { fi.close(); } catch (Exception exx) { } } return result; }
public void run() { boolean gotByePacket = false; try { /* stream to read from client */ ObjectInputStream fromClient = new ObjectInputStream(socket.getInputStream()); Packet packetFromClient; /* stream to write back to client */ ObjectOutputStream toClient = new ObjectOutputStream(socket.getOutputStream()); // writer to the disk // String file = "list"; // while (( packetFromClient = (Packet) fromClient.readObject()) != null) { /* create a packet to send reply back to client */ packetFromClient = (Packet) fromClient.readObject(); Packet packetToClient = new Packet(); packetToClient.type = Packet.LOOKUP_REPLY; packetToClient.data = new ArrayList<String>(); if (packetFromClient.type == Packet.LOOKUP_REQUEST) { // called by client System.out.println("Request from Client:" + packetFromClient.type); packetToClient.type = Packet.LOOKUP_REPLY; long start = packetFromClient.start; long length = packetFromClient.length; if (start > dict.size()) { // set the error field, return packetToClient.error_code = Packet.ERROR_OUT_OF_RANGE; } else { for (int i = (int) start; i < start + length && i < dict.size(); i++) { packetToClient.data.add(dict.get(i)); } } toClient.writeObject(packetToClient); // continue; } // } /* cleanup when client exits */ fromClient.close(); toClient.close(); socket.close(); // close the filehandle } catch (IOException e) { if (!gotByePacket) { e.printStackTrace(); } } catch (ClassNotFoundException e) { if (!gotByePacket) e.printStackTrace(); } }
/** * Load the database from the database file given in "database.json" if the file doesn't exist, it * gets created here if the file has a database in it already, it is loaded here * * @return false if there is an error opening the database */ public boolean open() { try { System.out.println(dbPath); File dbFile = new File(dbPath); // Only read the database from the file if it exists if (dbFile.exists()) { FileInputStream fileIn = new FileInputStream(dbPath); ObjectInputStream in = new ObjectInputStream(fileIn); // load the database here database = (HashMap<K, V>) in.readObject(); // make sure the streams close properly in.close(); fileIn.close(); Debug.println("Database loaded"); } else { dbFile.getParentFile().mkdirs(); dbFile.createNewFile(); Debug.println("Database created"); } return true; } catch (Exception e) { System.err.println("Error opening database"); System.err.println(e); return false; } }
/** * Load, creates if missing, information about the local users * * @param file The file with the data * @throws IOException On I/O error */ private static void loadMe(final String file) throws IOException { myFile = file; final File $file = new File(file); if ($file.exists() == false) { myUUID = UUID.randomUUID(); updateMe(null); } else { ObjectInputStream is = null; try { is = new ObjectInputStream(new BufferedInputStream(new FileInputStream($file))); Object obj; for (; ; ) if ((obj = is.readObject()) instanceof UUID) { System.err.println("Loading UUID: " + obj); myUUID = (UUID) obj; break; } else { System.err.println("Loading DNS: " + obj); myDNSes.add((String) obj); } } catch (final ClassNotFoundException err) { throw new IOError(err); } finally { if (is != null) try { is.close(); } catch (final Throwable err) { // Do nothing } } } }
public void testSerial() { assertTrue(_nbhm.isEmpty()); final String k1 = "k1"; final String k2 = "k2"; assertThat(_nbhm.put(k1, "v1"), nullValue()); assertThat(_nbhm.put(k2, "v2"), nullValue()); // Serialize it out try { FileOutputStream fos = new FileOutputStream("NBHM_test.txt"); ObjectOutputStream out = new ObjectOutputStream(fos); out.writeObject(_nbhm); out.close(); } catch (IOException ex) { ex.printStackTrace(); } // Read it back try { File f = new File("NBHM_test.txt"); FileInputStream fis = new FileInputStream(f); ObjectInputStream in = new ObjectInputStream(fis); NonBlockingIdentityHashMap nbhm = (NonBlockingIdentityHashMap) in.readObject(); in.close(); assertThat( "serialization works", nbhm.toString(), anyOf(is("{k1=v1, k2=v2}"), is("{k2=v2, k1=v1}"))); if (!f.delete()) throw new IOException("delete failed"); } catch (IOException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } }
public static GA GAWithCheckpoint(String checkpoint) throws Exception { File checkpointFile = new File(checkpoint); FileInputStream zin = new FileInputStream(checkpointFile); GZIPInputStream in = new GZIPInputStream(zin); ObjectInputStream oin = new ObjectInputStream(in); Checkpoint ckpt = (Checkpoint) oin.readObject(); GA ga = ckpt.ga; ga._checkpoint = ckpt; ckpt.checkpointNumber++; // because it gets increased only after ckpt is // written oin.close(); System.out.println(ckpt.report.toString()); // Do we want to append to the file if it exists? Or just overwrite it? // Heu! Quae enim quaestio animas virorum vero pertemptit. // Wowzers! This is, indeed, a question that truly tests mens' souls. if (ga._outputfile != null) ga._outputStream = new FileOutputStream(new File(ga._outputfile)); else ga._outputStream = System.out; return ga; }
private void setHPubAccessHandleString(String encodedHandleWithSpaces) { String encodedHandle = removeSpaceCharacters(encodedHandleWithSpaces); if ((encodedHandle == null) || (encodedHandle.length() < 5)) { return; } try { byte[] handleByteArray = null; sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); try { handleByteArray = dec.decodeBuffer(encodedHandle); } catch (Exception e) { System.out.println("AccessEJBTemplate::setHPubAccessHandleString() decoding buffer"); } ; ByteArrayInputStream bais = new ByteArrayInputStream(handleByteArray); javax.ejb.Handle h1 = null; try { ObjectInputStream ois = new ObjectInputStream(bais); hPubAccessHandle = (javax.ejb.Handle) ois.readObject(); } catch (Exception ioe) { System.out.println("Exception reading handle object"); } } catch (Exception e) { e.printStackTrace(System.err); System.out.println("Exception AccessEJBTemplate::setHPubAccessHandleString()"); } return; }
public static Object loadObjectFromFile(String fileName) throws Exception { FileInputStream fis = new FileInputStream(fileName); ObjectInputStream ois = new ObjectInputStream(fis); Object obj = ois.readObject(); ois.close(); return obj; }
/** * Read an object from a deserialization stream. * * @param s An object deserialization stream. * @throws ClassNotFoundException If the object's class read from the stream cannot be found. * @throws IOException If an error occurs reading from the stream. */ @SuppressWarnings("unchecked") private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { s.defaultReadObject(); final T value = (T) s.readObject(); final List<Node<T>> children = (List<Node<T>>) s.readObject(); node = new Node<>(value, children); }
public void testResultListSerializableComplex() throws Exception { // Create mutliple objects removeAll(Object.class); for (int i = 0; i < 20; i++) getStore().save(new Book("Learning Java 1." + i, "" + i)); for (int i = 0; i < 20; i++) getStore().save(new Referrer(i)); for (int i = 0; i < 20; i++) getStore().save(new User()); for (int i = 0; i < 20; i++) getStore().save(new MapHolder()); // Get the result list for all objects List result = getStore().find("find object"); Assert.assertEquals(result.size(), 80); // Now serialize ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream objectOut = new ObjectOutputStream(byteOut); objectOut.writeObject(result); objectOut.close(); // Close the store, let's pretend we're outside it tearDownStore(); try { // Deserialize ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream objectIn = new ObjectInputStream(byteIn); List deList = (List) objectIn.readObject(); // Test object Assert.assertEquals(deList.size(), 80); Assert.assertEquals(getCount(deList, Book.class), 20); Assert.assertEquals(getCount(deList, Referrer.class), 20); Assert.assertEquals(getCount(deList, User.class), 20); Assert.assertEquals(getCount(deList, MapHolder.class), 20); } finally { // Setup store for next tests setUpStore(); } }
/** * Loads the friends list * * @param file The file with the data * @throws IOException On I/O error */ private static void loadFriends(final String file) throws IOException { friendFile = file; final File $file = new File(file); friends = new HashSet<Player>(); if ($file.exists() == false) saveFriends(); else { ObjectInputStream is = null; Object obj = null; try { is = new ObjectInputStream(new BufferedInputStream(new FileInputStream($file))); while ((obj = is.readObject()) != null) friends.add((Player) obj); } catch (final ClassNotFoundException err) { throw new IOError(err); } catch (final IOException | RuntimeException | Error err) { System.err.println(err); System.err.println("obj: " + obj); System.err.println("is: " + is); throw err; } finally { if (is != null) try { is.close(); } catch (final Throwable err) { // Do nothing } } } }
/** DOCUMENT ME! */ public void loadRaids() { File f = new File(REPO); if (!f.exists()) { return; } FileInputStream fIn = null; ObjectInputStream oIn = null; try { fIn = new FileInputStream(REPO); oIn = new ObjectInputStream(fIn); // de-serializing object raids = (HashMap<String, GregorianCalendar>) oIn.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { oIn.close(); fIn.close(); } catch (IOException e1) { e1.printStackTrace(); } } }
public static void main(String[] argv) { String hostName; if (argv.length == 0) hostName = "localhost"; else hostName = argv[0]; try { Socket sock = new Socket(hostName, TIME_PORT); ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(sock.getInputStream())); // Read and validate the Object Object o = is.readObject(); if (o == null) { System.err.println("Read null from server!"); } else if ((o instanceof Date)) { // Valid, so cast to Date, and print Date d = (Date) o; System.out.println("Server host is " + hostName); System.out.println("Time there is " + d.toString()); } else { throw new IllegalArgumentException("Wanted Date, got " + o); } } catch (ClassNotFoundException e) { System.err.println("Wanted date, got INVALID CLASS (" + e + ")"); } catch (IOException e) { System.err.println(e); } }
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // We have to call defaultReadObject first. in.defaultReadObject(); // Read version number. byte major = in.readByte(); byte minor = in.readByte(); if (major != 1) { throw new IOException("LogRecord: bad version: " + major + "." + minor); } int len = in.readInt(); if (len == -1) { parameters = null; } else { parameters = new Object[len]; for (int i = 0; i < parameters.length; i++) { parameters[i] = in.readObject(); } } // If necessary, try to regenerate the resource bundle. if (resourceBundleName != null) { try { resourceBundle = ResourceBundle.getBundle(resourceBundleName); } catch (MissingResourceException ex) { // This is not a good place to throw an exception, // so we simply leave the resourceBundle null. resourceBundle = null; } } needToInferCaller = false; }
/** * @param it Iterator. * @param bound Value bound. * @throws Exception If failed. */ private void testIteratorSerialization(Iterator<?> it, int bound) throws Exception { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(byteOut)) { out.writeObject(it); } byte[] bytes = byteOut.toByteArray(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); Iterator<?> it0 = (Iterator<?>) in.readObject(); int cnt = 0; while (it0.hasNext()) { Object obj = it0.next(); if (obj instanceof GridCacheEntry) checkEntry((GridCacheEntry<String, Integer>) obj, bound); else if (obj instanceof String) checkKey((String) obj); else if (obj instanceof Integer) checkValue((Integer) obj, bound); else assert false : "Wrong type."; cnt++; } assert cnt == bound; }
public static void main(String args[]) { List<User> users = Arrays.asList( new User("jack", 40), new User("john", 32), new User("jill", 47), new User("mike", 28)); List<User> readUsers = null; try { ObjectOutputStream objWrite = new ObjectOutputStream(new FileOutputStream(output_fn)); try { objWrite.writeObject(users); objWrite.flush(); } finally { objWrite.close(); } // Olion tietojen lukeminen ObjectInputStream objRead = new ObjectInputStream(new FileInputStream(output_fn)); try { readUsers = (List<User>) objRead.readObject(); } finally { objRead.close(); } } catch (IOException | ClassNotFoundException ex) { System.out.println(ex); } for (User user : readUsers) { System.out.print(user.name + ": "); System.out.println(user.age); } }
void ReceiveFileChunksFromServer() throws Exception, ClassNotFoundException { try { if (flagFilename) { filename = (String) in.readObject(); totalChunks = Integer.parseInt((String) in.readObject()); flagFilename = false; } if (availableChunks == null) availableChunks = new File[totalChunks]; if (requiredChunks == null) requiredChunks = new File[totalChunks]; int partNumber = Integer.parseInt((String) in.readObject()); File partFile = new File("chunks/" + filename + "." + partNumber); byte[] msg = (byte[]) in.readObject(); Files.write(partFile.toPath(), msg); availableChunks[partNumber] = partFile; System.out.println("Received chunk " + partNumber); } catch (ClassNotFoundException e) { flag = true; } catch (Exception e) { flag = true; } }
/** Loads the extraction model from the file. */ public void loadModel() throws Exception { BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(m_modelName)); ObjectInputStream in = new ObjectInputStream(inStream); m_KEAFilter = (KEAFilter) in.readObject(); in.close(); }
// get drivername, user, pw & server, and return connection id public void serve(InputStream i, OutputStream o) throws IOException { // TODOServiceList.getSingleInstance(); initialize(); NameListMessage nameListMessage = null; try { // read input to know which target panel is required ObjectInputStream input = new ObjectInputStream(i); nameListMessage = (NameListMessage) input.readObject(); // parse the required panel parseSqlFile(nameListMessage); } catch (ClassNotFoundException ex) { if (Debug.isDebug()) ex.printStackTrace(); nameListMessage.errorMessage = ex.toString(); } // send object to the caller ObjectOutputStream output = new ObjectOutputStream(o); output.writeObject(nameListMessage); // end socket connection o.close(); i.close(); }
public FileCollectionSnapshot snapshot(FileCollection files) { try { File snapshotFile = cache.get(files); if (snapshotFile == null) { assert cache.size() == 0; FileCollectionSnapshot snapshot = snapshotter.snapshot(files); snapshotFile = new File(tmpDir, String.valueOf(cache.size())); ObjectOutputStream outstr = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(snapshotFile))); try { outstr.writeObject(snapshot); } finally { outstr.close(); } cache.put(files, snapshotFile); return snapshot; } else { ObjectInputStream instr = new ObjectInputStream(new BufferedInputStream(new FileInputStream(snapshotFile))); try { return (FileCollectionSnapshot) instr.readObject(); } finally { instr.close(); } } } catch (Exception e) { throw new UncheckedIOException(e); } }
// @include public static String findStudentWithTopThreeAverageScores(InputStream ifs) { Map<String, TreeSet<UniqueInteger>> studentScores = new HashMap<>(); try { long sequence = 0; ObjectInputStream ois = new ObjectInputStream(ifs); while (true) { String name = ois.readUTF(); int score = ois.readInt(); TreeSet<UniqueInteger> scores = studentScores.get(name); if (scores == null) { scores = new TreeSet<>(); } scores.add(new UniqueInteger(score, sequence++)); studentScores.put(name, scores); } } catch (IOException e) { } String topStudent = "no such student"; int currentTopThreeScoresSum = 0; for (Map.Entry<String, TreeSet<UniqueInteger>> scores : studentScores.entrySet()) { if (scores.getValue().size() >= 3) { int currentScoresSum = getTopThreeScoresSum(scores.getValue()); if (currentScoresSum > currentTopThreeScoresSum) { currentTopThreeScoresSum = currentScoresSum; topStudent = scores.getKey(); } } } return topStudent; }
static LMClassifier loadModel(String model) throws ClassNotFoundException, IOException { System.out.println("-----Loading Model File <" + model + ">-----"); FileInputStream fileIn = new FileInputStream(model); ObjectInputStream objIn = new ObjectInputStream(fileIn); LMClassifier loadedModelClassifier = (LMClassifier) objIn.readObject(); Streams.closeInputStream(objIn); return loadedModelClassifier; }
public static Object deserialize(InputStream in) throws IOException { ObjectInputStream oin = new ObjectInputStream(in); try { return (oin.readObject()); } catch (ClassNotFoundException e) { return (null); } }
public static Grammar load(InputStream inputStream) { Grammar grammar; try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(inputStream))) { grammar = (Grammar) in.readObject(); } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(e); } return grammar; }
private void doControlTask() throws IOException, ClassNotFoundException { BlockingTaskSummaryResponseHandler handler = new BlockingTaskSummaryResponseHandler(); client.getTasksAssignedAsPotentialOwner("control", "en-UK", handler); List<TaskSummary> sums = handler.getResults(); assertNotNull(sums); assertEquals(1, sums.size()); BlockingTaskOperationResponseHandler startTaskOperationHandler = new BlockingTaskOperationResponseHandler(); client.start(sums.get(0).getId(), "control", startTaskOperationHandler); BlockingGetTaskResponseHandler getTaskHandler = new BlockingGetTaskResponseHandler(); client.getTask(sums.get(0).getId(), getTaskHandler); Task controlTask = getTaskHandler.getTask(); BlockingGetContentResponseHandler getContentHandler = new BlockingGetContentResponseHandler(); client.getContent(controlTask.getTaskData().getDocumentContentId(), getContentHandler); Content content = getContentHandler.getContent(); assertNotNull(content); ByteArrayInputStream bais = new ByteArrayInputStream(content.getContent()); ObjectInputStream ois = new ObjectInputStream(bais); Map<String, Object> deserializedContent = (Map<String, Object>) ois.readObject(); Emergency retrivedEmergency = (Emergency) deserializedContent.get("emergency"); assertNotNull(retrivedEmergency); ActivePatients retrivedActivePatients = (ActivePatients) deserializedContent.get("activePatients"); assertNotNull(retrivedActivePatients); assertEquals(1, retrivedActivePatients.size()); SuggestedProcedures retrivedSuggestedProcedures = (SuggestedProcedures) deserializedContent.get("suggestedProcedures"); assertNotNull(retrivedSuggestedProcedures); assertEquals( "[DefaultHeartAttackProcedure: ]", retrivedSuggestedProcedures.getSuggestedProceduresString()); Map<String, Object> info = new HashMap<String, Object>(); SelectedProcedures selectedProcedures = new SelectedProcedures(retrivedEmergency.getId()); selectedProcedures.addSelectedProcedureName("DefaultHeartAttackProcedure"); info.put("selectedProcedures", selectedProcedures); ContentData result = new ContentData(); result.setAccessType(AccessType.Inline); result.setType("java.util.Map"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(info); out.close(); result.setContent(bos.toByteArray()); BlockingTaskOperationResponseHandler completeTaskOperationHandler = new BlockingTaskOperationResponseHandler(); client.complete(sums.get(0).getId(), "control", result, completeTaskOperationHandler); }
/** Metodo que le os clientes de um ficheiro */ public void lerobjLocalidades(String fileLocalidades) throws FileNotFoundException, IOException, ClassNotFoundException { FileInputStream fisloc = new FileInputStream(fileLocalidades); ObjectInputStream oisloc = new ObjectInputStream(fisloc); this.localidades = (TreeMap<String, Localidade>) oisloc.readObject(); oisloc.close(); fisloc.close(); }