Example #1
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();
    }
  }
  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;
  }
Example #3
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);
    }
  }
Example #4
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()
Example #5
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;
  }
Example #6
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()
Example #7
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;
  }
Example #8
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);
   }
 }
  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);
   }
 }
Example #11
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);
 }
Example #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());
        }
      }
    }
  }
Example #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 void addErrorsTo(List<HtmlCheckError> errors) throws Exception {
    @SuppressWarnings("unchecked")
    List<Element> elements =
        XPath.selectNodes(page.getRoot(), "//body//*[@id]/*[@id]/*[@id]/*[@id]/*[@id]");

    for (Element element : elements) {
      errors.add(
          new HtmlCheckError(
              String.format(
                  "ID ABUSE: %s has four or more parents which already have id attributes",
                  Selector.from(element))));
    }
  }
Example #15
0
  @SuppressWarnings("unchecked")
  private List<Element> parseElements(XPath xPath, Element root) throws RESTLightClientException {
    List<Element> elements = null;

    try {
      elements = xPath.selectNodes(root);
    } catch (JDOMException e) {
      throw new RESTLightClientException(
          "XPath selection failed: '" + xPath + "' (Root node: " + root.getName() + ").", e);
    }

    return (List<Element>) (elements == null ? Collections.emptyList() : elements);
  }
Example #16
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));
  }
Example #17
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);
   }
 }
Example #18
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;
 }
Example #19
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);
  }
 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()));
     }
   }
 }
Example #21
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);
       }
     }
   }
 }
Example #22
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;
  }
  public String tags2LowerCase(String payload) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    builder.setValidation(false);
    builder.setIgnoringElementContentWhitespace(true);
    Document xmldoc = builder.build(new StringReader(payload));

    XPath xpath = XPath.newInstance("//*");
    List result = xpath.selectNodes(xmldoc);
    Iterator it = result.iterator();
    while (it.hasNext()) {
      Element element = (Element) it.next();
      element.setName(element.getName().toLowerCase());
      element.setNamespace(null);
    }

    XMLOutputter outputter = new XMLOutputter();
    ByteArrayOutputStream parsed = new ByteArrayOutputStream();
    outputter.output(xmldoc, parsed);

    return parsed.toString();
  }
  public void init(Element root, String nodeId) throws Exception {
    String strXpath = "//Node[NodeID=" + nodeId + "]";

    List nodeList = XPath.selectNodes(root, strXpath);
    Set uSet = new HashSet();

    for (int i = 0; i < nodeList.size(); i++) {
      Element e = (Element) nodeList.get(i);
      String tranId = Utilities.getXmlNodeValue(e.getChild("TranCodeStr"), "");
      if (!uSet.contains(tranId)) {
        uSet.add(tranId);
      }
    }
    for (Iterator it = uSet.iterator(); it.hasNext(); ) {
      String tranId = (String) it.next();
      BaseFixedMsgPackager fp = new BaseFixedMsgPackager();
      fp.initFldByXmlNode(root, nodeId, tranId);
      // fp.setTranId(tranId);
      pMap.put(tranId, fp);
    }
  }
Example #25
0
  private List<ToolIdentity> createFileIdentities(Document dom, ToolInfo info) {
    List<ToolIdentity> identities = new ArrayList<ToolIdentity>();
    try {
      XPath xpath = XPath.newInstance("//fits:identity");
      xpath.addNamespace(ns);
      @SuppressWarnings("unchecked")
      List<Element> identElements = xpath.selectNodes(dom);
      for (Element element : identElements) {
        Attribute formatAttr = element.getAttribute("format");
        Attribute mimetypeAttr = element.getAttribute("mimetype");
        Element versionElement = element.getChild("version", ns);

        String format = null;
        String mimetype = null;
        String version = null;

        if (formatAttr != null) {
          format = formatAttr.getValue();
        }
        if (mimetypeAttr != null) {
          mimetype = mimetypeAttr.getValue();
        }
        if (versionElement != null) {
          version = versionElement.getText();
        }
        ToolIdentity identity = new ToolIdentity(mimetype, format, version, info);
        List<Element> xIDElements = element.getChildren("externalIdentifier", ns);
        for (Element xIDElement : xIDElements) {
          String type = xIDElement.getAttributeValue("type");
          String value = xIDElement.getText();
          ExternalIdentifier xid = new ExternalIdentifier(type, value, info);
          identity.addExternalIdentifier(xid);
        }
        identities.add(identity);
      }
    } catch (JDOMException e) {
      e.printStackTrace();
    }
    return identities;
  }
 /**
  * Retrieve information about page title normalization.
  *
  * @param root Root element.
  * @param normalization Map containing information about title normalization (From => To).
  * @throws JDOMException
  */
 public void retrieveNormalization(Element root, Map<String, String> normalization)
     throws JDOMException {
   if (normalization == null) {
     return;
   }
   XPath xpaNormalized = XPath.newInstance("/api/query/normalized/n");
   List listNormalized = xpaNormalized.selectNodes(root);
   if ((listNormalized == null) || (listNormalized.isEmpty())) {
     return;
   }
   Iterator itNormalized = listNormalized.iterator();
   XPath xpaFrom = XPath.newInstance("./@from");
   XPath xpaTo = XPath.newInstance("./@to");
   while (itNormalized.hasNext()) {
     Element normalized = (Element) itNormalized.next();
     String from = xpaFrom.valueOf(normalized);
     String to = xpaTo.valueOf(normalized);
     if ((from != null) && (to != null)) {
       normalization.put(from, to);
     }
   }
 }
Example #27
0
  protected final void command_output(String rest) {
    String xpe = rest;
    if (xpe.length() == 0) {
      System.out.printf("Error: expected an XPath expression");
      return;
    }
    // Select nodes
    List nodelist = null;
    try {
      nodelist = XPath.selectNodes(current_context, xpe);
    } catch (Exception ex) {
      System.out.printf("XPath.selectNodes() failed:\n");
      System.out.printf("%s\n", ex.getMessage());
      return;
    } // try-catch

    System.out.printf("Outputting %d nodes\n", nodelist.size());

    if (nodelist.size() == 0) {
      return;
    }

    if (nodelist.size() != 1) {
      // TODO: error?
    }

    try {
      xmloutputter.output(nodelist, writer);
      System.out.printf("\n");
    } catch (Exception ex) {
      String msg = ex.getMessage();
      if (msg == null) {
        ex.printStackTrace();
      } else {
        System.out.printf("XMLOutputter.output(): %s\n", ex.getMessage());
      }
    } // try-catch
  } // command_output()
  public void checkCorpus(Document corpus, String CORPUS_BASEDIRECTORY)
      throws JDOMException, SAXException, JexmaraldaException, URISyntaxException {
    corpusDocument = corpus;
    XPath xpath =
        XPath.newInstance(
            "//Transcription[Description/Key[@Name='segmented']/text()='false']/NSLink");
    List transcriptionList = xpath.selectNodes(corpus);
    for (int pos = 0; pos < transcriptionList.size(); pos++) {
      Element nslink = (Element) (transcriptionList.get(pos));
      currentElement = nslink;
      final String fullTranscriptionName =
          CORPUS_BASEDIRECTORY + System.getProperty("file.separator", "/") + nslink.getText();
      System.out.println("Reading " + fullTranscriptionName + "...");
      currentFilename = fullTranscriptionName;

      count++;

      fireCorpusInit((double) count / (double) transcriptionList.size(), nslink.getText());

      BasicTranscription bt = new BasicTranscription(currentFilename);
      processTranscription(bt, currentFilename);
    }
  }
  public String getSaveAsPayload(String original) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    builder.setValidation(false);
    builder.setIgnoringElementContentWhitespace(true);
    Document xmldoc = builder.build(new StringReader(original));
    Document ret = builder.build(new StringReader(original));

    ((Element) ret.getContent(0)).removeContent();

    XPath xpath = XPath.newInstance("//DISK[SAVE_AS]");
    List result = xpath.selectNodes(xmldoc);
    Iterator it = result.iterator();
    while (it.hasNext()) {
      Element element = (Element) it.next();
      element.setNamespace(null);
      ret.getRootElement().addContent((Element) element.clone());
    }

    XMLOutputter outputter = new XMLOutputter();
    ByteArrayOutputStream parsed = new ByteArrayOutputStream();
    outputter.output(ret, parsed);

    return parsed.toString();
  }
Example #30
0
  private void fillResults() {
    // TODO Auto-generated method stub

    String xpathExpression = this.xPathExpression.getText();
    if (xpathExpression != null && xpathExpression.length() > 0) {
      StringBuffer buff = new StringBuffer();

      try {
        XPath x = XPath.newInstance(xpathExpression);
        List<?> l = x.selectNodes(this.dspXML);
        for (Iterator<?> iter = l.iterator(); iter.hasNext(); ) {
          Object element = (Object) iter.next();

          buff.append(element.toString() + "\n");
        }

        this.xPathResults.setText(buff.toString());

      } catch (JDOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }