org.jdom2.JDOMException Java Examples

The following examples show how to use org.jdom2.JDOMException. 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: MCRNodeBuilderTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testExpressionsToIgnore() throws JaxenException, JDOMException {
    Element built = new MCRNodeBuilder().buildElement("element[2]", null, null);
    assertNotNull(built);
    assertEquals("element", built.getName());

    built = new MCRNodeBuilder().buildElement("element[contains(.,'foo')]", null, null);
    assertNotNull(built);
    assertEquals("element", built.getName());

    built = new MCRNodeBuilder().buildElement("foo|bar", null, null);
    assertNull(built);

    Attribute attribute = new MCRNodeBuilder().buildAttribute("@lang[preceding::*/foo='bar']", "value", null);
    assertNotNull(attribute);
    assertEquals("lang", attribute.getName());
    assertEquals("value", attribute.getValue());

    built = new MCRNodeBuilder().buildElement("parent/child/following::node/foo='bar'", null, null);
    assertNotNull(built);
    assertEquals("child", built.getName());
    assertNotNull(built.getParentElement());
    assertEquals("parent", built.getParentElement().getName());
    assertEquals(0, built.getChildren().size());
    assertEquals("", built.getText());
}
 
Example #2
Source File: NcmlCollectionReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read an NcML file from a URL location, and construct a NcmlCollectionReader from its scan or scanFmrc element.
 *
 * @param ncmlLocation the URL location string of the NcML document
 * @param errlog put error messages here
 * @return the resulting NetcdfDataset
 * @throws IOException on read error, or bad referencedDatasetUri URI
 */
public static NcmlCollectionReader open(String ncmlLocation, Formatter errlog) throws IOException {
  if (!ncmlLocation.startsWith("http:") && !ncmlLocation.startsWith("file:"))
    ncmlLocation = "file:" + ncmlLocation;

  URL url = new URL(ncmlLocation);

  org.jdom2.Document doc;
  try {
    SAXBuilder builder = new SAXBuilder();
    if (debugURL)
      System.out.println(" NetcdfDataset URL = <" + url + ">");
    doc = builder.build(url);
  } catch (JDOMException e) {
    throw new IOException(e.getMessage());
  }
  if (debugXML)
    System.out.println(" SAXBuilder done");

  return readXML(doc, errlog, ncmlLocation);
}
 
Example #3
Source File: DBConfig.java    From mealOrdering with MIT License 6 votes vote down vote up
/**
 * 鍦ㄥ垵濮嬪寲鏃朵粠鏂囦欢涓幏鍙栭厤缃苟淇濆瓨
 */
public DBConfig() {
    SAXBuilder jdomBuilder = new SAXBuilder();

    try {
        String configPath = DBConfig.class.getResource("/") + "../../config/mysql.xml";

        Document document = jdomBuilder.build(configPath);

        Element root = document.getRootElement();

        setHost(root.getChildText("host").trim());
        setPort(root.getChildText("port").trim());
        setDatabase(root.getChildText("database").trim());
        setUsername(root.getChildText("username").trim());
        setPassword(root.getChildText("password").trim());
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}
 
Example #4
Source File: NcepLocalParams.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean readParameterTableFromResource(String resource) {
  if (debugOpen)
    logger.debug("readParameterTableFromResource from resource {}", resource);
  ClassLoader cl = this.getClass().getClassLoader();
  try (InputStream is = cl.getResourceAsStream(resource)) {
    if (is == null) {
      logger.info("Cant read resource " + resource);
      return false;
    }
    SAXBuilder builder = new SAXBuilder();
    org.jdom2.Document doc = builder.build(is);
    Element root = doc.getRootElement();
    paramMap = parseXml(root); // all at once - thread safe
    return true;

  } catch (IOException | JDOMException ioe) {
    ioe.printStackTrace();
    return false;
  }
}
 
Example #5
Source File: ClientResponseHandler.java    From jframe with Apache License 2.0 6 votes vote down vote up
/**
 * 解析XML内容
 */
@SuppressWarnings("rawtypes")
protected void doParse() throws JDOMException, IOException {
    String xmlContent = this.getContent();

    // 解析xml,得到map
    Map m = XMLUtil.doXMLParse(xmlContent);

    // 设置参数
    Iterator it = m.keySet().iterator();
    while (it.hasNext()) {
        String k = (String) it.next();
        String v = (String) m.get(k);
        this.setParameter(k, v);
    }

}
 
Example #6
Source File: StationList.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void loadFromXmlFile(String filename) {
  SAXBuilder builder = new SAXBuilder();
  File f = new File(filename);
  try {
    Document doc = builder.build(f);
    Element list = doc.getRootElement();
    for (Element station : list.getChildren()) {
      Element loc = station.getChild("location3D");
      String stid = station.getAttributeValue("value");
      Station newStation = addStation(stid, LatLonPoint.create(Double.valueOf(loc.getAttributeValue("latitude")),
          Double.valueOf(loc.getAttributeValue("longitude"))));
      newStation.setElevation(Double.valueOf(loc.getAttributeValue("elevation")));
      newStation.setName(station.getAttributeValue("name"));
      newStation.setState(station.getAttributeValue("state"));
      newStation.setCountry(station.getAttributeValue("country"));
    }
  } catch (IOException | JDOMException e) {
    e.printStackTrace();
  }
}
 
Example #7
Source File: TestExtractionTest.java    From emissary with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckStringValueForCollection() throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder(org.jdom2.input.sax.XMLReaders.NONVALIDATING);
    String resourceName = "/emissary/test/core/TestExtractionTest.xml";
    InputStream inputStream = TestExtractionTest.class.getResourceAsStream(resourceName);
    Assert.assertNotNull("Could not locate: " + resourceName, inputStream);
    Document answerDoc = builder.build(inputStream);
    inputStream.close();

    WhyDoYouMakeMeDoThisExtractionTest test = new WhyDoYouMakeMeDoThisExtractionTest("nonsense");

    Element meta = answerDoc.getRootElement().getChild("answers").getChild("meta");
    test.checkStringValue(meta, "1;2;3;4;5;6;7", "testCheckStringValueForCollection");
    test.checkStringValue(meta, "1;3;4;2;5;6;7", "testCheckStringValueForCollection");
    test.checkStringValue(meta, "1;3;2;4;7;5;6", "testCheckStringValueForCollection");
    test.checkStringValue(meta, "7;6;5;4;3;2;1", "testCheckStringValueForCollection");
}
 
Example #8
Source File: NcMLReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read NcML doc from a Reader, and construct a NetcdfDataset.
 * eg: NcMLReader.readNcML(new StringReader(ncml), location, null);
 *
 * @param r the Reader containing the NcML document
 * @param ncmlLocation the URL location string of the NcML document, used to resolve reletive path of the referenced
 *        dataset,
 *        or may be just a unique name for caching purposes.
 * @param cancelTask allow user to cancel the task; may be null
 * @return the resulting NetcdfDataset
 * @throws IOException on read error, or bad referencedDatasetUri URI
 */
public static NetcdfDataset readNcML(Reader r, String ncmlLocation, CancelTask cancelTask) throws IOException {

  org.jdom2.Document doc;
  try {
    SAXBuilder builder = new SAXBuilder();
    doc = builder.build(r);
  } catch (JDOMException e) {
    throw new IOException(e.getMessage());
  }
  if (debugXML)
    System.out.println(" SAXBuilder done");

  if (showParsedXML) {
    XMLOutputter xmlOut = new XMLOutputter();
    System.out.println("*** NetcdfDataset/showParsedXML = \n" + xmlOut.outputString(doc) + "\n*******");
  }

  Element netcdfElem = doc.getRootElement();
  NetcdfDataset ncd = readNcML(ncmlLocation, netcdfElem, cancelTask);
  if (debugOpen)
    System.out.println("***NcMLReader.readNcML (stream) result= \n" + ncd);
  return ncd;
}
 
Example #9
Source File: CLI.java    From ixa-pipe-nerc with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the command interface parameters with the argParser.
 * 
 * @param args
 *          the arguments passed through the CLI
 * @throws IOException
 *           exception if problems with the incoming data
 * @throws JDOMException
 *           if xml format problems
 */
public final void parseCLI(final String[] args)
    throws IOException, JDOMException {
  try {
    parsedArguments = argParser.parseArgs(args);
    System.err.println("CLI options: " + parsedArguments);
    switch (args[0]) {
    case ANNOTATE_PARSER_NAME:
      annotate(System.in, System.out);
      break;
    case SERVER_PARSER_NAME:
      server();
      break;
    case CLIENT_PARSER_NAME:
      client(System.in, System.out);
      break;
    }
  } catch (ArgumentParserException e) {
    argParser.handleError(e);
    System.out.println("Run java -jar target/ixa-pipe-nerc-" + version
        + "-exec.jar (tag|server|client) -help for details");
    System.exit(1);
  }
}
 
Example #10
Source File: MCRMetsIIIFPresentationImpl.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
public Document getMets(String id) throws IOException, JDOMException, SAXException {

        String objectid = MCRLinkTableManager.instance().getSourceOf(id).iterator().next();
        MCRContentTransformer transformer = getTransformer();
        MCRParameterCollector parameter = new MCRParameterCollector();

        if (objectid != null && objectid.length() != 0) {
            MCRDerivate derObj = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(id));
            MCRObjectID ownerID = derObj.getOwnerID();
            objectid = ownerID.toString();

            parameter.setParameter("objectID", objectid);
            parameter.setParameter("derivateID", id);
        }

        MCRPath metsPath = MCRPath.getPath(id, "mets.xml");
        if (!Files.exists(metsPath)) {
            throw new MCRException("File not found: " + id);
        }

        MCRPathContent source = new MCRPathContent(metsPath);
        MCRContent content = transformer instanceof MCRParameterizedTransformer
            ? ((MCRParameterizedTransformer) transformer).transform(source, parameter)
            : transformer.transform(source);
        return content.asXML();
    }
 
Example #11
Source File: ISBNRange.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * 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 {
  XPathExpression<Element> xpa = XPathFactory.instance().compile(xpath, Filters.element());
  List<Element> results = xpa.evaluate(root);
  Iterator<Element> iter = results.iterator();
  while (iter.hasNext()) {
    Element node = 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 #12
Source File: XmlMetadataLoader.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T extends SourceMetadata> T read(String id, InputStream xml) {
    SAXBuilder builder = new SAXBuilder();
    Document doc;
    try {
        doc = builder.build(xml);
    } catch (JDOMException | IOException e) {
        throw new N2oException("Error reading metadata " + id, e);
    }
    Element root = doc.getRootElement();
    T n2o = (T) elementReaderFactory.produce(root).read(root);
    if (n2o == null)
        throw new MetadataReaderException("Xml Element Reader must return not null object");
    n2o.setId(id);
    return n2o;
}
 
Example #13
Source File: MCRSwapInsertTargetTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testSwap() throws JaxenException, JDOMException {
    Element template = new MCRNodeBuilder().buildElement("parent[name='a'][note][foo][name='b'][note[2]]", null,
        null);
    Document doc = new Document(template);
    MCRBinding root = new MCRBinding(doc);

    MCRRepeatBinding repeat = new MCRRepeatBinding("parent/name", root, 2, 0, "build");
    assertEquals(2, repeat.getBoundNodes().size());

    assertEquals("a", doc.getRootElement().getChildren().get(0).getText());
    assertEquals("b", doc.getRootElement().getChildren().get(3).getText());

    assertEquals("a", ((Element) (repeat.getBoundNodes().get(0))).getText());
    assertEquals("b", ((Element) (repeat.getBoundNodes().get(1))).getText());

    repeat.bindRepeatPosition();
    String swapParam = MCRSwapTarget.getSwapParameter(repeat, MCRSwapTarget.MOVE_DOWN);
    new MCRSwapTarget().handle(swapParam, root);

    assertEquals("b", doc.getRootElement().getChildren().get(0).getText());
    assertEquals("a", doc.getRootElement().getChildren().get(3).getText());
}
 
Example #14
Source File: XmlUtils.java    From gocd with Apache License 2.0 5 votes vote down vote up
private static Document buildXmlDocument(InputStream inputStream, SAXBuilder builder) throws JDOMException, IOException {
    XsdErrorTranslator errorHandler = new XsdErrorTranslator();
    builder.setErrorHandler(errorHandler);

    Document cruiseRoot = builder.build(inputStream);
    if (errorHandler.hasValidationError()) {
        throw new XsdValidationException(errorHandler.translate());
    }
    return cruiseRoot;
}
 
Example #15
Source File: XsdTypeProvider.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private void init() throws IOException, JDOMException {
    System.setProperty("javax.xml.parsers.SAXParserFactory",
            "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");

    SAXBuilder b = new SAXBuilder();

    for (Resource schemaFile : schemaFiles) {
        parseSchema(b, schemaFile);
    }
}
 
Example #16
Source File: MCRRealmFactory.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private static Document getRealms() throws JDOMException, TransformerException, SAXException, IOException {
    if (realmsFile == null) {
        return MCRSourceContent.getInstance(realmsURI.toASCIIString()).asXML();
    }
    if (!realmsFile.exists() || realmsFile.length() == 0) {
        LOGGER.info("Creating {}...", realmsFile.getAbsolutePath());
        MCRSourceContent realmsContent = MCRSourceContent.getInstance(RESOURCE_REALMS_URI);
        realmsContent.sendTo(realmsFile);
    }
    updateLastModified();
    return MCRXMLParserFactory.getNonValidatingParser().parseXML(new MCRFileContent(realmsFile));
}
 
Example #17
Source File: MCRORCIDResource.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Publishes a work in the current user's ORCID profile, or
 * updates an existing work there, given the object ID of the local MODS object.
 *
 * The request path must contain the MCRObjectID to publish.
 * The current user must have an ORCID profile and must have authorized this application
 * to add or updated works.
 *
 * Returns the new publication status as by {@link #getPublicationStatus(String)}
 *
 * @author Frank L\u00FCtzenkirchen
 */
@GET
@Path("publish/{objectID}")
@Produces(MediaType.APPLICATION_JSON)
public String publish(@PathParam("objectID") String objectID) throws JDOMException, IOException, SAXException {
    MCRObjectID oid = checkID(objectID);
    MCRORCIDUser user = MCRORCIDSession.getCurrentUser();

    MCRUserStatus userStatus = user.getStatus();
    if (!(userStatus.isORCIDUser() && userStatus.weAreTrustedParty())) {
        throw new WebApplicationException(Status.FORBIDDEN);
    }

    try {
        MCRORCIDProfile profile = user.getProfile();
        MCRWorksSection works = profile.getWorksSection();
        MCRPublicationStatus status = user.getPublicationStatus(oid);

        if (!status.isUsersPublication()) {
            throw new WebApplicationException(Status.FORBIDDEN);
        } else if (!status.isInORCIDProfile()) {
            works.addWorkFrom(oid);
        } else if (status.isInORCIDProfile()) {
            works.findWork(oid).get().update();
        }

        return publicationStatus(oid, user);
    } catch (Exception ex) {
        LOGGER.warn("Exception publishing " + oid + " to ORCID", ex);
        String msg = ex.getClass().getName() + " " + ex.getMessage();
        throw new InternalServerErrorException(msg);
    }
}
 
Example #18
Source File: XsdTypeProvider.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private void init() throws IOException, JDOMException {

        SAXBuilder b = new SAXBuilder();

        for (Resource schemaFile : schemaFiles) {
            parseSchema(b, schemaFile);
        }
    }
 
Example #19
Source File: MCRSubselectReturnTarget.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private String getBaseXPathForSubselect(MCREditorSession session) throws JaxenException, JDOMException {
    Document doc = session.getEditedXML();
    MCRChangeData change = session.getChangeTracker().findLastChange(doc);
    String text = change.getText();
    String xPath = text.substring(text.lastIndexOf(" ") + 1).trim();
    return bindsFirstOrMoreThanOneElement(xPath, session) ? xPath + "[1]" : xPath;
}
 
Example #20
Source File: CommandFlasher.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public XMLBootConfig getBootConfig() throws FileNotFoundException, IOException,X10FlashException, JDOMException, TAFileParseException, BootDeliveryException  {
if (!_bundle.hasBootDelivery()) {
	logger.info("No boot delivery into the bundle");
	return null;
}
logger.info("Parsing boot delivery");
XMLBootDelivery xml = _bundle.getXMLBootDelivery();
Vector<XMLBootConfig> found = new Vector<XMLBootConfig>();
  		Enumeration<XMLBootConfig> e = xml.getBootConfigs();
  		while (e.hasMoreElements()) {
  			// We get matching bootconfig from all configs
  			XMLBootConfig bc=e.nextElement();
  			bc.addMatcher("PLF_ROOT_HASH", phoneprops.getProperty("root-key-hash"));
  			if (bc.matchAttributes()) {
  				found.add(bc);
  			}
  		}
if (found.size()==0)
	throw new BootDeliveryException ("Found no matching boot config. Aborting");
// if found more thant 1 config
boolean same = true;
if (found.size()>1) {
	// Check if all found configs have the same fileset
	Iterator<XMLBootConfig> masterlist = found.iterator();
	while (masterlist.hasNext()) {
		XMLBootConfig masterconfig = masterlist.next();
		Iterator<XMLBootConfig> slavelist = found.iterator();
		while (slavelist.hasNext()) {
			XMLBootConfig slaveconfig = slavelist.next();
			if (slaveconfig.compare(masterconfig)==2)
				throw new BootDeliveryException ("Cannot decide among found configurations. Skipping boot delivery");
		}
	}
}
found.get(found.size()-1).setFolder(_bundle.getBootDelivery().getFolder());
logger.info("Found a boot delivery");
return found.get(found.size()-1);
  }
 
Example #21
Source File: CmSynchronizer.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
protected void reconcileCourseSets(Document doc) {
	long start = System.currentTimeMillis();
	if(log.isInfoEnabled()) log.info("Reconciling CourseSets");
	
	try {
		XPath docsPath = XPath.newInstance("/cm-data/course-sets/course-set");
		List items = docsPath.selectNodes(doc);
		if(log.isDebugEnabled()) log.debug("Found " + items.size() + " course sets to reconcile");

		// Add or update each of the course offerings specified in the xml
		for(Iterator iter = items.iterator(); iter.hasNext();) {
			Element element = (Element)iter.next();
			String eid = element.getChildText("eid");
			if(log.isDebugEnabled()) log.debug("Reconciling course set " + eid);

			CourseSet courseSet = null;
			if(cmService.isCourseSetDefined(eid)) {
				courseSet = updateCourseSet(cmService.getCourseSet(eid), element);
			} else {
				courseSet = addCourseSet(element);
			}
			
			// Update the members
			Element members = element.getChild("members");
			if(members != null) {
				updateCourseSetMembers(members, courseSet);
			}
		}
	} catch (JDOMException jde) {
		log.error(jde.getMessage());
	}
	if(log.isInfoEnabled()) log.info("Finished reconciling CourseSets in " + (System.currentTimeMillis()-start) + " ms");
}
 
Example #22
Source File: SelectiveUtil.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <N > N read(String source, ElementReaderFactory readerFactory) {
    try (Reader stringReader = new StringReader(source)) {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(stringReader);
        Element root = doc.getRootElement();
        return (N) readerFactory.produce(root).read(root);
    } catch (JDOMException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: MCRUserTransformer.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private static Document getDocument(MCRUser user) {
    MCRJAXBContent<MCRUser> content = new MCRJAXBContent<>(JAXB_CONTEXT, user);
    try {
        Document userXML = content.asXML();
        sortAttributes(userXML);
        return userXML;
    } catch (SAXParseException | JDOMException | IOException e) {
        throw new MCRException("Exception while transforming MCRUser " + user.getUserID() + " to JDOM document.",
            e);
    }
}
 
Example #24
Source File: LightweightBMLParser.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * scans the incoming stream for bml-string and interprets
 * the xml-tree for bml-data.
 * 
 * @param bmlString the string for parsing the bml tree
 * @return BML-Message with a list of bml information
 * @throws JDOMException xml-string is corrupted
 * @throws IOException cannot read from stream
 */
public final BML generateBML(final String bmlString) throws JDOMException,
    IOException {
  // Build XML-Tree
  Document doc = xmlBuilder.build(new StringReader(bmlString.trim()));
  Element root = doc.getRootElement();

  // Generate BML From Document
  return generateBML(root);
}
 
Example #25
Source File: MCRStaticXEditorFileServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/** For defined document types like static webpages, replace editor elements with complete editor definition */
@Override
protected MCRContent getResourceContent(HttpServletRequest request, HttpServletResponse response, URL resource)
    throws IOException, JDOMException, SAXException {
    MCRContent content = super.getResourceContent(request, response, resource);

    if (mayContainEditorForm(content)) {
        content = doExpandEditorElements(content, request, response,
            request.getParameter(MCREditorSessionStore.XEDITOR_SESSION_PARAM),
            request.getRequestURL().toString());
    }
    return content;
}
 
Example #26
Source File: ConsistentDatesTest.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
@Ignore("WMS not working")
public void checkWMSDates() throws JDOMException, IOException {
  String endpoint = TestOnLocalServer.withHttpPath(
      "/wms/cdmUnitTest/ncss/climatology/PF5_SST_Climatology_Monthly_1985_2001.nc?service=WMS&version=1.3.0&request=GetCapabilities");
  byte[] result = TestOnLocalServer.getContent(endpoint, 200, ContentType.xml);
  Reader in = new StringReader(new String(result, StandardCharsets.UTF_8));
  SAXBuilder sb = new SAXBuilder();
  Document doc = sb.build(in);

  if (show) {
    XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
    fmt.output(doc, System.out);
  }

  XPath xPath = XPath.newInstance("//wms:Dimension");
  xPath.addNamespace("wms", doc.getRootElement().getNamespaceURI());
  Element dimNode = (Element) xPath.selectSingleNode(doc);
  // List<String> content = Arrays.asList(dimNode.getText().trim().split(","));
  List<String> content = new ArrayList<>();
  for (String d : Arrays.asList(dimNode.getText().trim().split(","))) {
    // System.out.printf("Date= %s%n", d);
    CalendarDate cd = CalendarDate.parseISOformat(null, d);
    content.add(cd.toString());
  }

  assertEquals(expectedDatesAsDateTime, content);
}
 
Example #27
Source File: TestGridAsPointP.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void checkGridAsPointNetcdfOld(byte[] content, String varName) throws JDOMException, IOException {
  // Open the binary response in memory
  Formatter errlog = new Formatter();
  try (NetcdfFile nf = NetcdfFile.openInMemory("checkGridAsPointNetcdf.nc", content)) {
    FeatureDataset fd = FeatureDatasetFactoryManager.wrap(FeatureType.STATION, new NetcdfDataset(nf), null, errlog);
    assertNotNull(errlog.toString(), fd);
    VariableSimpleIF v = fd.getDataVariable(varName);
    assertNotNull(varName, v);
  }
}
 
Example #28
Source File: CmSynchronizer.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
protected void reconcileCourseSets(Document doc) {
	long start = System.currentTimeMillis();
	if(log.isInfoEnabled()) log.info("Reconciling CourseSets");
	
	try {
		XPath docsPath = XPath.newInstance("/cm-data/course-sets/course-set");
		List items = docsPath.selectNodes(doc);
		if(log.isDebugEnabled()) log.debug("Found " + items.size() + " course sets to reconcile");

		// Add or update each of the course offerings specified in the xml
		for(Iterator iter = items.iterator(); iter.hasNext();) {
			Element element = (Element)iter.next();
			String eid = element.getChildText("eid");
			if(log.isDebugEnabled()) log.debug("Reconciling course set " + eid);

			CourseSet courseSet = null;
			if(cmService.isCourseSetDefined(eid)) {
				courseSet = updateCourseSet(cmService.getCourseSet(eid), element);
			} else {
				courseSet = addCourseSet(element);
			}
			
			// Update the members
			Element members = element.getChild("members");
			if(members != null) {
				updateCourseSetMembers(members, courseSet);
			}
		}
	} catch (JDOMException jde) {
		log.error(jde.getMessage());
	}
	if(log.isInfoEnabled()) log.info("Finished reconciling CourseSets in " + (System.currentTimeMillis()-start) + " ms");
}
 
Example #29
Source File: GribVariableRenamer.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private List<VariableRenamerBean> readVariableRenameFile(String path) {
  java.util.List<VariableRenamerBean> beans = new ArrayList<>(1000);
  try (InputStream is = GribResourceReader.getInputStream(path)) {
    if (is == null) {
      logger.warn("Cant read file " + path);
      return null;
    }

    SAXBuilder builder = new SAXBuilder();
    org.jdom2.Document doc = builder.build(is);
    Element root = doc.getRootElement();
    List<Element> dsElems = root.getChildren("dataset");
    for (Element dsElem : dsElems) {
      String dsName = dsElem.getAttributeValue("name");
      List<Element> params = dsElem.getChildren("param");
      for (Element elem : params) {
        String oldName = elem.getAttributeValue("oldName");
        String newName = elem.getAttributeValue("newName");
        String varId = elem.getAttributeValue("varId");
        beans.add(new VariableRenamerBean(dsName, oldName, newName, varId));
      }
    }
    return beans;

  } catch (IOException | JDOMException ioe) {
    ioe.printStackTrace();
    return null;
  }
}
 
Example #30
Source File: MCRXEditorTransformerTest.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testValidation() throws IOException, URISyntaxException, TransformerException, JDOMException,
    SAXException, JaxenException {
    MCREditorSession session = testTransformation("testValidation-editor.xml",
        "testBasicInputComponents-source.xml", "testValidation-transformed1.xml");
    assertTrue(session.getValidator().isValid());
    session = testTransformation("testValidation-editor.xml", null, "testValidation-transformed2.xml");
    assertFalse(session.getValidator().isValid());
    testTransformation("testValidation-editor.xml", null, session, "testValidation-transformed3.xml");
}