Example usage for org.w3c.dom Node hasAttributes

List of usage examples for org.w3c.dom Node hasAttributes

Introduction

In this page you can find the example usage for org.w3c.dom Node hasAttributes.

Prototype

public boolean hasAttributes();

Source Link

Document

Returns whether this node (if it is an element) has any attributes.

Usage

From source file:de.elbe5.base.data.XmlData.java

public Map<String, String> getAttributes(Node node) {
    Map<String, String> map = new HashMap<>();
    if (node.hasAttributes()) {
        NamedNodeMap attrMap = node.getAttributes();
        for (int i = 0; i < attrMap.getLength(); i++) {
            Node attr = attrMap.item(i);
            map.put(attr.getNodeName(), attr.getNodeValue());
        }//from   w  w w  .j  a  v  a2s . c  o  m
    }
    return map;
}

From source file:de.elbe5.base.data.XmlData.java

public LocalDateTime getDateAttribute(Node node, String key) {
    LocalDateTime result = null;//from  w  ww. ja v  a 2  s .c  om
    if (node.hasAttributes()) {
        NamedNodeMap attrMap = node.getAttributes();
        Node attr = attrMap.getNamedItem(key);
        if (attr != null) {
            try {
                result = LocalDateTime.parse(attr.getNodeValue(), datetimeFormatter);
            } catch (Exception ignored) {
            }
        }
    }
    return result;
}

From source file:controllerTas.config.xml.TasControllerConfigXmlParser.java

private Object parseElementNode(Node element) throws NoSuchMethodException, InvocationTargetException,
        IllegalAccessException, ClassNotFoundException, InstantiationException {

    Class clazz = Class.forName(packageName + element.getNodeName());
    Object newInstance = clazz.newInstance();
    if (element.hasAttributes()) {
        for (int k = 0; k < element.getAttributes().getLength(); k++) {
            Node attribute = element.getAttributes().item(k);
            String nodeName = attribute.getNodeName();
            String param = attribute.getNodeValue();
            this.invokeSet(newInstance, clazz, nodeName, param);
        }/*from   ww w  .  j a v  a 2  s. com*/
    }

    return newInstance;
}

From source file:de.elbe5.base.data.XmlData.java

public Locale getLocaleAttribute(Node node, String key) {
    Locale result = Locale.getDefault();
    if (node.hasAttributes()) {
        NamedNodeMap attrMap = node.getAttributes();
        Node attr = attrMap.getNamedItem(key);
        if (attr != null) {
            try {
                result = new Locale(attr.getNodeValue());
            } catch (Exception ignored) {
            }//from   www  .java 2s.  c  o m
        }
    }
    return result;
}

From source file:org.jetbrains.webdemo.help.HelpLoader.java

private String getTagValueWithTagName(Node node) {
    StringBuilder result = new StringBuilder();

    if (node.getNodeType() == 3) {
        result.append(node.getNodeValue());
    } else {/*from ww  w.  j  a  va2s .c o  m*/
        result.append("<");
        result.append(node.getNodeName());
        if (node.getNodeName().equals("a")) {
            result.append(" target=\"_blank\" ");
        }
        if (node.hasAttributes()) {
            result.append(" ");
            NamedNodeMap map = node.getAttributes();
            for (int i = 0; i < map.getLength(); i++) {
                result.append(map.item(i).getNodeName());
                result.append("=\"");
                result.append(map.item(i).getTextContent());
                result.append("\" ");
            }
        }
        result.append(">");
        if (node.hasChildNodes()) {
            NodeList nodeList = node.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                result.append(getTagValueWithTagName(nodeList.item(i)));
            }
        }
        result.append("</");
        result.append(node.getNodeName());
        result.append(">");
    }
    return result.toString();
}

From source file:ar.com.zauber.commons.gis.street.impl.GMapsStreetDao.java

/**
 *
 * @param node en este nodo esta el placemark
 * @return un {@link Result} con los datos.
 *//*from   ww w .j av  a 2 s  . c om*/
private Result getPlace(final Node node) throws NumberFormatException {
    Validate.notNull(node);
    Validate.isTrue(node.getNodeName().equals("Placemark"));
    Result res = null;

    Node details = find("AddressDetails", node);
    Node coordenadas = find("coordinates", node);
    // obtengo coordenadas y si es preciso
    if (coordenadas != null && details != null && details.hasAttributes()) {
        Node nprecision = details.getAttributes().getNamedItem("Accuracy");
        if (nprecision != null) {
            String precision = nprecision.getTextContent();
            boolean preciso = Integer.parseInt(precision) >= accu;
            String coord = coordenadas.getTextContent();
            final String[] lonLat = coord.split(",");
            if (lonLat.length > 2 && preciso) {
                final Double lon = Double.valueOf(lonLat[0]);
                final Double lat = Double.valueOf(lonLat[1]);

                // obtengo nombre entero de la direccion
                String name = find("address", node).getTextContent();

                //obtengo pais
                Node country = find("CountryNameCode", details);
                String countryCode = (country == null) ? null : country.getTextContent();

                // obtengo ciudad
                Node place = find("LocalityName", details);
                Node ciudad = (place == null) ? find("AdministrativeAreaName", details) : place;
                String city = (ciudad == null) ? null : ciudad.getTextContent();

                //armo el resultado
                if (lon != null && lat != null && name != null && city != null && countryCode != null) {
                    res = new StreetResult(name, geometryFactory.createPoint(new Coordinate(lon, lat)), city,
                            countryCode);
                }
            }
        }
    }
    return res;
}

From source file:com.francelabs.datafari.servlets.admin.FieldWeight.java

/**
 * Retrieve the default search handler '/select' from a list of request
 * handlers//from w  w  w.  j  a va  2  s .co  m
 *
 * @param requestHandlers
 * @return the search handler or null if not found
 */
private Node getSearchHandler(final NodeList requestHandlers) {
    for (int i = 0; i < requestHandlers.getLength(); i++) {

        final Node rh = requestHandlers.item(i);
        if (rh.hasAttributes()) {
            final NamedNodeMap rhAttributes = rh.getAttributes();
            for (int j = 0; j < rhAttributes.getLength(); j++) {
                if (rhAttributes.item(j).getNodeName().equals("name")
                        && rhAttributes.item(j).getNodeValue().equals("/select")) {
                    return rh;
                }
            }
        }

    }
    return null;
}

From source file:com.photon.phresco.impl.DrupalApplicationProcessor.java

public List<Configuration> getConfigObjFromXml(String featureManifestXml) throws PhrescoException {
    List<Configuration> configs = new ArrayList<Configuration>();
    try {//from  ww w .  j  av  a2s  .c  o  m
        File featureManifestXmlFile = new File(featureManifestXml);

        Configuration config = null;
        if (featureManifestXmlFile.isFile()) {
            config = new Configuration(featureManifestXmlFile.getName(), FEATURES);
        } else {
            return Collections.emptyList();
        }

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(featureManifestXmlFile);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName(CONFIG_TAG);
        Properties properties = new Properties();
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            // get attributes
            if (nNode.hasAttributes()) {
                NamedNodeMap attributes = nNode.getAttributes();
                Node name = attributes.getNamedItem(NAME);
                if (name != null) {
                    Element eElement = (Element) nNode;
                    String defaultValue = getTagValue(DEFAULT_VALUE, eElement);
                    String currentValue = getTagValue(CURRENT_VALUE, eElement);
                    String value = StringUtils.isNotEmpty(currentValue) ? currentValue : defaultValue;
                    properties.put(name.getNodeValue(), value);
                }
            }
        }
        config.setProperties(properties);
        configs.add(config);
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return configs;
}

From source file:com.websystique.springmvc.youtube_api.Function.java

@SuppressWarnings({ "static-access", "unchecked" })

private String printNote(NodeList nodeList) {
    List<VideoSub> listsub = new ArrayList<VideoSub>();
    List<VideoSub> savelistsub = new ArrayList<VideoSub>();
    for (int count = 0; count < nodeList.getLength(); count++) {
        VideoSub v = new VideoSub();
        Node tempNode = nodeList.item(count);
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
            v.setTextsb(replace_all(replacetext(tempNode.getTextContent().replace("...", "."))));
            if (tempNode.hasAttributes()) {
                NamedNodeMap nodeMap = tempNode.getAttributes();
                for (int i = 0; i < nodeMap.getLength(); i++) {
                    Node node = nodeMap.item(i);
                    if (i == 0) {
                        v.setEnd(node.getNodeValue());
                    } else {
                        v.setStart(node.getNodeValue());
                    }/*from w w w.j  a  v  a2s .  c  om*/
                }
            }
        }
        listsub.add(v);
    }
    String savetext = "";
    double sodu = 0;
    double savedur = 0;
    String dutext = "";
    double start = 0;
    String kq = "";
    boolean flag = true;// vo lan dau
    boolean flagchamcuoi = false;// vo lan dau
    for (int i = 0; i < listsub.size(); i++) {
        String cau = listsub.get(i).getTextsb();
        if (flag || flagchamcuoi == true) {
            start = Double.parseDouble(listsub.get(i).getStart());
            savedur = Double.parseDouble(listsub.get(i).getEnd());
            flag = false;
            flagchamcuoi = false;
        }

        double dur = Double.parseDouble(listsub.get(i).getEnd());
        if (sodu != 0) {
            savetext += dutext;
            start = Double.parseDouble(listsub.get(i).getStart());
            start -= sodu;
            System.out.println(sodu + "So du" + start);
            dutext = "";
            sodu = 0;
        }
        if (cau.contains("####") == true) {
            float sogiay = (float) dur;
            float phantram = 0;
            int socau = 0;
            int sotu = demsotu(cau);
            String[] savecau = new String[100];
            int[] savesotu = new int[1000];
            double[] phantramsotu = new double[1000];
            for (String retval : cau.split("####")) { // split("\\|;\\s*|\\.\\s*|\\?\\s*")
                if (retval != "" && retval.length() > 0) {
                    savecau[socau] = retval;
                    savesotu[socau] = (1 + StringUtils.countMatches(retval.trim(), " "));
                    double pt = 0.0;
                    double so1 = (double) savesotu[socau];
                    double so2 = (double) sotu;
                    pt = so1 / so2;
                    phantramsotu[socau] = pt * sogiay;
                    socau++;
                }
            }

            // *******************************
            char[] array = cau.toCharArray();
            // save cau 1
            VideoSub cau1 = new VideoSub();
            cau1.setTextsb((savetext + " " + savecau[0]).replace("\n", " ").replace("'", " ").trim());
            cau1.setStart(start + "");
            String end = (savedur + phantramsotu[0]) + "";
            cau1.setEnd(end + "");
            if (savecau[0] != ".")
                savelistsub.add(cau1);
            // add vao
            savetext = "";
            // cap nhat start
            start += Double.parseDouble(cau1.getEnd());

            savedur = 0;
            // save cau giua
            for (int i1 = 1; i1 < socau - 1; i1++) {
                // add vao
                VideoSub Cau2 = new VideoSub();
                Cau2.setTextsb(savecau[i1].replace("\n", " ").replace("'", " ").trim());
                Cau2.setStart(start + "");
                Cau2.setEnd(phantramsotu[i1] + "");
                if (savecau[i1] != ".")
                    savelistsub.add(Cau2);

                start += phantramsotu[i1];
            }

            // save cau cuoi
            if (array[cau.length() - 5] == '.' || array[cau.length() - 5] == '?'
                    || array[cau.length() - 5] == ';') {
                flagchamcuoi = true;

            }

            System.out.println(cau);
            if (array[cau.length() - 5] == '.' || array[cau.length() - 5] == ';'
                    || array[cau.length() - 5] == '?') {
                if (socau - 1 != 0) {
                    VideoSub Cau3 = new VideoSub();
                    Cau3.setTextsb(savecau[socau - 1].replace("\n", " ").replace("'", "-").trim());
                    Cau3.setStart(start + "");
                    Cau3.setEnd(phantramsotu[socau - 1] + "");
                    if (savecau[socau - 1] != ".")
                        savelistsub.add(Cau3);

                    start += phantramsotu[socau - 1];
                }
            } else {
                dutext = savecau[socau - 1];
                sodu = phantramsotu[socau - 1];
            }
        } else {
            savetext += " " + cau;
            savedur += dur;
        }
    }
    // ================Xuat File Json===============
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < savelistsub.size(); i++) {
        JSONObject obj = new JSONObject();
        if (savelistsub.get(i).getTextsb() != ".") {
            String startadd = savelistsub.get(i).getStart();
            String duradd = savelistsub.get(i).getEnd();
            String textadd = savelistsub.get(i).getTextsb();
            obj.put("start", startadd);
            obj.put("dur", duradd);
            obj.put("text", textadd);
            jsonArray.add(obj);
        }

    }
    String out_String = jsonArray.toJSONString();
    out_String = out_String.toString();

    // ================Xuat File Json===============

    return out_String;
}

From source file:hoot.services.controllers.osm.ChangesetDbWriter.java

private List<Element> write(Document changesetDoc) throws Exception {
    logger.debug(XmlDocumentBuilder.toString(changesetDoc));

    ChangesetErrorChecker changesetErrorChecker = new ChangesetErrorChecker(changesetDoc, requestChangesetMapId,
            conn);//from   w ww.j av  a 2 s.  co m
    dbNodeCache = changesetErrorChecker.checkForElementExistenceErrors();
    changesetErrorChecker.checkForVersionErrors();
    changesetErrorChecker.checkForElementVisibilityErrors();

    initParsedElementCache();

    // The "if-unused" attribute in the delete tag prevents any element
    // being used by another element from being deleted (e.g. node can't be deleted that is still
    // being used by a way or relation, etc.); its attribute value is ignored; only the presence
    // of the attribute or lack thereof is looked at. This seems a little confusing to me,
    // but that's how the OSM rails port parses it, and I'm trying to stay consistent with
    // what it does when possible.
    logger.debug("Changeset delete unused check...");
    boolean deleteIfUnused = false;
    Node deleteXml = XPathAPI.selectSingleNode(changesetDoc, "//osmChange/delete");
    if ((deleteXml != null) && deleteXml.hasAttributes()
            && (deleteXml.getAttributes().getNamedItem("if-unused") != null)) {
        deleteIfUnused = true;
    }

    logger.debug("Inserting new OSM elements and updating existing OSM elements...");

    // By storing the elements and the element records in two different
    // collections, changesetDiffElements and recordsToStore, data is being duplicated
    // here since Element already has a copy of the UpdatableRecord. However, this prevents
    // having to parse through the records a second time to collect them to pass on to the database
    // with the batch method. This is wasteful of memory, so perhaps there is a better way to do this.
    List<Element> changesetDiffElements = new ArrayList<>();
    long changesetDiffElementsSize = 0;

    // Process on entity change type at a time, different database update
    // types must be batched separately (inserts/updates/deletes).
    for (EntityChangeType entityChangeType : EntityChangeType.values()) {
        // Process one element type at a time. For create/modify operations
        // we want to make sure elements that contain an element type are processed after that
        // element type (ways contain nodes, so process ways after nodes). This corresponds to the
        // default ordering of ElementType. For delete operations we want to go in the reverse order.
        List<ElementType> elementTypeValues = Arrays.asList(ElementType.values());

        if (entityChangeType == EntityChangeType.DELETE) {
            Collections.reverse(elementTypeValues);
        }

        for (ElementType elementType : elementTypeValues) {
            if (elementType != ElementType.Changeset) {
                logger.debug("Parsing {} for {}", entityChangeType, elementType);

                // parse the elements from the request XML for the given element type
                changesetDiffElements.addAll(parseElements(
                        XPathAPI.selectNodeList(changesetDoc,
                                "//osmChange/" + entityChangeType.toString().toLowerCase() + "/"
                                        + elementType.toString().toLowerCase()),
                        elementType, entityChangeType, deleteIfUnused));

                // If any elements were actually parsed for this element and entity update type, update the
                // database with the parsed elements, their related records, and their tags
                if (changesetDiffElements.size() > changesetDiffElementsSize) {
                    changesetDiffElementsSize += (changesetDiffElements.size() - changesetDiffElementsSize);

                    // don't need to clear tags or related records out if
                    // this is a new element, since they won't exist yet
                    if (entityChangeType != EntityChangeType.CREATE) {
                        // Clear out *all* related elements (e.g. way nodes
                        // for node, relation members for relation, etc.) first (this is how the rails port
                        // does it, although while it seems necessary for ways, it doesn't seem necessary to
                        // me for relations). Any related elements to be created/retained specified in the
                        // request have already been added to relatedRecordsToStore and will be inserted into
                        // the db following this.
                        Element prototypeElement = ElementFactory.create(requestChangesetMapId, elementType,
                                conn);

                        // Elements which don't have related elements, will return a null for the
                        // relatedRecordType.
                        RelationalPathBase<?> relatedRecordTable = prototypeElement.getRelatedRecordTable();
                        Element.removeRelatedRecords(requestChangesetMapId, relatedRecordTable,
                                prototypeElement.getRelatedRecordJoinField(), parsedElementIds,
                                relatedRecordTable != null, conn);
                    }

                    // TODO: really need to be flushing these batch executions after they get
                    // TODO: to be a certain size to avoid memory problems; see maxRecordBatchSize
                    // TODO: make this code element generic; reinstate the DbSerializable interface??
                    if (elementType == ElementType.Node) {
                        DbUtils.batchRecordsDirectNodes(requestChangesetMapId, recordsToModify,
                                recordBatchTypeForEntityChangeType(entityChangeType), conn, maxRecordBatchSize);
                    } else if (elementType == ElementType.Way) {
                        DbUtils.batchRecordsDirectWays(requestChangesetMapId, recordsToModify,
                                recordBatchTypeForEntityChangeType(entityChangeType), conn, maxRecordBatchSize);
                    } else if (elementType == ElementType.Relation) {
                        DbUtils.batchRecordsDirectRelations(requestChangesetMapId, recordsToModify,
                                recordBatchTypeForEntityChangeType(entityChangeType), conn, maxRecordBatchSize);
                    }

                    // make the database updates for the element records
                    recordsToModify.clear();
                    parsedElementIds.clear();

                    // Add the related records after the parent element records to keep from violating
                    // foreign key constraints. Any existing related records
                    // for this element have already been completely cleared.
                    // TODO: make this code element generic; reinstate the
                    // DbSerializable interface??
                    if ((relatedRecordsToStore != null) && (!relatedRecordsToStore.isEmpty())) {
                        if (elementType == ElementType.Node) {
                            DbUtils.batchRecordsDirectNodes(requestChangesetMapId, relatedRecordsToStore,
                                    RecordBatchType.INSERT, conn, maxRecordBatchSize);
                        } else if (elementType == ElementType.Way) {
                            DbUtils.batchRecords(requestChangesetMapId, relatedRecordsToStore,
                                    QCurrentWayNodes.currentWayNodes, null, RecordBatchType.INSERT, conn,
                                    maxRecordBatchSize);
                        } else if (elementType == ElementType.Relation) {
                            DbUtils.batchRecords(requestChangesetMapId, relatedRecordsToStore,
                                    QCurrentRelationMembers.currentRelationMembers, null,
                                    RecordBatchType.INSERT, conn, maxRecordBatchSize);
                        }
                        relatedRecordsToStore.clear();
                    }
                }
            }
        }
    }

    changeset.updateNumChanges((int) changesetDiffElementsSize);

    // Even if a bounds is specified in the incoming changeset diff data, it
    // should be ignored, per OSM docs.
    BoundingBox newChangesetBounds = changeset.getBounds();
    newChangesetBounds.expand(diffBounds, Double.parseDouble(CHANGESET_BOUNDS_EXPANSION_FACTOR_DEEGREES));

    changeset.setBounds(newChangesetBounds);
    changeset.updateExpiration();

    return changesetDiffElements;
}