Example usage for java.beans XMLEncoder close

List of usage examples for java.beans XMLEncoder close

Introduction

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

Prototype

public void close() 

Source Link

Document

This method calls flush , writes the closing postamble and then closes the output stream associated with this stream.

Usage

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private void writeLevelColors(Map<LoggingEvent.Level, ColorScheme> colors) {
    File appPath = getStartupApplicationPath();
    File file = new File(appPath, LEVEL_COLORS_XML_FILENAME);
    try {/*from ww  w . j a  v a 2s  .c  o m*/
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        XMLEncoder e = new XMLEncoder(bos);
        PersistenceDelegate delegate = new EnumPersistenceDelegate();
        e.setPersistenceDelegate(LoggingEvent.Level.class, delegate);
        e.writeObject(colors);
        e.close();
    } catch (Throwable ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while writing colors!", ex);
        IOUtilities.interruptIfNecessary(ex);
    }
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private boolean writeSourceLists(Map<String, Set<String>> sourceLists) {
    File appPath = getStartupApplicationPath();
    File file = new File(appPath, SOURCE_LISTS_XML_FILENAME);
    XMLEncoder e = null;
    Throwable error = null;// w  w  w  .  j a v  a  2s . c  o m
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        e = new XMLEncoder(bos);
        e.writeObject(sourceLists);
    } catch (FileNotFoundException ex) {
        error = ex;
    } finally {
        if (e != null) {
            e.close();
        }
    }
    if (error != null) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while writing source lists!", error);
        return false;
    }
    return true;
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private boolean writeRecentFiles(List<String> recentFiles) {
    File appPath = getStartupApplicationPath();
    File file = new File(appPath, RECENT_FILES_XML_FILENAME);
    XMLEncoder e = null;
    Throwable error = null;//  www  .ja va2s  . c  o m
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        e = new XMLEncoder(bos);
        e.writeObject(recentFiles);
    } catch (FileNotFoundException ex) {
        error = ex;
    } finally {
        if (e != null) {
            e.close();
        }
    }
    this.recentFiles = null;
    if (error != null) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while writing recentFiles!", error);
        return false;
    }
    return true;
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private boolean writePreviousSearchStrings(List<String> searchStrings) {
    File appPath = getStartupApplicationPath();
    File file = new File(appPath, PREVIOUS_SEARCH_STRINGS_XML_FILENAME);
    XMLEncoder e = null;
    Throwable error = null;/* w ww. j ava  2 s .co  m*/
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        e = new XMLEncoder(bos);
        e.writeObject(searchStrings);
    } catch (FileNotFoundException ex) {
        error = ex;
    } finally {
        if (e != null) {
            e.close();
        }
    }
    this.previousSearchStrings = null;
    if (error != null) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while writing previous search strings!", error);
        return false;
    }
    return true;
}

From source file:statechum.analysis.learning.Visualiser.java

protected void setVisualiserKeyBindings() {
    persistAction = new graphAction("saveLayout", "save the layout of the visible graph") {

        /** Serial number. */
        private static final long serialVersionUID = 1L;

        @Override/*  w w w . j a  v  a  2 s  .  c om*/
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            XMLEncoder encoder = null;
            try {
                if (propName >= 0) {
                    String fileName = getLayoutFileName(graphs.get(currentGraph));
                    encoder = new XMLEncoder(new FileOutputStream(fileName));
                    Map<Integer, DoublePair> layout = ((XMLPersistingLayout) viewer.getModel().getGraphLayout())
                            .persist();
                    encoder.writeObject(layout);
                    XMLAffineTransformSerialised trV = new XMLAffineTransformSerialised();
                    trV.setFromAffineTransform(viewer.getViewTransformer().getTransform());
                    encoder.writeObject(trV);
                    XMLAffineTransformSerialised trL = new XMLAffineTransformSerialised();
                    trL.setFromAffineTransform(viewer.getLayoutTransformer().getTransform());
                    encoder.writeObject(trL);
                    ((XMLModalGraphMouse) viewer.getGraphMouse()).store(encoder);
                    encoder.writeObject(layoutOptions.get(currentGraph));
                    encoder.close();
                    encoder = null;
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            } finally {
                if (encoder != null) {
                    encoder.close();
                    encoder = null;
                }
            }
        }
    };
    keyToActionMap.put(KeyEvent.VK_F2, persistAction);
    keyToActionMap.put(KeyEvent.VK_F3,
            new graphAction("loadLayout", "loads the previously saved layout into the visible graph") {

                /** Serial number. */
                private static final long serialVersionUID = 2L;

                @Override
                public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
                    reloadLayout(false, true);
                }
            });
    keyToActionMap.put(KeyEvent.VK_F9,
            new graphAction("loadPreviousLayout", "loads the layout of the previous graph in the list") {

                /** Serial number. */
                private static final long serialVersionUID = 3L;

                @Override
                public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
                    if (currentGraph > 0) {
                        restoreLayout(false, currentGraph - 1);
                    }
                }
            });

    pickAction = new graphAction("pick", "Switches Jung into picking mode") {

        /** Serial number. */
        private static final long serialVersionUID = 7L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            ((XMLModalGraphMouse) viewer.getGraphMouse()).setMode(ModalGraphMouse.Mode.PICKING);
        }
    };
    keyToActionMap.put(KeyEvent.VK_F11, pickAction);

    transformAction = new graphAction("transform", "Switches Jung into transformation mode") {

        /** Serial number. */
        private static final long serialVersionUID = 8L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            ((XMLModalGraphMouse) viewer.getGraphMouse()).setMode(ModalGraphMouse.Mode.TRANSFORMING);
        }
    };
    keyToActionMap.put(KeyEvent.VK_F12, transformAction);

    keyToActionMap.put(KeyEvent.VK_UP, new graphAction("previous", "loads the previous graph") {

        /** Serial number. */
        private static final long serialVersionUID = 9L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            if (currentGraph > 0) {
                --currentGraph;
                reloadLayout(false, true);
            }
        }
    });
    keyToActionMap.put(KeyEvent.VK_DOWN, new graphAction("next", "loads the next graph") {

        /** Serial number. */
        private static final long serialVersionUID = 10L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            if (currentGraph < graphs.size() - 1) {
                ++currentGraph;
                reloadLayout(false, true);
            }
        }
    });

    keyToActionMap.put(KeyEvent.VK_F, new graphAction("negatives", "toggles negatives on or off") {

        /** Serial number. */
        private static final long serialVersionUID = 11L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            LayoutOptions options = layoutOptions.get(currentGraph);
            if (options != null) {
                options.showNegatives = !options.showNegatives;
                reloadLayout(false, false);
            }
        }
    });
    keyToActionMap.put(KeyEvent.VK_I, new graphAction("ignored states", "toggles ignored states on or off") {

        /** Serial number. */
        private static final long serialVersionUID = 12L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            LayoutOptions options = layoutOptions.get(currentGraph);
            if (options != null) {
                options.showIgnored = !options.showIgnored;
                reloadLayout(false, false);
            }
        }
    });
    keyToActionMap.put(KeyEvent.VK_PAGE_DOWN, new graphAction("refine", "reduces the abstraction level") {

        /** Serial number. */
        private static final long serialVersionUID = 13L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            LayoutOptions options = layoutOptions.get(currentGraph);
            if (options != null && options.componentsToPick < Integer.MAX_VALUE) {
                options.componentsToPick++;
                reloadLayout(false, false);
            }
        }
    });
    keyToActionMap.put(KeyEvent.VK_PAGE_UP, new graphAction("abstract", "increases abstraction level") {

        /** Serial number. */
        private static final long serialVersionUID = 14L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            LayoutOptions options = layoutOptions.get(currentGraph);
            if (options != null && options.componentsToPick != Integer.MAX_VALUE
                    && options.componentsToPick > 0) {
                --options.componentsToPick;
                reloadLayout(false, false);
            }
        }
    });
}

From source file:org.openmrs.reporting.ReportObjectXMLEncoder.java

@SuppressWarnings("unchecked")
public String toXmlString() {
    ByteArrayOutputStream arr = new ByteArrayOutputStream();
    EnumDelegate enumDelegate = new EnumDelegate();

    XMLEncoder enc = new XMLEncoder(new BufferedOutputStream(arr));
    enc.setPersistenceDelegate(User.class, new UserDelegate());
    enc.setPersistenceDelegate(Location.class, new LocationDelegate());
    enc.setPersistenceDelegate(Cohort.class, new CohortDelegate());
    enc.setPersistenceDelegate(Concept.class, new ConceptDelegate());
    enc.setPersistenceDelegate(Drug.class, new DrugDelegate());
    enc.setPersistenceDelegate(Encounter.class, new EncounterDelegate());
    enc.setPersistenceDelegate(Patient.class, new PatientDelegate());
    enc.setPersistenceDelegate(Program.class, new ProgramDelegate());
    enc.setPersistenceDelegate(ProgramWorkflow.class, new ProgramWorkflowDelegate());
    enc.setPersistenceDelegate(ProgramWorkflowState.class, new ProgramWorkflowStateDelegate());
    enc.setPersistenceDelegate(ConceptAnswer.class, new ConceptAnswerDelegate());
    enc.setPersistenceDelegate(EncounterType.class, new EncounterTypeDelegate());
    enc.setPersistenceDelegate(PersonAttributeType.class, new PersonAttributeTypeDelegate());
    enc.setPersistenceDelegate(ConceptNumeric.class, new ConceptNumericDelegate());

    Set<Class> alreadyAdded = new HashSet<Class>();
    {/*from  w w w .  j  av a 2  s.c  o  m*/
        List<Class> enumClasses = new ArrayList<Class>();
        enumClasses.add(PatientSetService.Modifier.class);
        enumClasses.add(PatientSetService.TimeModifier.class);
        enumClasses.add(PatientSetService.BooleanOperator.class);
        enumClasses.add(PatientSetService.GroupMethod.class);
        for (Class clz : enumClasses) {
            enc.setPersistenceDelegate(clz, enumDelegate);
            alreadyAdded.add(clz);
        }

    }
    // This original implementation won't handle enums that aren't direct properties of the bean, but I'm leaving it here anyway.
    for (Field f : this.objectToEncode.getClass().getDeclaredFields()) {
        Class clz = f.getType();
        if (clz.isEnum() && !alreadyAdded.contains(clz)) {
            try {
                enc.setPersistenceDelegate(clz, enumDelegate);
                alreadyAdded.add(clz);
            } catch (Exception e) {
                log.error("ReportObjectXMLEncoder failed to write enumeration " + f.getName(), e);
            }
        }
    }
    log.debug("objectToEncode.type: " + objectToEncode.getClass());
    enc.writeObject(this.objectToEncode);
    enc.close();

    return arr.toString();
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private boolean writeConditions(List<SavedCondition> conditions) {
    File appPath = getStartupApplicationPath();
    File file = new File(appPath, CONDITIONS_XML_FILENAME);
    XMLEncoder e = null;
    Throwable error = null;/*w w w  . j  a v  a 2  s.  c  o  m*/
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        e = new XMLEncoder(bos);
        e.writeObject(conditions);
        if (logger.isInfoEnabled())
            logger.info("Wrote conditions {}.", conditions);
    } catch (FileNotFoundException ex) {
        error = ex;
    } finally {
        if (e != null) {
            e.close();
        }
    }
    if (error != null) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while writing source lists!", error);
        return false;
    }
    return true;
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private boolean writeColumnLayout(File file,
        List<PersistentTableColumnModel.TableColumnLayoutInfo> layoutInfos) {
    XMLEncoder e = null;
    Throwable error = null;//ww  w .  j  a  v  a2  s.c  o m
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        e = new XMLEncoder(bos);
        e.writeObject(layoutInfos);
        if (logger.isInfoEnabled())
            logger.info("Wrote layouts {} to file '{}'.", layoutInfos, file.getAbsolutePath());
    } catch (FileNotFoundException ex) {
        error = ex;
    } finally {
        if (e != null) {
            e.close();
        }
    }
    if (error != null) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while writing layouts to file '" + file.getAbsolutePath() + "'!", error);
        return false;
    }
    return true;
}

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

@Override
public byte[] getProfile(int profileId, String profileType)
        throws AuthorizationDeniedException, EjbcaException, UnknownProfileTypeException {
    final EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession,
            caSession, certificateProfileSession, certificateStoreSession, endEntityAccessSession,
            endEntityProfileSession, hardTokenSession, endEntityManagementSession, webAuthenticationSession,
            cryptoTokenManagementSession);
    final AuthenticationToken admin = ejbhelper.getAdmin();
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
    logAdminName(admin, logger);//from w w w  . java  2s.c o m

    UpgradeableDataHashMap profile = null;
    if (StringUtils.equalsIgnoreCase(profileType, "eep")) {
        profile = endEntityProfileSession.getEndEntityProfileNoClone(profileId);
        if (profile == null) {
            throw EjbcaWSHelper.getEjbcaException(
                    new EndEntityProfileNotFoundException(
                            "Could not find end entity profile with ID '" + profileId + "' in the database."),
                    null, ErrorCode.EE_PROFILE_NOT_EXISTS, null);
        }
    } else if (StringUtils.equalsIgnoreCase(profileType, "cp")) {
        profile = certificateProfileSession.getCertificateProfile(profileId);
        if (profile == null) {
            throw EjbcaWSHelper.getEjbcaException(
                    new CertificateProfileDoesNotExistException(
                            "Could not find certificate profile with ID '" + profileId + "' in the database."),
                    null, ErrorCode.CERT_PROFILE_NOT_EXISTS, null);
        }
    } else {
        throw new UnknownProfileTypeException("Unknown profile type '" + profileType
                + "'. Recognized types are 'eep' for End Entity Profiles and 'cp' for Certificate Profiles");
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(baos);
    encoder.writeObject(profile.saveData());
    encoder.close();
    byte[] ba = baos.toByteArray();
    try {
        baos.close();
    } catch (IOException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } finally {
        logger.writeln();
        logger.flush();
    }
    return ba;
}

From source file:com.projity.pm.graphic.frames.GraphicManager.java

/**
 * Encode the current workspace and store it off in lastWorkspace.
 * Currently I use an XML format for easier debugging. It could be serialized as binary as well since
 * all objects in the graph implement Serializable
 *
 *//*  w  w w.  ja va  2s  .c  o m*/
private void encodeWorkspaceXML() {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(stream));
    encoder.writeObject(createWorkspace(SavableToWorkspace.VIEW));
    encoder.close();
    lastWorkspace = stream.toString();
    //      System.out.println(lastWorkspace);
}