Esempio n. 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));
  }
Esempio n. 2
0
 // returns a deep copy of an object
 public static Object deepCopy(Object oldObj) {
   ObjectOutputStream oos = null;
   ObjectInputStream ois = null;
   try {
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A
     oos = new ObjectOutputStream(bos); // B
     // serialize and pass the object
     oos.writeObject(oldObj); // C
     oos.flush(); // D
     ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E
     ois = new ObjectInputStream(bin); // F
     // return the new object
     Object object = ois.readObject();
     oos.close();
     ois.close();
     return object; // G
   } catch (Exception e) {
     return null;
   } finally {
     try {
       if (oos != null) oos.close();
       if (ois != null) ois.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
  @Override
  public void write(String path) throws IOException {
    File dir = FileUtils.getFile(path, "ensemble", getName());
    if (!dir.isDirectory()) {
      dir.mkdirs();
    }
    ObjectOutputStream oop =
        new ObjectOutputStream(new FileOutputStream(new File(dir, "similarityCoefficients")));
    oop.writeObject(simlarityCoefficients);
    oop.flush();
    oop.close();

    oop = new ObjectOutputStream(new FileOutputStream(new File(dir, "mostSimilarCoefficients")));
    oop.writeObject(mostSimilarCoefficients);
    oop.flush();
    oop.close();

    oop = new ObjectOutputStream(new FileOutputStream(new File(dir, "similarityInterpolator")));
    oop.writeObject(similarityInterpolator);
    oop.flush();
    oop.close();

    oop = new ObjectOutputStream(new FileOutputStream(new File(dir, "mostSimilarInterpolator")));
    oop.writeObject(mostSimilarInterpolator);
    oop.flush();
    oop.close();
  }
Esempio n. 4
0
  /**
   * Checks if the score is high enough to get to the high scores list, adds the name and score and
   * organizes the list. If HighScores.dat is not found, the method generates a blank one.
   *
   * @param name The nickname of the person getting to the list.
   * @param score The score gained.
   */
  public static void addHighScore(String name, int score) {

    // If we don't yet have a high scores table, we create a blank (and let the user know about it)
    if (!new File("HighScores.dat").exists()) {
      // This object matrix actually stores the information of the high scores list
      Object[][] highScores = new Object[10][3];
      // We fill the high scores list with blank entries:  #.    " "    0
      for (int i = 0; i < highScores.length; i++) {
        highScores[i][0] = (i + 1) + ".";
        highScores[i][1] = " ";
        highScores[i][2] = 0;
      }
      // This actually writes and makes the high scores file
      try {
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
        o.writeObject(highScores);
        o.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    // We read the file to check if we have a new high score, and then rewrite the highscore
    // This is done even if we didn't previously have a high scores list
    try {
      ObjectInputStream o = new ObjectInputStream(new FileInputStream("HighScores.dat"));
      // The object matrix does the same as the previous one.
      // Here we just take what we read from the HighScores.dat to the Object[][] HighScores.
      Object[][] highScores = (Object[][]) o.readObject();
      // Then we start searching for an entry for which the score is smaller than the achieved score
      for (int i = 0; i < highScores.length; i++) {
        if ((Integer) highScores[i][2] < score) {
          // Once found we start to move entries, which are below the score we had, downwards.
          // I.e. 10. becomes whatever 9. was. 9. becomes what 8. was etc...
          for (int j = 9; j > i; j--) {
            highScores[j][0] = (j + 1) + ".";
            highScores[j][1] = highScores[j - 1][1];
            highScores[j][2] = highScores[j - 1][2];
          }
          // Then we write the score and the name we just got to the correct place
          highScores[i][0] = (i + 1) + ".";
          highScores[i][1] = name;
          highScores[i][2] = score;
          // And break the loop.
          /*Maybe this could be avoided somehow? I haven't been able to come up with an easy way yet.*/
          break;
        }
      }
      try {
        // And finally we overwrite the HighScores.dat with our highScores object matrix
        ObjectOutputStream n = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
        n.writeObject(highScores);
        n.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (ClassNotFoundException | IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 5
0
  /** {@inheritDoc} */
  public synchronized boolean commit(GRootGroup currentState, int referenceVersion)
      throws RemoteException, VersionException, RepositoryException {
    // check that referenceVersion is a valid version
    if ((referenceVersion < 0) || (referenceVersion > currentVersion)) {
      throw new VersionException(
          "The reference version supplied at commit ("
              + referenceVersion
              + ") was either negative or greater than the current version on the repository.");
    }

    // tell the client that an update is needed before he can commit
    if (referenceVersion != currentVersion) {
      return false;
    }

    try {
      // the delta between version(n) and version(n+1) is stored in the file called v<n+1>
      File vFile = new File(repositoryPath + "v" + (new Integer(currentVersion + 1)).toString());
      ObjectOutputStream vfWriter =
          new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(vFile)));

      Datetime timestamp = new Datetime();
      vfWriter.writeObject(timestamp);
      vfWriter.writeObject(currentState);
      vfWriter.close();

      timestamps.add(timestamp);
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("Failed to write operations to file during commit.");

      throw new RepositoryException(
          "The repository failed to commit your version. Please notify " + "the administrator.");
    }

    // if we got this far, it means all went ok => we can increment currentVersion
    File versionFile = new File(repositoryPath + "version");

    System.out.println("Trying to update version file after a successful commit.");

    try {
      ObjectOutputStream vfWriter = new ObjectOutputStream(new FileOutputStream(versionFile));
      vfWriter.writeInt(currentVersion + 1);
      vfWriter.close();
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("Failed to update version file.");

      throw new RepositoryException(
          "The repository failed to commit your version. Please notify " + "the administrator.");
    }

    System.out.println("Version file successfully updated.");

    currentVersion++;

    return true;
  }
Esempio n. 6
0
  public void insert(FIncomePO po) throws RemoteException, IOException {
    ObjectOutputStream oos = null;
    try {
      FileOutputStream fs = new FileOutputStream(file, true);
      oos = new ObjectOutputStream(fs);
      oos.writeObject(po);
      oos.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      oos.close();
    }
  }
Esempio n. 7
0
  /**
   * Clone a <code>Serializable</code> object; for use when a <code>clone()</code> method is not
   * available.
   *
   * @param obj object to clone
   * @return clone object
   * @throws RuntimeException
   */
  public static Object cloneSerializable(Object obj) {
    Object ret = null;

    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream(StreamUtils.DEFAULT_BUFFER_SIZE);
      ObjectOutputStream oos = new ObjectOutputStream(baos);
      oos.writeObject(obj);
      oos.close();

      ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
      ObjectInputStream ois = new ObjectInputStream(bis);

      try {
        ret = ois.readObject();
      } catch (ClassNotFoundException cnfe) {
        assert false;
      }

      ois.close();
    } catch (IOException ioex) {
      throw new RuntimeException("Unable to clone object: " + obj);
    }

    return ret;
  }
 private void createDB() throws IOException {
   File db = new File(dbLocation);
   ObjectOutputStream w = new ObjectOutputStream(new FileOutputStream(dbLocation));
   w.writeObject(digestDB);
   w.flush();
   w.close();
 }
  public void InsertSupplier(Supplier supplier) {
    FileOutputStream fos = null;

    try {
      File file = new File("Suppliers.dat");

      if (file.exists()) {
        fos = new FileOutputStream(file, true);
        _aoos = new AppendableObjectOutputStream(fos);
        _aoos.writeObject(supplier);
        System.out.println("Fornecedor cadastrado com sucesso!");
      } else {
        fos = new FileOutputStream(file);
        _oos = new ObjectOutputStream(fos);
        _oos.writeObject(supplier);
        System.out.println("Fornecedor cadastrado com sucesso!");
      }

    } catch (IOException ex) {
      System.out.println("Falha ao cadastrar fornecedor!");
      ex.getStackTrace();
    } finally {
      try {
        if (_aoos != null) _aoos.close();
        if (_oos != null) _oos.close();
        if (fos != null) fos.close();
      } catch (IOException ex) {
        System.out.println("Falha ao cadastrar fornecedor!");
        ex.getStackTrace();
      }
    }
  }
 /**
  * Serialize an object to a byte array. (code by CB)
  *
  * @param object object to serialize
  * @return byte array that represents the object
  * @throws Exception
  */
 public static byte[] toByte(Object object) throws Exception {
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   ObjectOutputStream oos = new ObjectOutputStream((OutputStream) os);
   oos.writeObject(object);
   oos.close();
   return os.toByteArray();
 }
Esempio n. 11
0
  public void writeIndex(String location) {

    System.out.println("Writing index at: " + location);

    ObjectOutputStream objectOutputStream = null;

    try {

      File outputFile = new File(location);
      if (!outputFile.exists()) {
        outputFile.getParentFile().mkdirs();
        outputFile.createNewFile();
      }

      OutputStream file = new FileOutputStream(outputFile);
      BufferedOutputStream buffer = new BufferedOutputStream(file);
      objectOutputStream = new ObjectOutputStream(buffer);
      objectOutputStream.writeObject(tokenCountMap);
      objectOutputStream.writeObject(references);
    } catch (IOException ex) {
      System.out.println(
          "\nError writing index for " + author.getName() + " at location " + location);
    } finally {
      if (objectOutputStream != null)
        try {
          objectOutputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }
  }
Esempio n. 12
0
 /**
  * A getter for the high scores list. Reads it directly from file and throws an error if the file
  * is not found (!working on this!).
  *
  * @return Object[][] where [i][0] is the rank (String), [i][1] is the name (String) and [i][2] is
  *     the score (Integer).
  */
 public static Object[][] getHighScore() {
   if (!new File("HighScores.dat").exists()) {
     // This object matrix actually stores the information of the high scores list
     Object[][] highScores = new Object[10][3];
     // We fill the high scores list with blank entries:  #.    " "    0
     for (int i = 0; i < highScores.length; i++) {
       highScores[i][0] = (i + 1) + ".";
       highScores[i][1] = " ";
       highScores[i][2] = 0;
     }
     // This actually writes and makes the high scores file
     try {
       ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
       o.writeObject(highScores);
       o.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   try {
     // Read and return the read object matrix
     ObjectInputStream o = new ObjectInputStream(new FileInputStream("HighScores.dat"));
     Object[][] highScores = (Object[][]) o.readObject();
     o.close();
     return highScores;
   } catch (IOException | ClassNotFoundException e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 13
0
 public void serializeAndReplace(Object obj) throws IOException {
   FileOutputStream fOut = new FileOutputStream(this.getFilepath());
   ObjectOutputStream objOut = new ObjectOutputStream(fOut);
   objOut.writeObject(obj);
   objOut.close();
   fOut.close();
 }
Esempio n. 14
0
 public static void main(String[] args) throws Exception {
   ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("c:\\test.dat"));
   LinkedHashSet<String> set1 = new LinkedHashSet<String>();
   set1.add("New York");
   LinkedHashSet<String> set2 = (LinkedHashSet<String>) set1.clone();
   set1.add("Atlanta");
   output.writeObject(set1);
   output.writeObject(set2);
   output.close();
   ObjectInputStream input = new ObjectInputStream(new FileInputStream("c:\\test.dat"));
   set1 = (LinkedHashSet) input.readObject();
   set2 = (LinkedHashSet) input.readObject();
   System.out.println(set1);
   System.out.println(set2);
   output.close();
 }
 /**
  * Serializes the passed object to a byte array, returning a zero byte array if the passed object
  * is null, or fails serialization
  *
  * @param arg The object to serialize
  * @return the serialized object
  */
 public static byte[] serializeNoCompress(Object arg) {
   if (arg == null) return new byte[] {};
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   ObjectOutputStream oos = null;
   try {
     oos = new ObjectOutputStream(baos);
     oos.writeObject(arg);
     oos.flush();
     baos.flush();
     return baos.toByteArray();
   } catch (Exception ex) {
     return new byte[] {};
   } finally {
     try {
       baos.close();
     } catch (Exception ex) {
       /* No Op */
     }
     if (oos != null)
       try {
         oos.close();
       } catch (Exception ex) {
         /* No Op */
       }
   }
 }
Esempio n. 16
0
  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();
    }
  }
Esempio n. 17
0
  // add the new user to the encrypted users file which has the detailed stats for all users
  // synchronize to make sure that only one thread can be inside this block at a time.
  public static synchronized String addUserAndIssueCode(UserStats stats)
      throws IOException, GeneralSecurityException, ClassNotFoundException, NoMoreCodesException {

    // ok, now we have a list of stats objects, representing all users.
    // add this user to the list.
    // the code assigned to this user will simply be codes.get(users.size())
    // but do an error check first to be sure we're not out of codes
    List<UserStats> users = readUsersFile();

    if (users.size() >= MemoryStudy.codes.size()) {
      log.warn("NOC WARNING: codes file exhausted!!!!");
      throw new NoMoreCodesException();
    }

    // ok, we have enough codes, just give out one
    String passkey = MemoryStudy.codes.get(users.size());
    int USERID_BASE =
        100; // userid numbering starts from USERID_BASE, new id is base + # existing codes
    stats.userid = Integer.toString(USERID_BASE + users.size());
    stats.code = passkey;
    users.add(stats);

    // encrypt and write the users file back
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(users);
    oos.close();
    CryptoUtils.writeEncryptedBytes(baos.toByteArray(), USERS_FILE);

    return passkey;
  }
  /** Method: readFromFile() */
  @Test
  public void testReadFromFile() throws Exception {
    GameNode testGameNode = new GameNode();
    testGameNode.setPlayer("rarry");
    testGameNode.setOpponent("lobertie");
    testGameNode.setGameName("raddle");
    testGameNode.setWinLose(true);
    testGameNode.setScore(29);
    LinkedList<GameNode> testLLGN = new LinkedList<GameNode>();
    testLLGN.add(testGameNode);
    try {
      FileOutputStream fileOut = new FileOutputStream("gameStats.ser");
      ObjectOutputStream out = new ObjectOutputStream(fileOut);
      out.writeObject(testLLGN);
      out.close();
      fileOut.close();
    } catch (IOException e) {

    }

    testScoreboard.readFromFile();

    assertTrue(
        "Is a public method that returns void and only alters a private variable with no getter. Should be made"
            + " a private method, should allow for ScoreInfo access or should not be tested",
        false);
  }
  static boolean saveDat(String path) {
    try {
      //            DataOutputStream out = new DataOutputStream(new FileOutputStream(path));
      //            out.writeInt(start.length);
      //            for (int i : start)
      //            {
      //                out.writeInt(i);
      //            }
      //            out.writeInt(pair.length);
      //            for (int i : pair)
      //            {
      //                out.writeInt(i);
      //            }
      //            out.close();
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path));
      out.writeObject(start);
      out.writeObject(pair);
      out.close();
    } catch (Exception e) {
      logger.log(Level.WARNING, "在缓存" + path + "时发生异常", e);
      return false;
    }

    return true;
  }
 @SuppressWarnings("boxing")
 public void saveCache() {
   try {
     ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(CACHE_FILE));
     this.remoteDiscoveryImpl.syso("save cache");
     try {
       //					syso("size"+this.cache.size());
       out.writeObject(this.cache.size());
       for (Map.Entry<Class<? extends Plugin>, HashMap<RemoteManagerEndpoint, Entry>> he :
           this.cache.entrySet()) {
         //						syso(he.getKey()+" " +he.getValue().size());
         this.remoteDiscoveryImpl.syso(he.getKey().getCanonicalName());
         out.writeObject(he.getKey());
         out.writeObject(he.getValue().size());
         for (Entry me : he.getValue().values()) {
           //							syso("\t"+me);
           out.writeObject(me);
         }
       }
       //					out.writeObject(this.cache);
     } finally {
       out.close();
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Esempio n. 21
0
 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);
   }
 }
 public void windowClosing(WindowEvent e) // write file on finish
     {
   FileOutputStream out = null;
   ObjectOutputStream data = null;
   try {
     // open file for output
     out = new FileOutputStream(DB);
     data = new ObjectOutputStream(out);
     // write Person objects to file using iterator class
     Iterator<Person> itr = persons.iterator();
     while (itr.hasNext()) {
       data.writeObject((Person) itr.next());
     }
     data.flush();
     data.close();
   } catch (Exception ex) {
     JOptionPane.showMessageDialog(
         objUpdate.this,
         "Error processing output file" + "\n" + ex.toString(),
         "Output Error",
         JOptionPane.ERROR_MESSAGE);
   } finally {
     System.exit(0);
   }
 }
 public static void main(String[] args) throws IOException, ClassNotFoundException {
   File f = new File("objects2.dat");
   if (!f.exists()) {
     System.out.println("Creating objects and writing them to file:");
     SC c = new SC();
     SO o1 = new SO(1, c), o2 = new SO(2, c);
     o1.c.ci = 3;
     o2.c.ci = 4; // update the shared c twice
     o1.cprint();
     o2.cprint(); // prints i1c4 i2c4
     OutputStream os = new FileOutputStream(f);
     ObjectOutputStream oos1 = new ObjectOutputStream(os);
     oos1.writeObject(o1);
     oos1.flush();
     ObjectOutputStream oos2 = new ObjectOutputStream(os);
     oos2.writeObject(o2);
     oos2.close();
     System.out.println("\nRun the example again to read objects from file");
   } else {
     System.out.println("Reading objects from file (non-shared c):");
     InputStream is = new FileInputStream(f);
     ObjectInputStream ois1 = new ObjectInputStream(is);
     SO o1i = (SO) (ois1.readObject());
     ObjectInputStream ois2 = new ObjectInputStream(is);
     SO o2i = (SO) (ois2.readObject());
     o1i.cprint();
     o2i.cprint(); // prints i1c4 i2c4
     o1i.c.ci = 5;
     o2i.c.ci = 6; // update two different c's
     o1i.cprint();
     o2i.cprint(); // prints i1c5 i2c6
     f.delete();
   }
   System.out.println();
 }
Esempio n. 24
0
  public static void main(String[] args) throws IOException, ClassNotFoundException {

    Singleton instance = Singleton.getInstance();

    // Serializing the singleton instance
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton.tmp"));
    oos.writeObject(instance);
    oos.close();

    // Recreating the instance by reading the serialized object data store
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("singleton.tmp"));
    Singleton singleton = (Singleton) ois.readObject();
    ois.close();

    // Recreating the instance AGAIN by reading the serialized object data store
    ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream("singleton.tmp"));
    Singleton singleton1 = (Singleton) ois2.readObject();
    ois2.close();

    // The singleton behavior have been broken
    System.out.println("Instance reference check : " + singleton.getInstance());
    System.out.println("Instance reference check : " + singleton1.getInstance());
    System.out.println("=========================================================");
    System.out.println("Object reference check : " + singleton);
    System.out.println("Object reference check : " + singleton1);
  }
Esempio n. 25
0
  // ---------------------------------------------------------------------------
  private void writeCache() {
    try {
      Debug.print("Writing cache");
      FileOutputStream fos = new FileOutputStream(m_cacheFile);
      ObjectOutputStream oos = new ObjectOutputStream(fos);

      oos.writeObject(m_depCache);

      oos.writeInt(m_newModificationCache.size());

      Iterator<String> it = m_newModificationCache.keySet().iterator();

      while (it.hasNext()) {
        String key = it.next();

        oos.writeUTF(key);
        oos.writeLong(m_newModificationCache.get(key));
      }

      oos.close();
    } catch (Exception e) {
      Debug.print(e.getMessage());
      StringWriter sw = new StringWriter();
      e.printStackTrace(new PrintWriter(sw));
      Debug.print(sw.toString());
    }
  }
  @Override
  public void execute(JavaExecSpec javaExec) {
    configureReloadAgent(javaExec); // mutates the launch context

    OutputStream fileOut = null;
    ObjectOutputStream oos = null;
    try {
      fileOut = new FileOutputStream(contextDestination);
      oos = new ObjectOutputStream(fileOut);
      oos.writeObject(launchContext);

      javaExec.setWorkingDir(launchContext.getBaseDir());
      if (launchContext.getGrailsHome() != null) {
        javaExec.systemProperty("grails.home", launchContext.getGrailsHome().getAbsolutePath());
      }

      File launcherJar = findJarFile(ForkedGrailsLauncher.class);
      javaExec.classpath(launcherJar);
      javaExec.setMain(Main.class.getName());
      javaExec.args(contextDestination.getAbsolutePath());
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally {
      try {
        if (oos != null) {
          oos.close();
        }
        if (fileOut != null) {
          fileOut.close();
        }
      } catch (IOException ignore) {

      }
    }
  }
Esempio n. 27
0
  public void updateFile() {
    ArrayList<Product> products = new ArrayList<Product>();
    try {
      // products.clear();
      Statement s = connection.createStatement();
      // ((org.postgresql.jdbc3.AbstractJdbc3Statement)s).setQueryTimeout(1);

      String sql = "select * from stock";
      // ResultSet
      // resultset=((org.postgresql.jdbc3.AbstractJdbc3Statement)s).executeQuery(sql);
      ResultSet resultset = s.executeQuery(sql);
      // searchResult.clear();
      while (resultset.next()) {
        int id = resultset.getInt(1);
        String pname = resultset.getString(2);
        int amount = resultset.getInt(3);
        double price = resultset.getDouble(4);
        String feature = resultset.getString(5);
        products.add(new Product(id, pname, amount, price, feature));
      }
      System.out.println(products.size() + "beforewrite");
      oout = new ObjectOutputStream(new FileOutputStream(file));
      oout.writeObject(products);
      oout.close();
      System.out.println("all written");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 28
0
  public static void Ex() {
    System.out.println("-- do zapisu --");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    DowodOsobisty z = new DowodOsobisty(br);
    z.info();

    try {
      ObjectOutputStream outp = new ObjectOutputStream(new FileOutputStream("plik.dat"));
      outp.writeObject(z);
      outp.close();
    } catch (Exception e) {
      System.out.println(e);
    }

    System.out.println("\n-- z pliku --");
    ObjectInputStream inp;

    try {
      inp = new ObjectInputStream(new FileInputStream("plik.dat"));
      Object o = inp.readObject();
      DowodOsobisty x = (DowodOsobisty) o;
      inp.close();
      x.info();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Esempio n. 29
0
  public void run() {
    try {
      System.out.println("socked");
      sock = new Socket(ii, pp);
      oout = new ObjectOutputStream(sock.getOutputStream());
      oout.flush();

      oin = new ObjectInputStream(sock.getInputStream());
      System.out.println("read ");
      rf.setLength(0);
      do {
        System.out.println("read ");
        file f = (file) oin.readObject();
        if (f.length <= 0) break;
        write(f);
      } while (true);
      oout.close();
      oin.close();
      rf.close();
      sock.close();
      xx.ConfirmPopup("Haua file namano shesh!!!");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 30
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();
   }
 }