Java Code Examples for org.jdom.xpath.XPath#newInstance()

The following examples show how to use org.jdom.xpath.XPath#newInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Parser.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private void 
preProcessResources(Element the_manifest,
  DefaultHandler the_handler) {
 XPath path;
 List<Attribute> results;
 try {
  path = XPath.newInstance(FILE_QUERY);
  path.addNamespace(ns.getNs());
  results = path.selectNodes(the_manifest);
  for (Attribute result : results) {
	  the_handler.preProcessFile(result.getValue()); 
  }
 } catch (JDOMException | ClassCastException e) {
  log.info("Error processing xpath for files", e);
 }
}
 
Example 2
Source File: Parser.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private void 
preProcessResources(Element the_manifest,
  DefaultHandler the_handler) {
 XPath path;
 List<Attribute> results;
 try {
  path = XPath.newInstance(FILE_QUERY);
  path.addNamespace(ns.getNs());
  results = path.selectNodes(the_manifest);
  for (Attribute result : results) {
	  the_handler.preProcessFile(result.getValue()); 
  }
 } catch (JDOMException | ClassCastException e) {
  log.info("Error processing xpath for files", e);
 }
}
 
Example 3
Source File: CreoleAnnotationHandler.java    From gate-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
  * Extract all JAR elements from the given JDOM document and add the jars they
  * reference to the GateClassLoader.
  * 
  * @param jdomDoc
  *          JDOM document representing a parsed creole.xml file.
  */
public void addJarsToClassLoader(GateClassLoader gcl, Document jdomDoc) throws IOException {
	try {
		XPath jarXPath = XPath.newInstance("//*[translate(local-name(), 'ivy', 'IVY') = 'IVY']");
		if (jarXPath.selectNodes(jdomDoc).size() > 0) {
			throw new IOException("Using Ivy for dependency management is no longer supported");
		}
	} catch (JDOMException e) {
		throw new IOException("Unable to load plugin", e);
	}

	addJarsToClassLoader(gcl, jdomDoc.getRootElement());
}
 
Example 4
Source File: ProjectWrangler.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void cleanUpProjectForImport(@NotNull File projectPath) {
  File dotIdeaFolderPath = new File(projectPath, Project.DIRECTORY_STORE_FOLDER);
  if (dotIdeaFolderPath.isDirectory()) {
    File modulesXmlFilePath = new File(dotIdeaFolderPath, "modules.xml");
    if (modulesXmlFilePath.isFile()) {
      SAXBuilder saxBuilder = new SAXBuilder();
      try {
        Document document = saxBuilder.build(modulesXmlFilePath);
        XPath xpath = XPath.newInstance("//*[@fileurl]");
        //noinspection unchecked
        List<Element> modules = xpath.selectNodes(document);
        int urlPrefixSize = "file://$PROJECT_DIR$/".length();
        for (Element module : modules) {
          String fileUrl = module.getAttributeValue("fileurl");
          if (!StringUtil.isEmpty(fileUrl)) {
            String relativePath = toSystemDependentName(fileUrl.substring(urlPrefixSize));
            File imlFilePath = new File(projectPath, relativePath);
            if (imlFilePath.isFile()) {
              FileUtilRt.delete(imlFilePath);
            }
            // It is likely that each module has a "build" folder. Delete it as well.
            File buildFilePath = new File(imlFilePath.getParentFile(), "build");
            if (buildFilePath.isDirectory()) {
              FileUtilRt.delete(buildFilePath);
            }
          }
        }
      }
      catch (Throwable ignored) {
        // if something goes wrong, just ignore. Most likely it won't affect project import in any way.
      }
    }
    FileUtilRt.delete(dotIdeaFolderPath);
  }
}
 
Example 5
Source File: Parser.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private boolean
 processAuthorization(Element the_manifest,
                      DefaultHandler the_handler) throws ParseException {
   try {
     XPath path=XPath.newInstance(AUTH_QUERY);
     path.addNamespace(ns.getNs());
     path.addNamespace(ns.auth_ns());
     Element result=(Element)path.selectSingleNode(the_manifest);
     if (result!=null) {
  the_handler.getSimplePageBean().setErrMessage(
     the_handler.getSimplePageBean().getMessageLocator().getMessage("simplepage.cc-uses-auth"));
  return true;
  //        String import_scope=result.getAttributeValue(AUTH_IMPORT);
  //        String access_scope=result.getAttributeValue(AUTH_ACCESS);
  //        if (access_scope.equals(AUTH_ACCESS_CARTRIDGE)) {
  //          the_handler.startAuthorization(true, false, Boolean.parseBoolean(import_scope));
  //        } else {
  //          if (access_scope.equals(AUTH_ACCESS_RESOURCE)) {
  //            the_handler.startAuthorization(false, true, Boolean.parseBoolean(import_scope));
  //          }
  //        }
  //        Element authorizationElement = result.getChild(AUTH_AUTHORIZATION, AUTH_NS);
  //        the_handler.setAuthorizationServiceXml(authorizationElement);
  //        the_handler.setAuthorizationService(authorizationElement.getChildText(AUTH_CCID, AUTH_NS), 
  //                                            authorizationElement.getChildText(AUTH_WEBSERVICE,  AUTH_NS));
  //        the_handler.endAuthorization();
  //      } 
     }
   } catch (Exception e) {
throw new ParseException(e.getMessage(),e);
   }
   return false;
 }
 
Example 6
Source File: DiscussionParser.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void 
parseContent(DefaultHandler the_handler,
             CartridgeLoader the_cartridge, 
             Element the_resource,
             boolean isProtected) throws ParseException {
    // none of this is used
    if (false) {
  try {
    //ok, so we're looking at a discussion topic here...
    Element discussion = getXML(the_cartridge, ((Element)the_resource.getChildren(FILE, the_handler.getNs().cc_ns()).get(0)).getAttributeValue(HREF));
    Namespace topicNs = the_handler.getNs().topic_ns();
    the_handler.startDiscussion(discussion.getChildText(TITLE, topicNs),
                                discussion.getChild(TEXT, topicNs).getAttributeValue(TEXTTYPE),
                                discussion.getChildText(TEXT, topicNs),
                                isProtected);
    the_handler.setDiscussionXml(discussion);
    //discussion may have attachments
    XPath path = XPath.newInstance(ATTACHMENT_QUERY);
    if (!topicNs.equals(Namespace.NO_NAMESPACE))
 path.addNamespace(topicNs); 
    for (Iterator iter=path.selectNodes(discussion).iterator(); iter.hasNext();) {
      the_handler.addAttachment(((Element)iter.next()).getAttributeValue(HREF));
    }
    the_handler.endDiscussion();
  } catch (IOException e) {
    throw new ParseException(e);
  } catch (JDOMException je) {
    throw new ParseException(je);
  }
}  
}
 
Example 7
Source File: Parser.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private boolean
 processAuthorization(Element the_manifest,
                      DefaultHandler the_handler) throws ParseException {
   try {
     XPath path=XPath.newInstance(AUTH_QUERY);
     path.addNamespace(ns.getNs());
     path.addNamespace(ns.auth_ns());
     Element result=(Element)path.selectSingleNode(the_manifest);
     if (result!=null) {
  the_handler.getSimplePageBean().setErrMessage(
     the_handler.getSimplePageBean().getMessageLocator().getMessage("simplepage.cc-uses-auth"));
  return true;
  //        String import_scope=result.getAttributeValue(AUTH_IMPORT);
  //        String access_scope=result.getAttributeValue(AUTH_ACCESS);
  //        if (access_scope.equals(AUTH_ACCESS_CARTRIDGE)) {
  //          the_handler.startAuthorization(true, false, Boolean.parseBoolean(import_scope));
  //        } else {
  //          if (access_scope.equals(AUTH_ACCESS_RESOURCE)) {
  //            the_handler.startAuthorization(false, true, Boolean.parseBoolean(import_scope));
  //          }
  //        }
  //        Element authorizationElement = result.getChild(AUTH_AUTHORIZATION, AUTH_NS);
  //        the_handler.setAuthorizationServiceXml(authorizationElement);
  //        the_handler.setAuthorizationService(authorizationElement.getChildText(AUTH_CCID, AUTH_NS), 
  //                                            authorizationElement.getChildText(AUTH_WEBSERVICE,  AUTH_NS));
  //        the_handler.endAuthorization();
  //      } 
     }
   } catch (Exception e) {
throw new ParseException(e.getMessage(),e);
   }
   return false;
 }
 
Example 8
Source File: DiscussionParser.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void 
parseContent(DefaultHandler the_handler,
             CartridgeLoader the_cartridge, 
             Element the_resource,
             boolean isProtected) throws ParseException {
    // none of this is used
    if (false) {
  try {
    //ok, so we're looking at a discussion topic here...
    Element discussion = getXML(the_cartridge, ((Element)the_resource.getChildren(FILE, the_handler.getNs().cc_ns()).get(0)).getAttributeValue(HREF));
    Namespace topicNs = the_handler.getNs().topic_ns();
    the_handler.startDiscussion(discussion.getChildText(TITLE, topicNs),
                                discussion.getChild(TEXT, topicNs).getAttributeValue(TEXTTYPE),
                                discussion.getChildText(TEXT, topicNs),
                                isProtected);
    the_handler.setDiscussionXml(discussion);
    //discussion may have attachments
    XPath path = XPath.newInstance(ATTACHMENT_QUERY);
    if (!topicNs.equals(Namespace.NO_NAMESPACE))
 path.addNamespace(topicNs); 
    for (Iterator iter=path.selectNodes(discussion).iterator(); iter.hasNext();) {
      the_handler.addAttachment(((Element)iter.next()).getAttributeValue(HREF));
    }
    the_handler.endDiscussion();
  } catch (IOException e) {
    throw new ParseException(e);
  } catch (JDOMException je) {
    throw new ParseException(je);
  }
}  
}
 
Example 9
Source File: AnnotationRulesFactoryImpl.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void loadRegex(Document doc) {
		try{
			XPath regexRule = XPath.newInstance("//implementation/script[@language='regex']");			
			List<?> regexRules = regexRule.selectNodes(doc);

			for (Object obj : regexRules) {
				Element scriptElement = (Element) obj;

				String regex = scriptElement.getTextNormalize();
				boolean isCaseInsensitive = regex.endsWith("/i");

				//java doesn't like the /^ switch so it is replaced by ^
				regex = regex.replace("/^", "^");
				//java does not support the /i case in-sensitivity switch so it is removed
				regex = regex.replace("/i", "");

				final Element ruleElement = scriptElement.getParentElement().getParentElement().getParentElement();
				
				final String id = getElementValue(ruleElement.getChild("id"), "");
				final String title = getElementValue(ruleElement.getChild("title"), "");
				final String description = getElementValue(ruleElement.getChild("description"), null);
				
				String status = null;
				Date date = null;
				final Element statusElement = ruleElement.getChild("status");
				if (statusElement != null) {
					status = statusElement.getTextNormalize();
					String dateString = statusElement.getAttributeValue("date", (String) null);
					if (dateString != null) {
						try {
							date = status_df.get().parse(dateString);
						} catch (ParseException e) {
							LOG.warn("Could not parse String as status date: "+dateString, e);
						}
					}
				}
				
				// TODO add parsing for grand fathering date
//				Date grandFatheringDate = null;
				

				Pattern pattern;

				if (isCaseInsensitive) {
					pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
				} else {
					pattern = Pattern.compile(regex);
				}

				AnnotationRegularExpressionFromXMLRule rule = new AnnotationRegularExpressionFromXMLRule();
				rule.setRuleId(id);
				rule.setName(title);
				rule.setDescription(description);
				rule.setStatus(status);
				rule.setDate(date);
//				rule.setGrandFatheringDate(grandFatheringDate);
				rule.setErrorMessage(title);
				rule.setPattern(pattern);
				rule.setRegex(regex);

				annotationRules.add(rule);
			}
		}catch(Exception ex){
			LOG.error(ex.getMessage(), ex);
		}
	}
 
Example 10
Source File: XChangeImporter.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Find the registered Data handler that matches best the given element
 * 
 * @param el
 *            Element o be imported
 * @return the best matching handler or null if no handler exists at all for the given data type
 */
@SuppressWarnings("unchecked")
public IExchangeContributor findImportHandler(XChangeElement el){
	int matchedRestrictions = 0;
	IConfigurationElement cand = null;
	for (IConfigurationElement ice : container.getXChangeContributors()) {
		String datatype = ice.getAttribute("ElementType");
		if (datatype.equalsIgnoreCase(el.getXMLName())) {
			if (cand == null) {
				cand = ice;
			}
			String restriction = ice.getAttribute("restrictions");
			if (restriction != null) {
				String[] restrictions = restriction.split(",");
				int matches = 0;
				for (String r : restrictions) {
					try {
						XPath xpath = XPath.newInstance(r);
						List<Object> nodes = xpath.selectNodes(el);
						if (nodes.size() > 0) {
							if (++matches > matchedRestrictions) {
								cand = ice;
								matchedRestrictions = matches;
							} else if (matches == matchedRestrictions) {
								if (compareValues(ice, cand) == -1) {
									cand = ice;
								}
							}
						}
					} catch (JDOMException e) {
						ElexisStatus status =
							new ElexisStatus(ElexisStatus.WARNING, Hub.PLUGIN_ID,
								ElexisStatus.CODE_NONE, "Parse error JDOM: " + e.getMessage(),
								e, ElexisStatus.LOG_WARNINGS);
						throw new ExchangeException(status);
					}
				}
				
			} else {
				if (compareValues(ice, cand) == -1)
					cand = ice;
			}
		}
		
	}
	if (cand != null) {
		try {
			return (IExchangeContributor) cand.createExecutableExtension("Actor");
		} catch (CoreException ce) {
			ExHandler.handle(ce);
		}
	}
	return null;
}