Java源码示例:org.jdom2.transform.JDOMSource

示例1
protected void renderMergedOutputModel(Map model, HttpServletRequest req, HttpServletResponse res) throws Exception {
  res.setContentType(getContentType());

  Document doc = (Document) model.get("Document");
  String transform = (String) model.get("Transform");
  String resourceName = "/resources/xsl/" + transform;
  Resource resource = new ClassPathResource(resourceName);
  try (InputStream is = resource.getInputStream()) {
    Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(is));
    transformer.setParameter("tdsContext", req.getContextPath());

    JDOMSource in = new JDOMSource(doc);
    JDOMResult out = new JDOMResult();
    transformer.transform(in, out);
    Document html = out.getDocument();
    if (html == null)
      throw new IllegalStateException("Bad XSLT=" + resourceName);

    XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
    fmt.output(html, res.getOutputStream());
  }
}
 
示例2
@Override
public Source resolve(String href, String base) throws TransformerException {
    String id = href.substring(href.indexOf(":") + 1);
    LOGGER.debug("Reading METS for ID {}", id);
    MCRObjectID objId = MCRObjectID.getInstance(id);
    if (!objId.getTypeId().equals("derivate")) {
        String derivateID = getDerivateFromObject(id);
        if (derivateID == null) {
            return new JDOMSource(new Element("mets", Namespace.getNamespace("mets", "http://www.loc.gov/METS/")));
        }
        id = derivateID;
    }
    MCRPath metsPath = MCRPath.getPath(id, "/mets.xml");
    try {
        if (Files.exists(metsPath)) {
            //TODO: generate new METS Output
            //ignoreNodes.add(metsFile);
            return new MCRPathContent(metsPath).getSource();
        }
        Document mets = MCRMETSGeneratorFactory.create(MCRPath.getPath(id, "/")).generate().asDocument();
        return new JDOMSource(mets);
    } catch (Exception e) {
        throw new TransformerException(e);
    }
}
 
示例3
@Override
public Source resolve(String href, String base) throws TransformerException {
    String type = href.substring(href.indexOf(":") + 1);
    String path = "/templates/" + type + "/";
    LOGGER.debug("Reading templates from {}", path);
    Set<String> resourcePaths = context.getResourcePaths(path);
    ArrayList<String> templates = new ArrayList<>();
    if (resourcePaths != null) {
        for (String resourcePath : resourcePaths) {
            if (!resourcePath.endsWith("/")) {
                //only handle directories
                continue;
            }
            String templateName = resourcePath.substring(path.length(), resourcePath.length() - 1);
            LOGGER.debug("Checking if template: {}", templateName);
            if (templateName.contains("/")) {
                continue;
            }
            templates.add(templateName);
        }
        Collections.sort(templates);
    }
    LOGGER.info("Found theses templates: {}", templates);
    return new JDOMSource(getStylesheets(templates));
}
 
示例4
/**
 * Reads XML from a http or https URL.
 *
 * @param href
 *            the URL of the xml document
 * @return the root element of the xml document
 */
@Override
public Source resolve(String href, String base) throws TransformerException {
    LOGGER.debug("Reading xml from url {}", href);

    String path = href.substring(href.indexOf(":") + 1);

    int i = path.indexOf("?host");
    if (i > 0) {
        path = path.substring(0, i);
    }
    StringTokenizer st = new StringTokenizer(path, "/");

    String ownerID = st.nextToken();
    try {
        String aPath = MCRXMLFunctions.decodeURIPath(path.substring(ownerID.length() + 1));
        // TODO: make this more pretty
        if (ownerID.endsWith(":")) {
            ownerID = ownerID.substring(0, ownerID.length() - 1);
        }
        LOGGER.debug("Get {} path: {}", ownerID, aPath);
        return new JDOMSource(MCRPathXML.getDirectoryXML(MCRPath.getPath(ownerID, aPath)));
    } catch (IOException | URISyntaxException e) {
        throw new TransformerException(e);
    }
}
 
示例5
@Override
public Source resolve(String href, String base) throws TransformerException {
    String target = href.substring(href.indexOf(":") + 1);
    // fixes exceptions if suburi is empty like "mcrobject:"
    String subUri = target.substring(target.indexOf(":") + 1);
    if (subUri.length() == 0) {
        return new JDOMSource(new Element("null"));
    }
    // end fix
    LOGGER.debug("Ensuring xml is not null: {}", target);
    try {
        Source result = MCRURIResolver.instance().resolve(target, base);
        if (result != null) {
            return result;
        } else {
            LOGGER.debug("MCRNotNullResolver returning empty xml");
            return new JDOMSource(new Element("null"));
        }
    } catch (Exception ex) {
        LOGGER.info("MCRNotNullResolver caught exception: {}", ex.getLocalizedMessage());
        LOGGER.debug(ex.getStackTrace());
        LOGGER.debug("MCRNotNullResolver returning empty xml");
        return new JDOMSource(new Element("null"));
    }
}
 
示例6
/**
 * Returns a deleted mcr object xml for the given id. If there is no such object a dummy object with an empty
 * metadata element is returned.
 *
 * @param href
 *            an uri starting with <code>deletedMcrObject:</code>
 * @param base
 *            may be null
 */
@Override
public Source resolve(String href, String base) throws TransformerException {
    String[] parts = href.split(":");
    MCRObjectID mcrId = MCRObjectID.getInstance(parts[parts.length - 1]);
    LOGGER.info("Resolving deleted object {}", mcrId);
    try {
        MCRContent lastPresentVersion = MCRXMLMetadataManager.instance().retrieveContent(mcrId, -1);
        if (lastPresentVersion == null) {
            LOGGER.warn("Could not resolve deleted object {}", mcrId);
            return new JDOMSource(MCRObjectFactory.getSampleObject(mcrId));
        }
        return lastPresentVersion.getSource();
    } catch (IOException e) {
        throw new TransformerException(e);
    }
}
 
示例7
@Override
public Source resolve(String href, String base) throws TransformerException {
    String[] parts = href.split(":");
    String completePath = parts[1];
    String[] pathParts = completePath.split("/", 2);
    MCRObjectID derivateID = MCRObjectID.getInstance(pathParts[0]);
    MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
    MCRObjectDerivate objectDerivate = derivate.getDerivate();
    if (pathParts.length == 1) {
        //only derivate is given;
        Element fileset = new Element("fileset");
        if (objectDerivate.getURN() != null) {
            fileset.setAttribute("urn", objectDerivate.getURN());
            for (MCRFileMetadata fileMeta : objectDerivate.getFileMetadata()) {
                fileset.addContent(fileMeta.createXML());
            }
        }
        return new JDOMSource(fileset);
    }
    MCRFileMetadata fileMetadata = objectDerivate.getOrCreateFileMetadata("/" + pathParts[1]);
    return new JDOMSource(fileMetadata.createXML());
}
 
示例8
/**
 * validates <code>doc</code> using XML Schema defined <code>schemaURI</code>
 * @param doc document to be validated
 * @param schemaURI URI of XML Schema document
 * @throws SAXException if validation fails
 * @throws IOException if resolving resources fails
 */
public static void validate(Document doc, String schemaURI) throws SAXException, IOException {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    sf.setResourceResolver(MCREntityResolver.instance());
    Schema schema;
    try {
        schema = sf.newSchema(MCRURIResolver.instance().resolve(schemaURI, null));
    } catch (TransformerException e) {
        Throwable cause = e.getCause();
        if (cause == null) {
            throw new IOException(e);
        }
        if (cause instanceof SAXException) {
            throw (SAXException) cause;
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw new IOException(e);
    }
    Validator validator = schema.newValidator();
    validator.setResourceResolver(MCREntityResolver.instance());
    validator.validate(new JDOMSource(doc));
}
 
示例9
@Override
public Source resolve(String href, String base) throws TransformerException {
    final Optional<String> categoryURI = getAuthorityInfo(href)
        .map(MCRAuthorityInfo::getCategoryID)
        .map(category -> String.format(Locale.ROOT, "classification:metadata:0:parents:%s:%s", category.getRootID(),
            category.getID()));
    if (categoryURI.isPresent()) {
        LOGGER.debug("{} -> {}", href, categoryURI.get());
        return MCRURIResolver.instance().resolve(categoryURI.get(), base);
    }
    LOGGER.debug("no category found for {}", href);
    return new JDOMSource(new Element("empty"));
}
 
示例10
@Override
public Source resolve(String href, String base) throws TransformerException {
    String subHref = href.substring(href.indexOf(":") + 1);
    Element mods = MCRURIResolver.instance().resolve(subHref);
    MCRMODSSorter.sort(mods);
    return new JDOMSource(mods);
}
 
示例11
@Override
public Source resolve(String href, String base) throws TransformerException {
    href = href.substring(href.indexOf(":") + 1);
    String configID = href.substring(0, href.indexOf(':'));

    href = href.substring(href.indexOf(":") + 1);
    Element mods = MCRURIResolver.instance().resolve(href);

    enrichPublication(mods, configID);
    return new JDOMSource(mods);
}
 
示例12
protected void validateDocument(String id, Document resultDocument)
    throws MCRPersistentIdentifierException {
    try {
        getSchema().newValidator().validate(new JDOMSource(resultDocument));
    } catch (SAXException | IOException e) {
        throw new MCRPersistentIdentifierException(
            "Error while validating generated xml for " + id, e);
    }
}
 
示例13
@Override
public Source resolve(final String href, final String base) throws TransformerException {
    String realmID = href.split(":")[1];
    if ("all".equals(realmID)) {
        return MCRRealmFactory.getRealmsSource();
    } else if ("local".equals(realmID)) {
        realmID = MCRRealmFactory.getLocalRealm().getID();
    }
    return new JDOMSource(getElement(MCRRealmFactory.getRealm(realmID).getID()));
}
 
示例14
@Override
public Source resolve(final String href, final String base) throws TransformerException {
    final String target = href.substring(href.indexOf(":") + 1);
    final String[] part = target.split(":");
    final String method = part[0];
    try {
        if ("getAssignableGroupsForUser".equals(method)) {
            return new JDOMSource(getAssignableGroupsForUser());
        }
    } catch (final MCRAccessException exc) {
        throw new TransformerException(exc);
    }
    throw new TransformerException(new IllegalArgumentException("Unknown method " + method + " in uri " + href));
}
 
示例15
/**
 * Builds an MCRUser instance from the given element.
 * @param element as generated by {@link #buildExportableXML(MCRUser)}. 
 */
public static MCRUser buildMCRUser(Element element) {
    if (!element.getName().equals(USER_ELEMENT_NAME)) {
        throw new IllegalArgumentException("Element is not a mycore user element.");
    }
    try {
        Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
        return (MCRUser) unmarshaller.unmarshal(new JDOMSource(element));
    } catch (JAXBException e) {
        throw new MCRException("Exception while transforming Element to MCRUser.", e);
    }
}
 
示例16
/**
 * Builds an MCRRole instance from the given element.
 * @param element as generated by {@link #buildExportableXML(MCRRole)}. 
 */
public static MCRRole buildMCRRole(Element element) {
    if (!element.getName().equals(ROLE_ELEMENT_NAME)) {
        throw new IllegalArgumentException("Element is not a mycore role element.");
    }
    try {
        Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
        return (MCRRole) unmarshaller.unmarshal(new JDOMSource(element));
    } catch (JAXBException e) {
        throw new MCRException("Exception while transforming Element to MCRUser.", e);
    }
}
 
示例17
public static MCRUserAttributeMapper instance(Element attributeMapping) {
    try {
        JAXBContext jaxb = JAXBContext.newInstance(Mappings.class.getPackage().getName(),
            Mappings.class.getClassLoader());

        Unmarshaller unmarshaller = jaxb.createUnmarshaller();
        Mappings mappings = (Mappings) unmarshaller.unmarshal(new JDOMSource(attributeMapping));

        MCRUserAttributeMapper uam = new MCRUserAttributeMapper();
        uam.attributeMapping.putAll(mappings.getAttributeMap());
        return uam;
    } catch (Exception e) {
        return null;
    }
}
 
示例18
public Source resolve(String href, String base) throws TransformerException {
    try {
        String code = href.split(":")[1];
        MCRLanguage language = MCRLanguageFactory.instance().getLanguage(code);
        Document doc = new Document(buildXML(language));
        return new JDOMSource(doc);
    } catch (Exception ex) {
        throw new TransformerException(ex);
    }
}
 
示例19
/**
 * Parse a email from given {@link Element}.
 * 
 * @param xml the email
 * @return the {@link EMail} object
 */
public static EMail parseXML(final Element xml) {
    try {
        final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
        return (EMail) unmarshaller.unmarshal(new JDOMSource(xml));
    } catch (final JAXBException e) {
        throw new MCRException("Exception while transforming Element to EMail.", e);
    }
}
 
示例20
/**
 * Returns access controll rules as XML
 */
public Source resolve(String href, String base) throws TransformerException {
    String key = href.substring(href.indexOf(":") + 1);
    LOGGER.debug("Reading xml from query result using key :{}", key);

    String[] param;
    StringTokenizer tok = new StringTokenizer(key, "&");
    Hashtable<String, String> params = new Hashtable<>();

    while (tok.hasMoreTokens()) {
        param = tok.nextToken().split("=");
        params.put(param[0], param[1]);
    }

    String action = params.get(ACTION_PARAM);
    String objId = params.get(OBJECT_ID_PARAM);

    if (action == null || objId == null) {
        return null;
    }

    Element container = new Element("servacls").setAttribute("class", "MCRMetaAccessRule");

    if (action.equals("all")) {
        for (String permission : MCRAccessManager.getPermissionsForID(objId)) {
            // one pool Element under access per defined AccessRule in
            // Pool
            // for (Object-)ID
            addRule(container, permission, MCRAccessManager.getAccessImpl().getRule(objId, permission));
        }
    } else {
        addRule(container, action, MCRAccessManager.getAccessImpl().getRule(objId, action));
    }

    return new JDOMSource(container);
}
 
示例21
/**
 * returns a classification in a specific format. Syntax:
 * <code>classification:{editor[Complete]['['formatAlias']']|metadata}:{Levels}[:noEmptyLeaves]:{parents|
 * children}:{ClassID}[:CategID] formatAlias: MCRConfiguration property
 * MCR.UURResolver.Classification.Format.FormatAlias
 *
 * @param href
 *            URI in the syntax above
 * @return the root element of the XML document
 * @see MCRCategoryTransformer
 */
public Source resolve(String href, String base) throws TransformerException {
    LOGGER.debug("start resolving {}", href);
    String cacheKey = getCacheKey(href);
    Element returns = categoryCache.getIfUpToDate(cacheKey, getSystemLastModified());
    if (returns == null) {
        returns = getClassElement(href);
        if (returns != null) {
            categoryCache.put(cacheKey, returns);
        }
    }
    return new JDOMSource(returns);
}
 
示例22
@Override
public Source resolve(String href, String base) throws TransformerException {
    String target = href.substring(href.indexOf(":") + 1);

    try {
        return MCRURIResolver.instance().resolve(target, base);
    } catch (Exception ex) {
        LOGGER.debug("Caught {}. Put it into XML to process in XSL!", ex.getClass().getName());
        Element exception = new Element("exception");
        Element message = new Element("message");
        Element stacktraceElement = new Element("stacktrace");

        stacktraceElement.setAttribute("space", "preserve", Namespace.XML_NAMESPACE);

        exception.addContent(message);
        exception.addContent(stacktraceElement);

        message.setText(ex.getMessage());

        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            ex.printStackTrace(pw);
            stacktraceElement.setText(pw.toString());
        } catch (IOException e) {
            throw new MCRException("Error while writing Exception to String!", e);
        }

        return new JDOMSource(exception);
    }
}
 
示例23
@Override
public Source resolve(String href, String base) throws TransformerException {
    String includePart = href.substring(href.indexOf(":") + 1);
    Namespace xslNamespace = Namespace.getNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");

    Element root = new Element("stylesheet", xslNamespace);
    root.setAttribute("version", "1.0");

    // get the parameters from mycore.properties
    String propertyName = "MCR.URIResolver.xslIncludes." + includePart;
    List<String> propValue;
    if (includePart.startsWith("class.")) {
        MCRXslIncludeHrefs incHrefClass = MCRConfiguration2
            .getOrThrow(propertyName, MCRConfiguration2::instantiateClass);
        propValue = incHrefClass.getHrefs();
    } else {
        propValue = MCRConfiguration2.getString(propertyName)
            .map(MCRConfiguration2::splitValue)
            .map(s -> s.collect(Collectors.toList()))
            .orElseGet(Collections::emptyList);
    }

    for (String include : propValue) {
        // create a new include element
        Element includeElement = new Element("include", xslNamespace);
        includeElement.setAttribute("href", include);
        root.addContent(includeElement);
        LOGGER.debug("Resolved XSL include: {}", include);
    }
    return new JDOMSource(root);
}
 
示例24
@Override
public Source resolve(String href, String base) throws TransformerException {
    String importXSL = MCRXMLFunctions.nextImportStep(href.substring(href.indexOf(':') + 1));
    if (importXSL.isEmpty()) {
        LOGGER.debug("End of import queue: {}", href);
        Namespace xslNamespace = Namespace.getNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
        Element root = new Element("stylesheet", xslNamespace);
        root.setAttribute("version", "1.0");
        return new JDOMSource(root);
    }
    LOGGER.debug("xslImport importing {}", importXSL);
    return fallback.resolve("resource:xsl/" + importXSL, base);
}
 
示例25
private Source getSource(MCRStoredMetadata retrieve) throws IOException {
    Element e = new Element("versions");
    Element v = new Element("version");
    e.addContent(v);
    v.setAttribute("date", MCRXMLFunctions.getISODate(retrieve.getLastModified(), null));
    return new JDOMSource(e);
}
 
示例26
private Source getSource(List<MCRMetadataVersion> versions) {
    Element e = new Element("versions");
    for (MCRMetadataVersion version : versions) {
        Element v = new Element("version");
        v.setAttribute("user", version.getUser());
        v.setAttribute("date", MCRXMLFunctions.getISODate(version.getDate(), null));
        v.setAttribute("r", Long.toString(version.getRevision()));
        v.setAttribute("action", Character.toString(version.getType()));
        e.addContent(v);
    }
    return new JDOMSource(e);
}
 
示例27
/**
 * Resolves the I18N String value for the given property.<br><br>
 * <br>
 * Syntax: <code>i18n:{i18n-code},{i18n-prefix}*,{i18n-prefix}*...</code> or <br>
 *         <code>i18n:{i18n-code}</code>
 * <br>
 * Result: <code> <br>
 *     &lt;i18n&gt; <br>
 *   &lt;translation key=&quot;key1&quot;&gt;translation1&lt;/translation&gt; <br>
 *   &lt;translation key=&quot;key2&quot;&gt;translation2&lt;/translation&gt; <br>
 *   &lt;translation key=&quot;key3&quot;&gt;translation3&lt;/translation&gt; <br>
 * &lt;/i18n&gt; <br>
 * </code>
 * <br/>
 * If just one i18n-code is passed, then the translation element is skipped.
 * <code>
 *     &lt;i18n&gt; <br>translation&lt;/i18n&gt;<br>
 * </code>
 * @param href
 *            URI in the syntax above
 * @param base
 *            not used
 *
 * @return the element with result format above
 * @see javax.xml.transform.URIResolver
 */
@Override
public Source resolve(String href, String base) {
    String target = href.substring(href.indexOf(":") + 1);

    final Element i18nElement = new Element("i18n");
    if(!target.contains("*") && !target.contains(",")){
        i18nElement.addContent(MCRTranslation.translate(target));
        return new JDOMSource(i18nElement);
    }

    final String[] translationKeys = target.split(",");

    // Combine translations to prevent duplicates
    HashMap<String, String> translations = new HashMap<>();
    for (String translationKey : translationKeys) {
        if(translationKey.endsWith("*")){
            final String prefix = translationKey.substring(0, translationKey.length() - 1);
            translations.putAll(MCRTranslation.translatePrefix(prefix));
        } else {
            translations.put(translationKey,MCRTranslation.translate(translationKey));
        }
    }

    translations.forEach((key, value) -> {
        final Element translation = new Element("translation");
        translation.setAttribute("key", key);
        translation.setText(value);
        i18nElement.addContent(translation);
    });

    return new JDOMSource(i18nElement);
}
 
示例28
/**
 * Sets the name space on xml stream.
 *
 * @param in        the in
 * @param nameSpace the name space
 * @return the source
 * @throws JDOMException the JDOM exception
 * @throws IOException   Signals that an I/O exception has occurred.
 */
public static Source setNameSpaceOnXmlStream(final InputStream in, final String nameSpace)
		throws JDOMException, IOException {
	final SAXBuilder sb = new SAXBuilder(new XMLReaderSAX2Factory(false));
	sb.setExpandEntities(false);
	sb.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
	final Document doc = sb.build(in);
	doc.getRootElement().setNamespace(Namespace.getNamespace(nameSpace));
	return new JDOMSource(doc);
}
 
示例29
private Node jdom2dom(Element element) throws TransformerException, JDOMException {
    DOMResult result = new DOMResult();
    JDOMSource source = new JDOMSource(element);
    TransformerFactory.newInstance().newTransformer().transform(source, result);
    return result.getNode();
}
 
示例30
/**
 * Returns the Realms JDOM document as a {@link Source} useful for transformation processes.
 */
static Source getRealmsSource() {
    reInitIfNeeded();
    return new JDOMSource(realmsDocument);
}