Beispiel #1
1
  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));
  }
Beispiel #2
0
 /**
  * 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);
 }
Beispiel #3
0
  /**
   * Not only deserialises the object, also performs adjustments on the timestamps to bring them in
   * alignment with the local time. Reads the current time on the peer node first. If the timestamp
   * of any items in the cache or commands are newer throws and IOException, because that means the
   * object is corrupted. Sets the timestamp of the contribution of the peer (if any) to the current
   * local time.
   */
  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {

    name = (String) in.readObject();

    cache = new Hashtable();
    commands = new Hashtable();

    final long max = in.readLong(); // the timestamp that should be maximal
    final long diff = System.currentTimeMillis() - max;
    myContribution = (ContributionBox) in.readObject();
    if (myContribution != null) myContribution.timeStamp = max + diff;

    int cachesize = in.readInt();
    for (int i = 0; i < cachesize; ++i) {
      ContributionBox cb = (ContributionBox) in.readObject();
      if (cb.timeStamp > max)
        throw new IOException("corrupted timestamp in cache: " + cb.timeStamp + " " + max);
      cb.timeStamp += diff;
      cache.put(cb.contributor.name, cb);
    }

    int commandssize = in.readInt();
    for (int i = 0; i < commandssize; ++i) {
      Object comm = in.readObject();
      long time = in.readLong();
      if (time > max) throw new IOException("corrupted timestamp in commands: " + time + " " + max);
      time += diff;
      commands.put(comm, new Long(time));
    }
  }
  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;
    }
  }
 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();
   }
 }
 @SuppressWarnings({"boxing", "unchecked"})
 public void loadCache() {
   this.cache.clear();
   try {
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(CACHE_FILE));
     this.remoteDiscoveryImpl.syso("load cache");
     try {
       final int cacheSize = (Integer) in.readObject();
       //					syso("size "+cacheSize);
       for (int i = 0; i < cacheSize; ++i) {
         HashMap<RemoteManagerEndpoint, Entry> rmee = new HashMap<RemoteManagerEndpoint, Entry>();
         Class<? extends Plugin> plugin = (Class<? extends Plugin>) in.readObject();
         this.remoteDiscoveryImpl.syso(plugin.getCanonicalName());
         //						syso("\t"+i+"'"+pluginName+"'");
         int numEntries = (Integer) in.readObject();
         //						syso("\t"+numEntries);
         for (int j = 0; j < numEntries; ++j) {
           Entry entry = (Entry) in.readObject();
           //							syso("\t\t"+entry);
           rmee.put(entry.manager, entry);
         }
         this.cache.put(plugin, rmee);
       }
     } catch (ClassNotFoundException e) {
       e.printStackTrace();
     } finally {
       in.close();
     }
   } catch (FileNotFoundException e) {
     this.remoteDiscoveryImpl.logger.warning("Loading cache file" + CACHE_FILE + " failed.");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  public void run() {
    try {
      ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());

      BigInteger bg = dhSpec.getG();
      BigInteger bp = dhSpec.getP();
      oos.writeObject(bg);
      oos.writeObject(bp);

      KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
      kpg.initialize(1024);
      KeyPair kpa = (KeyPair) ois.readObject();
      KeyAgreement dh = KeyAgreement.getInstance("DH");
      KeyPair kp = kpg.generateKeyPair();

      oos.writeObject(kp);

      dh.init(kp.getPrivate());
      Key pk = dh.doPhase(kpa.getPublic(), true);

      MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
      byte[] rawbits = sha256.digest(dh.generateSecret());

      Cipher c = Cipher.getInstance(CIPHER_MODE);
      SecretKey key = new SecretKeySpec(rawbits, 0, 16, "AES");
      byte ivbits[] = (byte[]) ois.readObject();
      IvParameterSpec iv = new IvParameterSpec(ivbits);
      c.init(Cipher.DECRYPT_MODE, key, iv);

      Mac m = Mac.getInstance("HmacSHA1");
      SecretKey mackey = new SecretKeySpec(rawbits, 16, 16, "HmacSHA1");
      m.init(mackey);

      byte ciphertext[], cleartext[], mac[];
      try {
        while (true) {
          ciphertext = (byte[]) ois.readObject();
          mac = (byte[]) ois.readObject();
          if (Arrays.equals(mac, m.doFinal(ciphertext))) {
            cleartext = c.update(ciphertext);
            System.out.println(ct + " : " + new String(cleartext, "UTF-8"));
          } else {
            // System.exit(1);
            System.out.println(ct + "error");
          }
        }
      } catch (EOFException e) {
        cleartext = c.doFinal();
        System.out.println(ct + " : " + new String(cleartext, "UTF-8"));
        System.out.println("[" + ct + "]");
      } finally {
        if (ois != null) ois.close();
        if (oos != null) oos.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #8
0
  private Map<String, Pack> loadInstallationInformation(boolean modifyInstallation) {
    Map<String, Pack> installedpacks = new HashMap<String, Pack>();
    if (!modifyInstallation) {
      return installedpacks;
    }

    // installation shall be modified
    // load installation information
    ObjectInputStream oin = null;
    try {
      FileInputStream fin =
          new FileInputStream(
              new File(
                  installData.getInstallPath()
                      + File.separator
                      + InstallData.INSTALLATION_INFORMATION));
      oin = new ObjectInputStream(fin);
      List<Pack> packsinstalled = (List<Pack>) oin.readObject();
      for (Pack installedpack : packsinstalled) {
        installedpacks.put(installedpack.getName(), installedpack);
      }
      this.removeAlreadyInstalledPacks(installData.getSelectedPacks());
      logger.fine("Found " + packsinstalled.size() + " installed packs");

      Properties variables = (Properties) oin.readObject();

      for (Object key : variables.keySet()) {
        installData.setVariable((String) key, (String) variables.get(key));
      }
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      if (oin != null) {
        try {
          oin.close();
        } catch (IOException e) {
        }
      }
    }
    return installedpacks;
  }
 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;
 }
Beispiel #10
0
 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();
   }
 }
  // 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();
  }
Beispiel #12
0
 /**
  * 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
         }
     }
   }
 }
  /**
   * Constantly reads the client's input stream. Sends all objects that are read to the server. Not
   * to be called.
   */
  public final void run() {
    server.clientConnected(this);

    // This loop reads the input stream and responds to messages
    // from clients
    try {
      // The message from the client
      Object msg;

      while (!readyToStop) {
        // This block waits until it reads a message from the client
        // and then sends it for handling by the server
        msg = input.readObject();
        server.receiveMessageFromClient(msg, this);
      }
    } catch (Exception exception) {
      if (!readyToStop) {
        try {
          closeAll();
        } catch (Exception ex) {
        }

        server.clientException(this, exception);
      }
    }
  }
Beispiel #14
0
 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;
 }
  /** 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();
  }
  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();
    }
  }
 /**
  * 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;
   }
 }
  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);
    }
  }
Beispiel #19
0
  /**
   * 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;
    }
  }
  /**
   * @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 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);
   }
 }
Beispiel #22
0
  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 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;
  }
Beispiel #24
0
  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);
    }
  }
Beispiel #25
0
  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();
    }
  }
Beispiel #26
0
  /** 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();
      }
    }
  }
Beispiel #27
0
 /**
  * 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
         }
     }
   }
 }
 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;
 }
 private TaskObjectsExecutionResults runObject(TaskObjectsExecutionRequest obj)
     throws IOException, PDBatchTaskExecutorException {
   Object res = null;
   try {
     setAvailability(false);
     _oos.writeObject(obj);
     _oos.flush();
     res = _ois.readObject();
     setAvailability(true);
   } catch (IOException e) { // worker closed connection
     processException(e);
     throw e;
   } catch (ClassNotFoundException e) {
     processException(e);
     throw new IOException("stream has failed");
   }
   if (res instanceof TaskObjectsExecutionResults) {
     _isPrevRunSuccess = true;
     return (TaskObjectsExecutionResults) res;
   } else {
     PDBatchTaskExecutorException e =
         new PDBatchTaskExecutorException("worker failed to run tasks");
     if (_isPrevRunSuccess == false && !sameAsPrevFailedJob(obj._tasks)) {
       processException(e); // twice a loser, kick worker out
     }
     _isPrevRunSuccess = false;
     _prevFailedBatch = obj._tasks;
     throw e;
   }
 }
 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;
 }