Example usage for java.beans ExceptionListener ExceptionListener

List of usage examples for java.beans ExceptionListener ExceptionListener

Introduction

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

Prototype

ExceptionListener

Source Link

Usage

From source file:Main.java

public static byte[] encodeObject(Object object, final boolean noisy) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(outputStream);
    encoder.setExceptionListener(new ExceptionListener() {
        public void exceptionThrown(Exception ex) {
            if (noisy)
                ex.printStackTrace();/*from w w w  .  j  a v  a 2 s.c om*/
        }
    });

    encoder.writeObject(object);
    encoder.close();

    if (noisy)
        System.out.println(outputStream.toString());

    return outputStream.toByteArray();
}

From source file:Main.java

public static Object decodeObject(byte[] byteArray, final boolean noisy) {
    ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray);

    XMLDecoder decoder = new XMLDecoder(inputStream);
    decoder.setExceptionListener(new ExceptionListener() {
        public void exceptionThrown(Exception ex) {
            if (noisy)
                ex.printStackTrace();/*from   w  ww  .j a v a2  s  .c  o m*/
        }
    });

    Object copy = decoder.readObject();
    decoder.close();
    return copy;
}

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

/**
 * Laedt die vorhandenen Profile fuer das Format.
 * @param format das Format.//from   w  w  w.ja  va  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:de.willuhn.jameica.hbci.io.csv.ProfileUtil.java

/**
 * Speichert die Profile.//w ww.j  a v a 2  s  .com
 * @param format das Format.
 * @param profiles die zu speichernden Profile.
 */
public static void store(Format format, List<Profile> profiles) {
    if (format == null) {
        Application.getMessagingFactory().sendMessage(
                new StatusBarMessage(i18n.tr("Kein Format ausgewhlt"), StatusBarMessage.TYPE_ERROR));
        return;
    }

    if (profiles == null) {
        Application.getMessagingFactory().sendMessage(
                new StatusBarMessage(i18n.tr("Keine Profile angegeben"), StatusBarMessage.TYPE_ERROR));
        return;
    }

    // 2. Mal schauen, ob wir ein gespeichertes Profil fuer das Format haben
    File dir = new File(Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath(),
            "csv");
    if (!dir.exists()) {
        Logger.info("creating dir: " + dir);
        if (!dir.mkdirs()) {
            Application.getMessagingFactory()
                    .sendMessage(new StatusBarMessage(
                            i18n.tr("Ordner {0} kann nicht erstellt werden", dir.getAbsolutePath()),
                            StatusBarMessage.TYPE_ERROR));
            return;
        }
    }

    File file = new File(dir, format.getClass().getName() + ".xml");

    Logger.info("writing csv profile " + file);
    XMLEncoder encoder = null;
    try {
        encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(file)));
        encoder.setExceptionListener(new ExceptionListener() {
            public void exceptionThrown(Exception e) {
                throw new RuntimeException(e);
            }
        });

        for (Profile p : profiles) {
            // Das System-Profil wird nicht mit gespeichert
            if (p.isSystem())
                continue;

            // Ebenso Profile ohne Namen.
            if (StringUtils.trimToNull(p.getName()) == null)
                continue;

            encoder.writeObject(p);
        }
    } catch (Exception e) {
        Logger.error("unable to store profile " + file, e);
    } finally {
        if (encoder != null) {
            try {
                encoder.close();
            } catch (Exception e) {
                /* useless */}
        }
    }
}

From source file:lu.lippmann.cdb.graph.GraphUtil.java

/**
 * /*  w w  w.  j  a  va2  s .  co  m*/
 * @param g
 * @return
 */
public static String saveGraphWithOperation(final GraphWithOperations g) {
    final ArrayList<GraphOperation> operations = new ArrayList<GraphOperation>(g.getOperations());
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final XMLEncoder xmlEncoder = new XMLEncoder(baos);
    xmlEncoder.setExceptionListener(new ExceptionListener() {
        public void exceptionThrown(final Exception e) {
            throw new IllegalStateException(e);
        }
    });

    xmlEncoder.writeObject(new GraphTO(g.getId(), operations, g.getUntitledVertexCount(),
            g.getUntitledEdgeCount(), g.getVariables()));
    xmlEncoder.close();
    return baos.toString();
}

From source file:com.db4o.sync4o.ui.Db4oSyncSourceConfigPanel.java

private static void showTestUI() {

    // Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);

    // Create and set up the window.
    JFrame frame = new JFrame("Db4oSyncSourceConfigPanel Test Harness");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Create and set up the content pane.
    final Db4oSyncSource source = new Db4oSyncSource();
    Db4oSyncSourceConfigPanel p = new Db4oSyncSourceConfigPanel();
    p.setManagementObject(new SyncSourceManagementObject(source, null, null, null, null));
    p.updateForm();//from  w w w . java 2  s .  c  o  m
    p.setOpaque(true); // content panes must be opaque
    frame.setContentPane(p);

    frame.addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent ev) {

            XMLEncoder encoder = null;
            try {
                FileOutputStream s = new FileOutputStream("test.xml");
                encoder = new XMLEncoder(s);
                encoder.setExceptionListener(new ExceptionListener() {
                    public void exceptionThrown(Exception exception) {
                        exception.printStackTrace();
                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.exit(-1);
            }
            encoder.writeObject((Object) source);
            encoder.flush();
            encoder.close();

        }

    });

    // Display the window.
    frame.pack();
    frame.setVisible(true);

}

From source file:net.sf.taverna.t2.provenance.lineageservice.EventProcessor.java

/**
 * log raw event to file system/*w ww  . j a  v  a  2  s.co  m*/
 * 
 * @param content
 * @param eventType
 * @throws IOException
 */
public void saveEvent(ProvenanceItem provenanceItem, SharedVocabulary eventType) throws IOException {

    // HACK -- XMLEncoder fails on IterationEvents and there is no way to catch the exception...
    // so avoid this case
    if (eventType.equals(SharedVocabulary.ITERATION_EVENT_TYPE)) {
        return;
    }

    //      System.out.println("saveEvent: start");

    File f1 = null;

    f1 = new File(TEST_EVENTS_FOLDER);
    FileUtils.forceMkdir(f1);

    String fname = "event_" + eventCnt++ + "_" + eventType + ".xml";
    File f = new File(f1, fname);

    //      FileWriter fw = new FileWriter(f);

    XMLEncoder en = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(f)));

    en.setExceptionListener(new ExceptionListener() {
        public void exceptionThrown(Exception e) {
            logger.warn("XML encoding ERROR", e);
            return;
        }
    });

    logger.debug("saving to " + f); // save event for later inspection
    logger.debug(provenanceItem);

    en.writeObject(provenanceItem);

    logger.debug("writer ok");
    en.close();
    logger.debug("closed");

    //      fw.write(content);
    //      fw.flush();
    //      fw.close();

    //      FileWriter fw = new FileWriter(f);
    //      fw.write(content);
    //      fw.flush();
    //      fw.close();

    //      System.out.println("saved as file " + fname);

}

From source file:org.ejbca.ui.web.admin.certprof.CertProfilesBean.java

private XMLDecoder getXMLDecoder(ByteArrayInputStream is) {
    // Without the exception listener, when a faulty xml file is read, the XMLDecoder catches the exception,
    // writes an error message to stderr and continues reading. Ejbca wouldn't notice that the profile created 
    // based on this XML file is faulty until it is used.
    ExceptionListener elistener = new ExceptionListener() {
        @Override/*from  ww  w. j  av  a  2  s . com*/
        public void exceptionThrown(Exception e) {
            // This probably means that an extra byte is found or something. The certprofile that raises this exception 
            // does not seem to be faulty at all as far as I can test.
            if (StringUtils.equals("org.apache.xerces.impl.io.MalformedByteSequenceException",
                    e.getClass().getName())) {
                log.error("org.apache.xerces.impl.io.MalformedByteSequenceException: " + e.getMessage());
                log.error("Continuing ...");
            } else {
                log.error(e.getClass().getName() + ": " + e.getMessage());
                throw new IllegalArgumentException(e);
            }
        }
    };
    return new XMLDecoder(is, null, elistener);
}

From source file:org.ejbca.ui.web.admin.rainterface.RAInterfaceBean.java

private XMLDecoder getXMLDecoder(ByteArrayInputStream is) {
    // Without the exception listener, when a faulty xml file is read, the XMLDecoder catches the exception,
    // writes an error message to stderr and continues reading. Ejbca wouldn't notice that the profile created 
    // based on this XML file is faulty until it is used.
    ExceptionListener elistener = new ExceptionListener() {
        @Override/*from w  w w.j a v a  2  s  .  c  om*/
        public void exceptionThrown(Exception e) {
            // This probably means that an extra byte is found or something. The certprofile that raises this exception 
            // does not seem to be faulty at all as far as I can test.
            if (StringUtils.equals("org.apache.xerces.impl.io.MalformedByteSequenceException",
                    e.getClass().getName())) {
                log.error("org.apache.xerces.impl.io.MalformedByteSequenceException: " + e.getMessage());
                log.error("Continuing ...");
            } else {
                log.error(e.getClass().getName() + ": " + e.getMessage());
                throw new IllegalArgumentException(e);
            }
        }
    };

    return new XMLDecoder(is, null, elistener);
}

From source file:org.jtrfp.trcl.gui.ConfigWindow.java

private boolean readSettingsFromFile(File f) {
    try {/* w w w. j av  a 2  s  .co  m*/
        FileInputStream is = new FileInputStream(f);
        XMLDecoder xmlDec = new XMLDecoder(is);
        xmlDec.setExceptionListener(new ExceptionListener() {
            @Override
            public void exceptionThrown(Exception e) {
                e.printStackTrace();
            }
        });
        TRConfiguration src = (TRConfiguration) xmlDec.readObject();
        xmlDec.close();
        if (config != null)
            BeanUtils.copyProperties(config, src);
        else
            config = src;
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Failed to read the specified file:\n" + e.getLocalizedMessage(),
                "File read failure", JOptionPane.ERROR_MESSAGE);
        return false;
    }
    return true;
}