Esempio n. 1
0
  /**
   * Retrieves a single XML element given a simple xpath (like "a/b/c").
   *
   * @param xml
   * @param xpath
   * @param theNSs
   * @return
   * @throws JDOMException
   */
  public static Object selectSingle(Element xml, String xpath, List<Namespace> theNSs)
      throws JDOMException {

    XPath xp = prepareXPath(xml, xpath, theNSs);

    return xp.selectSingleNode(xml);
  }
Esempio n. 2
0
  protected String getRallyAPIError(String responseXML) {
    String errorMsg = "";

    try {

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Errors");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Element item = (Element) iter.next();
        errorMsg = item.getChildText("OperationResultError");
      }

    } catch (Exception e) {
      errorMsg = e.toString();
    }

    return errorMsg;
  }
Esempio n. 3
0
  /**
   * Returns a list of all the staging profile Ids.
   *
   * @return
   * @throws RESTLightClientException
   */
  @SuppressWarnings("unchecked")
  public List<StageProfile> getStageProfiles() throws RESTLightClientException {
    Document doc = get(PROFILES_PATH);

    // heavy lifting is done with xpath
    XPath profileXp = newXPath(STAGE_REPO_XPATH);

    List<Element> profiles;
    try {
      profiles = profileXp.selectNodes(doc.getRootElement());
    } catch (JDOMException e) {
      throw new RESTLightClientException(
          "XPath selection failed: '"
              + STAGE_REPO_XPATH
              + "' (Root node: "
              + doc.getRootElement().getName()
              + ").",
          e);
    }

    List<StageProfile> result = new ArrayList<StageProfile>();
    if (profiles != null) {
      for (Element profile : profiles) {
        // just pull out the id and name.
        String profileId = profile.getChild(PROFILE_ID_ELEMENT).getText();
        String name = profile.getChild(PROFILE_NAME_ELEMENT).getText();
        String mode = profile.getChild(PROFILE_MODE_ELEMENT).getText();

        result.add(new StageProfile(profileId, name, mode));
      }
    }
    return result;
  }
Esempio n. 4
0
  private void parseProperties(Document doc, CsvProperties properties) {
    try {

      ArrayList<String> els;

      // Get unique times
      List<Element> timeList = XPath.selectNodes(doc, ".//gml:timePosition");
      if (!timeList.isEmpty()) {
        ArrayList<String> times = new ArrayList<String>(timeList.size());
        for (Element e : timeList) {
          times.add(e.getValue());
        }
        els = new ArrayList(new HashSet(times));
        Collections.sort(els);
        properties.setTimesteps(els);
      }

      // Get unique variable names
      List<Element> varList = XPath.selectNodes(doc, ".//ioos:Quantity");
      if (!varList.isEmpty()) {
        ArrayList<String> vars = new ArrayList<String>(varList.size());
        for (Element e : varList) {
          vars.add(e.getAttributeValue("name"));
        }
        els = new ArrayList(new HashSet(vars));
        properties.setVariableHeaders(els);
      }

    } catch (JDOMException e1) {
      e1.printStackTrace();
    }
  }
Esempio n. 5
0
  @Override
  public Document read(Reader reader, Object... hints) throws TransformationException {
    try {
      ModelToModelConverter<Element, DocumentMetadata> metaConverter =
          new PdfxToMetadataConverter();
      ModelToModelConverter<Element, ContentStructure> structConverter =
          new PdfxToContentConverter();
      ModelToModelConverter<Element, BibEntry> refConverter = new ElementToBibEntryConverter();

      Element root = getRoot(reader);
      Document document = new Document();
      document.setMetadata(metaConverter.convert(root));

      document.setContent(structConverter.convert(root.getChild("article").getChild("body")));

      XPath xpath = XPath.newInstance("//ref-list/ref");
      List nodes = xpath.selectNodes(root);
      List<Element> refElems = new ArrayList<Element>();
      for (Object node : nodes) {
        refElems.add((Element) node);
      }
      document.setReferences(refConverter.convertAll(refElems));

      return document;
    } catch (JDOMException ex) {
      throw new TransformationException(ex);
    } catch (IOException ex) {
      throw new TransformationException(ex);
    }
  }
Esempio n. 6
0
  /**
   * Evaluates an XPath expression on an element and returns number result.
   *
   * @param xml
   * @param xpath
   * @param theNSs
   * @return
   * @throws JDOMException
   */
  public static Number selectNumber(Element xml, String xpath, List<Namespace> theNSs)
      throws JDOMException {

    XPath xp = prepareXPath(xml, xpath, theNSs);

    return xp.numberValueOf(xml);
  }
Esempio n. 7
0
  public static int countSelectedNodes(Document doc, String xPath) throws JDOMException {

    int count = 0;
    XPath xPathProc = XPath.newInstance(xPath);
    List list = xPathProc.selectNodes(doc);
    count = list.size();
    return count;
  }
 protected void transformXML(File[] files) {
   int number = 0;
   try {
     SAXBuilder builder = new SAXBuilder();
     for (int f = 0; f < files.length; f++) {
       int fn = f + 1;
       // split by treatment
       Document doc = builder.build(files[f]);
       Element root = doc.getRootElement();
       List<Element> treatments =
           XPath.selectNodes(root, "/tax:taxonx/tax:taxonxBody/tax:treatment");
       // detach all but one treatments from doc
       ArrayList<Element> saved = new ArrayList<Element>();
       for (int t = 1; t < treatments.size(); t++) {
         Element e = treatments.get(t);
         doc.removeContent(e);
         e.detach();
         saved.add(e);
       }
       // now doc is a template to create other treatment files
       // root.detach();
       formatDescription(
           (Element) XPath.selectSingleNode(root, "/tax:taxonx/tax:taxonxBody/tax:treatment"),
           ".//tax:div[@type='description']",
           ".//tax:p",
           fn,
           0);
       root.detach();
       writeTreatment2Transformed(root, fn, 0);
       listener.info((number++) + "", fn + "_0.xml"); // list the file on GUI here
       getDescriptionFrom(root, fn, 0);
       // replace treatement in doc with a new treatment in saved
       Iterator<Element> it = saved.iterator();
       int count = 1;
       while (it.hasNext()) {
         Element e = it.next();
         Element body = root.getChild("taxonxBody", root.getNamespace());
         Element treatment =
             (Element) XPath.selectSingleNode(root, "/tax:taxonx/tax:taxonxBody/tax:treatment");
         // in treatment/div[@type="description"], replace <tax:p> tag with <description
         // pid="1.txtp436_1.txt">
         int index = body.indexOf(treatment);
         e = formatDescription(e, ".//tax:div[@type='description']", ".//tax:p", fn, count);
         body.setContent(index, e);
         // write each treatment as a file in the target/transfromed folder
         // write description text in the target/description folder
         root.detach();
         writeTreatment2Transformed(root, fn, count);
         listener.info((number++) + "", fn + "_" + count + ".xml"); // list the file on GUI here
         getDescriptionFrom(root, fn, count);
         count++;
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
     LOGGER.error("Type4Transformer : error.", e);
   }
 }
Esempio n. 9
0
  /**
   * Creates and prepares an XPath element - simple xpath (like "a/b/c").
   *
   * @param xml
   * @param xpath
   * @param theNSs
   * @return
   * @throws JDOMException
   */
  private static XPath prepareXPath(Element xml, String xpath, List<Namespace> theNSs)
      throws JDOMException {
    XPath xp = XPath.newInstance(xpath);
    for (Namespace ns : theNSs) {
      xp.addNamespace(ns);
    }

    return xp;
  }
Esempio n. 10
0
 /**
  * Evaluates an XPath expression on an document and returns Elements.
  *
  * @param xml
  * @param xpath
  * @param theNSs
  * @return
  * @throws JDOMException
  */
 public static List<?> selectDocumentNodes(Element xml, String xpath, List<Namespace> theNSs)
     throws JDOMException {
   XPath xp = XPath.newInstance(xpath);
   for (Namespace ns : theNSs) {
     xp.addNamespace(ns);
   }
   xml = (Element) xml.clone();
   Document document = new Document(xml);
   return xp.selectNodes(document);
 }
  @Override
  public String parse(Element t) throws ParseException {
    try {

      XPath p = constructPath(this.getPath(), t);
      Element elem = (Element) p.selectSingleNode(t);
      return elem.getAttribute(attribute).getValue();
    } catch (JDOMException e) {
      throw new ParseException(e.getMessage(), 0);
    }
  }
Esempio n. 12
0
  @SuppressWarnings("unchecked")
  private void parseStageRepositoryDetails(
      final String profileId, final Map<String, StageRepository> repoStubs, boolean filterUser)
      throws RESTLightClientException {
    // System.out.println( repoStubs );

    Document doc = get(PROFILE_REPOS_PATH_PREFIX + profileId);

    // System.out.println( new XMLOutputter().outputString( doc ) );

    XPath repoXPath = newXPath(STAGE_REPO_DETAIL_XPATH);

    List<Element> repoDetails;
    try {
      repoDetails = repoXPath.selectNodes(doc.getRootElement());
    } catch (JDOMException e) {
      throw new RESTLightClientException(
          "Failed to select detail sections for staging-profile repositories.", e);
    }

    if (repoDetails != null && !repoDetails.isEmpty()) {
      for (Element detail : repoDetails) {
        String repoId = detail.getChild(REPO_ID_ELEMENT).getText();
        String key = profileId + "/" + repoId;

        StageRepository repo = repoStubs.get(key);

        if (repo == null) {
          continue;
        }

        Element uid = detail.getChild(USER_ID_ELEMENT);
        if (uid != null && getUser() != null && getUser().equals(uid.getText().trim())) {
          repo.setUser(uid.getText().trim());
        } else {
          if (filterUser) {
            repoStubs.remove(key);
          }
        }

        Element url = detail.getChild(REPO_URI_ELEMENT);
        if (url != null) {
          repo.setUrl(url.getText());
        }

        Element desc = detail.getChild(REPO_DESCRIPTION_ELEMENT);
        if (desc != null) {
          repo.setDescription(desc.getText());
        }
      }
    }
  }
Esempio n. 13
0
  public List getUserList() {
    List<Map> list = new ArrayList<Map>();

    try {

      /*
      String apiUrl=rallyApiHost+"/user?query="+
      	"((TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6169133135)%20or%20"+
      	"(TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6083311244))"+
      	"&fetch=true&order=Name&start=1&pagesize=100";
      */

      String apiUrl =
          rallyApiHost
              + "/user?query=(Disabled%20=%20false)"
              + "&fetch=true&order=Name&start=1&pagesize=100";

      log.info("apiUrl=" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();

        String userRef = item.getAttribute("ref").getValue();
        String userName = item.getAttribute("refObjectName").getValue();
        String userObjectId = item.getChildText("ObjectID");

        map.put("userRef", userRef);
        map.put("userObjectId", userObjectId);
        map.put("userName", userName);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("", ex);
    }

    return list;
  }
  public Element exec(Element params, ServiceContext context) throws Exception {
    Element response = new Element("response");

    Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);

    // --- check access
    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    DataManager dm = gc.getDataManager();

    boolean addEdit = false;

    // --- the request should contain an ID or UUID
    String id = Utils.getIdentifierFromParameters(params, context);

    if (id == null) {
      throw new MetadataNotFoundEx("No record has this UUID");
    }

    // --- check download access
    Lib.resource.checkPrivilege(context, id, AccessManager.OPER_DOWNLOAD);

    // --- get metadata
    boolean withValidationErrors = false, keepXlinkAttributes = false;
    Element elMd =
        gc.getDataManager()
            .getMetadata(context, id, addEdit, withValidationErrors, keepXlinkAttributes);

    if (elMd == null) throw new MetadataNotFoundEx("Metadata not found - deleted?");

    response.addContent(new Element("id").setText(id));

    // --- transform record into brief version
    String briefXslt = appPath + "xsl/metadata-brief.xsl";
    Element elBrief = Xml.transform(elMd, briefXslt);

    XPath xp;
    List elems;

    // --- process links to a file (have name field not blank)
    // --- if they are a reference to a downloadable local file then get size
    // --- and date modified, if not then set local to false
    xp = XPath.newInstance("link[starts-with(@protocol,'WWW:DOWNLOAD') and @name!='']");
    elems = xp.selectNodes(elBrief);
    response = processDownloadLinks(context, id, dm.getSiteURL(), elems, response);

    // --- now process web links so that they can be displayed as well
    xp = XPath.newInstance("link[starts-with(@protocol,'WWW:LINK')]");
    elems = xp.selectNodes(elBrief);
    response = processWebLinks(elems, response);

    return response;
  }
Esempio n. 15
0
  @Override
  protected void setUp() throws Exception {
    final Document document = new SAXBuilder().build(new File(getTestDataRoot(), "/RETest.xml"));
    final List<Element> list = XPath.selectNodes(document.getRootElement(), "//test");
    new File(getTestDataPath()).mkdirs();

    int i = 0;
    for (Element element : list) {
      final String name;
      final Element parent = (Element) element.getParent();
      final String s = parent.getName();
      final String t =
          parent.getAttribute("id") == null ? "" : parent.getAttribute("id").getValue() + "-";
      if (!"tests".equals(s)) {
        name = s + "/test-" + t + ++i + ".regexp";
      } else {
        name = "test-" + t + ++i + ".regexp";
      }
      final Result result =
          Result.valueOf((String) XPath.selectSingleNode(element, "string(expected)"));
      final boolean warn = !"false".equals(element.getAttributeValue("warning"));
      final boolean info = "true".equals(element.getAttributeValue("info"));
      myMap.put(name, new Test(result, warn, info));

      final File file = new File(getTestDataPath(), name);
      file.getParentFile().mkdirs();

      final FileWriter stream = new FileWriter(file);
      final String pattern = (String) XPath.selectSingleNode(element, "string(pattern)");
      if (!"false".equals(element.getAttributeValue("verify")))
        try {
          Pattern.compile(pattern);
          if (result == Result.ERR) {
            System.out.println("Incorrect FAIL value for " + pattern);
          }
        } catch (PatternSyntaxException e) {
          if (result == Result.OK) {
            System.out.println("Incorrect OK value for " + pattern);
          }
        }
      stream.write(pattern);
      stream.close();
    }

    super.setUp();

    myOut = new ByteArrayOutputStream();
    System.setErr(new PrintStream(myOut));
  }
Esempio n. 16
0
 /**
  * Analyze RangeMessage.xml file for Ranges.
  * 
  * @param root Root of RangeMessage.xml file.
  * @param ranges Current list of ranges.
  * @param xpath XPath selector.
  * @throws JDOMException
  */
 private static void analyzeRanges(Element root, List<Range> ranges, String xpath) throws JDOMException {
   XPath xpa = XPath.newInstance(xpath);
   List results = xpa.selectNodes(root);
   Iterator iter = results.iterator();
   while (iter.hasNext()) {
     Element node = (Element) iter.next();
     Element prefixNode = node.getChild("Prefix");
     String prefix = (prefixNode != null) ? prefixNode.getValue() : null;
     Element agencyNode = node.getChild("Agency");
     String agency = (agencyNode != null) ? agencyNode.getValue() : null;
     Range range = new Range(prefix, agency);
     analyzeRules(node, range);
     ranges.add(range);
   }
 }
Esempio n. 17
0
  @SuppressWarnings("unchecked")
  private List<JarConfig> loadConfig() {
    List<JarConfig> list_pair = new ArrayList<JarConfig>();
    SAXBuilder builder = new SAXBuilder();

    try {
      Document document = builder.build(this.config);
      Element root = document.getRootElement();
      Element ele = (Element) XPath.selectSingleNode(root, path.JAR.toString());
      List<Element> list = ele.getChildren();
      for (Element element : list) {
        JarConfig config =
            new JarConfig(
                classPath + element.getAttributeValue("jar").trim(),
                element.getAttributeValue("name").trim(),
                element.getAttributeValue("class").trim());

        list_pair.add(config);
      }
    } catch (JDOMException e) {
      WriteToLog.error("XML FORMAT ERROR!" + "\n" + e.getMessage());

    } catch (IOException e) {
      WriteToLog.error("XML FORMAT ERROR!" + "\n" + e.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      WriteToLog.error("XML ERROR!" + "\n" + e.getMessage());
    }
    return list_pair;
  }
Esempio n. 18
0
  protected final void command_set_context(String rest) {
    String xpe = rest;
    if (xpe.length() == 0) {
      System.out.printf("Error: expected an XPath expression");
      return;
    }
    System.out.printf("Evaluating \"%s\" against original context\n", xpe);

    // Select nodes
    List nodelist = null;
    try {
      nodelist = XPath.selectNodes(context_object, xpe);
    } catch (Exception ex) {
      System.out.printf("XPath.selectNodes() failed:\n");
      System.out.printf("%s\n", ex.getMessage());
      return;
    } // try-catch

    if (nodelist.size() == 0) {
      System.out.printf("Error: empty result set, cannot set context\n");
      return;
    }

    if (nodelist.size() == 1) {
      current_context = nodelist.get(0);
    } else {
      current_context = nodelist;
    }
    System.out.printf("Context set, %d nodes.\n", nodelist.size());
  } // command_set_context()
  /**
   * Uses HttpUnit functionality to retrieve a single sds workgroup from the sds, including the
   * offering and the members
   *
   * @param sdsWorkgroupId The id of the workgroup you want to retrieve
   * @return The SdsWorkgroup with all parameters set.
   * @throws IOException
   * @throws JDOMException
   * @throws SAXException
   */
  @SuppressWarnings("unchecked")
  protected SdsWorkgroup getWorkgroupInSds(Serializable sdsWorkgroupId)
      throws IOException, JDOMException, SAXException {
    String WORKGROUP_PATH = "/workgroup/" + sdsWorkgroupId;
    WebResponse webResponse = this.makeHttpRestGetRequest(WORKGROUP_PATH);
    assertEquals(HttpStatus.SC_OK, webResponse.getResponseCode());

    Document doc = createDocumentFromResponse(webResponse);
    SdsWorkgroup sdsWorkgroup = (SdsWorkgroup) this.applicationContext.getBean("sdsWorkgroup");

    Element workgroupElement = doc.getRootElement();
    sdsWorkgroup.setName(workgroupElement.getChild("name").getValue());
    sdsWorkgroup.setSdsObjectId(new Long(workgroupElement.getChild("id").getValue()));

    Integer sdsOfferingId = new Integer(workgroupElement.getChild("offering-id").getValue());
    SdsOffering sdsOffering = this.getOfferingAlternativeMethod(sdsOfferingId);
    sdsWorkgroup.setSdsOffering(sdsOffering);

    WebResponse membersWebResponse = this.makeHttpRestGetRequest(WORKGROUP_PATH + "/membership");
    assertEquals(HttpStatus.SC_OK, membersWebResponse.getResponseCode());
    Document membersDoc = createDocumentFromResponse(membersWebResponse);

    List<Element> memberElements =
        XPath.newInstance("/workgroup-memberships/workgroup-membership/sail-user-id")
            .selectNodes(membersDoc);

    for (Element memberNode : memberElements) {
      SdsUser sdsUser = this.getUserInSds(new Long(memberNode.getValue()));
      sdsWorkgroup.addMember(sdsUser);
    }

    return sdsWorkgroup;
  }
Esempio n. 20
0
  private static void evaluate_xpath(Object context, String xpe) {
    // Select nodes
    List nodelist = null;
    try {
      nodelist = XPath.selectNodes(context, xpe);
    } catch (Exception ex) {
      System.out.printf("XPath.selectNodes() failed:\n");
      System.out.printf("%s\n", ex.getMessage());
      return;
    } // try-catch

    display_node_list(nodelist);

    // If the XPath expression results in a single node,
    // attempt to do a reverse XPath resolution.
    if (nodelist.size() == 1) {
      // Single individual
      String xpath_reverse = null;
      try {
        // XPathIdentification.is_doable()
        // XPathIdentification.do_for()
        xpath_reverse = XPathIdentification.get_xpath(nodelist.get(0));
        System.out.printf("Reverse XPath resolution: %s\n", xpath_reverse);
      } catch (Exception ex) {
        System.out.printf("Reverse XPath resolution: failed!\n");
        System.out.printf("Error: %s\n", ex.getMessage());
      } // try-catch
    } // if
  } // command_resolve_xpath()
Esempio n. 21
0
 private XPath newXPath(final String xpath) throws RESTLightClientException {
   try {
     return XPath.newInstance(xpath);
   } catch (JDOMException e) {
     throw new RESTLightClientException("Failed to build xpath: '" + xpath + "'.", e);
   }
 }
Esempio n. 22
0
  @Override
  protected Element invokeInternal(Element arg0) throws Exception {

    TransportContext context = TransportContextHolder.getTransportContext();
    HttpServletConnection connection = (HttpServletConnection) context.getConnection();
    HttpServletRequest request = connection.getHttpServletRequest();
    String ipAddress = request.getRemoteAddr();

    String token = tokenExpression.valueOf(arg0);
    String type = typeExpression.valueOf(arg0);
    type = type.trim();
    User userWS = null;
    try {
      userWS = authenticationWS.authenticateToken(ipAddress, token);
    } catch (RuntimeException e) {
      throw new SOAPException(e.getMessage());
    }
    if (userWS == null) {
      throw new RuntimeException("User not found!");
    }

    if (!userWS.isEnabled()) {
      throw new RuntimeException("User disabled! Please Contact Admnistrator");
    }

    if (!AuthorizationWS.authorize(userWS, type)) {
      throw new SOAPException(
          "User not allowed to retrieve those informations. Contact Administrator");
    }
    return buildResult(userWS, arg0, "TokenAuthQueryResponse");
  }
Esempio n. 23
0
 public static List<Element> findXpath(Document xmlDocument, String xpath) {
   if (xmlDocument != null) {
     XPath filterXpression = null;
     try {
       filterXpression = XPath.newInstance(xpath);
       // String xpathCompiled = filterXpression.getXPath();
       List<Element> nodes = filterXpression.selectNodes(xmlDocument);
       return nodes;
     } catch (JDOMException e) {
       e
           .printStackTrace(); // To change body of catch statement use File | Settings | File
                               // Templates.
     }
   }
   return null;
 }
Esempio n. 24
0
  private void processFiles()
      throws UnsupportedEncodingException, FileNotFoundException, IOException, JDOMException,
          SAXException, ParserConfigurationException, TransformerConfigurationException,
          TransformerException {
    StylesheetFactory sf = new StylesheetFactory(true);
    for (File inputFile : inputFiles) {
      System.out.println("Reading " + inputFile.getName());
      Document xmlDocument = FileIO.readDocumentFromLocalFile(inputFile.getAbsolutePath());

      Element recordingElement =
          (Element) XPath.newInstance("//recording").selectSingleNode(xmlDocument);
      String absoluteAudioPath = "";

      String path = determineAudio(old2new, inputFile);
      recordingElement.setAttribute("path", path);
      absoluteAudioPath = RelativePath.resolveRelativePath(path, inputFile.getAbsolutePath());
      double lengthInSeconds = -1.0;
      if (new File(absoluteAudioPath).exists()) {
        player.setSoundFile(absoluteAudioPath);
        lengthInSeconds = player.getTotalLength();
      }

      String nakedName = inputFile.getName().substring(0, inputFile.getName().indexOf("TRA."));
      XPath xp = XPath.newInstance("//audio-file[starts-with(@name,'" + nakedName + "')]");
      List l = xp.selectNodes(compareDocument);
      if (l != null) {
        Element compareElement = new Element("compare");
        compareElement.setAttribute("file", inputFile.getName());
        Element audioElement1 = new Element("audio");
        audioElement1.setAttribute("file", absoluteAudioPath);
        audioElement1.setAttribute("length", Double.toString(lengthInSeconds));
        compareElement.addContent(audioElement1);
        for (Object o : l) {
          Element e = (Element) o;
          Element audioElement2 = new Element("audio");
          // <audio-file name="HLD02BW2.WAV" path="W:\TOENE\HL\HLD\HLD02BW2.WAV"
          // seconds="129.62449645996094"length="02:09.62" bytes="11432924"/>
          audioElement2.setAttribute("file", e.getAttributeValue("path"));
          audioElement2.setAttribute("length", e.getAttributeValue("seconds"));
          compareElement.addContent(audioElement2);
        }
        logRoot.addContent(compareElement);
      }
    }

    writeLogToXMLFile(logDocument);
  }
Esempio n. 25
0
 private static boolean xpathExists(String xpathString, Document doc) {
   try {
     List nodes = XPath.selectNodes(doc.getRootElement(), xpathString);
     return nodes.size() > 0;
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 26
0
 private void getJobDocumentation() {
   if (jobname != null && jobname.length() > 0) {
     try {
       XPath x = XPath.newInstance("//job[@name='" + jobname + "']/description/include");
       List listOfElement = x.selectNodes(schedulerDom.getDoc());
       if (!listOfElement.isEmpty()) {
         Element include = (Element) listOfElement.get(0);
         if (include != null) {
           jobDocumentation = Utils.getAttributeValue("file", include);
         }
       }
       if (jobDocumentation != null && jobDocumentation.length() > 0 && txtParamsFile != null) {
         txtParamsFile.setText(jobDocumentation);
       }
     } catch (Exception e) {
       System.out.println(JOE_M_0010.params("setParamsForWizzard", e.toString()));
     }
   }
 }
Esempio n. 27
0
 /**
  * Analyze RangeMessage.xml file Rules.
  * 
  * @param node Current node.
  * @param rangeElement Range element.
  * @throws JDOMException
  */
 private static void analyzeRules(Element node, Range rangeElement) throws JDOMException {
   XPath xpa = XPath.newInstance("./Rules/Rule");
   List results = xpa.selectNodes(node);
   Iterator iter = results.iterator();
   while (iter.hasNext()) {
     Element ruleNode = (Element) iter.next();
     Element rangeNode = ruleNode.getChild("Range");
     String range = (rangeNode != null) ? rangeNode.getValue() : null;
     Element lengthNode = ruleNode.getChild("Length");
     String length = (lengthNode != null) ? lengthNode.getValue() : null;
     if ((range != null) && (length != null)) {
       String[] rangeElements = range.split("\\-");
       if ((rangeElements != null) && (rangeElements.length == 2)) {
         Rule rule = new Rule(rangeElements[0], rangeElements[1], Integer.parseInt(length));
         rangeElement.addRule(rule);
       }
     }
   }
 }
  /**
   * Checks to see that the toc is a proprietary toc, rather than a Standard API toc.
   *
   * @param tocLocDoc The JDOM Document representing the toc-locations.xml file
   * @return True if the toc is a proprietary toc, False if the toc is a standard API toc
   */
  private static boolean isProprietaryTocLocation(Document tocLocDoc) {
    String expression = "/x:toc/x:topic/x:topic/x:standardapi/@title";
    XPath xpath;
    try {
      xpath = XPath.newInstance(expression);
    } catch (JDOMException e) {
      return true;
    }

    xpath.addNamespace("x", tocLocDoc.getRootElement().getNamespaceURI());

    String label;
    try {
      label = xpath.valueOf(tocLocDoc);
    } catch (JDOMException e) {
      return true;
    }

    return (label == null || label.length() == 0);
  }
  public HashID() {

    try {

      xmlString = "";
      gLOID = "";
      gLOMID = "";

      mmIdOaiCatalog =
          XPath.newInstance("//lom:lom/lom:metaMetadata/lom:identifier/lom:catalog/text()=\"oai\"");
      mmIdOaiCatalog.addNamespace(Namespace.NO_NAMESPACE);

      gIdOaiCatalog =
          XPath.newInstance("//lom:lom/lom:general/lom:identifier/lom:catalog/text()=\"oai\"");
      gIdOaiCatalog.addNamespace(Namespace.NO_NAMESPACE);
    } catch (JDOMException e) {
      // NOOP
      e.printStackTrace();
    }
  }
Esempio n. 30
0
  public List getProjectList() {
    List<Map> list = new ArrayList<Map>();

    try {

      String apiUrl = rallyApiHost + "/project?" + "fetch=true&order=Name&start=1&pagesize=200";

      log.info("rallyApiUrl:" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String state = item.getChildText("State");

        map.put("objId", objId);
        map.put("name", name);
        map.put("state", state);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }