Java 类org.jdom2.JDOMException 实例源码

项目:goobi-viewer-connector    文件:Utils.java   
/**
 * Create a JDOM document from an XML string.
 * 
 * @param string
 * @param encoding
 * @return
 * @throws IOException
 * @throws JDOMException
 * @should build document correctly
 */
public static Document getDocumentFromString(String string, String encoding) throws JDOMException, IOException {
    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
    }

    byte[] byteArray = null;
    try {
        byteArray = string.getBytes(encoding);
    } catch (UnsupportedEncodingException e) {
    }
    ByteArrayInputStream baos = new ByteArrayInputStream(byteArray);
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(baos);

    return document;
}
项目:goobi-viewer-indexer    文件:Utils.java   
/**
 * Create a JDOM document from an XML string.
 *
 * @param string
 * @return
 * @throws IOException
 * @throws JDOMException
 * @should build document correctly
 */
public static Document getDocumentFromString(String string, String encoding) throws JDOMException, IOException {
    if (string == null) {
        throw new IllegalArgumentException("string may not be null");
    }
    if (encoding == null) {
        encoding = "UTF-8";
    }

    byte[] byteArray = null;
    try {
        byteArray = string.getBytes(encoding);
    } catch (UnsupportedEncodingException e) {
    }
    ByteArrayInputStream baos = new ByteArrayInputStream(byteArray);

    // Reader reader = new StringReader(hOCRText);
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(baos);

    return document;
}
项目:Java-Data-Science-Cookbook    文件:TestJdom.java   
public void parseXml(String fileName){
    SAXBuilder builder = new SAXBuilder();
    File file = new File(fileName);
    try {
        Document document = (Document) builder.build(file);
        Element rootNode = document.getRootElement();
        List list = rootNode.getChildren("author");
        for (int i = 0; i < list.size(); i++) {
            Element node = (Element) list.get(i);
            System.out.println("First Name : " + node.getChildText("firstname"));
            System.out.println("Last Name : " + node.getChildText("lastname"));
        }
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }



}
项目:bibliometrics    文件:AuthorBuilder.java   
/**
   * retrieves the ScopusAuthorID for an author and puts it into the <code>PublicationAuthor</code> object
   * @throws HttpException thrown upon connecting to the source
* @throws JDOMException thrown upon parsing the source response
* @throws IOException thrown upon reading profiles from disc
* @throws SAXException thrown when parsing the files from disc
*/
  public void retrieveScopusAuthorID() throws HttpException, JDOMException, IOException, SAXException {
      ScopusConnector connection = new ScopusConnector();
      Element result = connection.retrieveScopusAuthorID(author).asXML().detachRootElement().clone();

      List<String> allIDs = new ArrayList<>();
      for (Element child : result.getChildren()) {
          if (result.getName().equals("error")) continue;
          if (child.getName().equals("entry")) {
              Element identifier = child.getChild("identifier",DC_NS);
              String value = identifier.getValue().replace("AUTHOR_ID:", "");
              allIDs.add(value);
          }
      }
      if (allIDs.size() == 1) {
          author.setScopusAuthorID(allIDs.get(0));
          LOGGER.info("found ScopusID: " + author.getScopusAuthorID());
      } else
          author.setScopusAuthorID(toBeChecked);
  }
项目:bibliometrics    文件:Institution.java   
public JSONObject createGeoJsonPoint() throws HttpException, JDOMException, IOException, SAXException {
    JSONObject geoJSONInd = new JSONObject();
    JSONObject geometry = new JSONObject();
    geometry.put("type", "Point");
    JSONArray coordinates = new JSONArray();
    coordinates.put(longitude).put(latitude);
    geometry.put("coordinates", coordinates);
    geoJSONInd.put("geometry", geometry);

    geoJSONInd.put("type", "Feature");
    JSONObject properties = new JSONObject();
    properties.put("name", city);
    geoJSONInd.put("properties", properties);
    String description = institution;
    if (!department.isEmpty())
        description = description + "<br />" + department;
    properties.put("popupContent", description);
    return geoJSONInd;
}
项目:bibliometrics    文件:MyCoReConnector.java   
private int getNumberOfPublications(String queryURL) throws JDOMException, IOException, SAXException {
    //build API URL

    //get response as XML-file
    Document response = getResponse(queryURL).asXML();

    int numberOfPublications  =0;

    //read and return total number of publications from XML-file
    try {
        numberOfPublications = Integer.parseInt(response.getRootElement().getChild("result").getAttributeValue("numFound"));
    } catch (Exception e) {
        LOGGER.info("found no documents in repository");
    }
    return numberOfPublications;
}
项目:bibliometrics    文件:ScopusConnector.java   
public Set<Element> getPublicationsForAuthor(PublicationAuthor author)
        throws IOException, JDOMException, SAXException {
    if (!author.getScopusAuthorID().isEmpty()) {
        Set<Element> publications = new HashSet<>();
        String queryURL = API_URL + "/author/AUTHOR_ID:" + author.getScopusAuthorID()
                + "?start=0&count=200&view=DOCUMENTS&apikey=" + API_KEY;
        XPathExpression<Element> xPath = XPathFactory.instance().compile(pathToDocumentIdentifier,
                Filters.element());
        List<Element> identifierElements = xPath
                .evaluate(getResponse(queryURL).asXML().detachRootElement().clone());
        for (Element idElement : identifierElements) {
            publications.add(getPublicationByID(idElement.getValue()));
        }
        return publications;
    } else
        return null;
}
项目:bibliometrics    文件:ScopusConnector.java   
public Element getCitationInformation(String scopusID)
        throws IOException, JDOMException, SAXException {
    // build API URL
    String queryURL = API_URL + "/abstract/citation-count?scopus_id=" + scopusID + "&apikey=" + API_KEY
            + "&httpAccept=application%2Fxml";
    XPathExpression<Element> xPathCount = XPathFactory.instance().compile(pathToCitationCount, Filters.element());
    XPathExpression<Element> xPathLink = XPathFactory.instance().compile(pathToCitationLink, Filters.element());
    XPathExpression<Element> xPathArticleLink = XPathFactory.instance().compile(pathToArticleLink, Filters.element());
    Element response = getResponse(queryURL).asXML().detachRootElement().clone();
    String citationCount = xPathCount.evaluateFirst(response).getValue();
    String citationLink = xPathLink.evaluateFirst(response).getAttributeValue("href");
    String articleLink = xPathArticleLink.evaluateFirst(response).getAttributeValue("href");
    Element citationInformation = new Element("citationInformation");
    citationInformation.addContent(new Element("count").setText(citationCount));
    citationInformation.addContent(new Element("citationLink").setText(citationLink));
    citationInformation.addContent(new Element("articleLink").setText(articleLink));
    return citationInformation;
}
项目:bibliometrics    文件:ScopusConnector.java   
public List<MCRContent> getAll() throws IOException, JDOMException, SAXException {
    // prepare list of results blocks
    List<MCRContent> resultsSet = new ArrayList<>();
    // build basic part of API URL
    String baseQueryURL = API_URL + "/affiliation/AFFILIATION_ID:" + AFFIL_ID + "?apikey=" + API_KEY
            + "&view=DOCUMENTS";

    // divide API request in blocks a XXX documents (in final version 200
    // documents per block, number of blocks determined by total number of
    // documents)
    // int numberOfPublications = getNumberOfPublications(baseQueryURL);
    // at the moment only testing, two blocks a 10 documents
    for (int i = 0; i < 2; i++) {
        int start = 10 * i;
        int count = 10;

        // build API URL
        String queryURL = baseQueryURL + "&start=" + start + "&count=" + count + "&view=DOCUMENTS";

        // add block to list of blocks
        resultsSet.add(getResponse(queryURL));
    }
    // return API-response
    return resultsSet;
}
项目:mycore    文件:MCREditorSubmission.java   
private void setSubmittedValues(MCRBinding binding, String[] values) throws JDOMException, JaxenException {
    List<Object> boundNodes = binding.getBoundNodes();

    while (boundNodes.size() < values.length) {
        binding.cloneBoundElement(boundNodes.size() - 1);
    }

    for (int i = 0; i < values.length; i++) {
        String value = values[i] == null ? "" : values[i].trim();
        value = MCRXMLFunctions.normalizeUnicode(value);
        value = MCRXMLHelper.removeIllegalChars(value);
        binding.setValue(i, value);
    }

    removeXPaths2CheckResubmission(binding);
    binding.detach();
}
项目:mycore    文件:MCREditorSubmissionTest.java   
@Test
public void testSubmitTextfields() throws JaxenException, JDOMException, IOException {
    String template = "document[title='Titel'][author[@firstName='John'][@lastName='Doe']]";
    MCREditorSession session = new MCREditorSession();
    session.setEditedXML(new Document(new MCRNodeBuilder().buildElement(template, null, null)));

    Map<String, String[]> submittedValues = new HashMap<>();
    submittedValues.put("/document/title", new String[] { "Title" });
    submittedValues.put("/document/author/@firstName", new String[] { "Jim" });
    submittedValues.put("/document/author/@lastName", new String[] { "" });
    session.getSubmission().setSubmittedValues(submittedValues);
    session.getSubmission().emptyNotResubmittedNodes();

    template = "document[title='Title'][author[@firstName='Jim'][@lastName='']]";
    Document expected = new Document(new MCRNodeBuilder().buildElement(template, null, null));
    Document result = session.getEditedXML();
    result = MCRChangeTracker.removeChangeTracking(result);
    assertTrue(MCRXMLHelper.deepEqual(expected, result));
}
项目:HELM2NotationToolkit    文件:ChangeObjects.java   
/**
 * method to replace the MonomerID with the new MonomerID for a given
 * polymer type
 *
 * @param helm2notation
 *            HELM2Notation
 * @param polymerType
 *            String of the polymer type
 * @param existingMonomerID
 *            old MonomerID
 * @param newMonomerID
 *            new MonomerID
 * @throws NotationException
 *             if notation was not valid
 * @throws MonomerException
 *             if monomer is not valid
 * @throws ChemistryException
 *             if chemistry engine could not be initialized
 * @throws CTKException
 *             general ChemToolKit exception passed to HELMToolKit
 * @throws IOException IO error
 * @throws JDOMException jdome error
 *             
 */
public final static void replaceMonomer(HELM2Notation helm2notation, String polymerType, String existingMonomerID,
        String newMonomerID) throws NotationException, MonomerException,
                ChemistryException, CTKException, IOException, JDOMException {
    validateMonomerReplacement(polymerType, existingMonomerID, newMonomerID);
    /*
     * if(newMonomerID.length()> 1){ if( !( newMonomerID.startsWith("[") &&
     * newMonomerID.endsWith("]"))){ newMonomerID = "[" + newMonomerID +
     * "]"; } }
     */
    for (int i = 0; i < helm2notation.getListOfPolymers().size(); i++) {
        if (helm2notation.getListOfPolymers().get(i).getPolymerID().getType().equals(polymerType)) {
            for (int j = 0; j < helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements()
                    .size(); j++) {
                MonomerNotation monomerNotation = replaceMonomerNotation(
                        helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements().get(j),
                        existingMonomerID, newMonomerID);
                if (monomerNotation != null) {
                    helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements().set(j,
                            monomerNotation);
                }
            }
        }
    }
}
项目:mycore    文件:MCRMediaThumbnailServlet.java   
private BufferedImage getThumbnail(MCRFile thumbFile) throws IOException, JDOMException {
    ImageReader reader = getImageReader();
    BufferedImage level1Image = readThumb(thumbFile, reader);
    final double width = level1Image.getWidth();
    final double height = level1Image.getHeight();
    final int newWidth = width < height ? (int) Math.ceil(thumbnailSize * width / height) : thumbnailSize;
    final int newHeight = width < height ? thumbnailSize : (int) Math.ceil(thumbnailSize * height / width);
    int imageType = level1Image.getType();
    if (imageType == BufferedImage.TYPE_CUSTOM) {
        imageType = BufferedImage.TYPE_INT_RGB;
    }
    final BufferedImage bicubic = new BufferedImage(newWidth, newHeight, imageType);
    final Graphics2D bg = bicubic.createGraphics();
    bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    bg.scale(newWidth / width, newHeight / height);
    bg.drawImage(level1Image, 0, 0, null);
    bg.dispose();
    return bicubic;
}
项目:mycore    文件:MCRSwapInsertTargetTest.java   
@Test
public void testSwapParameter() throws JaxenException, JDOMException {
    Element template = new MCRNodeBuilder().buildElement("parent[name='aa'][name='ab'][name='bc'][name='ac']", null,
        null);
    Document doc = new Document(template);
    MCRBinding root = new MCRBinding(doc);

    MCRRepeatBinding repeat = new MCRRepeatBinding("parent/name[contains(text(),'a')]", root, 0, 0, "build");
    assertEquals(3, repeat.getBoundNodes().size());

    repeat.bindRepeatPosition();
    repeat.bindRepeatPosition();
    assertEquals("/parent|1|build|name[contains(text(), \"a\")]",
        MCRSwapTarget.getSwapParameter(repeat, MCRSwapTarget.MOVE_UP));
    assertEquals("/parent|2|build|name[contains(text(), \"a\")]",
        MCRSwapTarget.getSwapParameter(repeat, MCRSwapTarget.MOVE_DOWN));
}
项目:mycore    文件:MCRSwapInsertTargetTest.java   
@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());
}
项目:cucumber-runner-maven-plugin    文件:StreamingJSONFormatterTest.java   
@Test
public void testReportsGeneratedUsingStreamingJSONFormatter() throws IOException, InterruptedException, XmlPullParserException, JDOMException, MergeException {
    setup();

    String jsonString = FileUtils.readFileToString(outputFile,"UTF-8");
    JSONArray json = new JSONArray(jsonString);
    assertEquals("The report generated does not contain 3 feature files",3, json.length());

    List<JSONObject> testCases = new ArrayList<>();

    for (Object o : json) {
        if(!(o instanceof JSONObject))
            throw new IllegalArgumentException();

        JSONObject jsonObject = (JSONObject) o;
        JSONArray elements = jsonObject.getJSONArray("elements");
        for (Object testCase : elements) {
            testCases.add((JSONObject) testCase);
        }
    }
    assertEquals("Report generated does not have data of 15 test cases. Streaming JSON results merger failed",15, testCases.size());
}
项目:mycore    文件:MCRNodeBuilderTest.java   
@Test
public void testBuildingElements() throws JaxenException, JDOMException {
    Element built = new MCRNodeBuilder().buildElement("element", null, null);
    assertNotNull(built);
    assertEquals("element", built.getName());
    assertTrue(built.getText().isEmpty());

    built = new MCRNodeBuilder().buildElement("element", "text", null);
    assertNotNull(built);
    assertEquals("element", built.getName());
    assertEquals("text", built.getText());

    Element root = new Element("root");
    built = new MCRNodeBuilder().buildElement("element", null, root);
    assertNotNull(built);
    assertEquals("element", built.getName());
    assertNotNull(built.getParentElement());
    assertEquals("root", built.getParentElement().getName());
}
项目:mycore    文件:MCRSolrTransformerInputDocumentFactory.java   
@Override
public Iterator<SolrInputDocument> getDocuments(Map<MCRObjectID, MCRContent> contentMap) throws IOException,
    SAXException {
    if (contentMap.isEmpty()) {
        return Collections.emptyIterator();
    }
    try {
        Document doc = getMergedDocument(contentMap);
        if (isJAXBTransformer) {
            MCRParameterCollector param = new MCRParameterCollector();
            @SuppressWarnings("unchecked")
            MCRXSL2JAXBTransformer<MCRSolrInputDocumentList> jaxbTransformer = (MCRXSL2JAXBTransformer<MCRSolrInputDocumentList>) transformer;
            MCRSolrInputDocumentList input = jaxbTransformer.getJAXBObject(new MCRJDOMContent(doc), param);
            return MCRSolrInputDocumentGenerator.getSolrInputDocuments(input.getDoc()).iterator();
        } else {
            MCRContent result = transformer.transform(new MCRJDOMContent(doc));
            return getSolrInputDocuments(result);
        }
    } catch (TransformerConfigurationException | JAXBException | JDOMException e) {
        throw new IOException(e);
    }
}
项目:mycore    文件:MCRBindingTest.java   
@Test
public void testComplexBindings() throws JDOMException, JaxenException {
    binding = new MCRBinding("document/title[contains(text(),'1')]", true, binding);
    assertEquals("title1", binding.getValue());
    binding = binding.getParent();

    binding = new MCRBinding("//title[@type]", true, binding);
    assertEquals("title1", binding.getValue());
    binding = binding.getParent();

    binding = new MCRBinding("//title[not(@type='main')]", true, binding);
    assertEquals("title2", binding.getValue());
    binding = binding.getParent();

    binding = new MCRBinding("/document/title[../author/lastName='Doe'][2]", true, binding);
    assertEquals("title2", binding.getValue());
    binding = binding.getParent();

    binding = new MCRBinding("//*", true, binding);
    binding = new MCRBinding("*[name()='title'][2]", true, binding);
    assertEquals("title2", binding.getValue());
    binding = binding.getParent();
    binding = binding.getParent();
}
项目:mycore    文件:MCRCreateObjectServlet.java   
@Override
void handlePersistenceOperation(HttpServletRequest request, HttpServletResponse response)
    throws MCRAccessException, ServletException, MCRActiveLinkException, SAXParseException, JDOMException,
    IOException {
    Document editorSubmission = MCRPersistenceHelper.getEditorSubmission(request, false);
    MCRObjectID objectID;
    if (editorSubmission != null) {
        objectID = createObject(editorSubmission);
    } else {
        //editorSubmission is null, when editor input is absent (redirect to editor form in render phase)
        String projectID = getProperty(request, "project");
        String type = getProperty(request, "type");
        String formattedId = MCRObjectID.formatID(projectID + "_" + type, 0);
        objectID = MCRObjectID.getInstance(formattedId);

    }
    checkCreatePrivilege(objectID);
    request.setAttribute(OBJECT_ID_KEY, objectID);
}
项目:mycore    文件:MCRMigrationCommands.java   
@MCRCommand(syntax = "add missing children to {0}",
    help = "Adds missing children to structure of parent {0}. (MCR-1480)",
    order = 15)
public static void fixMissingChildren(String id) throws IOException, JDOMException, SAXException {
    MCRObjectID parentId = MCRObjectID.getInstance(id);
    Collection<String> children = MCRLinkTableManager.instance().getSourceOf(parentId,
        MCRLinkTableManager.ENTRY_TYPE_PARENT);
    if (children.isEmpty()) {
        return;
    }
    MCRObject parent = MCRMetadataManager.retrieveMCRObject(parentId);
    MCRObjectStructure parentStructure = parent.getStructure();
    int sizeBefore = parentStructure.getChildren().size();
    children.stream().map(MCRObjectID::getInstance)
        .filter(cid -> !parentStructure.getChildren().stream()
            .anyMatch(candidate -> candidate.getXLinkHrefID().equals(cid)))
        .sorted().map(MCRMigrationCommands::toLinkId).sequential()
        .peek(lid -> LOGGER.info("Adding {} to {}", lid, parentId)).forEach(parentStructure::addChild);
    if (parentStructure.getChildren().size() != sizeBefore) {
        MCRMetadataManager.fireUpdateEvent(parent);
    }
}
项目:Arcade2    文件:ArcadeCommands.java   
private void reload(Sender sender) {
    if (!sender.hasPermission("arcade.command.reload")) {
        throw new CommandPermissionException("arcade.command.reload");
    }

    Settings settings = this.plugin.getSettings();
    sender.sendInfo("Reloading settings file...");

    try {
        settings.setDocument(settings.readSettingsFile());
        this.plugin.getEventBus().publish(new SettingsReloadEvent(this.plugin, settings));

        sender.sendSuccess("Successfully reloaded settings file. Well done!");
    } catch (IOException io) {
        io.printStackTrace();
        throw new CommandException("Could not reload settings file: " + io.getMessage());
    } catch (JDOMException jdom) {
        jdom.printStackTrace();
        throw new CommandException("Could not reload XML file: " + jdom.getMessage());
    }
}
项目:bbb-resources    文件:GuestBookBean.java   
private ArrayList<Entry> getEntriesFromXML () throws JDOMException, IOException, ParseException {
  ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
  ArrayList<Entry> entries = new ArrayList<Entry>();
  SAXBuilder saxBuilder = new SAXBuilder();

  File inputFile = new File(ec.getRealPath("/") + "WEB-INF\\entries.xml");
  Document document = saxBuilder.build(inputFile);
  Element root = document.getRootElement();
  List<Element> children = root.getChildren();

  for (Element entry : children) {
    entries.add(new Entry(
      Integer.valueOf(entry.getChild("id").getText()),
      entry.getChild("title").getText(),
      Date.from(Instant.parse(entry.getChild("createdAt").getText())),
      entry.getChild("message").getText()
    ));
  }

  return entries;
}
项目:mycore    文件:MCRNodeBuilderTest.java   
@Test
public void testSimplePredicates() throws JaxenException, JDOMException {
    Element built = new MCRNodeBuilder().buildElement("element[child]", null, null);
    assertNotNull(built);
    assertEquals("element", built.getName());
    assertNotNull(built.getChild("child"));

    built = new MCRNodeBuilder().buildElement("element[child/grandchild]", null, null);
    assertNotNull(built);
    assertEquals("element", built.getName());
    assertNotNull(built.getChild("child"));
    assertNotNull(built.getChild("child").getChild("grandchild"));

    built = new MCRNodeBuilder().buildElement("parent[child1]/child2", null, null);
    assertNotNull(built);
    assertEquals("child2", built.getName());
    assertNotNull(built.getParentElement());
    assertEquals("parent", built.getParentElement().getName());
    assertNotNull(built.getParentElement().getChild("child1"));
}
项目:qpp-conversion-tool    文件:XmlUtils.java   
/**
 * Parses a stream of XML into a tree of XML elements.
 *
 * @param xmlStream The XML.
 * @return The root element of the XML tree.
 * @throws XmlException When a failure to parse the XML.
 */
public static Element parseXmlStream(InputStream xmlStream) throws XmlException {
    try {
        SAXBuilder saxBuilder = new SAXBuilder();
        saxBuilder.setFeature(DISALLOW_DTD,true);
        saxBuilder.setFeature(EXT_GENERAL_ENTITIES , false);
        saxBuilder.setFeature(EXT_PARAM_ENTITIES, false);

        return saxBuilder.build(xmlStream).getRootElement();
    } catch (JDOMException | IOException e) {
        throw new XmlException("Failed to process XML String into DOM Element", e);
    }
}
项目:he-rss-poll    文件:PollingVerticle.java   
private void parseXml(Buffer buffer, Future<Void> future) {
    String xmlFeed = buffer.toString("UTF-8");

    final SAXBuilder sax = new SAXBuilder();

    try {

        Document doc = sax.build(new InputSource(new StringReader(xmlFeed)));
        List<JsonObject> entries = RssUtils.toJson(doc);
        vertx.eventBus().publish((CommonConstants.VERTX_EVENT_BUS_HE_RSS_JDG_PUT), new JsonArray(entries));
        future.complete();

    } catch (JDOMException | IOException e) {
        future.fail(new RuntimeException("Exception caught when building SAX Document", e));
    }
}
项目:sumo    文件:SumoSafeReader.java   
public SumoSafeReader(String safePath) throws JDOMException, IOException,
        JAXBException {
    SAXBuilder builder = new SAXBuilder();
    safe = builder.build(new File(safePath));
    xFactory = XPathFactory.instance();
    this.safePath = safePath;
}
项目:sumo    文件:TestSumoJaxbSafeReader.java   
/**
 * Test method for {@link jrc.it.xml.wrapper.SumoJaxbSafeReader#SumoJaxbSafeReader(java.io.File)}.
 */
@Test
public void testSumoJaxbSafeReaderFile() {
    try {
        SumoJaxbSafeReader reader=new SumoJaxbSafeReader(new File(safeFile));
        assertNotNull(reader);
    } catch (JDOMException | IOException | JAXBException e) {
        fail(e.getMessage());
    }
}
项目:sumo    文件:TestSumoJaxbSafeReader.java   
/**
 * Test method for {@link jrc.it.xml.wrapper.SumoJaxbSafeReader#getOrbitReference()}.
 */
@Test
public void testGetOrbitReference() {
    try {
        SumoJaxbSafeReader reader=new SumoJaxbSafeReader(new File(safeFile));
        OrbitReference orbit=reader.getOrbitReference();
        assertNotNull(orbit);
    } catch (JDOMException | IOException | JAXBException e) {
        fail(e.getMessage());
    }
}
项目:sumo    文件:TestSumoJaxbSafeReader.java   
/**
 * Test method for {@link jrc.it.xml.wrapper.SumoJaxbSafeReader#setOrbitReference(jrc.it.safe.reader.jaxb.OrbitReference)}.
 */
@Test
public void testSetOrbitReference() {
    try {
        SumoJaxbSafeReader reader=new SumoJaxbSafeReader(new File(safeFile));
        AcquisitionPeriod period=reader.getAcquisitionPeriod();
        assertNotNull(period);
    } catch (JDOMException | IOException | JAXBException e) {
        fail(e.getMessage());
    }
}
项目:sumo    文件:TestSumoJaxbSafeReader.java   
/**
 * Test method for {@link jrc.it.xml.wrapper.SumoJaxbSafeReader#getProductInformation()}.
 */
@Test
public void testGetProductInformation() {
    try {
        SumoJaxbSafeReader reader=new SumoJaxbSafeReader(new File(safeFile));
        StandAloneProductInformation p=reader.getProductInformation();
        assertNotNull(p);
    } catch (JDOMException | IOException | JAXBException e) {
        fail(e.getMessage());
    }
}
项目:sumo    文件:TestSumoJaxbSafeReader.java   
/**
 * Test method for {@link jrc.it.xml.wrapper.SumoJaxbSafeReader#getAcquisitionPeriod()}.
 */
@Test
public void testGetAcquisitionPeriod() {
    try {
        SumoJaxbSafeReader reader=new SumoJaxbSafeReader(new File(safeFile));
        AcquisitionPeriod acq=reader.getAcquisitionPeriod();
        assertNotNull(acq);
    } catch (JDOMException | IOException | JAXBException e) {
        fail(e.getMessage());
    }
}
项目:sumo    文件:TestSumoJaxbSafeReader.java   
/**
 * Test method for {@link jrc.it.xml.wrapper.SumoJaxbSafeReader#getFrameSet()}.
 */
@Test
public void testGetFrameSet() {
    try {
        SumoJaxbSafeReader reader=new SumoJaxbSafeReader(new File(safeFile));
        FrameSet frame=reader.getFrameSet();
        assertNotNull(frame);
    } catch (JDOMException | IOException | JAXBException e) {
        fail(e.getMessage());
    }
}
项目:sumo    文件:TestSumoJaxbSafeReader.java   
/**
 * 
 */
@Test
public void testGetHrefsTiff() {
    try {
        SumoJaxbSafeReader reader=new SumoJaxbSafeReader(new File(safeFile));
        String[] tiffs=reader.getHrefsTiff();
        for(String t:tiffs)
            System.out.println("Tiff:"+t.toString());
        assertNotNull(tiffs);
    } catch (JDOMException | IOException | JAXBException e) {
        fail(e.getMessage());
    }

}
项目:sumo    文件:Sentinel1Factory.java   
public static List<GeoImageReader> instanceS1Reader(File f,String geoAlgorithm) throws JDOMException, IOException, JAXBException{
    List<GeoImageReader> girList=new ArrayList<GeoImageReader>();
    final SumoJaxbSafeReader safeReader=new SumoJaxbSafeReader(f.getAbsolutePath());
    boolean multipleImages=false;

    //for multiple images. For SLC product we can have 1 images for each sub-swat and for each polarization
    //we create 1 reader for each sub-swath
    String[] swath=safeReader.getSwaths();
    if(swath.length>1)
        multipleImages=true;

    Sentinel1 sentinel=null;
    String parent=f.getParent();
    for(String sw:swath){
        if(parent.contains("SLC_")){
            sentinel=new Sentinel1SLC(sw,f,geoAlgorithm);
        }else{
           try{
               if(PlatformConfiguration.getConfigurationInstance().getUseGdalForS1(false)&&GDALUtilities.isGDALAvailable()){
                   gdal.AllRegister();
                   sentinel=new GDALSentinel1(sw,f,geoAlgorithm);
               }else{
                   sentinel=new Sentinel1GRD(sw,f,geoAlgorithm);
               }
           }catch(Exception e){
                sentinel=new Sentinel1GRD(sw,f,geoAlgorithm);
           }
        }
        sentinel.setContainsMultipleImage(multipleImages);
        if (sentinel.initialise()) {
               logger.info("Successfully reading {0} as {1}...", new Object[]{f.getName(),sentinel.getClass()});
           }else{
            logger.warn("Problem reading {0} as {1}...", new Object[]{f.getName(),sentinel.getClass()});
           }
        girList.add(sentinel);
    }


    return girList;
}
项目:PokemonXMLFilter    文件:XMLReader.java   
private void cargarXml() {
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File(xml);
    try {
        Document document = (Document) builder.build(xmlFile);
        Element rootNode = document.getRootElement();
        List list = rootNode.getChildren("pokemon");

        for (int i = 0; i < list.size(); i++) {
            Element tabla = (Element) list.get(i);
            List lista_campos = tabla.getChildren();
            String name = null;
            int height = 0;
            int weight = 0;
            int baseExperience = 0;
            for (int j = 1; j <= 5; j++) {
                Element campo = (Element) lista_campos.get(j);
                if (j == 1) {
                    name = campo.getText();
                } else if (j == 3) {
                    height = Integer.valueOf(campo.getValue());
                } else if (j == 4) {
                    weight = Integer.valueOf(campo.getValue());
                } else if (j == 5) {
                    baseExperience = Integer.valueOf(campo.getValue());
                }

            }

            pokemons.add(new Pokemon(name, height, weight, baseExperience));

        }
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }
}
项目:ProjectAres    文件:ObserverToolFactory.java   
@Nullable ItemStack loadHowToBook(Path file) {
    try {
        if(!Files.isRegularFile(file)) return null;
        return itemParser.parseBook(saxBuilder.build(file.toFile())
                                              .getRootElement());
    }
    catch(JDOMException | IOException | InvalidXMLException e) {
        logger.log(Level.SEVERE, "Failed to parse how-to book from XML file " + file, e);
        return null;
    }
}
项目:Equella    文件:RssPortletRenderer.java   
private SAXBuilder createBuilder()
{
    return new SAXBuilder(new XMLReaderJDOMFactory()
    {
        @Override
        public XMLReader createXMLReader() throws JDOMException
        {
            SAXParserFactory fac = SAXParserFactory.newInstance();
            // All JDOM parsers are namespace aware.
            fac.setNamespaceAware(true);
            fac.setValidating(false);
            try
            {
                fac.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
                return fac.newSAXParser().getXMLReader();
            }
            catch (ParserConfigurationException | SAXException e)
            {
                throw new RuntimeException(e);
            }
        }

        @Override
        public boolean isValidating()
        {
            return false;
        }
    }, null, null);
}
项目:bibliometrics    文件:InstitutionBuilder.java   
public static Institution buildByAffilID(String id) {
    if (!id.isEmpty()) {
    Institution institution = new Institution(id);

    //prepare the file of exported data
    File outputFile = new File(affiliationsDir, "scopus_affiliationExport_" + id + ".xml");

    //get the affiliation export from scopus, either from a file on disk or from the api.
    Element affilData;
    try {
        affilData = new SAXBuilder().build(outputFile).detachRootElement().clone();
    } catch (JDOMException | IOException e) {
        ScopusConnector connector = new ScopusConnector();
        LOGGER.info("Retrieving AffilData for affilID" + id + " from Scopus.");
        try {
            affilData = connector.getAffiliationProfile(id).asXML().detachRootElement().clone();
        } catch (JDOMException | IOException | SAXException e1) {
            LOGGER.info("could not get scopus response.");
            affilData = new Element("error")
                    .addContent(new Element("status").setText("could not get scopus response"));
        }
    }

    //if no errors occurred, build the institution from the obtained data.
    if (affilData.getChild("status") == null) {
        //build institution with the scopus data
        //if geo-coordinates are present, they have been transferred into the institution as well. 
        addDataFromScopusProfile(affilData, "full", institution);
    }
    return institution;
    } else return null;
}