Example usage for java.beans XMLDecoder close

List of usage examples for java.beans XMLDecoder close

Introduction

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

Prototype

public void close() 

Source Link

Document

This method closes the input stream associated with this stream.

Usage

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

/**
 * Decode the current workspace (currently using XML though could be binary)
 * @return workspace object decoded from lastWorkspace static
 *//* ww  w  .j a v a  2s . co  m*/
private Workspace decodeWorkspaceXML() {
    ByteArrayInputStream stream = new ByteArrayInputStream(((String) lastWorkspace).getBytes());
    XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(stream));
    Workspace workspace = (Workspace) decoder.readObject();
    decoder.close();
    return workspace;
}

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

/** Loads the layout of the specific graph in the list.
 *
 *  @param whether to ignore loading errors.
 *  @param graphNumber the number of the graph to load.
 *//*from  ww w.  ja v a 2  s . c  om*/
protected void restoreLayout(boolean ignoreErrors, int graphNumber) {
    XMLDecoder decoder = null;
    try {
        String fileName = getLayoutFileName(graphs.get(graphNumber));
        if (propName >= 0 && (new File(fileName)).canRead()) {
            decoder = new XMLDecoder(new FileInputStream(fileName));
            //@SuppressWarnings("unchecked")
            Map<Integer, DoublePair> map = (Map<Integer, DoublePair>) decoder.readObject();

            // Most rotate/share/translate are stateless, so I only need to get the cumulative transform
            // for layout and view via getTransform() which should return AffineTransform
            // which I should be able to persist into XML.
            // Only ScalingGraphMousePlugin has a state
            // in the form of getIn()/setIn()/getOut()/setOut().
            viewer.getViewTransformer().setToIdentity();
            viewer.getViewTransformer()
                    .concatenate(((XMLAffineTransformSerialised) decoder.readObject()).getAffineTransform());

            viewer.getLayoutTransformer().setToIdentity();
            viewer.getLayoutTransformer()
                    .concatenate(((XMLAffineTransformSerialised) decoder.readObject()).getAffineTransform());
            ((XMLModalGraphMouse) viewer.getGraphMouse()).restore(decoder);
            layoutOptions.put(propName, (LayoutOptions) decoder.readObject());
            ((XMLPersistingLayout) viewer.getModel().getGraphLayout()).initialize(getSize());
            ((XMLPersistingLayout) viewer.getModel().getGraphLayout()).restore(map);
            viewer.invalidate();
        }
    } catch (Exception e1) {
        if (!ignoreErrors) {
            e1.printStackTrace();
        }
    } finally {
        if (decoder != null) {
            decoder.close();
            decoder = null;
        }
    }
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * This method de-serialize XML object graph. In addition if there are parameterized strings such as
 * <code>%s(accessToken)</code> in the XML file, those will be parsed and and replace with the values
 * specified in the Connection Properties resource file or the parameter map passed in to this method. <br>
 * <br>/*from   ww w  .ja  v  a 2 s  .  c o m*/
 * <b>Example XML file.</b><br>
 * 
 * <pre>
 * {@code
 * <?xml version="1.0" encoding="UTF-8"?> 
 * <java class="java.beans.XMLDecoder"> 
 *  <object class="test.base.Person"> 
 *   <void property="address"> 
 *    <object class="test.base.Address"> 
 *     <void property="city"> 
 *      <string>Test City</string> 
 *     </void> 
 *     <void property="country"> 
 *      <string>Test Country</string> 
 *     </void> 
 *     <void property="street"> 
 *      <string>Test street</string> 
 *     </void> 
 *    </object> 
 *   </void> 
 *  <void property="age"> 
 *    <int>20</int> 
 *   </void> 
 *   <void property="name"> 
 *    <string>Test Person Name</string> 
 *   </void> 
 *  </object> 
 * </java>
 *  }
 * </pre>
 * 
 * @param filePath file name including path to the XML serialized file.
 * @param paramMap map containing key value pairs where key being the parameter specified in the XML file
 *        if parameter in XML is <code>%s(accessToken)</code>, the key should be just
 *        <code>accessToken</code>.
 * @return the de-serialized object, user can cast this to the object type specified in the XML.
 * @throws IOException if file path is null or empty as well as if there's any exception while reading the
 *         XML file.
 */
protected Object loadObjectFromFile(String fileName, Map<String, String> paramMap) throws IOException {

    String filePath = pathToRequestsDirectory + fileName;
    if (filePath == null || filePath.isEmpty()) {
        throw new IOException("File path cannot be null or empty.");
    }

    Object retObj = null;
    BufferedInputStream bi = null;
    XMLDecoder decoder = null;

    try {
        bi = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buf = new byte[bi.available()];
        bi.read(buf);
        String content = new String(buf);

        if (connectorProperties != null) {
            // We don't need to change the original connection properties in case same key is sent with
            // different value.
            Properties prop = (Properties) connectorProperties.clone();
            if (paramMap != null) {
                prop.putAll(paramMap);
            }
            Matcher matcher = Pattern.compile("%s\\(([A-Za-z0-9]*)\\)", Pattern.DOTALL).matcher(content);
            while (matcher.find()) {
                String key = matcher.group(1);
                content = content.replaceAll("%s\\(" + key + "\\)",
                        Matcher.quoteReplacement(prop.getProperty(key)));
            }
        }

        ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes(Charset.defaultCharset()));

        decoder = new XMLDecoder(in);
        retObj = decoder.readObject();
    } finally {
        if (bi != null) {
            bi.close();
        }
        if (decoder != null) {
            decoder.close();
        }
    }

    return retObj;
}

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

private void initSourceLists() {
    File appPath = getStartupApplicationPath();
    File sourceListsFile = new File(appPath, SOURCE_LISTS_XML_FILENAME);

    if (sourceListsFile.isFile()) {
        long lastModified = sourceListsFile.lastModified();
        if (sourceLists != null && lastSourceListsModified >= lastModified) {
            if (logger.isDebugEnabled())
                logger.debug("Won't reload source lists.");
            return;
        }/*from www.j a  va2 s .  c  o m*/
        XMLDecoder d = null;
        try {
            d = new XMLDecoder(new BufferedInputStream(new FileInputStream(sourceListsFile)));

            Map<String, Set> interimMap = transformToMap(String.class, Set.class, d.readObject());

            Map<String, Set<String>> resultMap = null;
            if (interimMap != null) {
                resultMap = new HashMap<>();
                for (Map.Entry<String, Set> current : interimMap.entrySet()) {
                    Set<String> value = transformToSet(String.class, current.getValue());
                    if (value == null) {
                        continue;
                    }
                    resultMap.put(current.getKey(), value);
                }
            }
            sourceLists = resultMap;
            lastSourceListsModified = lastModified;
        } catch (Throwable ex) {
            if (logger.isWarnEnabled())
                logger.warn("Exception while loading source lists from sourceListsFile '"
                        + sourceListsFile.getAbsolutePath() + "'!", ex);
            sourceLists = new HashMap<>();
            IOUtilities.interruptIfNecessary(ex);
        } finally {
            if (d != null) {
                d.close();
            }
        }
    } else if (sourceLists == null) {
        sourceLists = new HashMap<>();
    }
}

From source file:psidev.psi.mi.filemakers.xmlMaker.XmlMakerGui.java

private void load(File mappingFile) {
    try {//from ww  w .  j  a v  a2s  .  c  o  m
        FileInputStream fin = new FileInputStream(mappingFile);

        Utils.lastVisitedDirectory = mappingFile.getPath();
        Utils.lastVisitedMappingDirectory = mappingFile.getPath();
        //Utils.lastMappingFile = mappingFile.getName();
        // Create XML encoder.
        XMLDecoder xdec = new XMLDecoder(fin);

        /* get mapping */
        Mapping mapping = (Mapping) xdec.readObject();

        /* flat files */
        flatFileTabbedPanel.flatFileContainer.flatFiles = new ArrayList();

        for (int i = 0; i < mapping.flatFiles.size(); i++) {
            FlatFileMapping ffm = (FlatFileMapping) mapping.flatFiles.get(i);
            FlatFile f = new FlatFile();
            if (ffm != null) {
                f.lineSeparator = ffm.lineSeparator;
                f.firstLineForTitles = ffm.fisrtLineForTitle;
                f.setSeparators(ffm.getSeparators());

                try {
                    URL url = new File(ffm.getFileURL()).toURL();
                    if (url != null)
                        f.load(url);
                } catch (FileNotFoundException fe) {
                    JOptionPane.showMessageDialog(new JFrame(), "Unable to load file" + ffm.getFileURL(),
                            "[PSI makers: PSI maker] load flat file", JOptionPane.ERROR_MESSAGE);
                }
            }
            treePanel.flatFileTabbedPanel.flatFileContainer.addFlatFile(f);
        }
        treePanel.flatFileTabbedPanel.reload();

        /* dictionaries */
        dictionnaryLists.dictionaries.dictionaries = new ArrayList();

        for (int i = 0; i < mapping.getDictionaries().size(); i++) {
            DictionaryMapping dm = (DictionaryMapping) mapping.getDictionaries().get(i);
            Dictionary d = new Dictionary();

            try {
                URL url = null;
                if (dm.getFileURL() != null)
                    url = new File(dm.getFileURL()).toURL();
                if (url != null)
                    d = new Dictionary(url, dm.getSeparator(), dm.caseSensitive);
                else
                    d = new Dictionary();
            } catch (FileNotFoundException fe) {
                JOptionPane.showMessageDialog(new JFrame(), "Unable to load file" + dm.getFileURL(),
                        "[PSI makers: PSI maker] load dictionnary", JOptionPane.ERROR_MESSAGE);
                d = new Dictionary();
            }
            treePanel.dictionaryPanel.dictionaries.addDictionary(d);
        }
        treePanel.dictionaryPanel.reload();

        /* tree */
        TreeMapping treeMapping = mapping.getTree();

        File schema = new File(treeMapping.getSchemaURL());
        try {
            treePanel.loadSchema(schema);
            ((XsdTreeStructImpl) treePanel.xsdTree).loadMapping(treeMapping);

            treePanel.xsdTree.check();
            treePanel.reload();

            /* set titles for flat files */
            for (int i = 0; i < mapping.flatFiles.size(); i++) {
                try {
                    flatFileTabbedPanel.tabbedPane.setTitleAt(i,
                            ((XsdNode) xsdTree.getAssociatedFlatFiles().get(i)).toString());
                } catch (IndexOutOfBoundsException e) {
                    /** TODO: manage exception */
                }
            }

        } catch (FileNotFoundException fe) {
            JOptionPane.showMessageDialog(new JFrame(), "File not found: " + schema.getName(), "[PSI makers]",
                    JOptionPane.ERROR_MESSAGE);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(new JFrame(), "Unable to load file" + ioe.toString(), "[PSI makers]",
                    JOptionPane.ERROR_MESSAGE);
        }
        xdec.close();
        fin.close();
    } catch (FileNotFoundException fe) {
        JOptionPane.showMessageDialog(new JFrame(), "Unable to load mapping" + mappingFile.getName(),
                "[PSI makers: PSI maker] load mapping", JOptionPane.ERROR_MESSAGE);
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(new JFrame(), "IO error, unable to load mapping",
                "[PSI makers: PSI maker] load mapping", JOptionPane.ERROR_MESSAGE);
    } catch (NoSuchElementException nsee) {
        nsee.printStackTrace();
        JOptionPane.showMessageDialog(new JFrame(), "Unable to load file", "[PSI makers]",
                JOptionPane.ERROR_MESSAGE);
    }

}

From source file:uk.ac.ebi.sail.server.data.DataManager.java

private void loadExpressions(Statement stmt) throws SQLException {
    IntMap<GroupRequestItem> exprMap = new IntTreeMap<GroupRequestItem>();

    ResultSet rst = stmt.executeQuery("SELECT * FROM " + TBL_EXPRESSION);

    while (rst.next()) {
        String name = rst.getString(FLD_NAME);

        GroupRequestItem expr = null;// ww w  .j  a va  2  s .c  o m

        if (name == null)
            expr = new GroupRequestItem();
        else
            expr = new ExpressionRequestItem();

        expr.setId(rst.getInt(FLD_ID));
        expr.setName(rst.getString(FLD_NAME));
        expr.setDepth(rst.getInt(FLD_EXPRESSION_DEPTH));
        expr.setDescription(rst.getString(FLD_DESCRIPTION));

        exprMap.put(expr.getId(), expr);
    }

    rst.close();

    int rid = 1;

    rst = stmt.executeQuery("SELECT * FROM " + TBL_EXPRESSION_CONTENT);

    while (rst.next()) {
        int rpId = rst.getInt(FLD_EXPRESSION_ID);

        GroupRequestItem expr = exprMap.get(rpId);

        if (expr == null) {
            logger.warn("Abandoned subexpression ExpressionID=" + rpId);
            continue;
        }

        int sid = rst.getInt(FLD_PARAMETER_ID);

        if (sid > 0) {
            Parameter p = params.get(sid);

            if (p == null) {
                logger.warn("Invalid parameter subexpression ExpressionID=" + rpId + " ParameterID=" + sid);
                continue;
            }

            String filtTxt = rst.getString(FLD_EXPRESSION_FILTER);

            RequestItem ri = null;

            if (filtTxt != null && filtTxt.length() > 0) {
                Object fo = null;

                try {
                    XMLDecoder dec = new XMLDecoder(new StringInputStream(filtTxt));

                    fo = dec.readObject();

                    dec.close();
                } catch (Exception e) {
                }

                if (fo instanceof ComplexFilter) {
                    ComplexFilter cf = (ComplexFilter) fo;

                    cf.setParameter(p);

                    ri = new ComplexFilteredRequestItem(p.getName(), cf);
                }
            } else
                ri = new ParameterRequestItem(p.getName(), p);

            ri.setId(rid++);

            expr.addItem(ri);
        } else {
            sid = rst.getInt(FLD_SUBEXPRESSION_ID);

            if (sid <= 0) {
                logger.warn("Invalid subexpression ExpressionID=" + rpId
                        + " ParameterID or SubexpressionID must be non-zero");
                continue;
            }

            GroupRequestItem sbexp = exprMap.get(sid);

            if (sbexp == null) {
                logger.warn("Invalid parameter subexpression ExpressionID=" + rpId + " SubexpressionID=" + sid);
                continue;
            }

            expr.addItem(sbexp);
        }

    }
    rst.close();

    expressions.clear();

    for (GroupRequestItem expi : exprMap.values()) {
        if (expi.getName() != null)
            expressions.add((ExpressionRequestItem) expi);
    }

}