Example usage for org.dom4j Element attributeValue

List of usage examples for org.dom4j Element attributeValue

Introduction

In this page you can find the example usage for org.dom4j Element attributeValue.

Prototype

String attributeValue(QName qName);

Source Link

Document

This returns the attribute value for the attribute with the given fully qualified name or null if there is no such attribute or the empty string if the attribute value is empty.

Usage

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

private static IQ getNodeSubscriptions(PubSubService service, IQ iq, Element affiliationsElement) {
    String nodeID = affiliationsElement.attributeValue("node");
    if (nodeID == null) {
        // NodeID was not provided. Return bad-request error.
        return createErrorPacket(iq, PacketError.Condition.bad_request, null);
    }/*w  ww . jav  a 2s . c om*/
    Node node = service.getNode(nodeID);
    if (node == null) {
        // Node does not exist. Return item-not-found error.
        return createErrorPacket(iq, PacketError.Condition.item_not_found, null);
    }
    if (!node.isAdmin(iq.getFrom())) {
        // Requesting entity is prohibited from getting affiliates list. Return forbidden error.
        return createErrorPacket(iq, PacketError.Condition.forbidden, null);
    }

    // Ask the node to send the list of subscriptions to the owner
    node.sendSubscriptions(iq);
    return createSuccessPacket(iq);
}

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

private static IQ modifyNodeSubscriptions(PubSubService service, IQ iq, Element entitiesElement) {
    String nodeID = entitiesElement.attributeValue("node");
    if (nodeID == null) {
        // NodeID was not provided. Return bad-request error.
        return createErrorPacket(iq, PacketError.Condition.bad_request, null);
    }//from w w w  .j a v  a2 s. c  o  m
    Node node = service.getNode(nodeID);
    if (node == null) {
        // Node does not exist. Return item-not-found error.
        return createErrorPacket(iq, PacketError.Condition.item_not_found, null);
    }
    if (!node.isAdmin(iq.getFrom())) {
        // Requesting entity is prohibited from getting affiliates list. Return forbidden error.
        return createErrorPacket(iq, PacketError.Condition.forbidden, null);
    }

    IQ reply = IQ.createResultIQ(iq);

    // Process modifications or creations of affiliations and subscriptions.
    for (Iterator it = entitiesElement.elementIterator("subscription"); it.hasNext();) {
        Element entity = (Element) it.next();
        JID subscriber = new JID(entity.attributeValue("jid"));
        // TODO Assumed that the owner of the subscription is the bare JID of the subscription JID. Waiting StPeter answer for explicit field.
        JID owner = new JID(subscriber.getNode(), subscriber.getDomain(), null, true);
        String subStatus = entity.attributeValue("subscription");
        String subID = entity.attributeValue("subid");
        // Process subscriptions changes
        // Get current subscription (if any)
        NodeSubscription subscription = null;
        if (node.isMultipleSubscriptionsEnabled()) {
            if (subID != null) {
                subscription = node.getSubscription(subID);
            }
        } else {
            subscription = node.getSubscription(subscriber);
        }
        if ("none".equals(subStatus) && subscription != null) {
            // Owner is cancelling an existing subscription
            node.cancelSubscription(subscription);
        } else if ("subscribed".equals(subStatus)) {
            if (subscription != null) {
                // Owner is approving a subscription (i.e. making active)
                node.approveSubscription(subscription, true);
            } else {
                // Owner is creating a subscription for an entity to the node
                node.createSubscription(null, owner, subscriber, false, null);
            }
        }
    }
    return reply;
}

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

private static IQ getNodeAffiliations(PubSubService service, IQ iq, Element affiliationsElement) {
    String nodeID = affiliationsElement.attributeValue("node");
    if (nodeID == null) {
        // NodeID was not provided. Return bad-request error.
        return createErrorPacket(iq, PacketError.Condition.bad_request, null);
    }/*from   w w  w  . ja  va  2s  .c om*/
    Node node = service.getNode(nodeID);
    if (node == null) {
        // Node does not exist. Return item-not-found error.
        return createErrorPacket(iq, PacketError.Condition.item_not_found, null);
    }
    if (!node.isAdmin(iq.getFrom())) {
        // Requesting entity is prohibited from getting affiliates list. Return forbidden error.
        return createErrorPacket(iq, PacketError.Condition.forbidden, null);
    }

    // Ask the node to send the list of affiliations to the owner
    //node.sendAffiliations(iq);
    return createSuccessPacket(iq);
}

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

private static IQ modifyNodeAffiliations(PubSubService service, IQ iq, Element entitiesElement) {
    String nodeID = entitiesElement.attributeValue("node");
    if (nodeID == null) {
        // NodeID was not provided. Return bad-request error.
        return createErrorPacket(iq, PacketError.Condition.bad_request, null);
    }//from   w  ww.j  ava  2 s .  c om
    Node node = service.getNode(nodeID);
    if (node == null) {
        // Node does not exist. Return item-not-found error.
        return createErrorPacket(iq, PacketError.Condition.item_not_found, null);
    }
    if (!node.isAdmin(iq.getFrom())) {
        // Requesting entity is prohibited from getting affiliates list. Return forbidden error.
        return createErrorPacket(iq, PacketError.Condition.forbidden, null);
    }

    IQ reply = IQ.createResultIQ(iq);
    Collection<JID> invalidAffiliates = new ArrayList<JID>();

    // Process modifications or creations of affiliations
    for (Iterator it = entitiesElement.elementIterator("affiliation"); it.hasNext();) {
        Element affiliation = (Element) it.next();
        JID owner = new JID(affiliation.attributeValue("jid"));
        String newAffiliation = affiliation.attributeValue("affiliation");
        // Get current affiliation of this user (if any)
        NodeAffiliate affiliate = node.getAffiliate(owner);

        // Check that we are not removing the only owner of the node
        if (affiliate != null && !affiliate.getAffiliation().name().equals(newAffiliation)) {
            // Trying to modify an existing affiliation
            if (affiliate.getAffiliation() == NodeAffiliate.Affiliation.owner && node.getOwners().size() == 1) {
                // Trying to remove the unique owner of the node. Include in error answer.
                invalidAffiliates.add(owner);
                continue;
            }
        }

        // Owner is setting affiliations for new entities or modifying
        // existing affiliations
        if ("owner".equals(newAffiliation)) {
            node.addOwner(owner);
        } else if ("publisher".equals(newAffiliation)) {
            node.addPublisher(owner);
        } else if ("none".equals(newAffiliation)) {
            node.addNoneAffiliation(owner);
        } else {
            node.addOutcast(owner);
        }
    }

    // Process invalid entities that tried to remove node owners. Send original affiliation
    // of the invalid entities.
    if (!invalidAffiliates.isEmpty()) {
        reply.setError(PacketError.Condition.not_acceptable);
        Element child = reply.setChildElement("pubsub", "http://jabber.org/protocol/pubsub#owner");
        Element entities = child.addElement("affiliations");
        if (!node.isRootCollectionNode()) {
            entities.addAttribute("node", node.getNodeID());
        }
        for (JID affiliateJID : invalidAffiliates) {
            NodeAffiliate affiliate = node.getAffiliate(affiliateJID);
            Element entity = entities.addElement("affiliation");
            entity.addAttribute("jid", affiliate.getJID().toString());
            entity.addAttribute("affiliation", affiliate.getAffiliation().name());
        }
    }
    return reply;
}

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

/**
 * Returns the data form included in the configure element sent by the node owner or
 * <tt>null</tt> if none was included or access model was defined. If the
 * owner just wants to set the access model to use for the node and optionally set the
 * list of roster groups (i.e. contacts present in the node owner roster in the
 * specified groups are allowed to access the node) allowed to access the node then
 * instead of including a data form the owner can just specify the "access" attribute
 * of the configure element and optionally include a list of group elements. In this case,
 * the method will create a data form including the specified data. This is a nice way
 * to accept both ways to configure a node but always returning a data form.
 *
 * @param configureElement the configure element sent by the owner.
 * @return the data form included in the configure element sent by the node owner or
 *         <tt>null</tt> if none was included or access model was defined.
 *//*from www  .  j  av  a 2s. co  m*/
private static DataForm getSentConfigurationForm(Element configureElement) {
    DataForm completedForm = null;
    FormField formField;
    Element formElement = configureElement.element(QName.get("x", "jabber:x:data"));
    if (formElement != null) {
        completedForm = new DataForm(formElement);
    }
    String accessModel = configureElement.attributeValue("access");
    if (accessModel != null) {
        if (completedForm == null) {
            // Create a form (i.e. simulate that the user sent a form with roster groups)
            completedForm = new DataForm(DataForm.Type.submit);
            // Add the hidden field indicating that this is a node config form
            formField = completedForm.addField();
            formField.setVariable("FORM_TYPE");
            formField.setType(FormField.Type.hidden);
            formField.addValue("http://jabber.org/protocol/pubsub#node_config");
        }
        if (completedForm.getField("pubsub#access_model") == null) {
            // Add the field that will specify the access model of the node
            formField = completedForm.addField();
            formField.setVariable("pubsub#access_model");
            formField.addValue(accessModel);
        } else {
            Log.debug("PubSubEngine: Owner sent access model in data form and as attribute: "
                    + configureElement.asXML());
        }
        // Check if a list of groups was specified
        List groups = configureElement.elements("group");
        if (!groups.isEmpty()) {
            // Add the field that will contain the specified groups
            formField = completedForm.addField();
            formField.setVariable("pubsub#roster_groups_allowed");
            // Add each group as a value of the groups field
            for (Iterator it = groups.iterator(); it.hasNext();) {
                formField.addValue(((Element) it.next()).getTextTrim());
            }
        }
    }
    return completedForm;
}

From source file:com.ah.be.common.NmsUtil.java

public static List<USBModemProfile> getUSBModemInfo() {
    List<USBModemProfile> usbInfos = new ArrayList<>();

    try {/*from ww w  . j a  v  a 2  s .  c o  m*/
        String cfgPath = AhDirTools.getConstantConfigDir() + "hiveos_usb_modem_config.xml";
        Document usbDoc = CLICommonFunc.readXml(cfgPath);
        List<?> nodeList = usbDoc.selectNodes("/hiveos-modem-support-list/modems/modem");
        if (nodeList != null) {
            for (Object node : nodeList) {
                Element eleObj = (Element) node;

                USBModemProfile usbProfile = new USBModemProfile();
                usbProfile.setModemName(eleObj.attributeValue("id"));

                Node disNode = eleObj.selectSingleNode("display");
                if (disNode != null) {
                    usbProfile.setDisplayName(((Element) disNode).attributeValue("name"));
                }

                Node apnNode = eleObj.selectSingleNode("connect/apn");
                if (apnNode != null) {
                    usbProfile.setApn(((Element) apnNode).attributeValue("value"));
                }

                Node dialstringNode = eleObj.selectSingleNode("connect/dialstring");
                if (dialstringNode != null) {
                    usbProfile.setDialupNum(((Element) dialstringNode).attributeValue("value"));
                }

                Node usernameNode = eleObj.selectSingleNode("connect/user-auth/username");
                if (usernameNode != null) {
                    usbProfile.setUserId(((Element) usernameNode).attributeValue("value"));
                }

                Node passwordNode = eleObj.selectSingleNode("connect/user-auth/password");
                if (passwordNode != null) {
                    usbProfile.setPassword(((Element) passwordNode).attributeValue("value"));
                }

                Node versionNode = eleObj.selectSingleNode("hiveos-version");
                if (versionNode != null) {
                    usbProfile.setOsVersion(((Element) versionNode).attributeValue("min") + ".0");
                }

                usbInfos.add(usbProfile);
            }

            //add for BR200_LTE
            USBModemProfile usb8 = new USBModemProfile();
            usb8.setDisplayName("Verizon Embedded LTE");
            usb8.setModemName("novatel_E362");
            usb8.setOsVersion("6.0.1.0");
            usb8.setCellularMode(USBModemProfile.CELLULAR_MODE_AUTO);
            usbInfos.add(usb8);
        }
    } catch (Throwable t) {
        log.error("Init USB modem failed.", t);
    }

    return usbInfos;
}

From source file:com.ah.be.ls.stat.StatManager.java

private static List<StatConfig> readStatConfig() {
    if (stats != null && !stats.isEmpty()) {
        return stats;
    }/* w w w .ja va2  s . c  o  m*/
    stats = new ArrayList<StatConfig>();
    // read from stat-config.xml
    SAXReader reader = new SAXReader();
    File ff = new File(System.getenv("HM_ROOT") + "/resources/stat-config.xml");
    if (!ff.exists()) {
        // for test
        ff = new File("stat-config.xml");
    }
    try {
        Document doc = reader.read(ff);

        Element roota = doc.getRootElement();
        log.info("StatManager", "roota..nodcount=" + roota.nodeCount());

        Iterator<?> iters = roota.elementIterator("feature");
        while (iters.hasNext()) {
            StatConfig stat = new StatConfig();
            Element foo = (Element) iters.next();
            if (foo.attribute("ignore") != null) {
                continue;
            }
            stat.setFeatureId(Integer.valueOf(foo.attributeValue("id")));
            stat.setFeatureName(foo.attributeValue("name"));

            Element e2 = foo.element("bo-class");
            Element e4 = foo.element("search-rule");
            stat.setBoClassName(e2.attributeValue("name"));
            stat.setSearchRule(e4.attributeValue("value"));
            stat.setSearchType(e4.attributeValue("type"));

            stats.add(stat);
        }

        return stats;
    } catch (ClassNotFoundException e) {
        log.error("StatManager", "readStatConfig: ClassNotFoundException", e);
    } catch (Exception e) {
        log.error("StatManager", "readStatConfig: Exception", e);
    }

    return null;
}

From source file:com.ah.be.parameter.BeParaModuleDefImpl.java

private void changeOsVersionFile() {
    String fingerprints = ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME;
    String fingerprintsChg = ImportTextFileAction.OS_VERSION_FILE_PATH
            + ImportTextFileAction.OS_VERSION_FILE_NAME_CHG;
    FileWriter fWriter = null;//from   w ww .  ja va 2s  . c  o  m
    try {
        if (new File(fingerprints).exists() && new File(fingerprintsChg).exists()) {
            List<String> lines = NmsUtil.readFileByLines(fingerprints);
            List<String> replaceOsName = new ArrayList<>();
            List<String> replaceOption55 = new ArrayList<>();
            String preHmVer = NmsUtil.getHiveOSVersion(NmsUtil
                    .getVersionInfo(BeAdminCentOSTools.ahBackupdir + File.separatorChar + "hivemanager.ver"));

            // parse os_dhcp_fingerprints_changes.xml
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(fingerprintsChg));
            Element root = document.getRootElement();
            List<?> fingerprintElems = root.elements();
            for (Object obj : fingerprintElems) {
                Element fingerprintElem = (Element) obj;
                String osName = fingerprintElem.attributeValue("osname");
                for (Iterator<?> iterator = fingerprintElem.elementIterator(); iterator.hasNext();) {
                    Element option55Elem = (Element) iterator.next();
                    String node_option55_text = option55Elem.getText();
                    Attribute version = option55Elem.attribute("version");
                    String version_text = version.getText();
                    if (NmsUtil.compareSoftwareVersion(preHmVer, version_text) <= 0) {
                        if (!replaceOption55.contains(node_option55_text)) {
                            replaceOsName.add(osName);
                            replaceOption55.add(node_option55_text);
                        }
                    }
                }
            }

            if (replaceOption55.isEmpty()) {
                log.debug("No need to modify os_dhcp_fingerprints.txt.");
                FileUtils.deleteQuietly(new File(fingerprintsChg));
                return;
            }

            for (String option55 : replaceOption55) {
                int size = lines.size();
                boolean remove = false;
                for (int i = size - 1; i >= 0; i--) {
                    if (remove) {
                        lines.remove(i);
                        remove = false;
                    } else {
                        if (option55.equals(lines.get(i))) {
                            if (i < size - 1 && i > 0
                                    && lines.get(i - 1).startsWith(ImportTextFileAction.OS_STR)
                                    && lines.get(i + 1).equals(ImportTextFileAction.END_STR)) {
                                lines.remove(i + 1);
                                lines.remove(i);
                                remove = true;
                            } else {
                                lines.remove(i);
                            }
                        }
                    }
                }
            }

            //insert
            for (int i = 0; i < replaceOption55.size(); i++) {
                String option55 = replaceOption55.get(i);
                String osName = ImportTextFileAction.OS_STR + replaceOsName.get(i);

                if (!lines.contains(option55)) {
                    if (lines.contains(osName)) {
                        List<String> temp = lines.subList(lines.indexOf(osName), lines.size());
                        int index = lines.indexOf(osName) + temp.indexOf(ImportTextFileAction.END_STR);
                        lines.add(index, option55);

                    } else {
                        lines.add(osName);
                        lines.add(option55);
                        lines.add(ImportTextFileAction.END_STR);
                    }
                }
            }

            fWriter = new FileWriter(fingerprints, false);
            for (String line : lines) {
                if (line != null && line.startsWith(ImportTextFileAction.VERSION_STR)) {
                    String version = line.substring(line.indexOf(ImportTextFileAction.VERSION_STR)
                            + ImportTextFileAction.VERSION_STR.length());
                    BigDecimal b1 = new BigDecimal(version);
                    BigDecimal b2 = new BigDecimal("0.1");
                    float fVer = b1.add(b2).floatValue();
                    String versionStr = ImportTextFileAction.VERSION_STR + String.valueOf(fVer) + "\r\n";
                    fWriter.write(versionStr);
                } else {
                    fWriter.write(line + "\r\n");
                }
            }
            fWriter.close();

            //compress file
            String strCmd = "";
            StringBuffer strCmdBuf = new StringBuffer();
            strCmdBuf.append("tar zcvf ");
            strCmdBuf.append(
                    ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME_TAR);
            strCmdBuf.append(" -C ");
            strCmdBuf.append(ImportTextFileAction.OS_VERSION_FILE_PATH);
            strCmdBuf.append(" " + ImportTextFileAction.OS_VERSION_FILE_NAME);
            strCmd = strCmdBuf.toString();
            boolean compressResult = BeAdminCentOSTools.exeSysCmd(strCmd);
            if (!compressResult) {
                log.error("compress os_dhcp_fingerprints.txt error.");
                return;
            }

            FileUtils.deleteQuietly(new File(fingerprintsChg));
        } else {
            if (new File(fingerprintsChg).exists()) {
                FileUtils.deleteQuietly(new File(fingerprintsChg));
            }
        }
    } catch (Exception e) {
        setDebugMessage("change OsVersionFile error: ", e);
    } finally {
        if (fWriter != null) {
            try {
                fWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:com.ah.be.parameter.BeParaModuleDefImpl.java

public void insertDefaultCustomReportField() {
    try {//w  w w . jav a 2s .co  m
        long rowCount = QueryUtil.findRowCount(AhCustomReportField.class, null);

        if (rowCount > 0) {
            return;
        }

        List<AhCustomReportField> reportFields = new ArrayList<>();

        SAXReader reader = new SAXReader();
        String docName = AhDirTools.getHmRoot() + "resources" + File.separator + "customReport" + File.separator
                + "custom_report_table.xml";
        Document doc = reader.read(new File(docName));
        Element root = doc.getRootElement();
        List<?> rootLst = root.elements();

        for (Object obj : rootLst) {
            List<?> rowlst = ((Element) obj).elements();
            AhCustomReportField reportField = new AhCustomReportField();
            for (int j = 0; j < rowlst.size(); j++) {
                Element elm = (Element) rowlst.get(j);
                //               String name = elm.attributeValue("name");
                String value = elm.attributeValue("value");
                if (j == 0) {
                    reportField.setId(Long.parseLong(value));
                } else if (j == 1) {
                    reportField.setType(Integer.parseInt(value));
                } else if (j == 2) {
                    reportField.setDetailType(Integer.parseInt(value));
                } else if (j == 3) {
                    reportField.setTableName(value);
                } else if (j == 4) {
                    reportField.setTableField(value);
                } else if (j == 5) {
                    reportField.setFieldString(value);
                } else if (j == 6) {
                    reportField.setStrUnit(value);
                } else if (j == 7) {
                    reportField.setDescription(value);
                }
            }
            reportFields.add(reportField);
        }

        root.clearContent();
        doc.clearContent();

        QueryUtil.bulkCreateBos(reportFields);
    } catch (Exception e) {
        setDebugMessage("insert default custom report field: ", e);
    }
}

From source file:com.ah.be.performance.db.TablePartitionProcessor.java

private void init() {
    try {/* w w w. ja  v  a  2  s  . co m*/
        File f = new File(TABLE_PARTITION_CONF_FILE);
        SAXReader reader = new SAXReader();
        Document doc = reader.read(f);
        Element root = doc.getRootElement();
        Element cata = null;

        int catalog = 1;
        for (Iterator<?> i = root.elementIterator(); i.hasNext();) {
            //for catalog
            cata = (Element) i.next();
            String enable = cata.elementText("enable");
            if (enable != null && enable.equalsIgnoreCase("false"))
                continue;
            int default_maxtime = Integer.parseInt(cata.elementTextTrim("default_maxtime"));
            int default_interval = Integer.parseInt(cata.elementTextTrim("default_interval"));
            int table_partition_number = Integer.parseInt(cata.elementTextTrim("table_partition_number"));
            int default_max_record = Integer.parseInt(cata.elementTextTrim("default_max_record"));
            int default_max_record_per_partition = Integer
                    .parseInt(cata.elementTextTrim("default_max_record_per_partition"));
            int maxtime_policy = Integer.parseInt(cata.elementTextTrim("maxtime_policy"));
            int interval_policy = Integer.parseInt(cata.elementTextTrim("interval_policy"));
            int max_record_policy = Integer.parseInt(cata.elementTextTrim("max_record_policy"));

            addTableCatalogInfo(catalog, default_maxtime, default_interval, table_partition_number,
                    default_max_record, default_max_record_per_partition, maxtime_policy, interval_policy,
                    max_record_policy);

            List<?> tableElements = cata.elements("table");
            //for table in catalog
            for (int j = 0; j < tableElements.size(); j++) {
                Element table = (Element) tableElements.get(j);
                String tableName = table.attributeValue("name");
                String schemaName = table.elementTextTrim("schemaname");
                String timeField = table.elementTextTrim("timefield");
                addTableInfo(schemaName, tableName, timeField, catalog);
            }

            catalog++;
        }
    } catch (Exception e) {
        BeLogTools.error(HmLogConst.M_PERFORMANCE_TABLEPARTITION, "Fail to init table partition configure file",
                e);
    }
}