Example usage for org.w3c.dom Document getElementsByTagName

List of usage examples for org.w3c.dom Document getElementsByTagName

Introduction

In this page you can find the example usage for org.w3c.dom Document getElementsByTagName.

Prototype

public NodeList getElementsByTagName(String tagname);

Source Link

Document

Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.

Usage

From source file:com.surevine.alfresco.webscript.gsa.canuserseeitems.CanUserSeeItemsCommandWebscriptImpl.java

public Map<Integer, Object> requestToNodeRefCollection(String requestXMLString)
        throws SAXException, ParserConfigurationException, IOException, GSAInvalidParameterException {
    Map<Integer, Object> responseItems = new HashMap<Integer, Object>();

    Collection<NodeRef> nodeRefs = new ArrayList<NodeRef>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);//from w  w  w.j a v  a  2 s  .  c o m
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document document = parser.parse(new ByteArrayInputStream(requestXMLString.getBytes("UTF-8")));

    NodeList allNodeRefs = document.getElementsByTagName("nodeRef");
    Element documentElement = document.getDocumentElement();
    String runAsUser = documentElement.getAttribute("runAsUser");

    //If the runAsUser is specified but doesn't exist, throw an error
    if (runAsUser != null && (!runAsUser.equals("")) && !personService.personExists(runAsUser)) {
        throw new GSAInvalidParameterException("The specified runAsUser(" + runAsUser + ") does not exist",
                null, 140611);
    }
    responseItems.put(RUN_AS_USER_KEY, runAsUser);

    int nodeRefCount = allNodeRefs.getLength();
    for (int i = 0; i < nodeRefCount; i++) {
        Node node = allNodeRefs.item(i);
        String nodeReference = node.getTextContent();

        NodeRef newNode = null;
        try {
            newNode = new NodeRef(nodeReference);
            if (_logger.isDebugEnabled()) {
                _logger.debug("Created nodeRef " + newNode + " from request");
            }
        } catch (Exception e) {
            //some problem creating the NodeRef - probably a syntactically invalid node ref.
            //ignore and continue:
            GSAProcessingException wrapped = new GSAProcessingException(
                    "Could not serialise " + nodeReference + " to a NodeRef Collection", e, 34831);
            _logger.warn(
                    "NodeRef could not be instantiated for supplied node reference [" + nodeReference + "].",
                    wrapped);
            continue;
        }

        nodeRefs.add(newNode);
    }

    responseItems.put(NODE_REFS_KEY, nodeRefs);

    return responseItems;
}

From source file:com.dmsl.anyplace.googleapi.GMapV2Direction.java

public ArrayList<LatLng> getDirection(Document doc) {
    NodeList nl1, nl2, nl3;//from   w ww. j av a 2 s  .c  o m
    ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
    nl1 = doc.getElementsByTagName("step");
    if (nl1.getLength() > 0) {
        for (int i = 0; i < nl1.getLength(); i++) {
            Node node1 = nl1.item(i);
            nl2 = node1.getChildNodes();

            Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
            nl3 = locationNode.getChildNodes();
            Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
            double lat = Double.parseDouble(latNode.getTextContent());
            Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            double lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));

            locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "points"));
            //ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
            List<LatLng> arr = PolyUtil.decode(latNode.getTextContent());
            for (int j = 0; j < arr.size(); j++) {
                listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
            }

            locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "lat"));
            lat = Double.parseDouble(latNode.getTextContent());
            lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));
        }
    }

    return listGeopoints;
}

From source file:gov.nih.nci.caadapter.ws.AddNewScenario.java

/**
* Update the reference in .map to the .scs and .h3s files.
*
* @param  mapplingFileName  mapping file name
*//*w  w w.ja  v  a2s. c  o  m*/
public void updateMapping(String mapplingBakFileName) throws Exception {
    Document xmlDOM = readFile(mapplingBakFileName);

    NodeList components = xmlDOM.getElementsByTagName("component");
    for (int i = 0; i < components.getLength(); i++) {
        Element component = (Element) components.item(i);
        //update location of SCS, H3S
        Attr locationAttr = component.getAttributeNode("location");
        Attr kindAttr = component.getAttributeNode("kind");
        if (locationAttr != null) {
            String cmpKind = "";
            if (kindAttr != null)
                cmpKind = kindAttr.getValue();
            if (cmpKind != null && cmpKind.equalsIgnoreCase("v2"))
                continue;
            String localName = extractOriginalFileName(locationAttr.getValue());
            locationAttr.setValue(localName);
        }
        //update VOM reference
        Attr groupAttr = component.getAttributeNode("group");
        if (groupAttr != null && groupAttr.getValue() != null
                && groupAttr.getValue().equalsIgnoreCase("vocabulary")) {
            NodeList chldComps = component.getElementsByTagName("data");
            for (int j = 0; j < chldComps.getLength(); j++) {
                Element chldElement = (Element) chldComps.item(j);
                Attr valueAttr = chldElement.getAttributeNode("value");
                if (valueAttr != null) {
                    String localFileName = extractOriginalFileName(valueAttr.getValue());
                    valueAttr.setValue(localFileName);
                }
            }
        }
    }
    System.out.println("AddNewScenario.updateMapping()..mapbakfile:" + mapplingBakFileName);

    outputXML(xmlDOM, mapplingBakFileName.substring(0, mapplingBakFileName.lastIndexOf(".bak")));
}

From source file:com.sms.server.service.parser.NFOParser.java

public MediaElement parse(MediaElement mediaElement) {
    // Get XML file
    File nfoFile = getNFOFile(mediaElement.getParentPath());

    if (nfoFile != null) {
        LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME,
                "Parsing NFO file " + nfoFile.getPath(), null);

        try {//from   w w w. ja  va2s. c  om
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dbFactory.newDocumentBuilder();
            Document document = builder.parse(nfoFile);

            // Optimise XML before proceeding to minimise errors
            document.getDocumentElement().normalize();

            if (document.getElementsByTagName("title").getLength() > 0) {
                if (!document.getElementsByTagName("title").item(0).getTextContent().equals("")) {
                    mediaElement.setTitle(document.getElementsByTagName("title").item(0).getTextContent());
                }
            }

            if (document.getElementsByTagName("rating").getLength() > 0) {
                if (!document.getElementsByTagName("rating").item(0).getTextContent().equals("")) {
                    Float rating = Float
                            .valueOf(document.getElementsByTagName("rating").item(0).getTextContent());
                    mediaElement.setRating(rating);
                }
            }

            if (document.getElementsByTagName("year").getLength() > 0) {
                if (!document.getElementsByTagName("year").item(0).getTextContent().equals("")) {
                    Short year = Short
                            .parseShort(document.getElementsByTagName("year").item(0).getTextContent());
                    mediaElement.setYear(year);
                }
            }

            if (document.getElementsByTagName("genre").getLength() > 0) {
                if (!document.getElementsByTagName("genre").item(0).getTextContent().equals("")) {
                    mediaElement.setGenre(document.getElementsByTagName("genre").item(0).getTextContent());
                }
            }

            if (document.getElementsByTagName("outline").getLength() > 0) {
                if (!document.getElementsByTagName("outline").item(0).getTextContent().equals("")) {
                    mediaElement
                            .setDescription(document.getElementsByTagName("outline").item(0).getTextContent());
                }
            }

            if (document.getElementsByTagName("tagline").getLength() > 0) {
                if (!document.getElementsByTagName("tagline").item(0).getTextContent().equals("")) {
                    mediaElement.setTagline(document.getElementsByTagName("tagline").item(0).getTextContent());
                }
            }

            if (document.getElementsByTagName("mpaa").getLength() > 0) {
                if (!document.getElementsByTagName("mpaa").item(0).getTextContent().equals("")) {
                    mediaElement.setCertificate(document.getElementsByTagName("mpaa").item(0).getTextContent());
                }
            }

            if (document.getElementsByTagName("set").getLength() > 0) {
                if (!document.getElementsByTagName("set").item(0).getTextContent().equals("")) {
                    mediaElement.setCollection(document.getElementsByTagName("set").item(0).getTextContent());
                }
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME,
                    "Unable to parse NFO file " + nfoFile.getPath(), e);
        }
    }

    return mediaElement;
}

From source file:de.huberlin.wbi.hiway.am.dax.DaxApplicationMaster.java

@Override
public void parseWorkflow() {
    Map<Object, TaskInstance> tasks = new HashMap<>();
    System.out.println("Parsing Pegasus DAX " + getWorkflowFile());

    try {//  w  w w . j a  va 2 s.c  o  m
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new File(getWorkflowFile().getLocalPath().toString()));
        NodeList jobNds = doc.getElementsByTagName("job");

        for (int i = 0; i < jobNds.getLength(); i++) {
            Element jobEl = (Element) jobNds.item(i);
            String id = jobEl.getAttribute("id");
            String taskName = jobEl.getAttribute("name");
            DaxTaskInstance task = new DaxTaskInstance(getRunId(), taskName);
            task.setRuntime(
                    jobEl.hasAttribute("runtime") ? Double.parseDouble(jobEl.getAttribute("runtime")) : 0d);
            tasks.put(id, task);

            StringBuilder arguments = new StringBuilder();
            NodeList argumentNds = jobEl.getElementsByTagName("argument");
            for (int j = 0; j < argumentNds.getLength(); j++) {
                Element argumentEl = (Element) argumentNds.item(j);

                NodeList argumentChildNds = argumentEl.getChildNodes();
                for (int k = 0; k < argumentChildNds.getLength(); k++) {
                    Node argumentChildNd = argumentChildNds.item(k);
                    String argument = "";

                    switch (argumentChildNd.getNodeType()) {
                    case Node.ELEMENT_NODE:
                        Element argumentChildEl = (Element) argumentChildNd;
                        if (argumentChildEl.getNodeName().equals("file")) {
                            if (argumentChildEl.hasAttribute("name")) {
                                argument = argumentChildEl.getAttribute("name");
                            }
                        } else if (argumentChildEl.getNodeName().equals("filename")) {
                            if (argumentChildEl.hasAttribute("file")) {
                                argument = argumentChildEl.getAttribute("file");
                            }
                        }
                        break;
                    case Node.TEXT_NODE:
                        argument = argumentChildNd.getNodeValue().replaceAll("\\s+", " ").trim();
                        break;
                    default:
                    }

                    if (argument.length() > 0) {
                        arguments.append(" ").append(argument);
                    }
                }
            }

            NodeList usesNds = jobEl.getElementsByTagName("uses");
            for (int j = 0; j < usesNds.getLength(); j++) {
                Element usesEl = (Element) usesNds.item(j);
                String link = usesEl.getAttribute("link");
                String fileName = usesEl.getAttribute("file");
                long size = usesEl.hasAttribute("size") ? Long.parseLong(usesEl.getAttribute("size")) : 0l;
                List<String> outputs = new LinkedList<>();

                switch (link) {
                case "input":
                    if (!getFiles().containsKey(fileName)) {
                        Data data = new Data(fileName);
                        data.setInput(true);
                        getFiles().put(fileName, data);
                    }
                    Data data = getFiles().get(fileName);
                    task.addInputData(data, size);
                    break;
                case "output":
                    if (!getFiles().containsKey(fileName))
                        getFiles().put(fileName, new Data(fileName));
                    data = getFiles().get(fileName);
                    task.addOutputData(data, size);
                    data.setInput(false);
                    outputs.add(fileName);
                    break;
                default:
                }

                task.getReport()
                        .add(new JsonReportEntry(task.getWorkflowId(), task.getTaskId(), task.getTaskName(),
                                task.getLanguageLabel(), Long.valueOf(task.getId()), null,
                                JsonReportEntry.KEY_INVOC_OUTPUT, new JSONObject().put("output", outputs)));
            }

            task.setCommand(taskName + arguments.toString());
            System.out.println(
                    "Adding task " + task + ": " + task.getInputData() + " -> " + task.getOutputData());
        }

        NodeList childNds = doc.getElementsByTagName("child");
        for (int i = 0; i < childNds.getLength(); i++) {
            Element childEl = (Element) childNds.item(i);
            String childId = childEl.getAttribute("ref");
            TaskInstance child = tasks.get(childId);

            NodeList parentNds = childEl.getElementsByTagName("parent");
            for (int j = 0; j < parentNds.getLength(); j++) {
                Element parentEl = (Element) parentNds.item(j);
                String parentId = parentEl.getAttribute("ref");
                TaskInstance parent = tasks.get(parentId);

                child.addParentTask(parent);
                parent.addChildTask(child);
            }
        }

        for (TaskInstance task : tasks.values()) {
            if (task.getChildTasks().size() == 0) {
                for (Data data : task.getOutputData()) {
                    data.setOutput(true);
                }
            }

            task.getReport()
                    .add(new JsonReportEntry(task.getWorkflowId(), task.getTaskId(), task.getTaskName(),
                            task.getLanguageLabel(), Long.valueOf(task.getId()), null,
                            JsonReportEntry.KEY_INVOC_SCRIPT, task.getCommand()));
        }

    } catch (WorkflowStructureUnknownException | IOException | JSONException | ParserConfigurationException
            | SAXException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    getScheduler().addTasks(tasks.values());
}

From source file:org.jasig.portlet.notice.util.PortletXmlRoleService.java

@PostConstruct
public void init() {
    final Document doc = parseXml();

    if (doc != null) {
        String roleNameCandidate;
        Set<String> set = new HashSet<>();

        // Find all the <security-role-ref> elements in the file
        final NodeList roleSections = doc.getElementsByTagName("security-role-ref");
        for (int i = 0; i < roleSections.getLength(); i++) {
            // for each <security-role-ref>, get the child nodes
            if (roleSections.item(i).hasChildNodes()) {
                final NodeList roleNames = roleSections.item(i).getChildNodes();
                for (int j = 0; j < roleNames.getLength(); j++) {
                    // go through the child nodes of each <security-role-ref> to find the <role-name> node
                    if (roleNames.item(j).getNodeName().equalsIgnoreCase("role-name")) {
                        // copy the <role-name> to the roles list if it's not there already
                        roleNameCandidate = roleNames.item(j).getTextContent();
                        set.add(roleNameCandidate);
                    }/*from ww w  .j  a v a  2 s.  c o  m*/
                }
            }
        }

        roles = Collections.unmodifiableSet(set);
        logger.info("Successfully instantiated and found roles: {}", roles);
    } else {
        logger.error("Error parsing the file: {}. See other messages for trace.", PORTLET_XML_PATH);
    }
}

From source file:it.geosolutions.geobatch.migrationmonitor.statuschecker.CheckerAction.java

@Override
public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> arg0) throws ActionException {

    // return object
    final Queue<FileSystemEvent> outputEvents = new LinkedList<FileSystemEvent>();

    try {// ww w .  j ava 2 s  .c  om
        //gather the input file in order to read the database table name
        File flowTempDirectory = new File(getTempDir().getParent());
        File[] files = flowTempDirectory.listFiles();
        File inputEventFile = null;
        if (files != null && files.length > 0) {
            for (File f : files) {
                if (f.isFile() && f.getName().endsWith(".xml")) {
                    inputEventFile = f;
                }
            }
        } else {
            throw new Exception("One file, type xml,  is expected in the root of the temp directory");
        }

        // set as the action output event the flow input event
        FileSystemEvent fse = new FileSystemEvent(inputEventFile, FileSystemEventType.FILE_ADDED);
        outputEvents.add(fse);

        //parse the xml file and get the table name
        String tableName = "";
        String host = "";
        String db = "";
        String schema = "";
        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder;
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputEventFile);
            doc.getDocumentElement().normalize();
            NodeList nodes = doc.getElementsByTagName("typeName");
            if (nodes == null || nodes.getLength() != 1) {
                throw new Exception(
                        "more than one typeName has been found in the input event... this is not possible...");
            }
            Node n = nodes.item(0);
            tableName = n.getTextContent();
            NodeList entries = doc.getElementsByTagName("entry");
            host = extractEntry("server", entries);
            if (host == null) {
                host = extractEntry("host", entries);
            }
            db = extractEntry("instance", entries);
            if (db == null) {
                db = extractEntry("database", entries);
            }
            schema = extractEntry("schema", entries);
            LOGGER.info("Changing state to MIGRATED for records with: server_ip:'" + host + "' db:'" + db
                    + "' schema_nome:'" + schema + "' tabella:'" + tableName + "'");
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new Exception("Error while parsing input file... exception message: " + e.getMessage());
        }
        LOGGER.info("The table name is: " + tableName);

        //change the status in the strati_rif table
        MigrationMonitor mm = migrationMonitorDAO.findByTablename(host, db, schema, tableName);
        mm.setMigrationStatus(MigrationStatus.MIGRATED.toString().toUpperCase());
        migrationMonitorDAO.merge(mm);

    } catch (Exception t) {
        final String message = "CheckerAction::execute(): " + t.getLocalizedMessage();
        if (LOGGER.isErrorEnabled())
            LOGGER.error(message, t);
        final ActionException exc = new ActionException(this, message, t);
        listenerForwarder.failed(exc);
        throw exc;
    }

    return outputEvents;
}

From source file:fr.redteam.dressyourself.plugins.weather.yahooWeather.YahooWeatherUtils.java

private WeatherInfo parseWeatherInfo(Context context, Document doc) {
    WeatherInfo weatherInfo = new WeatherInfo();
    try {/*from   w  ww  .  ja v  a  2 s.c om*/

        Node titleNode = doc.getElementsByTagName("title").item(0);

        if (titleNode.getTextContent().equals(YAHOO_WEATHER_ERROR)) {
            return null;
        }

        weatherInfo.setTitle(titleNode.getTextContent());
        weatherInfo.setDescription(doc.getElementsByTagName("description").item(0).getTextContent());
        weatherInfo.setLanguage(doc.getElementsByTagName("language").item(0).getTextContent());
        weatherInfo.setLastBuildDate(doc.getElementsByTagName("lastBuildDate").item(0).getTextContent());

        Node locationNode = doc.getElementsByTagName("yweather:location").item(0);
        weatherInfo.setLocationCity(locationNode.getAttributes().getNamedItem("city").getNodeValue());
        weatherInfo.setLocationRegion(locationNode.getAttributes().getNamedItem("region").getNodeValue());
        weatherInfo.setLocationCountry(locationNode.getAttributes().getNamedItem("country").getNodeValue());

        Node windNode = doc.getElementsByTagName("yweather:wind").item(0);
        weatherInfo.setWindChill(windNode.getAttributes().getNamedItem("chill").getNodeValue());
        weatherInfo.setWindDirection(windNode.getAttributes().getNamedItem("direction").getNodeValue());
        weatherInfo.setWindSpeed(windNode.getAttributes().getNamedItem("speed").getNodeValue());

        Node atmosphereNode = doc.getElementsByTagName("yweather:atmosphere").item(0);
        weatherInfo
                .setAtmosphereHumidity(atmosphereNode.getAttributes().getNamedItem("humidity").getNodeValue());
        weatherInfo.setAtmosphereVisibility(
                atmosphereNode.getAttributes().getNamedItem("visibility").getNodeValue());
        weatherInfo
                .setAtmospherePressure(atmosphereNode.getAttributes().getNamedItem("pressure").getNodeValue());
        weatherInfo.setAtmosphereRising(atmosphereNode.getAttributes().getNamedItem("rising").getNodeValue());

        Node astronomyNode = doc.getElementsByTagName("yweather:astronomy").item(0);
        weatherInfo.setAstronomySunrise(astronomyNode.getAttributes().getNamedItem("sunrise").getNodeValue());
        weatherInfo.setAstronomySunset(astronomyNode.getAttributes().getNamedItem("sunset").getNodeValue());

        weatherInfo.setConditionTitle(doc.getElementsByTagName("title").item(2).getTextContent());
        weatherInfo.setConditionLat(doc.getElementsByTagName("geo:lat").item(0).getTextContent());
        weatherInfo.setConditionLon(doc.getElementsByTagName("geo:long").item(0).getTextContent());

        Node currentConditionNode = doc.getElementsByTagName("yweather:condition").item(0);
        weatherInfo.setCurrentCode(
                Integer.parseInt(currentConditionNode.getAttributes().getNamedItem("code").getNodeValue()));
        weatherInfo.setCurrentText(currentConditionNode.getAttributes().getNamedItem("text").getNodeValue());
        weatherInfo.setCurrentTempF(
                Integer.parseInt(currentConditionNode.getAttributes().getNamedItem("temp").getNodeValue()));
        weatherInfo.setCurrentConditionDate(
                currentConditionNode.getAttributes().getNamedItem("date").getNodeValue());

        this.parseForecastInfo(weatherInfo.getForecastInfo1(), doc, 0);
        this.parseForecastInfo(weatherInfo.getForecastInfo2(), doc, 1);

    } catch (NullPointerException e) {
        e.printStackTrace();
        Toast.makeText(context, "Parse XML failed - Unrecognized Tag", Toast.LENGTH_SHORT).show();
        weatherInfo = null;
    }

    return weatherInfo;
}

From source file:com.threadswarm.imagefeedarchiver.parser.RssDOMFeedParser.java

private RssChannel parseChannel(Document document) {
    RssChannel channel = new RssChannel();
    List<RssItem> rssItemList = new LinkedList<RssItem>();
    NodeList channelNodes = document.getElementsByTagName("channel");
    Element channelElement = (Element) channelNodes.item(0);

    NodeList channelChildren = channelElement.getChildNodes();
    for (int x = 0; x < channelChildren.getLength(); x++) {
        Node node = channelChildren.item(x);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element childElement = (Element) node;
            if (childElement.getTagName().equals("title")) {
                channel.setTitle(childElement.getTextContent());
            } else if (childElement.getTagName().equals("pubDate")) {
                /*/*ww  w. java 2s .co m*/
                String pubDateString = childElement.getTextContent().trim();
                if(pubDateString != null && !pubDateString.isEmpty()){
                DateFormat dateFormat = DateFormat.getInstance();
                try{
                    Date pubDate = dateFormat.parse(pubDateString);
                    channel.setPubDate(pubDate);
                }catch(ParseException e){
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                }
                */
            } else if (childElement.getTagName().equals("description")) {
                channel.setDescription(childElement.getTextContent());
            } else if (childElement.getTagName().equals("item")) {
                RssItem rssItem = parseItem(childElement);
                if (rssItem != null)
                    rssItemList.add(rssItem);
            }
        }
    }

    channel.setItems(rssItemList);

    return channel;
}