Example usage for javax.xml.xpath XPathConstants STRING

List of usage examples for javax.xml.xpath XPathConstants STRING

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants STRING.

Prototype

QName STRING

To view the source code for javax.xml.xpath XPathConstants STRING.

Click Source Link

Document

The XPath 1.0 string data type.

Maps to Java String .

Usage

From source file:org.opencastproject.remotetest.server.UnscheduledCaptureTest.java

@Ignore
@Test//from   www .  j  av  a2  s . com
public void testUnscheduledCapture() throws Exception {

    // Agent Registered (Capture Admin Agents)
    HttpResponse response = CaptureAdminResources.agents(httpClient);
    assertEquals("Response code (agents):", 200, response.getStatusLine().getStatusCode());
    Document xml = Utils.parseXml(response.getEntity().getContent());
    assertTrue("Agent included? (agents):", Utils.xpathExists(xml,
            "//*[local-name() = 'agent-state-update'][name=\'" + CaptureResources.AGENT + "\']"));

    // Agent Registered (Capture Admin Agent)
    response = CaptureAdminResources.agent(httpClient, CaptureResources.AGENT);
    assertEquals("Response code (agent):", 200, response.getStatusLine().getStatusCode());
    xml = Utils.parseXml(response.getEntity().getContent());
    assertTrue("Agent included? (agent):", Utils.xpathExists(xml,
            "//*[local-name() = 'agent-state-update'][name=\'" + CaptureResources.AGENT + "\']"));

    // Agent idle (State)
    response = StateResources.getState(httpClient);
    assertEquals("Response code (getState):", 200, response.getStatusLine().getStatusCode());
    assertEquals("Agent idle? (getState):", "idle", EntityUtils.toString(response.getEntity(), "UTF-8"));

    // Get initial recording count (Admin Proxy)
    response = AdminResources.countRecordings(httpClient);
    assertEquals("Response code (countRecordings):", 200, response.getStatusLine().getStatusCode());
    JSONObject initialRecordingCount = Utils.parseJson(EntityUtils.toString(response.getEntity(), "UTF-8"));
    // System.out.println("Initial: " + initialRecordingCount);

    // Start capture (Capture)
    response = CaptureResources.startCaptureGet(httpClient);
    assertEquals("Response code (startCapture):", 200, response.getStatusLine().getStatusCode());

    // Get capture ID (Capture)
    recordingId = CaptureResources.captureId(response);

    // Confirm recording started (State)
    int retries = 0;
    int timeout = 60;
    while (retries < timeout) {
        Thread.sleep(1000);

        // Check capture agent status
        response = StateResources.getState(httpClient);
        assertEquals("Response code (workflow instance):", 200, response.getStatusLine().getStatusCode());
        if (EntityUtils.toString(response.getEntity(), "UTF-8").equals("capturing")) {
            break;
        }

        retries++;
    }

    if (retries == timeout) {
        fail("State Service failed to reflect that recording had started.");
    }

    // Confirm recording started (Capture Admin)
    retries = 0;
    timeout = 10;
    while (retries < timeout) {
        Thread.sleep(1000);

        // Check capture agent status
        response = CaptureAdminResources.agents(httpClient);
        assertEquals("Response code (agents):", 200, response.getStatusLine().getStatusCode());
        xml = Utils.parseXml(response.getEntity().getContent());
        if (Utils.xpath(xml, "//*[local-name() = 'agent-state-update'][name=\'" + CaptureResources.AGENT
                + "\']/*[local-name() = 'state']", XPathConstants.STRING).equals("capturing")) {
            break;
        }

        retries++;
    }

    if (retries == timeout) {
        fail("Capture Admin failed to reflect that recording had started.");
    }

    // Get capturing recording count (Admin Proxy)
    response = AdminResources.countRecordings(httpClient);
    assertEquals("Response code (countRecordings):", 200, response.getStatusLine().getStatusCode());
    JSONObject capturingRecordingCount = Utils.parseJson(EntityUtils.toString(response.getEntity(), "UTF-8"));
    // System.out.println("Recording Started: " + capturingRecordingCount);

    // Compare total recording count
    assertEquals("Total recording count the same (schedule to capture):",
            (Long) initialRecordingCount.get("total") + 1, capturingRecordingCount.get("total"));
    // Compare capturing recording count
    assertEquals("Capture recording count increased by one:", (Long) initialRecordingCount.get("capturing") + 1,
            capturingRecordingCount.get("capturing"));

    // Stop capture (Capture)
    response = CaptureResources.stopCapturePost(httpClient, recordingId);
    assertEquals("Response code (stopCapturePost):", 200, response.getStatusLine().getStatusCode());

    // Confirm recording stopped (State)
    retries = 0;
    timeout = 10;
    while (retries < timeout) {
        Thread.sleep(1000);

        // Check capture agent status
        response = StateResources.getState(httpClient);
        assertEquals("Response code (workflow instance):", 200, response.getStatusLine().getStatusCode());
        if (EntityUtils.toString(response.getEntity(), "UTF-8").equals("idle")) {
            break;
        }

        retries++;
    }

    if (retries == timeout) {
        fail("State Service failed to reflect that recording had stopped.");
    }

    // Confirm recording stopped (Capture Admin)
    retries = 0;
    while (retries < timeout) {
        Thread.sleep(1000);

        // Check capture agent status
        response = CaptureAdminResources.agents(httpClient);
        assertEquals("Response code (agents):", 200, response.getStatusLine().getStatusCode());
        xml = Utils.parseXml(response.getEntity().getContent());
        if (Utils.xpath(xml, "//*[local-name() = 'agent-state-update'][name=\'" + CaptureResources.AGENT
                + "\']/*[local-name() = 'state']", XPathConstants.STRING).equals("idle")) {
            break;
        }

        retries++;
    }

    if (retries == timeout) {
        fail("Capture Admin Service failed to reflect that recording had stopped.");
    }

    // Get processing recording count (Admin Proxy)
    response = AdminResources.countRecordings(httpClient);
    assertEquals("Response code (countRecordings):", 200, response.getStatusLine().getStatusCode());
    JSONObject processingRecordingCount = Utils.parseJson(EntityUtils.toString(response.getEntity(), "UTF-8"));
    System.out.println("Process Recording: " + processingRecordingCount);

    // Compare total recording count
    assertEquals("Total recording count the same (capture to process):",
            (Long) capturingRecordingCount.get("total"), processingRecordingCount.get("total"));
    // Compare capturing recording count
    assertEquals("Capture recording count decreased by one:",
            (Long) capturingRecordingCount.get("capturing") - 1, processingRecordingCount.get("capturing"));
    // Compare processing recording count
    assertEquals("Process recording count increased by one:",
            (Long) capturingRecordingCount.get("processing") + 1, processingRecordingCount.get("processing"));

    // TODO Confirm recording indexed

    Thread.sleep(15000);

    // Get finished recording count (Admin Proxy)
    response = AdminResources.countRecordings(httpClient);
    assertEquals("Response code (countRecordings):", 200, response.getStatusLine().getStatusCode());
    JSONObject finishedRecordingCount = Utils.parseJson(EntityUtils.toString(response.getEntity(), "UTF-8"));
    System.out.println("Finished Recording: " + finishedRecordingCount);

    // Compare total recording count
    assertEquals("Total recording count the same (process to finish):",
            (Long) processingRecordingCount.get("total"), finishedRecordingCount.get("total"));
    // Compare processing recording count
    assertEquals("Process recording count decreased by one:",
            (Long) processingRecordingCount.get("processing") - 1, finishedRecordingCount.get("processing"));
    // Compare finished recording count
    assertEquals("Finished recording count increased by one:",
            (Long) processingRecordingCount.get("finished") + 1, finishedRecordingCount.get("finished"));

}

From source file:de.bitzeche.video.transcoding.zencoder.ZencoderClient.java

/**
 * Complete output IDs from response.//from  ww  w .ja  v  a  2  s  . c om
 * 
 * @param job
 * @param response
 */
private void completeJobInfo(ZencoderJob job, Document response) {
    try {
        NodeList outputs = (NodeList) xPath.evaluate("/api-response/job/outputs", response,
                XPathConstants.NODESET);
        if (job.getOutputs().size() == 1) {
            Integer id = findIdFromOutputNode(outputs.item(0));
            if (id != null) {
                job.getOutputs().get(0).setId(id);
            }
        } else {
            // try via labels
            Map<String, Integer> ids = new HashMap<String, Integer>();
            int outputSize = outputs.getLength();
            for (int i = 0; i < outputSize; i++) {
                String label = (String) xPath.evaluate("output/label", outputs.item(i), XPathConstants.STRING);
                if (label != null && !label.isEmpty()) {
                    int id = findIdFromOutputNode(outputs.item(i));
                    ids.put(label, new Integer(id));
                }
            }
            for (ZencoderOutput zcOutput : job.getOutputs()) {
                Integer foundId = ids.get(zcOutput.getLabel());
                if (foundId != null) {
                    zcOutput.setId(foundId);
                }
            }
        }

    } catch (XPathExpressionException e) {
        LOGGER.error("XPath threw Exception", e);
    }
}

From source file:eu.planets_project.tb.impl.services.EvaluationTestbedServiceTemplateImpl.java

/**
 * @param node a Node obtained by getAllEvalResultsRootNodes()
 * @return//www .  j a v a2 s  .  c o  m
 * @throws XPathExpressionException
 */
public String getEvalResultName(Node node) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    String result = (String) xpath.evaluate(sXPathForBMGoalName, node, XPathConstants.STRING);
    return result;
}

From source file:com.act.lcms.LCMSmzMLParser.java

protected LCMSSpectrum handleSpectrumEntry(Document doc) throws XPathException {
    XPath xpath = getXPathFactory().newXPath();

    Double spectrumIndexD = (Double) xpath.evaluate(SPECTRUM_PATH_INDEX, doc, XPathConstants.NUMBER);
    if (spectrumIndexD == null) {
        System.err.format("WARNING: found spectrum document without index attribute.\n");
        return null;
    }//from   ww  w  .  j  a  va 2s .c o  m
    Integer spectrumIndex = spectrumIndexD.intValue();

    if (xpath.evaluate(SPECTRUM_PATH_EXPECTED_VERSION, doc, XPathConstants.NODE) == null) {
        // if it is not MS1 Spectrum data then we will skip from the output.

        // check if it entry we see here is the diode array data, those we expect to silently skip
        // if on the other hand, even that is not matched; we truly have some unexpected entries, so report to user
        if (xpath.evaluate(SPECTRUM_PATH_EXPECTED_VERSION_DIODE_ARRAY, doc, XPathConstants.NODE) == null) {
            System.err.format(
                    "WARNING: found unexpected MS spectrum version in spectrum document %d.  Skipping.\n",
                    spectrumIndex);
        }

        return null;
    }

    String spectrumId = (String) xpath.evaluate(SPECTRUM_PATH_ID, doc, XPathConstants.STRING);
    if (spectrumId == null) {
        System.err.format("WARNING: no spectrum id found for documnt %d\n", spectrumIndex);
        return null;
    }

    Matcher matcher = SPECTRUM_EXTRACTION_REGEX.matcher(spectrumId);
    if (!matcher.find()) {
        System.err.format("WARNING: spectrum id for documnt %d did not match regex: %s\n", spectrumIndex,
                spectrumId);
        return null;
    }
    Integer spectrumFunction = Integer.parseInt(matcher.group(1));
    Integer spectrumScan = Integer.parseInt(matcher.group(3));

    Integer scanListCount = ((Double) xpath.evaluate(SPECTRUM_PATH_SCAN_LIST_COUNT, doc, XPathConstants.NUMBER))
            .intValue();
    if (!Integer.valueOf(1).equals(scanListCount)) {
        System.err.format("WARNING: unexpected number of scan entries in spectrum document %d: %d",
                spectrumIndex, scanListCount);
        return null;
    }

    Integer binaryDataCount = ((Double) xpath.evaluate(SPECTRUM_PATH_BINARY_DATA_ARRAY_LIST_COUNT, doc,
            XPathConstants.NUMBER)).intValue();
    if (!Integer.valueOf(2).equals(binaryDataCount)) {
        System.err.format("WARNING: unexpected number of binary data entries in spectrum document %d: %d",
                spectrumIndex, binaryDataCount);
        return null;
    }

    Double basePeakMz = (Double) xpath.evaluate(SPECTRUM_PATH_BASE_PEAK_MZ, doc, XPathConstants.NUMBER);
    if (basePeakMz == null) {
        System.err.format("WARNING: no base peak m/z found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    Double basePeakIntensity = (Double) xpath.evaluate(SPECTRUM_PATH_BASE_PEAK_INTENSITY, doc,
            XPathConstants.NUMBER);
    if (basePeakIntensity == null) {
        System.err.format("WARNING: no base peak intensity found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    Double scanStartTime = (Double) xpath.evaluate(SPECTRUM_PATH_SCAN_START_TIME, doc, XPathConstants.NUMBER);
    if (scanStartTime == null) {
        System.err.format("WARNING: no scan start time found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    String scanStartTimeUnit = (String) xpath.evaluate(SPECTRUM_PATH_SCAN_START_TIME_UNIT, doc,
            XPathConstants.STRING);
    if (scanStartTimeUnit == null) {
        System.err.format("WARNING: no scan start time unit found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    String mzData = (String) xpath.evaluate(SPECTRUM_PATH_MZ_BINARY_DATA, doc, XPathConstants.STRING);
    if (mzData == null) {
        System.err.format("WARNING: no m/z data found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    String intensityData = (String) xpath.evaluate(SPECTRUM_PATH_INTENSITY_BINARY_DATA, doc,
            XPathConstants.STRING);
    if (intensityData == null) {
        System.err.format("WARNING: no intensity data found for spectrum document %d\n", spectrumIndex);
        return null;
    }

    List<Double> mzs = base64ToDoubleList(mzData);
    List<Double> intensities = base64ToDoubleList(intensityData);
    List<Pair<Double, Double>> mzIntensityPairs = zipLists(mzs, intensities);

    return new LCMSSpectrum(spectrumIndex, scanStartTime, scanStartTimeUnit, mzIntensityPairs, basePeakMz,
            basePeakIntensity, spectrumFunction, spectrumScan, null);
}

From source file:com.amalto.core.storage.datasource.DataSourceFactory.java

private static DataSource getDataSourceConfiguration(Node document, String name, String path)
        throws XPathExpressionException {
    Node dataSource = (Node) evaluate(document, path, XPathConstants.NODE);
    if (dataSource == null) {
        return null;
    }//from w ww .j  a va2  s. c  o m
    String type = (String) evaluate(dataSource, "type", XPathConstants.STRING); //$NON-NLS-1$
    // Invoke extensions for datasource extensions
    ServiceLoader<DataSourceExtension> extensions = ServiceLoader.load(DataSourceExtension.class);
    if (LOGGER.isDebugEnabled()) {
        StringBuilder extensionsAsString = new StringBuilder();
        int i = 0;
        for (DataSourceExtension extension : extensions) {
            extensionsAsString.append(extension.getClass().getName()).append(' ');
            i++;
        }
        if (i == 0) {
            LOGGER.debug("No datasource extension found");
        } else {
            LOGGER.debug("Found datasource extensions (" + i + " found): " + extensionsAsString);
        }
    }
    for (DataSourceExtension extension : extensions) {
        if (extension.accept(type)) {
            return extension.create(dataSource, name);
        } else {
            LOGGER.debug("Extension '" + extension + "' is not eligible for datasource type '" + type + "'.");
        }
    }
    throw new NotImplementedException("No support for type '" + type + "'.");
}

From source file:com.provenance.cloudprovenance.policyhandler.ws.support.PolicyRequestProcessor.java

public String getIdforPolicyMatch(String responseContent, String xpathToDocumentId)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
        XPathFactoryConfigurationException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//  w  ww .  j  a  v a  2  s .  co  m
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(responseContent));
    Document doc = builder.parse(is);

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();
    xpath.setNamespaceContext(cProvMapper);

    XPathExpression xPathExpr;
    xPathExpr = xpath.compile(xpathToDocumentId);

    logger.debug("XpathExpression to match: " + xpathToDocumentId);
    logger.debug("Document to match is: " + responseContent);

    return (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
}

From source file:com.esri.gpt.server.openls.provider.services.poi.DirectoryProvider.java

/**
 * Parse directory request// w w w  . j  a  v  a2  s.  c  om
 * @param context
 * @param ndReq
 * @param xpath
 * @throws XPathExpressionException
 */
private void parseRequest(OperationContext context, Node ndReq, XPath xpath) throws XPathExpressionException {
    DirectoryParams params = context.getRequestOptions().getDirectoryOptions();
    HashMap<String, String> poiProperties = null;
    HashMap<String, Object> poiLocations = null;

    Node ndPoiLoc = (Node) xpath.evaluate("xls:POILocation", ndReq, XPathConstants.NODE);
    if (ndPoiLoc != null) {
        poiLocations = new HashMap<String, Object>();
        Node ndPos = (Node) xpath.evaluate("xls:Nearest/xls:Position/gml:Point/gml:pos", ndPoiLoc,
                XPathConstants.NODE);
        if (ndPos != null) {
            String[] xy = ndPos.getTextContent().split(" ");
            Point loc = new Point(xy[0], xy[1]);
            poiLocations.put("nearest", loc);
        }
        @SuppressWarnings("unused")
        Node ndWDAL = (Node) xpath.evaluate("xls:WithinDistance/xls:POI/xls:POIAttributeList/xls:POIInfoList",
                ndPoiLoc, XPathConstants.NODE);
        String maxDist = (String) xpath.evaluate("xls:WithinDistance/xls:MaximumDistance/@value", ndPoiLoc,
                XPathConstants.STRING);
        if (maxDist != null) {
            poiLocations.put("withinDistance", maxDist);
        }

    }
    Node ndPoiProp = (Node) xpath.evaluate("xls:POIProperties", ndReq, XPathConstants.NODE);
    if (ndPoiProp != null) {
        NodeList nlProp = (NodeList) xpath.evaluate("xls:POIProperty", ndPoiProp, XPathConstants.NODESET);
        if (nlProp != null) {
            for (int j = 0; j < nlProp.getLength(); j++) {
                Node ndProp = nlProp.item(j);
                poiProperties = new HashMap<String, String>();
                String name = (String) xpath.evaluate("@name", ndProp, XPathConstants.STRING);
                String param = context.getRequestContext().getApplicationConfiguration()
                        .getCatalogConfiguration().getParameters().getValue(name);
                String value = (String) xpath.evaluate("@value", ndProp, XPathConstants.STRING);
                poiProperties.put(param, value);
            }
        }
    }
    params.setPoiLocations(poiLocations);
    params.setPoiProperties(poiProperties);
}

From source file:de.egore911.versioning.deployer.performer.PerformCopy.java

private boolean copy(String uri, String target, String targetFilename) {
    URL url;/* w  ww .ja  va  2  s .com*/
    try {
        url = new URL(uri);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        return false;
    }
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();

        int lastSlash = uri.lastIndexOf('/');
        if (lastSlash < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        int lastDot = uri.lastIndexOf('.');
        if (lastDot < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        String filename;
        if (StringUtils.isEmpty(targetFilename)) {
            filename = uri.substring(lastSlash + 1);
        } else {
            filename = targetFilename;
        }

        XmlHolder xmlHolder = XmlHolder.getInstance();
        XPathExpression finalNameXpath = xmlHolder.xPath.compile("/project/build/finalName/text()");

        if (response == HttpURLConnection.HTTP_OK) {
            String downloadFilename = UrlUtil.concatenateUrlWithSlashes(target, filename);

            File downloadFile = new File(downloadFilename);
            FileUtils.forceMkdir(downloadFile.getParentFile());
            try (InputStream in = connection.getInputStream();
                    FileOutputStream out = new FileOutputStream(downloadFilename)) {
                IOUtils.copy(in, out);
            }
            LOG.debug("Downloaded {} to {}", url, downloadFilename);

            if (StringUtils.isEmpty(targetFilename)) {
                // Check if finalName if exists in pom.xml
                String destFile = null;
                try (ZipFile zipFile = new ZipFile(downloadFilename)) {
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        if (entry.getName().endsWith("/pom.xml")) {

                            String finalNameInPom;
                            try (InputStream inputStream = zipFile.getInputStream(entry)) {
                                try {
                                    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
                                    Model model = mavenreader.read(inputStream);
                                    finalNameInPom = model.getBuild().getFinalName();
                                } catch (Exception e) {
                                    Document doc = xmlHolder.documentBuilder.parse(inputStream);
                                    finalNameInPom = (String) finalNameXpath.evaluate(doc,
                                            XPathConstants.STRING);
                                }
                            }

                            if (StringUtils.isNotEmpty(finalNameInPom)) {
                                destFile = UrlUtil.concatenateUrlWithSlashes(target,
                                        finalNameInPom + "." + uri.substring(lastDot + 1));
                            }
                            break;
                        }
                    }
                }

                // Move file to finalName if existed in pom.xml
                if (destFile != null) {
                    try {
                        File dest = new File(destFile);
                        if (dest.exists()) {
                            FileUtils.forceDelete(dest);
                        }
                        FileUtils.moveFile(downloadFile.getAbsoluteFile(), dest.getAbsoluteFile());
                        LOG.debug("Moved file from {} to {}", downloadFilename, destFile);
                    } catch (IOException e) {
                        LOG.error("Failed to move file to it's final name: {}", e.getMessage(), e);
                    }
                }
            }

            return true;
        } else {
            LOG.error("Could not download file: {}", uri);
            return false;
        }
    } catch (SAXException | IOException | XPathExpressionException e) {
        LOG.error("Could not download file ({}): {}", uri, e.getMessage(), e);
        return false;
    }
}

From source file:com.impetus.ankush.common.utils.NmapUtil.java

/**
 * @throws ParserConfigurationException/*from ww w  . ja  v  a 2 s. c o  m*/
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
private static Map<String, String> getHostIPMapping(String filePath)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    // loading the XML document from a file
    DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
    builderfactory.setNamespaceAware(true);

    DocumentBuilder builder = builderfactory.newDocumentBuilder();
    File file = new File(filePath);
    Document xmlDocument = builder.parse(file);

    XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
    XPath xPath = factory.newXPath();

    // getting the name of the book having an isbn number == ABCD7327923
    XPathExpression hostXpath = xPath.compile("//host");

    XPathExpression ipXpath = xPath.compile("address[@addrtype='ipv4']/@addr");

    XPathExpression hostNameXpath = xPath.compile("hostnames/hostname[@type='user']/@name");

    NodeList nodeListHost = (NodeList) hostXpath.evaluate(xmlDocument, XPathConstants.NODESET);

    Map<String, String> hostIpMapping = new HashMap<String, String>();
    for (int index = 0; index < nodeListHost.getLength(); index++) {
        String ip = (String) ipXpath.evaluate(nodeListHost.item(index), XPathConstants.STRING);
        String host = (String) hostNameXpath.evaluate(nodeListHost.item(index), XPathConstants.STRING);

        hostIpMapping.put(host, ip);

    }
    // deleting the temporary xml file.
    FileUtils.deleteQuietly(file);
    return hostIpMapping;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.common.informationflow.VisioInformationFlowTemplateParser.java

/**
 * Extracts the relevant information from the given {@link Node} into a
 * {@link VisioInformationFlowTemplateNode} and adds this to the given
 * nodes map. Child nodes will be recursively added to the map, too, and the
 * parent/child references of affected {@link VisioInformationFlowTemplateNode}
 * updated.//from w  w w . j a v a  2 s.co  m
 * @param node
 *          {@link Node} to parse.
 * @param parentNode
 *          The, already parsed, parent of the node to be parsed here. Can be null for the root node.
 */
private void parseNodeAndAddToMap(Node node, VisioInformationFlowTemplateNode parentNode)
        throws XPathExpressionException {

    XPath xPath = XPathFactory.newInstance().newXPath();

    String idString = (String) xPath.evaluate(ID_PROPERTY_XPATH, node, XPathConstants.STRING);
    Integer id = Integer.valueOf(idString);
    String pinXString = (String) xPath.evaluate(PINX_XPATH, node, XPathConstants.STRING);
    double pinX = Double.parseDouble(pinXString);
    String pinYString = (String) xPath.evaluate(PINY_XPATH, node, XPathConstants.STRING);
    double pinY = Double.parseDouble(pinYString);

    VisioInformationFlowTemplateNode parsedNode = new VisioInformationFlowTemplateNode(id, pinX, pinY);
    parsedNodes.put(id, parsedNode);

    if (parentNode != null) {
        parsedNode.setParentId(parentNode.getId());
        parentNode.addChildrenId(id);
    }

    NodeList childApplicationNodes = (NodeList) xPath.evaluate(APPLICATION_SHAPE_XPATH, node,
            XPathConstants.NODESET);

    for (int i = 0; i < childApplicationNodes.getLength(); i++) {
        parseNodeAndAddToMap(childApplicationNodes.item(i), parsedNode);
    }
}