Example usage for java.beans XMLDecoder XMLDecoder

List of usage examples for java.beans XMLDecoder XMLDecoder

Introduction

In this page you can find the example usage for java.beans XMLDecoder XMLDecoder.

Prototype

public XMLDecoder(InputSource is) 

Source Link

Document

Creates a new decoder to parse XML archives created by the XMLEncoder class.

Usage

From source file:net.sourceforge.fenixedu.util.tests.ResponseExternalization.java

private static Response getResponse(String xmlResponse) {
    XMLDecoder decoder = null;/*from  w  w  w  .  j  a v  a 2 s .co  m*/
    try {
        decoder = new XMLDecoder(new ByteArrayInputStream(xmlResponse.getBytes(CharEncoding.UTF_8)));
    } catch (UnsupportedEncodingException e1) {
        logger.error(e1.getMessage(), e1);
    }
    Response response = null;
    try {
        response = (Response) decoder.readObject();
    } catch (ArrayIndexOutOfBoundsException e) {
        logger.error(e.getMessage(), e);
    }
    decoder.close();
    return response;
}

From source file:de.willuhn.jameica.hbci.io.csv.ProfileUtil.java

/**
 * Laedt die vorhandenen Profile fuer das Format.
 * @param format das Format./*w ww  .java  2  s. c  om*/
 * @return die Liste der Profile.
 */
public static List<Profile> read(Format format) {
    List<Profile> result = new ArrayList<Profile>();

    if (format == null) {
        Logger.warn("no format given");
        Application.getMessagingFactory().sendMessage(
                new StatusBarMessage(i18n.tr("Kein Format ausgewhlt"), StatusBarMessage.TYPE_ERROR));
        return result;
    }

    final Profile dp = format.getDefaultProfile();
    result.add(dp); // System-Profil wird immer vorn einsortiert

    // 1. Mal schauen, ob wir gespeicherte Profil fuer das Format haben
    File dir = new File(Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath(),
            "csv");
    if (!dir.exists())
        return result;

    File file = new File(dir, format.getClass().getName() + ".xml");
    if (!file.exists() || !file.canRead())
        return result;

    Logger.info("reading csv profile " + file);
    XMLDecoder decoder = null;
    try {
        decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(file)));
        decoder.setExceptionListener(new ExceptionListener() {
            public void exceptionThrown(Exception e) {
                throw new RuntimeException(e);
            }
        });

        // Es ist tatsaechlich so, dass "readObject()" nicht etwa NULL liefert, wenn keine Objekte mehr in der
        // Datei sind sondern eine ArrayIndexOutOfBoundsException wirft.
        try {
            for (int i = 0; i < 1000; ++i) {
                Profile p = (Profile) decoder.readObject();
                // Migration aus der Zeit vor dem Support mulitpler Profile:
                // Da konnte der User nur das eine existierende Profil aendern, es wurde automatisch gespeichert
                // Das hatte gar keinen Namen. Falls also ein Profil ohne Name existiert (inzwischen koennen keine
                // mehr ohne Name gespeichert werden), dann ist es das vom User geaenderte Profil. Das machen wir
                // automatisch zum ersten User-spezifischen Profil
                if (StringUtils.trimToNull(p.getName()) == null) {
                    p.setName(dp.getName() + " 2");
                    p.setSystem(false);
                }
                result.add(p);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            // EOF
        }

        Logger.info("read " + (result.size() - 1) + " profiles from " + file);
        Collections.sort(result);

        // Der User hat beim letzten Mal eventuell nicht alle Spalten zugeordnet.
        // Die wuerden jetzt hier in dem Objekt fehlen. Daher nehmen wir
        // noch die Spalten aus dem Default-Profil und haengen die fehlenden noch an.
    } catch (Exception e) {
        Logger.error("unable to read profile " + file, e);
        Application.getMessagingFactory().sendMessage(new StatusBarMessage(
                i18n.tr("Laden der Profile fehlgeschlagen: {0}", e.getMessage()), StatusBarMessage.TYPE_ERROR));
    } finally {
        if (decoder != null) {
            try {
                decoder.close();
            } catch (Exception e) {
                /* useless */}
        }
    }
    return result;
}

From source file:org.clickframes.testframes.TestResultsParser.java

public static ProjectTestResults parseTestResults(File zip) throws IOException {
    // tmp directory
    File tmpDirectory = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    tmpDirectory.mkdirs();/*from  w w  w .jav  a2 s  .  c om*/

    ZipInputStream zis = new ZipInputStream(new FileInputStream(zip));
    ZipEntry entry;
    int BUFFER = 4096;
    while ((entry = zis.getNextEntry()) != null) {
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        File destinationFile = new File(tmpDirectory, entry.getName());
        destinationFile.getParentFile().mkdirs();
        FileOutputStream fos = new FileOutputStream(destinationFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
    }

    File firefoxDir = new File(tmpDirectory, "firefox");

    if (!firefoxDir.exists()) {
        throw new RuntimeException("Invalid test results zip file uploaded. firefox directory does not exist.");
    }

    File testResultsXmlFile = new File(tmpDirectory, "testResults.xml");

    XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream(testResultsXmlFile)));
    ProjectTestResults projectTestResults = (ProjectTestResults) d.readObject();
    d.close();

    return projectTestResults;
}

From source file:fi.vm.sade.log.client.LoggerJms.java

/**
 * Decode XML to LogEvent. Encoded in "encode" method.
 *
 * @param xml//from   w  w w . j a  va  2  s.c o  m
 * @return
 */
public static LogEvent decode(String xml) {
    if (xml == null) {
        return null;
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
    XMLDecoder xmlDecoder = new XMLDecoder(bais);
    LogEvent logEvent = (LogEvent) xmlDecoder.readObject();
    xmlDecoder.close();

    return logEvent;
}

From source file:org.cesecore.util.HashMapTest.java

@SuppressWarnings("rawtypes")
@Test//www  .  j a v  a  2s .  c  o m
public void testHashMapNormal() throws Exception {
    HashMap<String, Comparable> a = new HashMap<String, Comparable>();
    a.put("foo0", Boolean.FALSE);
    a.put("foo1", "fooString");
    a.put("foo2", Integer.valueOf(2));
    a.put("foo3", Boolean.TRUE);

    // Write to XML
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(baos);
    encoder.writeObject(a);
    encoder.close();
    String data = baos.toString("UTF8");
    //log.error(data);

    XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(data.getBytes("UTF8")));
    HashMap<?, ?> b = (HashMap<?, ?>) decoder.readObject();
    decoder.close();
    assertEquals(((Boolean) b.get("foo0")).booleanValue(), false);
    assertEquals(((Boolean) b.get("foo3")).booleanValue(), true);
    assertEquals(((String) b.get("foo1")), "fooString");
    assertEquals(((Integer) b.get("foo2")).intValue(), 2);

}

From source file:PersistentFrameTest.java

 public void load()
{
   // show file chooser dialog
   int r = chooser.showOpenDialog(null);

   // if file selected, open
   if(r == JFileChooser.APPROVE_OPTION)
   {//from  w  w w  .j a v a2s .c o  m
      try
      {
         File file = chooser.getSelectedFile();
         XMLDecoder decoder = new XMLDecoder(new FileInputStream(file));
         decoder.readObject(); 
         decoder.close();
      }
      catch (IOException e)
      {
         JOptionPane.showMessageDialog(null, e);
      }
   }
}

From source file:com.npower.dl.FirmwareMimeTypeHelper.java

public static List<DownloadMimeType> load(InputStream in) throws IOException {
    XMLDecoder decoder = new XMLDecoder(in);
    List<DownloadMimeType> types = (List<DownloadMimeType>) decoder.readObject();
    return types;
}

From source file:edu.wisc.my.portlets.bookmarks.dao.file.FileSystemBookmarkStore.java

/**
 * @see edu.wisc.my.portlets.bookmarks.dao.BookmarkStore#getBookmarkSet(java.lang.String, java.lang.String)
 *//*from   w  ww .  ja v a 2 s  .  co  m*/
public BookmarkSet getBookmarkSet(String owner, String name) {
    final File storeFile = this.getStoreFile(owner, name);

    //Ok if the file doesn't exist, the user hasn't stored one yet.
    if (!storeFile.exists()) {
        return null;
    }

    try {
        final FileInputStream fis = new FileInputStream(storeFile);
        final BufferedInputStream bis = new BufferedInputStream(fis);
        final XMLDecoder d = new XMLDecoder(bis);

        try {
            final BookmarkSet bs = (BookmarkSet) d.readObject();
            return bs;
        } finally {
            d.close();
        }
    } catch (FileNotFoundException fnfe) {
        final String errorMsg = "Error reading BookmarkSet for owner='" + owner + "', name='" + name
                + "' from file='" + storeFile + "'";
        logger.error(errorMsg, fnfe);
        throw new DataAccessResourceFailureException(errorMsg);
    }
}

From source file:org.jumpmind.vaadin.ui.sqlexplorer.DefaultSettingsProvider.java

public Settings load() {
    synchronized (getClass()) {
        File file = getSettingsFile();
        if (file.exists() && file.length() > 0) {
            FileInputStream is = null;
            try {
                is = new FileInputStream(file);
                XMLDecoder decoder = new XMLDecoder(is);
                Settings settings = (Settings) decoder.readObject();
                decoder.close();//from www  .  j a  v a  2 s  .  c  o m
                return settings;
            } catch (Exception ex) {
                log.error("Failed to load settings", ex);
                FileUtils.deleteQuietly(file);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
        return new Settings();
    }
}

From source file:org.geomajas.plugin.deskmanager.domain.types.XmlSerialisationType.java

private Object fromXmlString(String xmlString) {
    if (xmlString == null) {
        return null;
    }//www .  ja va  2  s.  c o  m
    try {
        ByteArrayInputStream is = new ByteArrayInputStream(xmlString.getBytes(ENCODING));
        XMLDecoder decoder = new XMLDecoder(is);
        return decoder.readObject();
    } catch (UnsupportedEncodingException e) {
        LOG.warn(e.getLocalizedMessage());
        IllegalArgumentException ex = new IllegalArgumentException("cannot disassemble the object");
        ex.setStackTrace(e.getStackTrace());
        throw ex;
    }
}