Example usage for org.w3c.dom Element hasAttribute

List of usage examples for org.w3c.dom Element hasAttribute

Introduction

In this page you can find the example usage for org.w3c.dom Element hasAttribute.

Prototype

public boolean hasAttribute(String name);

Source Link

Document

Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.

Usage

From source file:lucee.runtime.config.XMLConfigWebFactory.java

/**
 * loads datasource settings from XMl DOM
 * //from  ww  w  .  ja va  2s  .co m
 * @param configServer
 * @param config
 * @param doc
 * @throws BundleException 
 * @throws ClassNotFoundException
 */
private static void loadDataSources(ConfigServerImpl configServer, ConfigImpl config, Document doc, Log log) {

    // load JDBC Driver defintion
    {
        Element jdbc = getChildByName(doc.getDocumentElement(), "jdbc");
        Element[] drivers = getChildren(jdbc, "driver");
        Map<String, JDBCDriver> map = new HashMap<String, JDBCDriver>();

        // first add the server drivers, so they can be overwritten
        if (configServer != null) {
            JDBCDriver[] sds = configServer.getJDBCDrivers();
            for (JDBCDriver sd : sds) {
                map.put(sd.cd.toString(), sd);
            }
        }

        ClassDefinition cd;
        String label;
        for (Element driver : drivers) {
            cd = getClassDefinition(driver, "", config.getIdentification());
            label = driver.getAttribute("label");
            // check if label exists
            if (StringUtil.isEmpty(label)) {
                log.error("Datasource", "missing label for jdbc driver [" + cd.getClassName() + "]");
                continue;
            }
            // check if it is a bundle
            if (!cd.isBundle()) {
                log.error("Datasource", "jdbc driver [" + label + "] does not describe a bundle");
                continue;
            }
            map.put(cd.toString(), new JDBCDriver(label, cd));
        }
        config.setJDBCDrivers(map.values().toArray(new JDBCDriver[map.size()]));
    }

    // When set to true, makes JDBC use a representation for DATE data that
    // is compatible with the Oracle8i database.
    System.setProperty("oracle.jdbc.V8Compatible", "true");

    boolean hasCS = configServer != null;
    Map<String, DataSource> datasources = new HashMap<String, DataSource>();

    // Copy Parent datasources as readOnly
    if (hasCS) {
        Map<String, DataSource> ds = configServer.getDataSourcesAsMap();
        Iterator<Entry<String, DataSource>> it = ds.entrySet().iterator();
        Entry<String, DataSource> entry;
        while (it.hasNext()) {
            entry = it.next();
            if (!entry.getKey().equals(QOQ_DATASOURCE_NAME))
                datasources.put(entry.getKey(), entry.getValue().cloneReadOnly());
        }
    }

    // TODO support H2
    // Default query of query DB
    /*
     * setDatasource(datasources, QOQ_DATASOURCE_NAME, "org.h2.Driver" ,"" ,""
     * ,-1 ,"jdbc:h2:.;MODE=HSQLDB" ,"sa" ,"" ,-1 ,-1 ,true ,true
     * ,DataSource.ALLOW_ALL, new StructImpl() );
     */
    // Default query of query DB
    try {
        setDatasource(config, datasources, QOQ_DATASOURCE_NAME,
                new ClassDefinitionImpl("org.hsqldb.jdbcDriver", "hsqldb", "1.8.0", config.getIdentification()),
                "hypersonic-hsqldb", "", -1, "jdbc:hsqldb:.", "sa", "", -1, -1, 60000, true, true,
                DataSource.ALLOW_ALL, false, false, null, new StructImpl(), "");
    } catch (Exception e) {
        log.error("Datasource", e);
    }

    SecurityManager sm = config.getSecurityManager();
    short access = sm.getAccess(SecurityManager.TYPE_DATASOURCE);
    int accessCount = -1;
    if (access == SecurityManager.VALUE_YES)
        accessCount = -1;
    else if (access == SecurityManager.VALUE_NO)
        accessCount = 0;
    else if (access >= SecurityManager.VALUE_1 && access <= SecurityManager.VALUE_10) {
        accessCount = access - SecurityManager.NUMBER_OFFSET;
    }

    // Databases
    Element databases = getChildByName(doc.getDocumentElement(), "data-sources");
    // if(databases==null)databases=doc.createElement("data-sources");

    // PSQ
    String strPSQ = databases.getAttribute("psq");
    if (StringUtil.isEmpty(strPSQ)) {
        // prior version was buggy, was the opposite
        strPSQ = databases.getAttribute("preserve-single-quote");
        if (!StringUtil.isEmpty(strPSQ)) {
            Boolean b = Caster.toBoolean(strPSQ, null);
            if (b != null)
                strPSQ = b.booleanValue() ? "false" : "true";
        }
    }
    if (access != SecurityManager.VALUE_NO && !StringUtil.isEmpty(strPSQ)) {
        config.setPSQL(toBoolean(strPSQ, true));
    } else if (hasCS)
        config.setPSQL(configServer.getPSQL());

    // Data Sources
    Element[] dataSources = getChildren(databases, "data-source");
    if (accessCount == -1)
        accessCount = dataSources.length;
    if (dataSources.length < accessCount)
        accessCount = dataSources.length;

    // if(hasAccess) {
    ClassDefinition cd;
    for (int i = 0; i < accessCount; i++) {
        Element dataSource = dataSources[i];
        if (dataSource.hasAttribute("database")) {

            try {
                setDatasource(config, datasources, dataSource.getAttribute("name"),
                        getClassDefinition(dataSource, "", config.getIdentification()),
                        dataSource.getAttribute("host"), dataSource.getAttribute("database"),
                        Caster.toIntValue(dataSource.getAttribute("port"), -1), dataSource.getAttribute("dsn"),
                        dataSource.getAttribute("username"),
                        ConfigWebUtil.decrypt(dataSource.getAttribute("password")),
                        Caster.toIntValue(dataSource.getAttribute("connectionLimit"), -1),
                        Caster.toIntValue(dataSource.getAttribute("connectionTimeout"), -1),
                        Caster.toLongValue(dataSource.getAttribute("metaCacheTimeout"), 60000),
                        toBoolean(dataSource.getAttribute("blob"), true),
                        toBoolean(dataSource.getAttribute("clob"), true),
                        Caster.toIntValue(dataSource.getAttribute("allow"), DataSource.ALLOW_ALL),
                        toBoolean(dataSource.getAttribute("validate"), false),
                        toBoolean(dataSource.getAttribute("storage"), false),
                        dataSource.getAttribute("timezone"), toStruct(dataSource.getAttribute("custom")),
                        dataSource.getAttribute("dbdriver"));
            } catch (Exception e) {
                log.error("Datasource", e);
            }
        }
    }
    // }
    config.setDataSources(datasources);

}

From source file:de.interactive_instruments.ShapeChange.Options.java

/**
 * Parses the given TargetXmlSchema element and returns a map of all
 * XsdMapEntries it contains./*from w ww .j  a  va 2 s . co  m*/
 *
 * @param targetXmlSchemaElement
 *            The TargetXmlSchema element from the ShapeChangeConfiguration
 * @return map of the XsdMapEntries contained in the TargetXmlSchema element
 *         (key: XsdMapEntry type)
 */
private List<XsdMapEntry> parseXsdMapEntries(Element targetXmlSchemaElement) {

    List<XsdMapEntry> result = new ArrayList<XsdMapEntry>();

    NodeList xsdMapEntriesNl = targetXmlSchemaElement.getElementsByTagName("XsdMapEntry");
    Node xsdMapEntryN;
    Element xsdMapEntryE;

    if (xsdMapEntriesNl != null && xsdMapEntriesNl.getLength() != 0) {

        for (int k = 0; k < xsdMapEntriesNl.getLength(); k++) {

            xsdMapEntryN = xsdMapEntriesNl.item(k);
            if (xsdMapEntryN.getNodeType() == Node.ELEMENT_NODE) {

                xsdMapEntryE = (Element) xsdMapEntryN;

                String type = xsdMapEntryE.getAttribute("type");

                List<String> encodingRules = new ArrayList<String>();
                String encodingRulesValue = xsdMapEntryE.getAttribute("xsdEncodingRules");
                if (encodingRulesValue != null && encodingRulesValue.trim().length() > 0) {
                    encodingRulesValue = encodingRulesValue.toLowerCase();
                    encodingRules = new ArrayList<String>(Arrays.asList(encodingRulesValue.split("\\s")));
                }

                String xmlType = xsdMapEntryE.hasAttribute("xmlType") ? xsdMapEntryE.getAttribute("xmlType")
                        : null;

                String xmlTypeContent = "";
                if (xsdMapEntryE.hasAttribute("xmlTypeContent")) {
                    xmlTypeContent = xsdMapEntryE.getAttribute("xmlTypeContent").trim();
                }
                if (xmlTypeContent.length() == 0) {
                    xmlTypeContent = "complex";
                }

                String xmlTypeType = "";
                if (xsdMapEntryE.hasAttribute("xmlTypeType")) {
                    xmlTypeType = xsdMapEntryE.getAttribute("xmlTypeType").trim();
                }
                if (xmlTypeType.length() == 0) {
                    xmlTypeType = "complex";
                }

                String xmlTypeNilReason = "";
                if (xsdMapEntryE.hasAttribute("xmlTypeNilReason")) {
                    xmlTypeNilReason = xsdMapEntryE.getAttribute("xmlTypeNilReason").trim();
                }
                if (xmlTypeNilReason.length() == 0) {
                    if (xmlTypeType.equals("simple"))
                        xmlTypeNilReason = "false";
                    else
                        xmlTypeNilReason = "true";
                }

                String xmlElement = xsdMapEntryE.hasAttribute("xmlElement")
                        ? xsdMapEntryE.getAttribute("xmlElement")
                        : null;

                String xmlPropertyType = xsdMapEntryE.hasAttribute("xmlPropertyType")
                        ? xsdMapEntryE.getAttribute("xmlPropertyType")
                        : null;

                String xmlAttribute = xsdMapEntryE.hasAttribute("xmlAttribute")
                        ? xsdMapEntryE.getAttribute("xmlAttribute")
                        : null;

                String xmlAttributeGroup = xsdMapEntryE.hasAttribute("xmlAttributeGroup")
                        ? xsdMapEntryE.getAttribute("xmlAttributeGroup")
                        : null;

                String nsabr = xsdMapEntryE.hasAttribute("nsabr") ? xsdMapEntryE.getAttribute("nsabr") : null;

                result.add(new XsdMapEntry(type, encodingRules, xmlType, xmlTypeContent, xmlTypeType,
                        xmlTypeNilReason, xmlElement, xmlPropertyType, xmlAttribute, xmlAttributeGroup, nsabr));
            }
        }
    }
    return result;
}

From source file:de.interactive_instruments.ShapeChange.Options.java

private List<TargetConfiguration> parseTargetConfigurations(Document configurationDocument)
        throws ShapeChangeAbortException {

    List<TargetConfiguration> tgtConfigs = new ArrayList<TargetConfiguration>();

    NodeList tgtsNl = configurationDocument.getElementsByTagName("targets");

    for (int i = 0; i < tgtsNl.getLength(); i++) {
        Node tgtsN = tgtsNl.item(i);
        NodeList tgtNl = tgtsN.getChildNodes();

        // look for all Target/TargetXmlSchema elements in the "targets"
        // Node//from   ww  w .ja  va  2s.co  m
        for (int j = 0; j < tgtNl.getLength(); j++) {
            Node tgtN = tgtNl.item(j);

            if (tgtN.getNodeType() == Node.ELEMENT_NODE) {
                Element tgtE = (Element) tgtN;

                // parse content of target element

                // get name of config element for decision which type of
                // TargetConfiguration to instantiate later on
                String tgtType = tgtE.getNodeName();

                // get class name
                String tgtConfigName = tgtE.getAttribute("class");

                // get mode
                ProcessMode tgtMode = this.parseMode(tgtE);

                Map<String, String> processParameters = parseParameters(tgtE, "targetParameter");

                // now look up all ProcessRuleSet elements, if there are
                // any
                Map<String, ProcessRuleSet> processRuleSets = parseRuleSets(tgtE, "EncodingRule", true);

                // get the target inputs - can be null, then set it to
                // global input element
                Set<String> tgtConfigInputs;
                if (tgtE.hasAttribute("inputs")) {
                    String[] inputs = tgtE.getAttribute("inputs").split("\\s");
                    tgtConfigInputs = new HashSet<String>(Arrays.asList(inputs));
                } else {
                    tgtConfigInputs = new HashSet<String>();
                    tgtConfigInputs.add(getInputId());
                }

                Element advancedProcessConfigurations = parseAdvancedProcessConfigurations(tgtE);

                TargetConfiguration tgtConfig;
                if (tgtType.equals("Target")) {
                    // now look up all ProcessMapEntry elements, if there
                    // are any
                    List<ProcessMapEntry> processMapEntries = parseProcessMapEntries(tgtE, "MapEntry");

                    // also parse namespaces, if there are any
                    List<Namespace> namespaces = parseNamespaces(tgtE);

                    // create target config and add it to list
                    tgtConfig = new TargetConfiguration(tgtConfigName, tgtMode, processParameters,
                            processRuleSets, processMapEntries, tgtConfigInputs, namespaces,
                            advancedProcessConfigurations);

                } else if (tgtType.equals("TargetOwl")) {

                    // now look up all ProcessMapEntry elements, if there
                    // are any
                    List<ProcessMapEntry> processMapEntries = parseProcessMapEntries(tgtE, "MapEntry");

                    // also parse namespaces, if there are any
                    List<Namespace> namespaces = parseNamespaces(tgtE);

                    // also parse stereotype mappings, if there are any
                    Map<String, String> stereotypeMappings = parseStereotypeMappings(tgtE);

                    // create target owl config and add it to list
                    tgtConfig = new TargetOwlConfiguration(tgtConfigName, tgtMode, processParameters,
                            processRuleSets, processMapEntries, tgtConfigInputs, namespaces, stereotypeMappings,
                            advancedProcessConfigurations);
                } else {
                    // We're dealing with a TargetXmlSchema element

                    List<XsdMapEntry> xsdMapEntries = parseXsdMapEntries(tgtE);

                    List<XmlNamespace> xmlNamespaces = parseXmlNamespaces(tgtE);

                    tgtConfig = new TargetXmlSchemaConfiguration(tgtConfigName, tgtMode, processParameters,
                            processRuleSets, null, xsdMapEntries, xmlNamespaces, tgtConfigInputs,
                            advancedProcessConfigurations);
                }
                tgtConfigs.add(tgtConfig);
            }
        }
    }
    return tgtConfigs;
}

From source file:com.paniclauncher.workers.InstanceInstaller.java

private ArrayList<MojangDownloadable> getNeededResources() {
    ArrayList<MojangDownloadable> downloads = new ArrayList<MojangDownloadable>(); // All the files

    // Read in the resources needed

    if (!isServer) {
        try {/* ww w  . jav  a  2s .c  o  m*/
            boolean isTruncated;
            String marker = null;
            String add;
            do {
                if (marker == null) {
                    add = "";
                } else {
                    add = "?marker=" + marker;
                }
                URL resourceUrl = new URL("https://s3.amazonaws.com/Minecraft.Resources/" + add);
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(resourceUrl.openStream());
                isTruncated = Boolean
                        .parseBoolean(doc.getElementsByTagName("IsTruncated").item(0).getTextContent());
                NodeList nodeLst = doc.getElementsByTagName("Contents");
                for (int i = 0; i < nodeLst.getLength(); i++) {
                    Node node = nodeLst.item(i);

                    if (node.getNodeType() == 1) {
                        Element element = (Element) node;
                        String key = element.getElementsByTagName("Key").item(0).getChildNodes().item(0)
                                .getNodeValue();
                        String etag = element.getElementsByTagName("ETag") != null ? element
                                .getElementsByTagName("ETag").item(0).getChildNodes().item(0).getNodeValue()
                                : "-";
                        etag = getEtag(etag);
                        marker = key;
                        long size = Long.parseLong(element.getElementsByTagName("Size").item(0).getChildNodes()
                                .item(0).getNodeValue());

                        if (size > 0L) {
                            File file;
                            String filename;
                            if (key.contains("/")) {
                                filename = key.substring(key.lastIndexOf('/') + 1, key.length());
                                File directory = new File(App.settings.getResourcesDir(),
                                        key.substring(0, key.lastIndexOf('/')));
                                file = new File(directory, filename);
                            } else {
                                file = new File(App.settings.getResourcesDir(), key);
                                filename = file.getName();
                            }
                            if (!Utils.getMD5(file).equalsIgnoreCase(etag))
                                downloads.add(new MojangDownloadable(
                                        "https://s3.amazonaws.com/Minecraft.Resources/" + key, file, etag,
                                        this));
                        }
                    }
                }
            } while (isTruncated);
        } catch (Exception e) {
            App.settings.getConsole().logStackTrace(e);
        }
    }

    // Now lets see if we have custom mainclass and extraarguments

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(pack.getXML(version, false)));
        Document document = builder.parse(is);
        document.getDocumentElement().normalize();
        NodeList nodeList = document.getElementsByTagName("mainclass");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                if (element.hasAttribute("depends")) {
                    boolean found = false;
                    for (Mod mod : selectedMods) {
                        if (element.getAttribute("depends").equalsIgnoreCase(mod.getName())) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        break;
                    }
                }
                NodeList nodeList1 = element.getChildNodes();
                this.mainClass = nodeList1.item(0).getNodeValue();
            }
        }
    } catch (SAXException e) {
        App.settings.getConsole().logStackTrace(e);
    } catch (ParserConfigurationException e) {
        App.settings.getConsole().logStackTrace(e);
    } catch (IOException e) {
        App.settings.getConsole().logStackTrace(e);
    }

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(pack.getXML(version, false)));
        Document document = builder.parse(is);
        document.getDocumentElement().normalize();
        NodeList nodeList = document.getElementsByTagName("extraarguments");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                if (element.hasAttribute("depends")) {
                    boolean found = false;
                    for (Mod mod : selectedMods) {
                        if (element.getAttribute("depends").equalsIgnoreCase(mod.getName())) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        break;
                    }
                }
                NodeList nodeList1 = element.getChildNodes();
                this.extraArguments = nodeList1.item(0).getNodeValue();
            }
        }
    } catch (SAXException e) {
        App.settings.getConsole().logStackTrace(e);
    } catch (ParserConfigurationException e) {
        App.settings.getConsole().logStackTrace(e);
    } catch (IOException e) {
        App.settings.getConsole().logStackTrace(e);
    }

    // Now read in the library jars needed from the pack

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(pack.getXML(version, false)));
        Document document = builder.parse(is);
        document.getDocumentElement().normalize();
        NodeList nodeList = document.getElementsByTagName("library");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                String url = element.getAttribute("url");
                String file = element.getAttribute("file");
                Download download = Download.direct;
                if (element.hasAttribute("download")) {
                    download = Download.valueOf(element.getAttribute("download"));
                }
                String md5 = "-";
                if (element.hasAttribute("md5")) {
                    md5 = element.getAttribute("md5");
                }
                if (element.hasAttribute("depends")) {
                    boolean found = false;
                    for (Mod mod : selectedMods) {
                        if (element.getAttribute("depends").equalsIgnoreCase(mod.getName())) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        continue;
                    }
                }
                if (librariesNeeded == null) {
                    this.librariesNeeded = file;
                } else {
                    this.librariesNeeded += "," + file;
                }
                File downloadTo = null;
                if (isServer) {
                    if (!element.hasAttribute("server")) {
                        continue;
                    }
                    serverLibraries.add(new File(
                            new File(getLibrariesDirectory(),
                                    element.getAttribute("server").substring(0,
                                            element.getAttribute("server").lastIndexOf('/'))),
                            element.getAttribute("server").substring(
                                    element.getAttribute("server").lastIndexOf('/'),
                                    element.getAttribute("server").length())));
                }
                downloadTo = new File(App.settings.getLibrariesDir(), file);
                if (download == Download.server) {
                    downloads.add(new MojangDownloadable(App.settings.getFileURL(url), downloadTo, md5, this));
                } else {
                    downloads.add(new MojangDownloadable(url, downloadTo, md5, this));
                }
            }
        }
    } catch (SAXException e) {
        App.settings.getConsole().logStackTrace(e);
    } catch (ParserConfigurationException e) {
        App.settings.getConsole().logStackTrace(e);
    } catch (IOException e) {
        App.settings.getConsole().logStackTrace(e);
    }

    // Now read in the library jars needed from Mojang
    if (!isServer) {
        JSONParser parser = new JSONParser();

        try {
            Object obj = parser.parse(Utils.urlToString("https://s3.amazonaws.com/Minecraft.Download/versions/"
                    + this.minecraftVersion + "/" + this.minecraftVersion + ".json"));
            JSONObject jsonObject = (JSONObject) obj;
            if (this.mainClass == null) {
                this.mainClass = (String) jsonObject.get("mainClass");
            }
            this.minecraftArguments = (String) jsonObject.get("minecraftArguments");
            JSONArray msg = (JSONArray) jsonObject.get("libraries");
            Iterator<JSONObject> iterator = msg.iterator();
            while (iterator.hasNext()) {
                boolean shouldDownload = false;
                JSONObject object = iterator.next();
                String libraryName = (String) object.get("name");
                String[] parts = ((String) object.get("name")).split(":");
                String dir = parts[0].replace(".", "/") + "/" + parts[1] + "/" + parts[2];
                String filename = null;
                if (object.containsKey("rules")) {
                    JSONArray ruless = (JSONArray) object.get("rules");
                    Iterator<JSONObject> itt = ruless.iterator();
                    while (itt.hasNext()) {
                        JSONObject rules = itt.next();
                        if (((String) rules.get("action")).equalsIgnoreCase("allow")) {
                            if (rules.containsKey("os")) {
                                JSONObject rule = (JSONObject) rules.get("os");
                                if (((String) rule.get("name")).equalsIgnoreCase(Utils.getOSName())) {
                                    Pattern pattern = Pattern.compile((String) rule.get("version"));
                                    Matcher matcher = pattern.matcher(System.getProperty("os.version"));
                                    if (matcher.matches()) {
                                        shouldDownload = true;
                                    }
                                }
                            } else {
                                shouldDownload = true;
                            }
                        } else if (((String) rules.get("action")).equalsIgnoreCase("disallow")) {
                            if (rules.containsKey("os")) {
                                JSONObject rule = (JSONObject) rules.get("os");
                                if (((String) rule.get("name")).equalsIgnoreCase(Utils.getOSName())) {
                                    Pattern pattern = Pattern.compile((String) rule.get("version"));
                                    Matcher matcher = pattern.matcher(System.getProperty("os.version"));
                                    if (matcher.matches()) {
                                        shouldDownload = false;
                                    }
                                }
                            }
                        } else {
                            shouldDownload = true;
                        }
                    }
                } else {
                    shouldDownload = true;
                }

                if (shouldDownload) {
                    if (object.containsKey("natives")) {
                        JSONObject nativesObject = (JSONObject) object.get("natives");
                        String nativesName;
                        if (Utils.isWindows()) {
                            nativesName = (String) nativesObject.get("windows");
                        } else if (Utils.isMac()) {
                            nativesName = (String) nativesObject.get("osx");
                        } else {
                            nativesName = (String) nativesObject.get("linux");
                        }
                        filename = parts[1] + "-" + parts[2] + "-" + nativesName + ".jar";
                        if (nativesNeeded == null) {
                            this.nativesNeeded = filename;
                        } else {
                            this.nativesNeeded += "," + filename;
                        }
                    } else {
                        filename = parts[1] + "-" + parts[2] + ".jar";
                        if (librariesNeeded == null) {
                            this.librariesNeeded = filename;
                        } else {
                            this.librariesNeeded += "," + filename;
                        }
                    }
                    String url = "https://s3.amazonaws.com/Minecraft.Download/libraries/" + dir + "/"
                            + filename;
                    File file = new File(App.settings.getLibrariesDir(), filename);
                    downloads.add(new MojangDownloadable(url, file, null, this));
                }
            }

        } catch (ParseException e) {
            App.settings.getConsole().logStackTrace(e);
        }
    }

    if (isServer) {
        downloads.add(new MojangDownloadable(
                "https://s3.amazonaws.com/Minecraft.Download/versions/" + this.minecraftVersion
                        + "/minecraft_server." + this.minecraftVersion + ".jar",
                new File(App.settings.getJarsDir(), "minecraft_server." + this.minecraftVersion + ".jar"), null,
                this));
    } else {
        downloads.add(new MojangDownloadable(
                "https://s3.amazonaws.com/Minecraft.Download/versions/" + this.minecraftVersion + "/"
                        + this.minecraftVersion + ".jar",
                new File(App.settings.getJarsDir(), this.minecraftVersion + ".jar"), null, this));
    }
    return downloads;
}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

protected Document getMenuItem(User user, int key, boolean withParents, boolean complete,
        boolean includePageConfig, boolean withChildren) {

    Document doc;//from w ww . j a v a 2  s . c o m
    Element rootElement;
    doc = XMLTool.createDocument("menuitems");
    rootElement = doc.getDocumentElement();

    Connection con = null;
    PreparedStatement preparedStmt = null;
    ResultSet resultSet = null;
    try {
        con = getConnection();

        preparedStmt = con
                .prepareStatement(getSecurityHandler().appendMenuItemSQL(user, MENU_ITEM_SELECT_BY_KEY));
        preparedStmt.setInt(1, key);
        resultSet = preparedStmt.executeQuery();

        if (!withChildren) {
            if (resultSet.next()) {
                buildMenuItemXML(doc, rootElement, resultSet, -1, complete, includePageConfig, true, true, true,
                        -1);
            }

            // include parents?
            if (withParents) {
                // yep. call getMenuItemDOM recursivly.
                Element menuItemElement = (Element) doc.getDocumentElement().getFirstChild();
                if (menuItemElement.hasAttribute("parent")) {
                    int parentKey = Integer.valueOf(menuItemElement.getAttribute("parent"));
                    while (parentKey >= 0) {
                        // get the parent:
                        doc = getMenuItem(user, parentKey, false, false, false);

                        // move the child inside the parent:
                        rootElement = doc.getDocumentElement();
                        Element parentElement = (Element) rootElement.getFirstChild();
                        if (parentElement != null) {
                            Element menuItemsElement = XMLTool.createElement(doc, parentElement, "menuitems");
                            menuItemsElement.appendChild(doc.importNode(menuItemElement, true));
                            menuItemElement = parentElement;

                            if (menuItemElement.hasAttribute("parent")) {
                                parentKey = Integer.valueOf(menuItemElement.getAttribute("parent"));
                            } else {
                                parentKey = -1;
                            }
                        } else {
                            parentKey = -1;
                        }
                    }
                }
            }
        } else {
            buildMenuItemsXML(user, resultSet, doc, rootElement, -1, -1, complete, includePageConfig, true,
                    true, true);
        }
    } catch (SQLException sqle) {
        VerticalEngineLogger.error(this.getClass(), 30, "SQL error.", sqle);
    } finally {
        close(resultSet);
        close(preparedStmt);
        close(con);
    }

    return doc;

}

From source file:lucee.runtime.config.ConfigWebFactory.java

/**
 * @param configServer/*from   ww w  .  jav a 2s  . co  m*/
 * @param config
 * @param doc
 */
private static void loadCache(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
    boolean hasCS = configServer != null;
    Map<String, CacheConnection> caches = new HashMap<String, CacheConnection>();

    boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManagerImpl.TYPE_CACHE);
    // print.o("LOAD CACHE:"+hasAccess+":"+hasCS);

    Element eCache = getChildByName(doc.getDocumentElement(), "cache");

    // has changes

    String md5 = getMD5(eCache, hasCS ? configServer.getCacheMD5() : "");
    if (md5.equals(config.getCacheMD5()))
        return;
    config.setCacheMD5(md5);

    // default query
    String defaultResource = eCache.getAttribute("default-resource");
    if (hasAccess && !StringUtil.isEmpty(defaultResource)) {
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE, defaultResource);
    } else if (hasCS) {
        if (eCache.hasAttribute("default-resource"))
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE, "");
        else
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE,
                    configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE));
    } else
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE, "");

    // default function
    String defaultUDF = eCache.getAttribute("default-function");
    if (hasAccess && !StringUtil.isEmpty(defaultUDF)) {
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_FUNCTION, defaultUDF);
    } else if (hasCS) {
        if (eCache.hasAttribute("default-function"))
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_FUNCTION, "");
        else
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_FUNCTION,
                    configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_FUNCTION));
    } else
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_FUNCTION, "");

    // default include
    String defaultInclude = eCache.getAttribute("default-include");
    if (hasAccess && !StringUtil.isEmpty(defaultInclude)) {
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_INCLUDE, defaultInclude);
    } else if (hasCS) {
        if (eCache.hasAttribute("default-include"))
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_INCLUDE, "");
        else
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_INCLUDE,
                    configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_INCLUDE));
    } else
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_INCLUDE, "");

    // default query
    String defaultQuery = eCache.getAttribute("default-query");
    if (hasAccess && !StringUtil.isEmpty(defaultQuery)) {
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY, defaultQuery);
    } else if (hasCS) {
        if (eCache.hasAttribute("default-query"))
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY, "");
        else
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY,
                    configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY));
    } else
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY, "");

    // default template
    String defaultTemplate = eCache.getAttribute("default-template");
    if (hasAccess && !StringUtil.isEmpty(defaultTemplate)) {
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE, defaultTemplate);
    } else if (hasCS) {
        if (eCache.hasAttribute("default-template"))
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE, "");
        else
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE,
                    configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE));
    } else
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE, "");

    // default object
    String defaultObject = eCache.getAttribute("default-object");
    if (hasAccess && !StringUtil.isEmpty(defaultObject)) {
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT, defaultObject);
    } else if (hasCS) {
        if (eCache.hasAttribute("default-object"))
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT, "");
        else
            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT,
                    configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT));
    } else
        config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT, "");

    // cache connections
    Element[] eConnections = getChildren(eCache, "connection");

    // if(hasAccess) {
    String name, clazzName;
    CacheConnection cc;
    Class cacheClazz;
    // caches
    if (hasAccess)
        for (int i = 0; i < eConnections.length; i++) {
            Element eConnection = eConnections[i];
            name = eConnection.getAttribute("name");
            clazzName = deRailo(eConnection.getAttribute("class"));
            if (clazzName != null)
                clazzName = clazzName.trim();

            //
            try {
                Struct custom = toStruct(eConnection.getAttribute("custom"));

                // Workaround for old EHCache class defintions
                if (clazzName != null && clazzName.endsWith(".EHCacheLite")) {
                    cacheClazz = EHCache.class;
                    if (!custom.containsKey("distributed"))
                        custom.setEL("distributed", "off");
                    if (!custom.containsKey("asynchronousReplicationIntervalMillis"))
                        custom.setEL("asynchronousReplicationIntervalMillis", "1000");
                    if (!custom.containsKey("maximumChunkSizeBytes"))
                        custom.setEL("maximumChunkSizeBytes", "5000000");

                } else if (clazzName != null && clazzName.endsWith(".extension.io.cache.eh.EHCache"))
                    cacheClazz = EHCache.class;
                else
                    cacheClazz = ClassUtil.loadClass(config.getClassLoader(), clazzName);

                cc = new CacheConnectionImpl(config, name, cacheClazz, custom,
                        Caster.toBooleanValue(eConnection.getAttribute("read-only"), false),
                        Caster.toBooleanValue(eConnection.getAttribute("storage"), false));
                if (!StringUtil.isEmpty(name)) {
                    caches.put(name.toLowerCase(), cc);
                } else
                    SystemOut.print(config.getErrWriter(), "missing cache name");

            } catch (ClassException ce) {
                SystemOut.print(config.getErrWriter(), ExceptionUtil.getStacktrace(ce, true));
            } catch (IOException e) {
                SystemOut.print(config.getErrWriter(), ExceptionUtil.getStacktrace(e, true));
            }
        }
    // }

    // call static init once per driver
    {
        // group by classes
        final Map<Class<?>, List<CacheConnection>> _caches = new HashMap<Class<?>, List<CacheConnection>>();
        {
            Iterator<Entry<String, CacheConnection>> it = caches.entrySet().iterator();
            Entry<String, CacheConnection> entry;
            List<CacheConnection> list;
            while (it.hasNext()) {
                entry = it.next();
                cc = entry.getValue();
                list = _caches.get(cc.getClazz());
                if (list == null) {
                    list = new ArrayList<CacheConnection>();
                    _caches.put(cc.getClazz(), list);
                }
                list.add(cc);
            }
        }
        // call
        Iterator<Entry<Class<?>, List<CacheConnection>>> it = _caches.entrySet().iterator();
        Entry<Class<?>, List<CacheConnection>> entry;
        Class<?> clazz;
        List<CacheConnection> list;
        while (it.hasNext()) {
            entry = it.next();
            list = entry.getValue();
            clazz = entry.getKey();
            try {
                Method m = clazz.getMethod("init",
                        new Class[] { Config.class, String[].class, Struct[].class });
                if (Modifier.isStatic(m.getModifiers()))
                    m.invoke(null, new Object[] { config, _toCacheNames(list), _toArguments(list) });
                else
                    SystemOut.print(config.getErrWriter(),
                            "method [init(Config,String[],Struct[]):void] for class [" + clazz.getName()
                                    + "] is not static");

            } catch (InvocationTargetException e) {
                e.getTargetException().printStackTrace();
            } catch (RuntimeException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                SystemOut.print(config.getErrWriter(),
                        "missing method [public static init(Config,String[],Struct[]):void] for class ["
                                + clazz.getName() + "] ");
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    // Copy Parent caches as readOnly
    if (hasCS) {
        Map<String, CacheConnection> ds = configServer.getCacheConnections();
        Iterator<Entry<String, CacheConnection>> it = ds.entrySet().iterator();
        Entry<String, CacheConnection> entry;
        while (it.hasNext()) {
            entry = it.next();
            cc = entry.getValue();
            if (!caches.containsKey(entry.getKey()))
                caches.put(entry.getKey(), new ServerCacheConnection(configServer, cc));
        }
    }
    config.setCaches(caches);
}

From source file:de.interactive_instruments.ShapeChange.Options.java

/**
 * Parses all transformer configuration aspects available in the given
 * ShapeChangeConfiguration document./*from w w w . j  a  v  a  2 s  .  c  o  m*/
 *
 * @param configurationDocument
 * @throws ShapeChangeAbortException
 *
 */
private Map<String, TransformerConfiguration> parseTransformerConfigurations(Document configurationDocument)
        throws ShapeChangeAbortException {

    Map<String, TransformerConfiguration> trfConfigs = new HashMap<String, TransformerConfiguration>();

    NodeList trfsNl = configurationDocument.getElementsByTagName("transformers");

    for (int i = 0; i < trfsNl.getLength(); i++) {
        Node trfsN = trfsNl.item(i);
        NodeList trfNl = trfsN.getChildNodes();

        // look for all Transformer elements in the "transformers" Node
        for (int j = 0; j < trfNl.getLength(); j++) {
            Node trfN = trfNl.item(j);

            if (trfN.getNodeType() == Node.ELEMENT_NODE) {
                Element trfE = (Element) trfN;

                // parse content of Transformer element

                // get transformer id
                String trfConfigId = trfE.getAttribute("id");

                // get transformer class name
                String trfConfigName = trfE.getAttribute("class");

                // get transformer mode
                ProcessMode trfMode = parseMode(trfE);

                Map<String, String> processParameters = parseParameters(trfE, "ProcessParameter");

                // now look up all ProcessRuleSet elements, if there are
                // any
                Map<String, ProcessRuleSet> processRuleSets = parseRuleSets(trfE, "ProcessRuleSet", false);

                // now look up all ProcessMapEntry elements, if there
                // are any
                List<ProcessMapEntry> processMapEntries = parseProcessMapEntries(trfE, "ProcessMapEntry");

                // parse tagged values, if any are defined
                List<TaggedValueConfigurationEntry> taggedValues = parseTaggedValues(trfE);

                // get the transformer input - can be null, then set it to
                // global input element
                String trfConfigInput;
                if (trfE.hasAttribute("input")) {
                    trfConfigInput = trfE.getAttribute("input");
                } else {
                    trfConfigInput = getInputId();
                }

                if (trfConfigInput.equals(trfConfigId)) {
                    throw new ShapeChangeAbortException(
                            "Attributes input and id are equal in a transformer configuration element (class: "
                                    + trfConfigName + ") which is not allowed.");
                }

                Element advancedProcessConfigurations = parseAdvancedProcessConfigurations(trfE);

                // create transformer config and add it to list
                TransformerConfiguration trfConfig = new TransformerConfiguration(trfConfigId, trfConfigName,
                        trfMode, processParameters, processRuleSets, processMapEntries, taggedValues,
                        trfConfigInput, advancedProcessConfigurations);

                trfConfigs.put(trfConfig.getId(), trfConfig);
            }
        }
    }
    return trfConfigs;

}

From source file:com.paniclauncher.data.Settings.java

/**
 * Loads the Packs for use in the Launcher
 *//*  www .j  a va  2  s  .  co  m*/
private void loadPacks() {
    if (this.packs.size() != 0) {
        this.packs = new ArrayList<Pack>();
    }
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File(configsDir, "packs.xml"));
        document.getDocumentElement().normalize();
        NodeList nodeList = document.getElementsByTagName("pack");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                int id = Integer.parseInt(element.getAttribute("id"));
                String name = element.getAttribute("name");
                boolean logging = Boolean.parseBoolean(element.getAttribute("logging"));
                boolean latestlwjgl = Boolean.parseBoolean(element.getAttribute("latestlwjgl"));
                String[] versions;
                if (element.getAttribute("versions").isEmpty()) {
                    versions = new String[0];
                } else {
                    versions = element.getAttribute("versions").split(",");
                }
                String[] noUpdateVersions;
                if (element.getAttribute("noupdateversions").isEmpty()) {
                    noUpdateVersions = new String[0];
                } else {
                    noUpdateVersions = element.getAttribute("noupdateversions").split(",");
                }
                String[] minecraftVersions;
                if (element.getAttribute("minecraftversions").isEmpty()) {
                    minecraftVersions = new String[0];
                } else {
                    minecraftVersions = element.getAttribute("minecraftversions").split(",");
                }
                String[] devVersions;
                if (element.getAttribute("devversions").isEmpty()) {
                    devVersions = new String[0];
                } else {
                    devVersions = element.getAttribute("devversions").split(",");
                }
                String[] devMinecraftVersions;
                if (element.getAttribute("devminecraftversions").isEmpty()) {
                    devMinecraftVersions = new String[0];
                } else {
                    devMinecraftVersions = element.getAttribute("devminecraftversions").split(",");
                }
                String description = element.getAttribute("description");
                if (element.getAttribute("type").equalsIgnoreCase("private")) {
                    packs.add(new PrivatePack(id, name, logging, latestlwjgl, versions, noUpdateVersions,
                            minecraftVersions, devVersions, devMinecraftVersions, description));
                } else if (element.getAttribute("type").equalsIgnoreCase("semipublic")) {
                    if (element.hasAttribute("code")) {
                        packs.add(new SemiPublicPack(id, name, element.getAttribute("code"), logging,
                                latestlwjgl, versions, noUpdateVersions, minecraftVersions, devVersions,
                                devMinecraftVersions, description));
                    }
                } else {
                    packs.add(new Pack(id, name, logging, latestlwjgl, versions, noUpdateVersions,
                            minecraftVersions, devVersions, devMinecraftVersions, description));
                }
            }
        }
    } catch (SAXException e) {
        this.console.logStackTrace(e);
    } catch (ParserConfigurationException e) {
        this.console.logStackTrace(e);
    } catch (IOException e) {
        this.console.logStackTrace(e);
    }
}

From source file:lucee.runtime.config.XMLConfigWebFactory.java

/**
 * @param configServer//  ww  w  .j ava  2s.com
 * @param config
 * @param doc
 */
private static void loadCache(ConfigServerImpl configServer, ConfigImpl config, Document doc, Log log) {
    boolean hasCS = configServer != null;
    Map<String, CacheConnection> caches = new HashMap<String, CacheConnection>();

    boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManagerImpl.TYPE_CACHE);
    // print.o("LOAD CACHE:"+hasAccess+":"+hasCS);

    Element eCache = getChildByName(doc.getDocumentElement(), "cache");

    // has changes

    String md5 = getMD5(eCache, hasCS ? configServer.getCacheMD5() : "");
    if (md5.equals(config.getCacheMD5()))
        return;
    config.setCacheMD5(md5);

    String[] typeNames = new String[] { "resource", "function", "include", "query", "template", "object",
            "file", "http", "webservice" };
    int[] types = new int[] { ConfigImpl.CACHE_TYPE_RESOURCE, ConfigImpl.CACHE_TYPE_FUNCTION,
            ConfigImpl.CACHE_TYPE_INCLUDE, ConfigImpl.CACHE_TYPE_QUERY, ConfigImpl.CACHE_TYPE_TEMPLATE,
            ConfigImpl.CACHE_TYPE_OBJECT, ConfigImpl.CACHE_TYPE_FILE, ConfigImpl.CACHE_TYPE_HTTP,
            ConfigImpl.CACHE_TYPE_WEBSERVICE };

    // default cache
    for (int i = 0; i < types.length; i++) {
        String def = eCache.getAttribute("default-" + typeNames[i]);
        if (hasAccess && !StringUtil.isEmpty(def)) {
            config.setCacheDefaultConnectionName(types[i], def);
        } else if (hasCS) {
            if (eCache.hasAttribute("default-" + typeNames[i]))
                config.setCacheDefaultConnectionName(types[i], "");
            else
                config.setCacheDefaultConnectionName(types[i],
                        configServer.getCacheDefaultConnectionName(types[i]));
        } else
            config.setCacheDefaultConnectionName(+types[i], "");
    }

    // cache connections
    Element[] eConnections = getChildren(eCache, "connection");

    // if(hasAccess) {
    ClassDefinition cd;
    String name;
    CacheConnection cc;
    //Class cacheClazz;
    // caches
    if (hasAccess)
        for (int i = 0; i < eConnections.length; i++) {
            Element eConnection = eConnections[i];
            name = eConnection.getAttribute("name");
            cd = getClassDefinition(eConnection, "", config.getIdentification());

            try {
                Struct custom = toStruct(eConnection.getAttribute("custom"));

                // Workaround for old EHCache class defintions
                if (cd.getClassName() != null && cd.getClassName().endsWith(".EHCacheLite")) {
                    cd = new ClassDefinitionImpl(EHCache.class);
                    if (!custom.containsKey("distributed"))
                        custom.setEL("distributed", "off");
                    if (!custom.containsKey("asynchronousReplicationIntervalMillis"))
                        custom.setEL("asynchronousReplicationIntervalMillis", "1000");
                    if (!custom.containsKey("maximumChunkSizeBytes"))
                        custom.setEL("maximumChunkSizeBytes", "5000000");

                } else if (cd.getClassName() != null
                        && cd.getClassName().endsWith(".extension.io.cache.eh.EHCache"))
                    cd = new ClassDefinitionImpl(EHCache.class);
                // else cacheClazz = cd.getClazz();

                cc = new CacheConnectionImpl(config, name, cd, custom,
                        Caster.toBooleanValue(eConnection.getAttribute("read-only"), false),
                        Caster.toBooleanValue(eConnection.getAttribute("storage"), false));
                if (!StringUtil.isEmpty(name)) {
                    caches.put(name.toLowerCase(), cc);
                } else
                    SystemOut.print(config.getErrWriter(), "missing cache name");

            } catch (ClassException ce) {
                log.error("Cache", ce);
                //SystemOut.print(config.getErrWriter(), ExceptionUtil.getStacktrace(ce, true));
            } catch (BundleException be) {
                log.error("Cache", be);
                //SystemOut.print(config.getErrWriter(), ExceptionUtil.getStacktrace(be, true));
            } catch (IOException e) {
                log.error("Cache", e);
                //SystemOut.print(config.getErrWriter(), ExceptionUtil.getStacktrace(e, true));
            }
        }
    // }

    // call static init once per driver
    {
        // group by classes
        final Map<ClassDefinition, List<CacheConnection>> _caches = new HashMap<ClassDefinition, List<CacheConnection>>();
        {
            Iterator<Entry<String, CacheConnection>> it = caches.entrySet().iterator();
            Entry<String, CacheConnection> entry;
            List<CacheConnection> list;
            while (it.hasNext()) {
                entry = it.next();
                cc = entry.getValue();
                if (cc == null)
                    continue;// Jira 3196 ?!
                list = _caches.get(cc.getClassDefinition());
                if (list == null) {
                    list = new ArrayList<CacheConnection>();
                    _caches.put(cc.getClassDefinition(), list);
                }
                list.add(cc);
            }
        }
        // call
        Iterator<Entry<ClassDefinition, List<CacheConnection>>> it = _caches.entrySet().iterator();
        Entry<ClassDefinition, List<CacheConnection>> entry;
        List<CacheConnection> list;
        ClassDefinition _cd;
        while (it.hasNext()) {
            entry = it.next();
            list = entry.getValue();
            _cd = entry.getKey();
            try {
                Method m = _cd.getClazz().getMethod("init",
                        new Class[] { Config.class, String[].class, Struct[].class });
                if (Modifier.isStatic(m.getModifiers()))
                    m.invoke(null, new Object[] { config, _toCacheNames(list), _toArguments(list) });
                else
                    SystemOut.print(config.getErrWriter(),
                            "method [init(Config,String[],Struct[]):void] for class [" + _cd.toString()
                                    + "] is not static");

            } catch (InvocationTargetException e) {
                log.error("Cache", e.getTargetException());
                //e.getTargetException().printStackTrace();
            } catch (RuntimeException e) {
                log.error("Cache", e);
                //e.printStackTrace();
            } catch (NoSuchMethodException e) {
                log.error("Cache",
                        "missing method [public static init(Config,String[],Struct[]):void] for class ["
                                + _cd.toString() + "] ");
                //SystemOut.print(config.getErrWriter(), "missing method [public static init(Config,String[],Struct[]):void] for class [" + _cd.toString() + "] ");
            } catch (Throwable e) {
                log.error("Cache", e);
                //e.printStackTrace();
            }
        }
    }

    // Copy Parent caches as readOnly
    if (hasCS) {
        Map<String, CacheConnection> ds = configServer.getCacheConnections();
        Iterator<Entry<String, CacheConnection>> it = ds.entrySet().iterator();
        Entry<String, CacheConnection> entry;
        while (it.hasNext()) {
            entry = it.next();
            cc = entry.getValue();
            if (!caches.containsKey(entry.getKey()))
                caches.put(entry.getKey(), new ServerCacheConnection(configServer, cc));
        }
    }
    config.setCaches(caches);
}

From source file:com.concursive.connect.web.modules.wiki.utils.HTMLToWikiUtils.java

public static void processChildNodes(ArrayList<Node> nodeList, StringBuffer sb, int indentLevel, boolean doText,
        boolean withFormatting, boolean trim, String appendToCRLF, String contextPath, int projectId) {
    Iterator nodeI = nodeList.iterator();
    while (nodeI.hasNext()) {
        Node n = (Node) nodeI.next();
        if (n != null) {
            if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) {
                if (doText) {
                    String value = n.getNodeValue();
                    // Escaped characters
                    value = StringUtils.replace(value, "*", "\\*");
                    value = StringUtils.replace(value, "#", "\\#");
                    value = StringUtils.replace(value, "=", "\\=");
                    value = StringUtils.replace(value, "|", "\\|");
                    value = StringUtils.replace(value, "[", "\\{");
                    value = StringUtils.replace(value, "]", "\\}");
                    if (trim && !nodeI.hasNext()) {
                        // If within a cell, make sure returns include the cell value
                        //              String value = (appendToCRLF.length() > 0 ? StringUtils.replace(n.getNodeValue(), CRLF, CRLF + appendToCRLF) : n.getNodeValue());
                        LOG.trace(" <text:trim>");
                        // Output the value, trim is required
                        sb.append(StringUtils.fromHtmlValue(value.trim()));
                    } else {
                        // If within a cell, make sure returns include the cell value
                        if (appendToCRLF.length() > 0
                                && (hasParentNodeType(n, "th") || hasParentNodeType(n, "td"))
                                && value.trim().length() == 0) {
                            // This is an empty value... check to see if the previous line has content or not before appending a new line
                        } else {
                            LOG.trace(" <text>");
                            sb.append(StringUtils.fromHtmlValue((appendToCRLF.length() > 0
                                    ? StringUtils.replace(value, CRLF, CRLF + appendToCRLF)
                                    : value)));
                        }/*  www .  j ava  2 s . com*/
                    }
                }
            } else if (n.getNodeType() == Node.ELEMENT_NODE) {
                Element element = ((Element) n);
                String tag = element.getTagName();
                LOG.trace(tag);
                if ("h1".equals(tag)) {
                    startOnNewLine(sb, appendToCRLF);
                    sb.append("= ").append(StringUtils.fromHtmlValue(element.getTextContent().trim()))
                            .append(" =").append(CRLF + appendToCRLF);
                } else if ("h2".equals(tag)) {
                    startOnNewLine(sb, appendToCRLF);
                    sb.append("== ").append(StringUtils.fromHtmlValue(element.getTextContent().trim()))
                            .append(" ==").append(CRLF + appendToCRLF);
                } else if ("h3".equals(tag)) {
                    startOnNewLine(sb, appendToCRLF);
                    sb.append("=== ").append(StringUtils.fromHtmlValue(element.getTextContent().trim()))
                            .append(" ===").append(CRLF + appendToCRLF);
                } else if ("h4".equals(tag)) {
                    startOnNewLine(sb, appendToCRLF);
                    sb.append("==== ").append(StringUtils.fromHtmlValue(element.getTextContent().trim()))
                            .append(" ====").append(CRLF + appendToCRLF);
                } else if ("h5".equals(tag)) {
                    startOnNewLine(sb, appendToCRLF);
                    sb.append("===== ").append(StringUtils.fromHtmlValue(element.getTextContent().trim()))
                            .append(" =====").append(CRLF + appendToCRLF);
                } else if ("h6".equals(tag)) {
                    startOnNewLine(sb, appendToCRLF);
                    sb.append("====== ").append(StringUtils.fromHtmlValue(element.getTextContent().trim()))
                            .append(" ======").append(CRLF + appendToCRLF);
                } else if ("p".equals(tag) || "div".equals(tag)) {
                    if (n.getChildNodes().getLength() > 0
                            && (hasTextContent(n) || hasImageNodes(n.getChildNodes()))) {
                        // If this contains a Table, UL, OL, or object skip everything else to get there
                        ArrayList<Node> subNodes = new ArrayList<Node>();
                        getNodes(n.getChildNodes(), subNodes, new String[] { "table", "ul", "ol", "object" },
                                false);
                        if (subNodes.size() > 0) {
                            LOG.trace("  nonTextNodes - yes");
                            processChildNodes(subNodes, sb, indentLevel, true, true, false, appendToCRLF,
                                    contextPath, projectId);
                        } else {
                            LOG.trace("  nonTextNodes - no");
                            startOnNewLine(sb, appendToCRLF);
                            processChildNodes(getNodeList(n), sb, indentLevel, true, true, false, appendToCRLF,
                                    contextPath, projectId);
                        }
                    }
                } else if ("strong".equals(tag) || "b".equals(tag)) {
                    if (n.getChildNodes().getLength() > 0) {
                        if ("".equals(StringUtils.fromHtmlValue(n.getTextContent()).trim())) {
                            processChildNodes(getNodeList(n), sb, indentLevel, true, false, false, appendToCRLF,
                                    contextPath, projectId);
                        } else {
                            if (hasNonTextNodes(n.getChildNodes())) {
                                processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, false,
                                        appendToCRLF, contextPath, projectId);
                            } else {
                                if (withFormatting) {
                                    sb.append("'''");
                                }
                                processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, false,
                                        appendToCRLF, contextPath, projectId);
                                if (withFormatting) {
                                    sb.append("'''");
                                }
                            }
                        }
                    }
                } else if ("em".equals(tag) || "i".equals(tag)) {
                    if (n.getChildNodes().getLength() > 0) {
                        if ("".equals(StringUtils.fromHtmlValue(n.getTextContent()).trim())) {
                            processChildNodes(getNodeList(n), sb, indentLevel, true, false, trim, appendToCRLF,
                                    contextPath, projectId);
                        } else {
                            if (hasNonTextNodes(n.getChildNodes())) {
                                processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, trim,
                                        appendToCRLF, contextPath, projectId);
                            } else {
                                if (withFormatting) {
                                    sb.append("''");
                                }
                                processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, trim,
                                        appendToCRLF, contextPath, projectId);
                                if (withFormatting) {
                                    sb.append("''");
                                }
                            }
                        }
                    }
                } else if ("span".equals(tag)) {
                    if (n.getChildNodes().getLength() > 0
                            && !"".equals(StringUtils.fromHtmlValue(n.getTextContent()).trim())) {
                        if (element.hasAttribute("style")) {
                            String value = element.getAttribute("style");
                            if (withFormatting) {
                                if (value.contains("underline")) {
                                    sb.append("__");
                                }
                                if (value.contains("line-through")) {
                                    sb.append("<s>");
                                }
                                if (value.contains("bold")) {
                                    sb.append("'''");
                                }
                                if (value.contains("italic")) {
                                    sb.append("''");
                                }
                            }
                            processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, trim,
                                    appendToCRLF, contextPath, projectId);
                            if (withFormatting) {
                                if (value.contains("italic")) {
                                    sb.append("''");
                                }
                                if (value.contains("bold")) {
                                    sb.append("'''");
                                }
                                if (value.contains("line-through")) {
                                    sb.append("</s>");
                                }
                                if (value.contains("underline")) {
                                    sb.append("__");
                                }
                            }
                        } else {
                            processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, trim,
                                    appendToCRLF, contextPath, projectId);
                        }
                    }
                } else if ("ul".equals(tag) || "ol".equals(tag) || "dl".equals(tag)) {
                    ++indentLevel;
                    if (indentLevel == 1) {
                        if (appendToCRLF.length() == 0) {
                            startOnNewLine(sb, appendToCRLF);
                        } else {
                            // Something\n
                            // !
                            // !* Item 1
                            // !* Item 2
                            if (!sb.toString().endsWith("|") && !sb.toString().endsWith(CRLF + appendToCRLF)) {
                                LOG.trace("ul newline CRLF");
                                sb.append(CRLF + appendToCRLF);
                            }
                        }
                    }
                    if (indentLevel > 1 && !sb.toString().endsWith(CRLF + appendToCRLF)) {
                        LOG.trace("ul indent CRLF");
                        sb.append(CRLF + appendToCRLF);
                    }
                    processChildNodes(getNodeList(n), sb, indentLevel, false, false, trim, appendToCRLF,
                            contextPath, projectId);
                    --indentLevel;
                } else if ("li".equals(tag)) {
                    String parentTag = ((Element) element.getParentNode()).getTagName();
                    for (int counter = 0; counter < indentLevel; counter++) {
                        if ("ul".equals(parentTag)) {
                            sb.append("*");
                        } else if ("ol".equals(parentTag)) {
                            sb.append("#");
                        }
                    }
                    sb.append(" ");
                    processChildNodes(getNodeList(n), sb, indentLevel, true, false, true, appendToCRLF,
                            contextPath, projectId);
                    if (!sb.toString().endsWith(CRLF + appendToCRLF)) {
                        LOG.trace("li CRLF");
                        sb.append(CRLF + appendToCRLF);
                    }
                } else if ("dt".equals(tag) || "dd".equals(tag)) {
                    processChildNodes(getNodeList(n), sb, indentLevel, true, false, trim, appendToCRLF,
                            contextPath, projectId);
                    if (!sb.toString().endsWith(CRLF + appendToCRLF)) {
                        LOG.trace("dt CRLF");
                        sb.append(CRLF + appendToCRLF);
                    }
                } else if ("pre".equals(tag)) {
                    startOnNewLine(sb, appendToCRLF);
                    sb.append("<pre>");
                    processChildNodes(getNodeList(n), sb, indentLevel, true, true, trim, appendToCRLF,
                            contextPath, projectId);
                    sb.append("</pre>");
                    if (nodeI.hasNext()) {
                        sb.append(CRLF + appendToCRLF);
                        sb.append(CRLF + appendToCRLF);
                    }
                } else if ("code".equals(tag)) {
                    startOnNewLine(sb, appendToCRLF);
                    sb.append("<code>");
                    processChildNodes(getNodeList(n), sb, indentLevel, true, true, trim, appendToCRLF,
                            contextPath, projectId);
                    sb.append("</code>");
                    if (nodeI.hasNext()) {
                        sb.append(CRLF + appendToCRLF);
                        sb.append(CRLF + appendToCRLF);
                    }
                } else if ("br".equals(tag)) {
                    LOG.trace("br CRLF");
                    sb.append(CRLF + appendToCRLF);
                } else if ("table".equals(tag)) {
                    // Always start a table on a new line
                    startOnNewLine(sb, appendToCRLF);
                    processTable(n.getChildNodes(), sb, 0, false, false, contextPath, projectId, 0);
                    //if (nodeI.hasNext()) {
                    //  sb.append(CRLF);
                    //}
                } else if ("form".equals(tag)) {
                    // Always start a form on a new line
                    startOnNewLine(sb, appendToCRLF);
                    CustomForm form = processForm(n);
                    convertFormToWiki(form, sb);
                } else if ("a".equals(tag)) {
                    // Determine if the link is around text or around an image
                    if (n.getChildNodes().getLength() > 0 && hasImageNodes(n.getChildNodes())) {
                        // The link is around an image
                        LOG.debug("Processing link as an image");
                        // Get the img tag and pass to processImage...
                        ArrayList<Node> subNodes = new ArrayList<Node>();
                        getNodes(n.getChildNodes(), subNodes, new String[] { "img" }, false);
                        processImage(sb, subNodes.get(0), (Element) subNodes.get(0), appendToCRLF, contextPath,
                                projectId);
                    } else {
                        // The link is around text
                        processLink(sb, element, appendToCRLF, contextPath, projectId);
                    }
                } else if ("img".equals(tag)) {
                    processImage(sb, n, element, appendToCRLF, contextPath, projectId);
                } else if ("object".equals(tag)) {
                    startOnNewLine(sb, appendToCRLF);
                    processVideo(sb, n, element, appendToCRLF, contextPath);
                } else {
                    processChildNodes(getNodeList(n), sb, indentLevel, false, true, trim, appendToCRLF,
                            contextPath, projectId);
                }
            }
        }
    }
}