Example usage for org.w3c.dom Document getDocumentURI

List of usage examples for org.w3c.dom Document getDocumentURI

Introduction

In this page you can find the example usage for org.w3c.dom Document getDocumentURI.

Prototype

public String getDocumentURI();

Source Link

Document

The location of the document or null if undefined or if the Document was created using DOMImplementation.createDocument.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true); // Set namespace aware
    builderFactory.setValidating(true); // and validating parser feaures
    builderFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = builderFactory.newDocumentBuilder(); // Create the parser
    Document xmlDoc = builder.parse(new InputSource(new StringReader(xmlString)));

    System.out.println(xmlDoc.getDocumentURI());
}

From source file:Main.java

public static void deepCopyDocument(Document ttml, File target) throws IOException {
    try {/*  w  ww .j av  a 2  s.c o  m*/
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("//*/@backgroundImage");
        NodeList nl = (NodeList) expr.evaluate(ttml, XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); i++) {
            Node backgroundImage = nl.item(i);
            URI backgroundImageUri = URI.create(backgroundImage.getNodeValue());
            if (!backgroundImageUri.isAbsolute()) {
                copyLarge(new URI(ttml.getDocumentURI()).resolve(backgroundImageUri).toURL().openStream(),
                        new File(target.toURI().resolve(backgroundImageUri).toURL().getFile()));
            }
        }
        copyLarge(new URI(ttml.getDocumentURI()).toURL().openStream(), target);

    } catch (XPathExpressionException e) {
        throw new IOException(e);
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:net.sourceforge.dita4publishers.impl.ditabos.DitaBosHelper.java

/**
 * Constructs a full DITA BOS from the specified root map using the specified BOS construction options.
 * @param bosOptions/*from   ww  w . jav  a  2 s.  co  m*/
 * @param log 
 * @param rootMap
 * @return
 * @throws Exception 
 */
public static DitaBoundedObjectSet calculateMapBos(BosConstructionOptions bosOptions, Log log, Document rootMap)
        throws Exception {

    Map<URI, Document> domCache = bosOptions.getDomCache();

    if (domCache == null) {
        domCache = new HashMap<URI, Document>();
        bosOptions.setDomCache(domCache);
    }

    DitaBoundedObjectSet bos = new DitaBoundedObjectSetImpl(bosOptions);

    if (!bosOptions.isQuiet())
        log.info("calculateMapBos(): Starting map BOS calculation...");

    Element elem = rootMap.getDocumentElement();
    if (!DitaUtil.isDitaMap(elem) && !DitaUtil.isDitaTopic(elem)) {
        throw new DitaBosHelperException(
                "Input root map " + rootMap.getDocumentURI() + " does not appear to be a DITA map or topic.");
    }

    DitaKeySpace keySpace;
    try {
        DitaKeyDefinitionContext keyDefContext = new KeyDefinitionContextImpl(rootMap);
        keySpace = new InMemoryDitaKeySpace(keyDefContext, rootMap, bosOptions);
    } catch (DitaApiException e) {
        throw new BosException("DITA API Exception: " + e.getMessage(), e);
    }

    DitaTreeWalker walker = new DitaDomTreeWalker(log, keySpace, bosOptions);
    walker.setRootObject(rootMap);
    walker.walk(bos);

    if (!bosOptions.isQuiet())
        log.info("calculateMapBos(): Returning BOS. BOS has " + bos.size() + " members.");
    return bos;
}

From source file:net.sourceforge.dita4publishers.impl.ditabos.DitaBoundedObjectSetImpl.java

public XmlBosMember constructBosMember(BosMember parentMember, Document doc) throws Exception {
    XmlBosMember newMember = null;/* w w  w  . jav  a 2s  .  c  o  m*/
    Element elem = doc.getDocumentElement();
    String key = doc.getDocumentURI();
    if (key == null || "".equals(key.trim())) {
        throw new BosException(
                "Document has null or empty documentURI property. The documentURI must be set to use as the BOS member key.");
    }
    if (this.getMember(key) != null) {
        BosMember cand = this.getMember(key);
        if (!(cand instanceof XmlBosMember)) {
            throw new BosException(
                    "A BOS member with key \"" + key + "\" already exists and is not an XmlBosMember instance");
        }
        return (XmlBosMember) cand;
    }

    // FIXME: Integrate some sort of XML BOS member factory here.
    if (DitaUtil.isInDitaDocument(elem)) {
        if (DitaUtil.isDitaMap(elem)) {
            newMember = new DitaMapBosMemberImpl(this, doc);
        } else if (DitaUtil.isDitaTopic(elem)) {
            newMember = new DitaTopicBosMemberImpl(this, doc);
        } else if (DitaUtil.isDitaBase(elem)) {
            newMember = new DitaTopicBosMemberImpl(this, doc);
        } else {
            log.warn("constructBosMember(): Element \"" + elem.getLocalName()
                    + "\" is in a DITA document but is neither a map nor a topic.");
            newMember = new DitaBosMemberImpl(this, doc);
        }
    } else {
        newMember = new XmlBosMemberImpl(this, doc);
    }
    return newMember;
}

From source file:net.sourceforge.dita4publishers.api.dita.DitaLinkManagementServiceTest.java

public void testDitaKeyspaceConstruction() throws Exception {

    // get DOM for the rootMap.

    Element resourceElement = null;
    URI resourceUri = null;//from  w w  w.  j  a va 2 s . c  o m

    DitaKeySpace keySpace;

    // Map document contains 6 topicrefs, of which 5 define keys.

    // Test management of key space registry and handling of out-of-date
    // key spaces.

    KeyAccessOptions keyAccessOptions = new KeyAccessOptions();

    DitaKeyDefinitionContext keydefContext = dlmService.registerRootMap(rootMap);
    assertNotNull(keydefContext);
    DitaKeyDefinitionContext candKeydefContext = dlmService.getKeyDefinitionContext(rootMap);
    assertEquals(keydefContext, candKeydefContext);

    keySpace = dlmService.getKeySpace(keyAccessOptions, keydefContext);
    assertNotNull(keySpace);
    assertEquals(rootMap.getDocumentURI(), keySpace.getRootMap(keyAccessOptions).getDocumentURI());

    dlmService.unRegisterKeySpace(keydefContext);
    keySpace = dlmService.getKeySpace(keyAccessOptions, keydefContext);
    assertNull("Expected a null key space", keySpace);

    keydefContext = dlmService.registerRootMap(rootMap);
    assertNotNull(keydefContext);

    dlmService.markKeySpaceOutOfDate(keydefContext);
    assertNotNull(keydefContext);
    assertTrue(keydefContext.isOutOfDate());

    // Report the key space:

    // Default key sorting:
    KeyReportOptions reportOptions = new KeyReportOptions();
    KeySpaceReporter reporter = new TextKeySpaceReporter();
    reporter.setPrintStream(System.out);
    reporter.report(keyAccessOptions, dlmService.getKeySpace(keyAccessOptions, keydefContext), reportOptions);

    // Sort by map:
    reportOptions.setSortByMap(true);
    reporter.report(keyAccessOptions, dlmService.getKeySpace(keyAccessOptions, keydefContext), reportOptions);

    // All keys, not just effective keys:

    reportOptions.setSortByMap(false);
    reportOptions.setAllKeys(true);
    reporter.report(keyAccessOptions, dlmService.getKeySpace(keyAccessOptions, keydefContext), reportOptions);

    // Test operations on keys and key definitions:

    Set<String> keys = dlmService.getKeys(keyAccessOptions, keydefContext);

    assertNotNull(keys);
    assertEquals(keyCount, keys.size());

    keySpace = dlmService.getKeySpace(keyAccessOptions, keydefContext);
    assertNotNull(keySpace);
    assertEquals(keyCount, keySpace.size());

    Document candDoc = keySpace.getRootMap(keyAccessOptions);
    assertEquals(candDoc.getDocumentURI(), rootMap.getDocumentURI());

    // Get all key definitions in the repository:
    Set<DitaKeyDefinition> keyDefSet = dlmService.getEffectiveKeyDefinitions(keyAccessOptions, keydefContext);
    List<DitaKeyDefinition> keyDefList = null;
    assertNotNull("keydefs is null", keyDefSet);
    assertEquals(keyCount, keyDefSet.size());

    // Get effective key definition for a key in a context: 
    DitaKeyDefinition keyDef = dlmService.getKeyDefinition(keyAccessOptions, keydefContext, key01);
    assertNotNull("keyDef is null", keyDef);
    String rootMapId = keyDef.getBaseUri().toURL().toExternalForm();
    assertNotNull(rootMapId);
    assertEquals(rootMap.getDocumentURI(), rootMapId);

    // Get all the effective key definitions  in the repository for a key:

    keyDefSet = dlmService.getEffectiveKeyDefinitionsForKey(keyAccessOptions, key01);
    assertNotNull("Effective keyDefs for key01 are null", keyDefSet);
    assertEquals(1, keyDefSet.size());

    // Get all the key definitions (effective or not) in the repository for a key:

    keyDefList = dlmService.getAllKeyDefinitionsForKey(keyAccessOptions, key01);
    assertNotNull("All keyDefs for key01 are null", keyDefList);
    assertEquals(5, keyDefList.size());

    // Get the effective definition for a key in a specific context:

    keyDef = dlmService.getKeyDefinition(keyAccessOptions, keydefContext, key01);
    assertNotNull(keyDef);
    assertEquals(key01, keyDef.getKey());

    // Get key definitions based on filtering spec:

    KeyAccessOptions kaoNotWindows = new KeyAccessOptions();
    kaoNotWindows.addExclusion("platform", "windows");

    KeyAccessOptions kaoNotOsx = new KeyAccessOptions();
    kaoNotOsx.addExclusion("platform", "osx");

    KeyAccessOptions kaoNotOsxOrWin = new KeyAccessOptions();
    kaoNotOsxOrWin.addExclusion("platform", "osx");
    kaoNotOsxOrWin.addExclusion("platform", "windows");

    DitaKeyDefinition keyDefOsx = dlmService.getKeyDefinition(kaoNotWindows, keydefContext, key01);
    assertNotNull(keyDefOsx);
    assertEquals(keyDefOsx, keyDef); // Should be same because OSX keydef is first in map.

    assertTrue(keyDefOsx.getDitaPropsSpec().equals(keyDef.getDitaPropsSpec()));

    DitaKeyDefinition keyDefWindows = dlmService.getKeyDefinition(kaoNotOsx, keydefContext, key01);
    assertFalse(keyDefOsx.equals(keyDefWindows));
    assertFalse(keyDefOsx.getDitaPropsSpec().equals(keyDefWindows.getDitaPropsSpec()));

    // Get all the key definitions for a key in a specific context:

    keyDefList = dlmService.getAllKeyDefinitionsForKey(keyAccessOptions, keydefContext, key01);
    assertNotNull(keyDefList);
    assertEquals(5, keyDefList.size());

    DitaResource res;
    DitaElementResource elemRes;
    URL resUrl;

    res = dlmService.getResource(keyAccessOptions, keydefContext, key01);
    assertNotNull(res);

    assertTrue("Expected an element resource", res instanceof DitaElementResource);
    elemRes = (DitaElementResource) res;

    Element resElem = elemRes.getElement();
    assertNotNull("Resource element is null from element resource", resElem);

    resUrl = res.getUrl();
    assertNotNull("Resource URL is null", resUrl);

    res = dlmService.getResource(keyAccessOptions, keydefContext, key02);
    assertNotNull(res);

    assertFalse("Expected non-Element resource", res instanceof DitaElementResource);
    resUrl = res.getUrl();
    assertNotNull(resUrl);

    // Check if key is defined:

    assertTrue(dlmService.isKeyDefined(key01));
    assertTrue(dlmService.isKeyDefined(key01, keydefContext));
    assertFalse(dlmService.isKeyDefined("not-a-key"));
    assertFalse(dlmService.isKeyDefined("not-a-key", keydefContext));

}

From source file:mypackage.State_Auth.java

public void documentCreated(BrowserField browserField, ScriptEngine scriptEngine, Document document)
        throws Exception {
    super.documentCreated(browserField, scriptEngine, document);
    //updateStatus("documentCreated");
    //_authscreen.showActivityIndicator();

    // \URL//w  w  w.  j  av a 2 s . c o  m
    String url = document.getDocumentURI();

    // [Handling the response]
    // An error response:
    // https://your.redirect.uri/feedlyCallback?error=access_denied&state=state.passed.in
    // A code response
    // https://your.redirect.uri/feedlyCallback?code=AQAA7rJ7InAiOjEsImEiOiJmZWVk?c&state=state.passed.in
    if (url.startsWith("https://localhost" + "/?code=")) {
        // F??
        _authscreen.showCompliteMessage();

        // Get code
        int start = url.indexOf("code=") + "code=".length();
        int end = url.indexOf("&state=");
        String code = url.substring(start, end);

        getAccessToken(code);

    } else if (document.getDocumentURI().startsWith("https://localhost" + "/?error=")) {
        // F?s

        // ANeBreBCWP?[^?[??
        _authscreen.deleteActivityIndicator();

        // ]v?bZ?[W\?ABrowserField???B
        _authscreen.deleteBrowserField();

        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run() {
                //Dialog.alert("A communication error has occurred. Please make sure your device is connected to Internet.");
                int select = Dialog.ask("Authentication failed.", new Object[] { "Try again", "Quit" }, 0);

                switch (select) {
                case -1:
                    _feedlyclient.quitApp();
                    break;

                case 0:
                    _feedlyclient.reStartApp();
                    break;

                case 1:
                    _feedlyclient.quitApp();
                    break;
                }
            } //run()
        });
    }
}

From source file:com.amalto.core.history.accessor.AttributeAccessor.java

private QName getQName(Document domDocument) {
    QName qName;//w w  w .j a va  2s.  com
    String prefix = StringUtils.substringBefore(attributeName, ":"); //$NON-NLS-1$
    String name = StringUtils.substringAfter(attributeName, ":"); //$NON-NLS-1$
    if (name.isEmpty()) {
        // No prefix (so prefix is attribute name due to substring calls).
        String attributeNamespaceURI = domDocument.getDocumentURI();
        if (attributeNamespaceURI == null || attributeNamespaceURI.isEmpty()) {
            Node attributeNode = getAttributeNode(domDocument);
            if (attributeNode != null) {
                attributeNamespaceURI = attributeNode.getNamespaceURI();
            }
        }
        qName = new QName(attributeNamespaceURI, prefix);
    } else {
        String attributeNamespaceURI = domDocument.lookupNamespaceURI(prefix);
        if (attributeNamespaceURI == null || attributeNamespaceURI.isEmpty()) {
            Node attributeNode = getAttributeNode(domDocument);
            if (attributeNode != null) {
                attributeNamespaceURI = attributeNode.lookupNamespaceURI(prefix);
            }
        }
        qName = new QName(attributeNamespaceURI, name, prefix);
    }
    return qName;
}

From source file:net.sourceforge.dita4publishers.impl.dita.InMemoryDitaLinkManagementService.java

/**
 * @param rootMap//from   w  ww  . ja  v a2s  .com
 * @return
 */
public boolean isRegistered(Document rootMap) throws DitaApiException {
    if (rootMap == null)
        return false;
    String docURI = rootMap.getDocumentURI();
    if (docURI == null || "".equals(docURI))
        log.warn("isRegistered(): rootMap has null or empty document URI.");
    return this.contexts.containsKey(rootMap.getDocumentURI());
}

From source file:net.sourceforge.dita4publishers.impl.dita.InMemoryDitaLinkManagementService.java

public DitaKeyDefinitionContext getKeyDefinitionContext(Document rootMap) throws DitaApiException {
    if (rootMap == null)
        return null;
    if (!this.contexts.containsKey(rootMap.getDocumentURI())) {
        DitaKeyDefinitionContext context = new KeyDefinitionContextImpl(rootMap);
        this.contexts.put(rootMap.getDocumentURI(), context);
    }//  w w  w  . j a va2  s  .c  om
    return this.contexts.get(rootMap.getDocumentURI());

}

From source file:net.sourceforge.dita4publishers.impl.ditabos.DitaTreeWalkerBase.java

public void walk(DitaBoundedObjectSet bos, Document mapDoc) throws Exception {
    URI mapUri;/*from ww  w  .j  av  a 2  s .  com*/
    try {
        String mapUriStr = mapDoc.getDocumentURI();
        if (mapUriStr == null || "".equals(mapUriStr))
            throw new BosException("Map document has a null or empty document URI property. Cannot continue.");
        mapUri = new URI(mapUriStr);
    } catch (URISyntaxException e) {
        throw new BosException("Failed to construct URI from document URI \"" + mapDoc.getDocumentURI() + "\": "
                + e.getMessage());
    }
    log.debug("walk(): Walking document " + mapUri.toString() + "...");
    // Add this map's keys to the key space.

    XmlBosMember member = bos.constructBosMember((BosMember) null, mapDoc);
    Element elem = mapDoc.getDocumentElement();

    bos.setRootMember(member);
    bos.setKeySpace(keySpace);

    // NOTE: if input is a map, then walking the map
    // will populate the key namespace before processing
    // any topics, so that key references can be resolved.
    // If the input is a topic, then the key space must have
    // already been populated if there are any key references
    // to be resolved.

    if (DitaUtil.isDitaMap(elem)) {
        log.debug("walk(): Adding root map's keys to key space...");
        keySpace.addKeyDefinitions(elem);

        // Walk the map to determine the tree of maps and calculate
        // the key space rooted at the starting map:
        log.debug("walk(): Walking the map to calculate the map tree...");
        walkMapCalcMapTree(bos, member, mapDoc, 1);
        log.debug("walk(): Map tree calculated.");

        // At this point, we have a set of map BOS members and a populated key space;
        // Iterate over the maps to find all non-map dependencies (topics, images,
        // objects, xref targets, and link targets):

        log.debug("walk(): Calculating map dependencies for map " + member.getKey() + "...");
        Collection<BosMember> mapMembers = bos.getMembers();
        Iterator<BosMember> iter = mapMembers.iterator();
        while (iter.hasNext()) {
            BosMember mapMember = iter.next();
            walkMapGetDependencies(bos, (DitaMapBosMember) mapMember);
        }
        log.debug("walk(): Map dependencies calculated.");

    } else if (DitaUtil.isDitaTopic(elem)) {
        log.debug("walk(): Calculating topic dependencies for topic " + member.getKey() + "...");
        walkTopic(bos, (XmlBosMember) member, 1);
        log.debug("walk(): Topic dependencies calculated.");
    } else {
        // Not a map or topic, delegate walking:
        walkNonDitaResource(bos, (NonXmlBosMember) member, 1);
    }

}