Example usage for org.dom4j Node selectSingleNode

List of usage examples for org.dom4j Node selectSingleNode

Introduction

In this page you can find the example usage for org.dom4j Node selectSingleNode.

Prototype

Node selectSingleNode(String xpathExpression);

Source Link

Document

selectSingleNode evaluates an XPath expression and returns the result as a single Node instance.

Usage

From source file:org.rolap4j.parsers.Dom4jBasedCatalogParser.java

License:Apache License

/**
 * Get the table name that corresponds to the cube
 *
 * @param cubeNode//from w  ww .  j a  va  2  s .  c o  m
 * @param cubeName
 * @return table name that corresponds to the cube
 * @throws ParsingException
 * @see Cube
 */
private String getCubeTableName(final Node cubeNode, final String cubeName) throws ParsingException {

    final Node tableNode = cubeNode.selectSingleNode("Table");
    final String exceptionMessage = "The cube " + cubeName + " must specify a corresponding table";

    if (null == tableNode) {
        throw new ParsingException(exceptionMessage);
    }

    final String name = tableNode.valueOf("@name");
    if (StringUtil.isEmpty(name)) {
        throw new ParsingException(exceptionMessage);
    }
    return name;
}

From source file:org.rossjohnson.tvdb.io.TvDbDAO.java

License:Open Source License

public SeriesInfo getSeriesInfo(int seriesId) throws Exception {
    SeriesInfo series = null;/*  w  ww. j ava  2s.  c  o m*/
    String query = "http://www.thetvdb.com/data/series/" + seriesId + "/all/";
    log.info("Executing " + query);
    Document doc = new SAXReader().read(client.execute(new HttpGet(query)).getEntity().getContent());
    Node seriesElement = doc.selectSingleNode("/Data/Series");
    if (seriesElement != null) {
        series = new SeriesInfo();
        series.setSeriesId(String.valueOf(seriesId));
        series.setSeriesName(seriesElement.selectSingleNode("SeriesName").getText());
        try {
            Date firstAired = dateFormat.parse(seriesElement.selectSingleNode("FirstAired").getText());
            series.setFirstAired(firstAired);
        } catch (Exception e) {
        }
    }
    return series;
}

From source file:org.rundeck.api.parser.AbortParser.java

License:Apache License

@Override
public RundeckAbort parse(Node abortNode) {
    RundeckAbort abort = new RundeckAbort();

    try {//from  w  w  w.  ja  v a 2  s . c  o m
        abort.setStatus(AbortStatus.valueOf(StringUtils.upperCase(abortNode.valueOf("@status"))));
    } catch (IllegalArgumentException e) {
        abort.setStatus(null);
    }

    Node execNode = abortNode.selectSingleNode("execution");
    if (execNode != null) {
        RundeckExecution execution = new ExecutionParser().parseXmlNode(execNode);
        abort.setExecution(execution);
    }

    return abort;
}

From source file:org.rundeck.api.parser.ExecutionParser.java

License:Apache License

@Override
public RundeckExecution parse(Node execNode) {
    RundeckExecution execution = new RundeckExecution();

    execution.setId(Long.valueOf(execNode.valueOf("@id")));
    execution.setUrl(StringUtils.trimToNull(execNode.valueOf("@href")));
    try {// w w w  . j  a v a 2 s.c o m
        execution.setStatus(ExecutionStatus
                .valueOf(StringUtils.replace(StringUtils.upperCase(execNode.valueOf("@status")), "-", "_")));
    } catch (IllegalArgumentException e) {
        execution.setStatus(null);
    }
    execution.setDescription(StringUtils.trimToNull(execNode.valueOf("description")));
    execution.setArgstring(StringUtils.trimToNull(execNode.valueOf("argstring")));
    execution.setStartedBy(StringUtils.trimToNull(execNode.valueOf("user")));
    execution.setAbortedBy(StringUtils.trimToNull(execNode.valueOf("abortedby")));
    execution.setProject(StringUtils.trimToNull(execNode.valueOf("@project")));
    String startedAt = StringUtils.trimToNull(execNode.valueOf("date-started/@unixtime"));
    if (startedAt != null) {
        execution.setStartedAt(new Date(Long.valueOf(startedAt)));
    }
    String endedAt = StringUtils.trimToNull(execNode.valueOf("date-ended/@unixtime"));
    if (endedAt != null) {
        execution.setEndedAt(new Date(Long.valueOf(endedAt)));
    }

    Node jobNode = execNode.selectSingleNode("job");
    if (jobNode != null) {
        RundeckJob job = new JobParser().parseXmlNode(jobNode);
        execution.setJob(job);
    }

    final Node successfulNodes = execNode.selectSingleNode("successfulNodes");
    if (successfulNodes != null) {
        final List<RundeckNode> rundeckNodes = new ListParser<RundeckNode>(new NodeParser(),
                "successfulNodes/node").parseXmlNode(execNode);
        execution.setSuccessfulNodes(new HashSet<RundeckNodeIdentity>(rundeckNodes));
    } else {
        execution.setSuccessfulNodes(Collections.<RundeckNodeIdentity>emptySet());
    }

    final Node failedNodes = execNode.selectSingleNode("failedNodes");
    if (failedNodes != null) {
        final List<RundeckNode> rundeckNodes = new ListParser<RundeckNode>(new NodeParser(), "failedNodes/node")
                .parseXmlNode(execNode);
        execution.setFailedNodes(new HashSet<RundeckNodeIdentity>(rundeckNodes));
    } else {
        execution.setFailedNodes(Collections.<RundeckNodeIdentity>emptySet());
    }

    return execution;
}

From source file:org.rundeck.api.parser.JobParser.java

License:Apache License

@Override
public RundeckJob parse(Node jobNode) {

    RundeckJob job = new RundeckJob();

    job.setName(StringUtils.trimToNull(jobNode.valueOf("name")));
    job.setDescription(StringUtils.trimToNull(jobNode.valueOf("description")));
    job.setGroup(StringUtils.trimToNull(jobNode.valueOf("group")));

    // ID is either an attribute or an child element...
    String jobId = null;// w  w w.  ja  va 2s.  c om
    jobId = jobNode.valueOf("id");
    if (StringUtils.isBlank(jobId)) {
        jobId = jobNode.valueOf("@id");
    }
    job.setId(jobId);

    String averageDuration = StringUtils.trimToNull(jobNode.valueOf("@averageDuration"));
    if (averageDuration != null) {
        job.setAverageDuration(Long.valueOf(averageDuration));
    }

    // project is either a nested element of context, or just a child element
    Node contextNode = jobNode.selectSingleNode("context");
    if (contextNode != null) {
        job.setProject(StringUtils.trimToNull(contextNode.valueOf("project")));
    } else {
        job.setProject(StringUtils.trimToNull(jobNode.valueOf("project")));
    }

    return job;
}

From source file:org.saiku.plugin.PentahoDatasourceManager.java

License:Apache License

private void loadDatasourcesFromXml(String dataSources) {
    EntityResolver loader = new PentahoEntityResolver();
    Document doc = null;//w w  w. ja  v a  2 s. com
    try {
        doc = XmlDom4JHelper.getDocFromFile(dataSources, loader);
        String modified = doc.asXML();
        doc = XmlDom4JHelper.getDocFromString(modified, loader);

        List<Node> nodes = doc.selectNodes("/DataSources/DataSource/Catalogs/Catalog"); //$NON-NLS-1$
        int nr = 0;
        for (Node node : nodes) {
            nr++;
            String name = "PentahoDs" + nr;
            Element e = (Element) node;
            List<Attribute> list = e.attributes();
            for (Attribute attribute : list) {
                String aname = attribute.getName();
                if ("name".equals(aname)) {
                    name = attribute.getStringValue();
                }
            }

            Node ds = node.selectSingleNode("DataSourceInfo");
            Node cat = node.selectSingleNode("Definition");
            String connectStr = ds.getStringValue();
            PropertyList pl = Util.parseConnectString(connectStr);
            String dynProcName = pl.get(RolapConnectionProperties.DynamicSchemaProcessor.name());
            if (StringUtils.isNotBlank(dynamicSchemaProcessor) && StringUtils.isBlank(dynProcName)) {
                pl.put(RolapConnectionProperties.DynamicSchemaProcessor.name(), dynamicSchemaProcessor);

            }
            LOG.debug("NAME: " + name + " DSINFO: " + pl.toString() + "  ###CATALOG: "
                    + (cat != null ? cat.getStringValue() : "NULL"));
            Properties props = new Properties();
            props.put("driver", "mondrian.olap4j.MondrianOlap4jDriver");
            props.put("location", "jdbc:mondrian:" + pl.toString() + ";Catalog=" + cat.getStringValue());
            if (saikuDatasourceProcessor != null) {
                props.put(ISaikuConnection.DATASOURCE_PROCESSORS, saikuDatasourceProcessor);
            }
            if (saikuConnectionProcessor != null) {
                props.put(ISaikuConnection.CONNECTION_PROCESSORS, saikuConnectionProcessor);
            }
            props.list(System.out);

            SaikuDatasource sd = new SaikuDatasource(name, SaikuDatasource.Type.OLAP, props);
            datasources.put(name, sd);

        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error(e);
    }
    if (LOG.isDebugEnabled()) {
        if (doc == null) {
            LOG.debug("Original Document is null");
        } else {
            LOG.debug("Original Document:" + doc.asXML()); //$NON-NLS-1$
        }
    }

}

From source file:org.saiku.plugin.resources.PentahoRepositoryResource2.java

License:Apache License

/**
 * Get Saved Queries.//from w ww . j  a va  2s. com
 * @return A list of SavedQuery Objects.
 */
@GET
@Produces({ "application/json" })
public List<IRepositoryObject> getRepository(@QueryParam("path") String path, @QueryParam("type") String type) {
    List<IRepositoryObject> objects = new ArrayList<IRepositoryObject>();
    try {
        if (path != null && (path.startsWith("/") || path.startsWith("."))) {
            throw new IllegalArgumentException(
                    "Path cannot be null or start with \"/\" or \".\" - Illegal Path: " + path);
        }
        userSession = PentahoSessionHolder.getSession();
        repository = PentahoSystem.get(ISolutionRepository.class, userSession);
        if (StringUtils.isNotBlank(path)) {
            ISolutionFile sf = repository.getSolutionFile(path, ISolutionRepository.ACTION_EXECUTE);
            if (sf != null && !sf.isDirectory()
                    && (StringUtils.isBlank(type) || sf.getExtension().endsWith(type.toLowerCase()))) {
                List<AclMethod> acls = getAcl(path, false);
                String localizedName = repository.getLocalizedFileProperty(sf, "title", //$NON-NLS-1$
                        ISolutionRepository.ACTION_EXECUTE);
                objects.add(new RepositoryFileObject(localizedName, "#" + path, type, path, acls));
                return objects;
            }
        }
        Document navDoc = getRepositoryDocument(PentahoSessionHolder.getSession());
        Node tree = navDoc.getRootElement();
        // List nodes = tree.selectNodes("./file[@name='project']/file[@name='common']");
        String context = null;
        if (StringUtils.isNotBlank(path)) {
            String rootNodePath = ".";
            String[] parts = path.split("/");
            for (String part : parts) {
                rootNodePath += "/file[@name='" + part + "']";
            }
            tree = tree.selectSingleNode(rootNodePath);
            if (tree == null) {
                throw new Exception("Cannot find root folder with path: " + rootNodePath);
            }
            path = StringUtils.join(parts, "/");
            context = path;
        } else {
            context = "";
        }
        return processTree(tree, context, type);
    } catch (Exception e) {
        log.error(this.getClass().getName(), e);
        e.printStackTrace();
    }
    return objects;
}

From source file:org.sonar.report.pdf.entity.FileInfo.java

License:Open Source License

/**
 * A FileInfo object could contain information about violations, ccn or duplications, this cases are distinguished in
 * function of content param, and defined by project context.
 * //ww  w  .  ja va2s. c  o m
 * @param fileNode DOM Node that contains file info
 * @param content Type of content
 */
public void initFromNode(Node fileNode, int content) {
    this.setKey(fileNode.selectSingleNode(KEY).getText());
    this.setName(fileNode.selectSingleNode(NAME).getText());

    if (content == VIOLATIONS_CONTENT) {
        this.setViolations(fileNode.selectSingleNode(VIOLATIONS_NUMBER).getText());
    } else if (content == CCN_CONTENT) {
        this.setComplexity(fileNode.selectSingleNode(CCN).getText());
    } else if (content == DUPLICATIONS_CONTENT) {
        this.setDuplicatedLines(fileNode.selectSingleNode(DUPLICATED_LINES).getText());
    }
}

From source file:org.sonar.report.pdf.entity.FileInfo.java

License:Open Source License

public static List<FileInfo> initFromDocument(Document filesDocument, int content) {
    List<Node> fileNodes = filesDocument.selectNodes(ALL_FILES);
    List<FileInfo> fileInfoList = new LinkedList<FileInfo>();
    if (fileNodes != null) {
        Iterator<Node> it = fileNodes.iterator();
        while (it.hasNext()) {
            FileInfo file = new FileInfo();
            Node fileNode = it.next();
            // This first condition is a workarround for SONAR-830
            if (fileNode.selectSingleNode("msr") != null) {
                file.initFromNode(fileNode, content);
                if (file.isContentSet(content)) {
                    fileInfoList.add(file);
                }//from w w w  .j  av a  2 s  .c o m
            }
        }
    }
    return fileInfoList;
}

From source file:org.sonar.report.pdf.entity.Measure.java

License:Open Source License

/**
 * Init measure from XML node. The root node must be "msr".
 * /*from   ww w. j av a2 s . c  om*/
 * @param measureNode
 */
public void initFromNode(Node measureNode) {
    this.setKey(measureNode.selectSingleNode(KEY).getText());

    if (measureNode.selectSingleNode(FORMAT_VALUE) != null) {
        this.setFormatValue(measureNode.selectSingleNode(FORMAT_VALUE).getText());
        this.setValue(measureNode.selectSingleNode(VALUE).getText());
    }
    if (measureNode.selectSingleNode(TREND) != null) {
        this.setQualitativeTendency(Integer.parseInt(measureNode.selectSingleNode(TREND).getText()));
    } else {
        this.setQualitativeTendency(0);
    }

    if (measureNode.selectSingleNode(VAR) != null) {
        this.setQuantitativeTendency(Integer.parseInt(measureNode.selectSingleNode(VAR).getText()));
    } else {
        this.setQuantitativeTendency(0);
    }

    if (measureNode.selectSingleNode(VALUE) != null) {
        this.setTextValue(measureNode.selectSingleNode(VALUE).getText());
    } else if (measureNode.selectSingleNode(DATA) != null) {
        this.setTextValue(measureNode.selectSingleNode(DATA).getText());
    } else {
        this.setTextValue("");
    }

    if (measureNode.selectSingleNode(DATA) != null) {
        this.setDataValue(measureNode.selectSingleNode(DATA).getText());
    } else {
        this.setDataValue("");
    }
}