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:de.huxhorn.lilith.swing.ApplicationPreferences.java

private void initStatusColors() {
    if (statusColors == null) {
        File appPath = getStartupApplicationPath();
        File statusColorsFile = new File(appPath, STATUS_COLORS_XML_FILENAME);

        if (statusColorsFile.isFile()) {
            XMLDecoder d = null;// w ww  . j  a  v  a  2  s . co m
            try {
                d = new XMLDecoder(new BufferedInputStream(new FileInputStream(statusColorsFile)));

                statusColors = transformToMap(HttpStatus.Type.class, ColorScheme.class, d.readObject());
            } catch (Throwable ex) {
                if (logger.isWarnEnabled())
                    logger.warn("Exception while loading status Status-ColorSchemes from file '"
                            + statusColorsFile.getAbsolutePath() + "'!", ex);
                statusColors = null;
                IOUtilities.interruptIfNecessary(ex);
            } finally {
                if (d != null) {
                    d.close();
                }
            }
        }
    }

    if (statusColors != null && statusColors.size() != DEFAULT_STATUS_COLOR_SCHEMES.size()) {
        if (logger.isWarnEnabled())
            logger.warn("Reverting Status-ColorSchemes to defaults.");
        statusColors = null;
    }

    if (statusColors == null) {
        statusColors = cloneStatusColors(DEFAULT_STATUS_COLOR_SCHEMES);
    }
}

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   w  w w  .  j a v a 2 s . co 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: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 w w  w  .j a 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: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;//from  w w  w  . j a  va  2 s .c  om

        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);
    }

}

From source file:org.latticesoft.util.common.FileUtil.java

/**
 * Reads an object from a xml file//from ww  w .  j ava  2s  .c o m
 * @param filename the filename to read from
 * @return the object
 */
public static Object readFromXmlFile(String filename) {
    if (filename == null) {
        return null;
    }
    XMLDecoder decoder = null;
    Object o = null;
    try {
        decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(filename)));
        o = decoder.readObject();
    } catch (Exception e) {
    } finally {
        try {
            decoder.close();
        } catch (Exception e) {
        }
    }
    return o;
}

From source file:com.tao.realweb.util.StringUtil.java

/** 
* xml object /*from  w  w w.jav  a2 s. c om*/
*  
* @param xml 
* @return 
*/
public static Object xmlToObject(String xml) {
    try {
        ByteArrayInputStream in = new ByteArrayInputStream(xml.getBytes("UTF8"));
        XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(in));
        return decoder.readObject();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

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

private void initConditions() {
    File appPath = getStartupApplicationPath();
    File conditionsFile = new File(appPath, CONDITIONS_XML_FILENAME);

    if (conditionsFile.isFile()) {
        long lastModified = conditionsFile.lastModified();
        if (conditions != null && lastConditionsModified >= lastModified) {
            if (logger.isDebugEnabled())
                logger.debug("Won't reload conditions.");
            return;
        }//  www  . j  ava  2s.c  o  m
        XMLDecoder d = null;
        try {
            d = new XMLDecoder(new BufferedInputStream(new FileInputStream(conditionsFile)));

            conditions = transformToList(SavedCondition.class, d.readObject());
            lastConditionsModified = lastModified;
            if (logger.isDebugEnabled())
                logger.debug("Loaded conditions {}.", conditions);
        } catch (Throwable ex) {
            if (logger.isWarnEnabled())
                logger.warn("Exception while loading conditions from file '" + conditionsFile.getAbsolutePath()
                        + "'!", ex);
            IOUtilities.interruptIfNecessary(ex);
        } finally {
            if (d != null) {
                d.close();
            }
        }
    }

    if (conditions == null) {
        conditions = new ArrayList<>();
    }
}

From source file:org.kchine.r.server.RListener.java

public static String[] xmlGet(String url) {
    try {//from ww w.j a  v  a 2s . c  om

        RResponse rresponse = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            XMLDecoder decoder = new XMLDecoder(connection.getInputStream());
            rresponse = (RResponse) decoder.readObject();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (rresponse == null) {
            return new String[] { "NOK", convertToPrintCommand("Bad URL: " + url) };
        }

        long ref = DirectJNI.getInstance().putObject(rresponse.getValue());
        DirectJNI.getInstance().assignInPrivateEnv("xml.get.result", ref);

        return new String[] { "OK" };
    } catch (Exception e) {
        e.printStackTrace();
        return new String[] { "NOK", convertToPrintCommand(PoolUtils.getStackTraceAsString(e)) };
    }
}

From source file:com.alvermont.terraj.planet.ui.MainFrame.java

private void loadParamsItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_loadParamsItemActionPerformed
{//GEN-HEADEREND:event_loadParamsItemActionPerformed

    final int choice = xmlChooser.showOpenDialog(this);

    if (choice == JFileChooser.APPROVE_OPTION) {
        try {//from   w  ww .j a va 2  s.c  om
            final InputStream target = xmlChooser.getFileContents().getInputStream();

            final XMLDecoder decoder = new XMLDecoder(target);

            final AllPlanetParameters newParams = (AllPlanetParameters) decoder.readObject();

            this.params = newParams;

            updateAllFromParameters();
        } catch (IOException ioe) {
            log.error("Error reading file", ioe);

            JOptionPane.showMessageDialog(this,
                    "Error: " + ioe.getMessage() + "\nCheck log file for full details", "Error Loading",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

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

private List<PersistentTableColumnModel.TableColumnLayoutInfo> readColumnLayout(File file) {
    XMLDecoder d = null;/*from www  .j a v a2 s .  c om*/
    List<PersistentTableColumnModel.TableColumnLayoutInfo> result;
    try {
        d = new XMLDecoder(new BufferedInputStream(new FileInputStream(file)));

        result = transformToList(PersistentTableColumnModel.TableColumnLayoutInfo.class, d.readObject());
    } catch (Throwable ex) {
        if (logger.isInfoEnabled())
            logger.info("Exception while loading layouts from file '{}'':", file.getAbsolutePath(),
                    ex.getMessage());
        result = null;
        IOUtilities.interruptIfNecessary(ex);
    } finally {
        if (d != null) {
            d.close();
        }
    }
    return result;
}