示例#1
0
  @Test
  public void testAccountSerialization() throws Exception {
    Account a = ModelFactory.createAccount("Foo", ModelFactory.createAccountType("Cash", false));
    a.setInterestRate(1234);
    a.setNotes("Foo bar notes");
    a.setOverdraftCreditLimit(123);
    a.setStartingBalance(10000);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(os);
    encoder.writeObject(a);
    encoder.flush();
    encoder.close();

    InputStream is = new ByteArrayInputStream(os.toByteArray());
    XMLDecoder decoder = new XMLDecoder(is);
    Object o = decoder.readObject();
    decoder.close();

    if (!(o instanceof Account)) {
      throw new Exception("Deserialized object is not an account!");
    }

    Account newAccount = (Account) o;
    assertEquals(a.getName(), newAccount.getName());
    assertEquals(a.getAccountType(), newAccount.getAccountType());
    assertEquals(a.getInterestRate(), newAccount.getInterestRate());
    assertEquals(a.getNotes(), newAccount.getNotes());
    assertEquals(a.getOverdraftCreditLimit(), newAccount.getOverdraftCreditLimit());
    assertEquals(a.getStartingBalance(), newAccount.getStartingBalance());
  }
示例#2
0
 public static String toXml(Object thing) {
   XMLEncoder encoder = null;
   ByteArrayOutputStream baos = null;
   try {
     baos = new ByteArrayOutputStream(BUFF_SIZE);
     encoder = new XMLEncoder(baos);
     encoder.writeObject(thing);
     byte[] bytes = baos.toByteArray();
     return new String(bytes);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       if (encoder != null) {
         encoder.close();
       }
     } catch (Exception e) {
     }
     try {
       if (baos != null) {
         baos.close();
       }
     } catch (Exception e) {
     }
   }
   return null;
 }
示例#3
0
  public static void toFile(Object thing, String path) {
    if (path.endsWith(".xml")) {
      XMLEncoder encoder = null;
      try {
        encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(path)));
        encoder.writeObject(thing);

      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (encoder != null) {
          encoder.close();
        }
      }
    } else {
      ObjectOutputStream encoder = null;
      try {
        encoder = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
        encoder.writeObject(thing);

      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (encoder != null) {
          try {
            encoder.close();
          } catch (Exception e) {
          }
        }
      }
    }
  }
  /**
   * Saves all templates as XML files in the current template directory.
   *
   * @return Whether or not the save was successful.
   */
  public boolean saveTemplates() {

    if (templates == null) return true;
    if (directory == null || !directory.isDirectory()) return false;

    // Blow away all old XML files to start anew, as some might be from
    // templates we're removed from the template manager.
    File[] oldXMLFiles = directory.listFiles(new XMLFileFilter());
    if (oldXMLFiles == null) return false; // Either an IOException or it isn't a directory.
    int count = oldXMLFiles.length;
    for (int i = 0; i < count; i++) {
      /*boolean deleted = */ oldXMLFiles[i].delete();
    }

    // Save all current templates as XML.
    boolean wasSuccessful = true;
    for (Iterator i = templates.iterator(); i.hasNext(); ) {
      CodeTemplate template = (CodeTemplate) i.next();
      File xmlFile = new File(directory, template.getID() + ".xml");
      try {
        XMLEncoder e = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(xmlFile)));
        e.writeObject(template);
        e.close();
      } catch (IOException ioe) {
        ioe.printStackTrace();
        wasSuccessful = false;
      }
    }

    return wasSuccessful;
  }
 public static void storeHashMap(Map<String, List<String>> clusterMap) {
   File file = null;
   FileOutputStream fos = null;
   XMLEncoder encode = null;
   try {
     file = new File(BuildConstants.propFile);
     fos = new FileOutputStream(file);
     encode = new XMLEncoder(fos);
     encode.writeObject(clusterMap);
     log.info("Done Saving the Map to propFile.properties file");
   } catch (Exception ex) {
     ex.printStackTrace();
   } finally {
     try {
       if (encode != null) {
         encode.flush();
         encode.close();
       }
       if (fos != null) {
         fos.flush();
         fos.close();
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  @Override
  public void saving(ISaveContext context) throws CoreException {
    switch (context.getKind()) {
      case ISaveContext.FULL_SAVE:
      case ISaveContext.SNAPSHOT:
        int saveNumber = context.getSaveNumber();
        String saveFileName = "CMakeWorkBench-" + Integer.toString(saveNumber) + ".xml";
        File file = getStateLocation().append(saveFileName).toFile();

        XMLEncoder encoder = null;
        try {
          encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(file)));
          encoder.writeObject(this.session);
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } finally {
          if (encoder != null) {
            encoder.close();
          }
        }

        context.map(new Path("save"), new Path(saveFileName));
        context.needSaveNumber();

        // remove last saved state
        new File("CMakeWorkBench-" + Integer.toString(saveNumber - 1) + ".xml").delete();

        break;
    }
  }
示例#7
0
  /**
   * Ctor that gets the properties from the XML files and set them to the server If properties does
   * not exist then it will take default values
   */
  public MyModel() {
    this.clinetHandler = new MyClientHandler();
    this.clientsHandled = 0;
    this.killServer = false;
    this.serverOpen = false;
    File serverProp =
        new File("./resources/propServer.xml"); // check if server Properties xml file exists
    if (!serverProp.exists()) // if the file does not exists
    {
      try { // create the xml file
        XMLEncoder xml = new XMLEncoder(new FileOutputStream("./resources/propServer.xml"));
        xml.writeObject(new ServerProperties(1234, 10));
        xml.close();
      } catch (FileNotFoundException e) {
        setChanged();
        notifyObservers(new String[] {"error", e.getMessage()});
      }
    }

    try { // get the server properties from the xml file
      XMLDecoder xml = new XMLDecoder(new FileInputStream("./resources/propServer.xml"));
      ServerProperties properties = (ServerProperties) xml.readObject();
      this.port = properties.getPort();
      this.numOfClients = properties.getNumClients();
      xml.close();
    } catch (Exception e) {
      setChanged();
      notifyObservers(new String[] {"error", e.getMessage()});
    }
  }
  @Test
  public void testSaveLoad() throws FileNotFoundException, IOException {
    System.out.println("---  testSaveLoad...");
    XMLEncoder xmlEncoder = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;

    File f = new File("testProjects/TEMP_PROJECTS/Test.ser");

    System.out.println("Saving to: " + f.getCanonicalPath());

    fos = new FileOutputStream(f);
    bos = new BufferedOutputStream(fos);
    xmlEncoder = new XMLEncoder(bos);

    // Metric m = Metric.PATH_LENGTH_FROM_ROOT;
    Object o1 = pg1;

    System.out.println("Pre: " + o1);

    // ProximalPref p = ProximalPref.MOST_PROX_AT_0;

    xmlEncoder.writeObject(o1);
    xmlEncoder.close();

    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    XMLDecoder xd = new XMLDecoder(bis);

    Object o2 = xd.readObject();

    System.out.println("Post: " + o2);

    assertEquals(o2, o1);
  }
  /**
   * Persists the list of {@link AwaitedJob} to file
   *
   * @throws FileNotFoundException
   */
  protected synchronized void saveAwaitedJobsToFile() throws FileNotFoundException {

    File statusFileBK = new File(statusFilename + ".BAK");
    if (statusFileBK.isFile()) {
      statusFileBK.delete();
    }

    if (statusFile != null && statusFile.isFile()) statusFile.renameTo(statusFileBK);

    try {
      statusFile = new File(statusFilename);
      XMLEncoder encoder = new XMLEncoder(new FileOutputStream(statusFile));

      for (AwaitedJob aj : awaitedJobs.values()) {
        encoder.writeObject(aj);
      }
      encoder.flush();
      encoder.close();
    } catch (Throwable t) {
      logger.error(
          "Could not persist the list of awaited jobs. Some jobs output data might not be transfered after application restart ",
          t);
      // recover the status file from the backup file
      statusFile.delete();
      statusFileBK.renameTo(statusFile);
    }
  }
  private void guardarFicha(String fichero) {
    FichaCliente ficha = new FichaCliente();
    String cif, direccion, nombre, ciudad, cp;

    cif = cifjTextField2.getText();
    direccion = direccionCompnanyia.getText();
    nombre = nombreCompanyiajTextField1.getText();
    ciudad = ciudadjTextField.getText();
    cp = codigoPostaljTextField.getText();

    ficha.setCif(cif);
    ficha.setDireccion(direccion);
    ficha.setNombre(nombre);
    ficha.setCiudad(ciudad);
    ficha.setCodigoPostal(cp);

    if (!telefonojTextField.getText().equals(Util.PadLeft('_', DIGITOS_TELEFONO))) {
      ficha.setTelefono(telefonojTextField.getText());
    }

    try {
      XMLEncoder cofificador =
          new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fichero)));

      cofificador.writeObject(ficha);
      cofificador.close();
    } catch (FileNotFoundException e) {
      JOptionPane.showMessageDialog(null, e.getMessage());
    }
  }
示例#11
0
  /**
   * Create / edit properties file with default settings
   *
   * @param args Startup arguments
   */
  public static void main(String[] args) {
    XMLEncoder xmlEncoder;
    try {
      xmlEncoder =
          new XMLEncoder(
              new BufferedOutputStream(new FileOutputStream(CommonPresenter.PROPERTIES_FILE_NAME)));
    } catch (FileNotFoundException e) {
      System.err.println("unable to create/open properties file for writing");
      System.out.println("Press return to exit...");
      try {
        new BufferedReader(new InputStreamReader(System.in)).readLine();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      return;
    }

    Properties props = new Properties();
    props.setPoolSize(10);
    props.setMazeGeneratorType(MazeGeneratorTypes.MY);
    props.setMazeSearcherType(MazeSearcherTypes.A_STAR_MANHATTER);
    props.setViewType(ViewTypes.GUI);

    xmlEncoder.writeObject(props);
    xmlEncoder.close();

    System.out.println("default properties file created");
    System.out.println("Press return to exit...");
    try {
      new BufferedReader(new InputStreamReader(System.in)).readLine();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
示例#12
0
  /** Saves out our state (all the dot models) to the given file. Uses Java built-in XMLEncoder. */
  public void save(File file) {
    try {
      XMLEncoder xmlOut = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(file)));

      // Could do something like this to control which
      // properties are sent. By default, it just sends
      // all of them with getters/setters, which is fine in this case.
      //  xmlOut.setPersistenceDelegate(ManModel.class,
      //       new DefaultPersistenceDelegate(
      //           new String[]{ "x", "y", "color" }) );

      // Make a ManModel array of everything
      ManModel[] dotArray = dots.toArray(new ManModel[0]);

      // Dump that whole array
      xmlOut.writeObject(dotArray);

      // And we're done!
      xmlOut.close();
      setDirty(false);
      // cute: only clear dirty bit *after* all the things that
      // could fail/throw an exception
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 private byte[] getProfileBytes(UpgradeableDataHashMap profile) throws IOException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   XMLEncoder encoder = new XMLEncoder(baos);
   encoder.writeObject(profile.saveData());
   encoder.close();
   byte[] ba = baos.toByteArray();
   baos.close();
   return ba;
 }
示例#14
0
文件: User.java 项目: scubasam/ERS
  /** Encodes the current column visibility data into XML format for storing in the database. */
  public void serializeVisibilityMap() {
    if (columnVisibilityMap != null && columnVisibilityMap.size() > 0) {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      XMLEncoder xmlEncoder = new XMLEncoder(bos);
      xmlEncoder.writeObject(columnVisibilityMap);
      xmlEncoder.close();

      this.serializedVisibilityMap = bos.toString();
    }
  }
示例#15
0
  public void guardarLibro() {

    // transforma en xml y ademas hace el .close dentro, cuando termina el "try"
    try (XMLEncoder out = new XMLEncoder(new FileOutputStream("libro.xml"))) {

      out.writeObject(libro);

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
  /**
   * Creates a new instance of XML Encoder pre-configured for Violet beans serailization
   *
   * @param out
   * @return configured encoder
   */
  private XMLEncoder getXMLEncoder(OutputStream out) {
    XMLEncoder encoder = new XMLEncoder(out);

    encoder.setExceptionListener(
        new ExceptionListener() {
          public void exceptionThrown(Exception ex) {
            ex.printStackTrace();
          }
        });
    configure(encoder);
    return encoder;
  }
示例#17
0
  @Override
  public void salvaLista(ArrayList<Produto> p) {

    try {
      XMLEncoder xml = new XMLEncoder(new FileOutputStream("produtoDAO.xml"));
      xml.writeObject(p);
    } catch (IOException ex) {
      System.out.println(ex.getMessage());
    }

    throw new UnsupportedOperationException("Not supported yet.");
  }
 public void save() {
   if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
     try {
       File file = chooser.getSelectedFile();
       XMLEncoder encoder = new XMLEncoder(new FileOutputStream(file));
       encoder.writeObject(frame);
       encoder.close();
     } catch (IOException e) {
       JOptionPane.showMessageDialog(null, e);
     }
   }
 }
示例#19
0
 /**
  * Writes an object (in our case, the training set object) to XML making use of the {@link
  * java.io.Serializable serializable interface}.
  *
  * @param X The object to be written
  * @param filename The filename (with extension) to be written to
  */
 public static void saveToXML(Object X, String filename) {
   System.out.print("saving \"" + filename + "\" . . . ");
   XMLEncoder xmlOut = null;
   try {
     xmlOut = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(new File(filename))));
   } catch (IOException e) {
     e.printStackTrace();
   }
   xmlOut.writeObject(X);
   xmlOut.close();
   System.out.print("done saving\n");
 }
示例#20
0
文件: Main.java 项目: kpj/filius
  /**
   * Das Beenden des Programms laeuft folgendermassen ab:
   *
   * <ol>
   *   <li>Wechsel in den Entwurfsmodus (und damit beenden der virtuellen Software und der damit
   *       verbundenen Threads
   *   <li>Pruefung, ob eine Aenderung am Szenario vorgenommen wurde
   *       <ul>
   *         <li>wenn Szenario geaendert wurde, wird gefragt, ob die Datei noch gespeichert werden
   *             soll
   *         <li>wenn das Szenario nicht gespeichert werden soll, werden die Aenderungen verworfen
   *         <li>wenn die Abfrage abgebrochen wird, wird Filius nicht beendet
   *       </ul>
   *   <li>Programmkonfiguration wird gespeichert
   *   <li>das Verzeichnis fuer temporaere Dateien wird geloescht
   * </ol>
   */
  public static void beenden() {
    Main.debug.println("INVOKED (static) filius.Main, beenden()");
    Object[] programmKonfig;
    XMLEncoder encoder = null;
    FileOutputStream fos = null;
    int entscheidung;
    boolean abbruch = false;

    GUIContainer.getGUIContainer().getMenu().selectMode(GUIMainMenu.MODUS_ENTWURF);

    if (SzenarioVerwaltung.getInstance().istGeaendert()) {
      entscheidung =
          JOptionPane.showConfirmDialog(
              JMainFrame.getJMainFrame(),
              messages.getString("main_msg1"),
              messages.getString("main_msg2"),
              JOptionPane.YES_NO_OPTION);
      if (entscheidung == JOptionPane.YES_OPTION) {
        abbruch = false;
      } else {
        abbruch = true;
      }
    }
    if (!abbruch) {
      programmKonfig = new Object[4];
      programmKonfig[0] = JMainFrame.getJMainFrame().getBounds();
      programmKonfig[1] = SzenarioVerwaltung.getInstance().holePfad();
      programmKonfig[2] = Information.getInformation().getLocale().getLanguage();
      programmKonfig[3] = Information.getInformation().getLocale().getCountry();

      try {
        fos =
            new FileOutputStream(
                Information.getInformation().getArbeitsbereichPfad() + "konfig.xml");
        encoder = new XMLEncoder(new BufferedOutputStream(fos));

        encoder.writeObject(programmKonfig);
      } catch (Exception e) {
        e.printStackTrace(Main.debug);
      } finally {
        if (encoder != null) encoder.close();
        if (fos != null) {
          try {
            fos.close();
          } catch (IOException e) {
          }
        }
      }
      SzenarioVerwaltung.loescheVerzeichnisInhalt(Information.getInformation().getTempPfad());
      System.exit(0);
    }
  }
示例#21
0
  /**
   * Encodes an object as XML and then decodes it.
   *
   * @param <T> the type to operate on
   * @param object the object to encode/decode
   * @return a copy of the original object that was encoded and decoded
   * @see XMLEncoder
   * @see XMLDecoder
   */
  @SuppressWarnings("unchecked")
  public static <T> T encode(T object) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(baos);
    encoder.writeObject(object);
    encoder.close();

    XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(baos.toByteArray()));
    T copy = (T) decoder.readObject();
    decoder.close();

    return copy;
  }
示例#22
0
 public static String storeBean(Serializable bean, OutputStream out) {
   XMLEncoder encoder = null;
   try {
     encoder = new XMLEncoder(out, ContentContext.CHARACTER_ENCODING, true, 0);
     encoder.writeObject(bean);
     encoder.flush();
   } finally {
     if (encoder != null) {
       encoder.close();
     }
   }
   return null;
 }
示例#23
0
 private String toXML() {
   String xml = null;
   try {
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     XMLEncoder encoder = new XMLEncoder(out);
     encoder.writeObject(students); // serialize to XML
     encoder.close();
     xml = out.toString(); // stringify
   } catch (Exception e) {
   }
   // System.out.println(xml.trim());
   return xml;
 }
示例#24
0
  /* (non-Javadoc)
   * @see com.pri.messenger.MessageBody#toXML()
   */
  public String toXML() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder e = new XMLEncoder(baos);
    e.writeObject(this);
    e.close();

    try {
      return "<![CDATA[" + new String(baos.toByteArray(), "UTF-8") + "]]>";
    } catch (UnsupportedEncodingException e1) {
    }

    return "";
  }
  public void writeObjectXMLEncoder(Object obj) throws IOException {
    try {
      BufferedOutputStream oop = new BufferedOutputStream(new java.io.FileOutputStream(f));
      XMLEncoder xe = new java.beans.XMLEncoder(oop);

      xe.writeObject(obj);
      xe.close();
      oop.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 /**
  * Get a by array by serializing the specified object as XML
  *
  * @param object an object
  */
 public static byte[] marshallObject(Object object) {
   if (object == null) {
     throw new IllegalArgumentException("Null is not serializable");
   }
   if (!Serializable.class.isAssignableFrom(object.getClass())) {
     throw new IllegalArgumentException("The object must be Serializable");
   }
   ByteArrayOutputStream baOut = new ByteArrayOutputStream();
   XMLEncoder encoder = new XMLEncoder(baOut);
   encoder.writeObject(object);
   encoder.flush();
   encoder.close();
   return baOut.toByteArray();
 }
 public static byte[] getBytes(Object data) {
   byte[] result = null;
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     XMLEncoder encoder = new XMLEncoder(baos);
     encoder.writeObject(data);
     encoder.close();
     result = baos.toByteArray();
     baos.close();
   } catch (Exception e) {
     log.error("getBytes(): exception", e);
   }
   return result;
 }
示例#28
0
 /**
  * 将可序列化的对象转换为XML写入文件,已经存在的文件将被覆盖<br>
  * Writes serializable object to a XML file. Existing file will be overwritten
  *
  * @param <T>
  * @param dest 目标文件
  * @param t 对象
  * @throws IOException
  */
 public static <T> void writeObjectAsXml(File dest, T t) throws IOException {
   FileOutputStream fos = null;
   XMLEncoder xmlenc = null;
   try {
     fos = new FileOutputStream(dest);
     xmlenc = new XMLEncoder(new BufferedOutputStream(fos));
     xmlenc.writeObject(t);
   } finally {
     FileUtil.close(fos);
     if (xmlenc != null) {
       xmlenc.close();
     }
   }
 }
示例#29
0
 public static String storeBeanFromXML(Serializable bean) {
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   XMLEncoder encoder = new XMLEncoder(out, ContentContext.CHARACTER_ENCODING, true, 0);
   // XMLEncoder encoder = new XMLEncoder(out);
   encoder.writeObject(bean);
   encoder.flush();
   encoder.close();
   try {
     return new String(out.toByteArray(), ContentContext.CHARACTER_ENCODING);
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   return null;
 }
示例#30
0
 public static String storeBean(Serializable bean, File file) throws FileNotFoundException {
   OutputStream out = new FileOutputStream(file);
   XMLEncoder encoder = null;
   try {
     encoder = new XMLEncoder(out, ContentContext.CHARACTER_ENCODING, true, 0);
     encoder.writeObject(bean);
     encoder.flush();
   } finally {
     closeResource(out);
     if (encoder != null) {
       encoder.close();
     }
   }
   return null;
 }