Example usage for java.net URI resolve

List of usage examples for java.net URI resolve

Introduction

In this page you can find the example usage for java.net URI resolve.

Prototype

public URI resolve(String str) 

Source Link

Document

Constructs a new URI by parsing the given string and then resolving it against this URI.

Usage

From source file:com.vaushell.superpipes.tools.http.ImageExtractor.java

/**
 * Return the biggest image URI of this webpage.
 *
 * @param rootURI Webpage URI//  w  w w .  j  a v a 2  s .c o  m
 * @return Biggest image
 * @throws IOException
 */
public BufferedImage extractBiggest(final URI rootURI) throws IOException {
    final List<URI> imagesURIs = new ArrayList<>();
    HttpEntity responseEntity = null;
    try {
        // Exec request
        final HttpGet get = new HttpGet(rootURI);

        try (final CloseableHttpResponse response = client.execute(get)) {
            final StatusLine sl = response.getStatusLine();
            if (sl.getStatusCode() != 200) {
                throw new IOException(sl.getReasonPhrase());
            }

            responseEntity = response.getEntity();

            try (final InputStream is = responseEntity.getContent()) {
                final Document doc = Jsoup.parse(is, "UTF-8", rootURI.toString());

                final Elements elts = doc.select("img");
                if (elts != null) {
                    for (final Element elt : elts) {
                        final String src = elt.attr("src");
                        if (src != null && !src.isEmpty()) {
                            try {
                                imagesURIs.add(rootURI.resolve(src));
                            } catch (final IllegalArgumentException ex) {
                                // Ignore wrong encoded URI
                            }
                        }
                    }
                }
            }
        }
    } finally {
        if (responseEntity != null) {
            EntityUtils.consume(responseEntity);
        }
    }

    final BufferedImage[] images = new BufferedImage[imagesURIs.size()];
    final ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < imagesURIs.size(); ++i) {
        final int num = i;

        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    images[num] = HTTPhelper.loadPicture(client, imagesURIs.get(num));
                } catch (final IOException ex) {
                    images[num] = null;
                }
            }
        });
    }

    service.shutdown();

    try {
        service.awaitTermination(1L, TimeUnit.DAYS);
    } catch (final InterruptedException ex) {
        // Ignore
    }

    BufferedImage biggest = null;
    int biggestSize = Integer.MIN_VALUE;
    for (int i = 0; i < imagesURIs.size(); ++i) {
        if (images[i] != null) {
            final int actualSize = images[i].getWidth() * images[i].getHeight();
            if (actualSize > biggestSize) {
                biggest = images[i];

                biggestSize = actualSize;
            }
        }
    }

    return biggest;
}

From source file:net.sf.taverna.raven.plugins.PluginManager.java

/**
 * Returns all the <code>Plugin</code>s available from the
 * <code>PluginSite</code>.//from   ww w.  jav a  2s . c o m
 * 
 * @param pluginSite
 * @return all the <code>Plugin</code>s available from the
 *         <code>PluginSite</code>
 */
@SuppressWarnings("unchecked")
public List<Plugin> getPluginsFromSite(PluginSite pluginSite) {
    List<Plugin> plugins = new ArrayList<Plugin>();
    HttpClient client = new HttpClient();
    client.setConnectionTimeout(TIMEOUT);
    client.setTimeout(TIMEOUT);
    setProxy(client);

    if (pluginSite.getUrl() == null) {
        logger.error("No plugin site URL" + pluginSite);
        return plugins;
    }

    URI pluginSiteURI;
    try {
        pluginSiteURI = pluginSite.getUrl().toURI();
    } catch (URISyntaxException e) {
        logger.error("Invalid plugin site URL" + pluginSite);
        return plugins;
    }

    URI pluginsXML = pluginSiteURI.resolve("pluginlist.xml");

    HttpMethod getPlugins = new GetMethod(pluginsXML.toString());
    int statusCode;
    try {
        statusCode = client.executeMethod(getPlugins);
    } catch (UnknownHostException e) {
        logger.warn("Could not fetch plugins from non-existing host", e);
        return plugins;
    } catch (IOException e) {
        logger.warn("Could not fetch plugins " + pluginsXML, e);
        return plugins;
    }
    if (statusCode != HttpStatus.SC_OK) {
        logger.warn("HTTP status " + statusCode + " while getting plugins " + pluginsXML);
        return plugins;
    }

    Document pluginsDocument;
    try {
        pluginsDocument = new SAXBuilder().build(getPlugins.getResponseBodyAsStream());
    } catch (JDOMException e) {
        logger.warn("Could not parse plugins " + pluginsXML, e);
        return plugins;
    } catch (IOException e) {
        logger.warn("Could not read plugins " + pluginsXML, e);
        return plugins;
    }
    List<Element> pluginList = pluginsDocument.getRootElement().getChildren("plugin");
    for (Element pluginElement : pluginList) {
        URI pluginUri;
        try {
            pluginUri = pluginSiteURI.resolve(pluginElement.getTextTrim());
        } catch (IllegalArgumentException ex) {
            logger.warn("Invalid plugin URI " + pluginElement.getTextTrim());
            continue;
        }

        HttpMethod getPlugin = new GetMethod(pluginUri.toString());
        try {
            statusCode = client.executeMethod(getPlugin);
        } catch (IOException e) {
            logger.warn("Could not fetch plugin " + pluginUri, e);
            continue;
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("HTTP status " + statusCode + " while getting plugin " + pluginUri);
            continue;
        }

        Plugin plugin;
        try {
            XmlOptions xmlOptions = makeXMLOptions();
            xmlOptions.setLoadReplaceDocumentElement(new QName(PLUGINS_NS, "plugin"));
            PluginDocument pluginDoc = PluginDocument.Factory.parse(getPlugin.getResponseBodyAsStream(),
                    xmlOptions);
            plugin = Plugin.fromXmlBean(pluginDoc.getPlugin());
        } catch (XmlException e1) {
            logger.warn("Could not parse plugin " + pluginUri, e1);
            continue;
        } catch (IOException e1) {
            logger.warn("Could not read plugin " + pluginUri, e1);
            continue;
        }
        if (checkPluginCompatibility(plugin)) {
            plugins.add(plugin);
            logger.debug("Added plugin from " + pluginUri);
        } else {
            logger.debug("Plugin deemed incompatible so not added to available plugin list");
        }
    }
    logger.info("Added plugins from " + pluginSiteURI);
    return plugins;
}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlAuthenticationIT.java

/**
 * Submits a Shibboleth login form to the provided URI.
 *
 * @return A URI to which the "consent form" should be submitted.
 *///  www.  ja v a2  s  .  c o  m
private URI submitLoginForm(CloseableHttpClient client, BasicHttpContext context, URI formUri)
        throws IOException {
    final HttpPost form = new HttpPost(formUri);
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("j_username", "Thor"));
    params.add(new BasicNameValuePair("j_password", "NickFuryHeartsES"));
    params.add(new BasicNameValuePair("_eventId_proceed", ""));
    form.setEntity(new UrlEncodedFormEntity(params));

    final String redirect = execute(client, form, context, response -> {
        assertThat(response.getStatusLine().getStatusCode(), equalTo(302));
        return response.getFirstHeader("Location").getValue();
    });
    assertThat(redirect, startsWith("/"));

    String target = execute(client, new HttpGet(formUri.resolve(redirect)), context, response -> {
        assertHttpOk(response.getStatusLine());
        return getFormTarget(response.getEntity().getContent());
    });
    assertThat("Cannot find form target", target, Matchers.notNullValue());
    return formUri.resolve(target);
}

From source file:org.apache.axis2.jaxws.description.impl.URIResolverImpl.java

public InputSource resolveEntity(String namespace, String schemaLocation, String baseUri) {
    if (log.isDebugEnabled()) {
        log.debug("resolveEntity: [" + namespace + "][" + schemaLocation + "][ " + baseUri + "]");
    }//from  w w w .  j  av a  2  s.  c om

    InputStream is = null;
    URI pathURI = null;
    String pathURIStr = null;
    if (log.isDebugEnabled()) {
        log.debug("Import location: " + schemaLocation + " parent document: " + baseUri);
    }
    if (baseUri != null) {
        try {
            // if the location is an absolute path, build a URL directly
            // from it
            if (log.isDebugEnabled()) {
                log.debug("Base URI not null");
            }
            if (isAbsolute(schemaLocation)) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieving input stream for absolute schema location: " + schemaLocation);
                }
                is = getInputStreamForURI(schemaLocation);
            }

            else {
                if (log.isDebugEnabled()) {
                    log.debug("schemaLocation not in absolute path");
                }
                try {
                    pathURI = new URI(baseUri);
                } catch (URISyntaxException e) {
                    // Got URISyntaxException, Creation of URI requires 
                    // that we use special escape characters in path.
                    // The URI constructor below does this for us, so lets use that.
                    if (log.isDebugEnabled()) {
                        log.debug("Got URISyntaxException. Exception Message = " + e.getMessage());
                        log.debug("Implementing alternate way to create URI");
                    }
                    pathURI = new URI(null, null, baseUri, null);
                }
                pathURIStr = schemaLocation;
                // If this is absolute we need to resolve the path without the 
                // scheme information
                if (pathURI.isAbsolute()) {
                    if (log.isDebugEnabled()) {
                        log.debug("Parent document is at absolute location: " + pathURI.toString());
                    }
                    URL url = new URL(baseUri);
                    if (url != null) {
                        URI tempURI;
                        try {
                            tempURI = new URI(url.getPath());
                        } catch (URISyntaxException e) {
                            //Got URISyntaxException, Creation of URI requires 
                            // that we use special escape characters in path.
                            // The URI constructor below does this for us, so lets use that.
                            if (log.isDebugEnabled()) {
                                log.debug("Got URISyntaxException. Exception Message = " + e.getMessage());
                                log.debug("Implementing alternate way to create URI");
                            }
                            tempURI = new URI(null, null, url.getPath(), null);
                        }
                        URI resolvedURI = tempURI.resolve(schemaLocation);
                        // Add back the scheme to the resolved path
                        pathURIStr = constructPath(url, resolvedURI);
                        if (log.isDebugEnabled()) {
                            log.debug("Resolved this path to imported document: " + pathURIStr);
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Parent document is at relative location: " + pathURI.toString());
                    }
                    pathURI = pathURI.resolve(schemaLocation);
                    pathURIStr = pathURI.toString();
                    if (log.isDebugEnabled()) {
                        log.debug("Resolved this path to imported document: " + pathURIStr);
                    }
                }
                // If path is absolute, build URL directly from it
                if (isAbsolute(pathURIStr)) {
                    is = getInputStreamForURI(pathURIStr);
                }

                // if the location is relative, we need to resolve the
                // location using
                // the baseURI, then use the loadStrategy to gain an input
                // stream
                // because the URI will still be relative to the module
                if (is == null) {
                    is = classLoader.getResourceAsStream(pathURI.toString());
                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Exception occured in resolveEntity, ignoring exception continuing processing "
                        + e.getMessage());
                log.debug(e);
            }
        }
    }
    if (is == null) {
        if (log.isDebugEnabled()) {
            log.debug("XSD input stream is null after resolving import for: " + schemaLocation
                    + " from parent document: " + baseUri);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("XSD input stream is not null after resolving import for: " + schemaLocation
                    + " from parent document: " + baseUri);
        }
    }

    InputSource returnInputSource = new InputSource(is);
    // We need to set the systemId.  XmlSchema will use this value to maintain a collection of
    // imported XSDs that have been read.  If this value is null, then circular XSDs will 
    // cause infinite recursive reads.
    returnInputSource.setSystemId(pathURIStr != null ? pathURIStr : schemaLocation);

    if (log.isDebugEnabled()) {
        log.debug("returnInputSource :" + returnInputSource.getSystemId());
    }

    return returnInputSource;
}

From source file:org.apache.taverna.prov.W3ProvenanceExport.java

public void exportAsW3Prov() throws IOException {

    Path provFile = DataBundles.getWorkflowRunProvenance(bundle);

    // TODO: Make this thread safe using contexts?

    GregorianCalendar startedProvExportAt = new GregorianCalendar();

    runURI = URI.create(uriGenerator.makeWFInstanceURI(getWorkflowRunId()));

    URI provFileUri = toURI(provFile);
    Individual bundle = provModel.createBundle(provFileUri);

    // Mini-provenance about this provenance trace. Unkown URI for
    // agent/activity

    Individual storeProvenance = provModel.createActivity(provFileUri.resolve("#taverna-prov-export"));
    storeProvenance.setLabel("taverna-prov export of workflow run provenance", EN);

    provModel.setStartedAtTime(storeProvenance, startedProvExportAt);

    // The agent is an execution of the Taverna software (e.g. also an
    // Activity)//from w  ww  .j a v  a  2s . c  o  m
    Individual tavernaAgent = provModel.createTavernaEngine(provFileUri.resolve("#taverna-engine"));

    Individual plan = provModel.createPlan(getTavernaVersion());
    plan.setLabel(applicationConfig.getTitle(), EN);

    provModel.setWasAssociatedWith(storeProvenance, tavernaAgent, plan);
    provModel.setWasGeneratedBy(bundle, storeProvenance);

    Individual wfProcess = provModel.createWorkflowRun(runURI);

    bundle.setPropertyValue(FOAF.primaryTopic, wfProcess);

    DataflowInvocation dataflowInvocation = provenanceAccess.getDataflowInvocation(getWorkflowRunId());

    // TODO: Should we go through all of getDataflowInvocations() in order
    // to find
    // the plans etc. for the nested workflow executions and also cover
    // empty
    // nested workflow runs?

    String workflowName = provenanceAccess.getWorkflowNameByWorkflowID(dataflowInvocation.getWorkflowId());
    label(wfProcess, "Workflow run of " + workflowName);

    provModel.setWasInformedBy(storeProvenance, wfProcess);
    String wfUri = uriGenerator.makeWorkflowURI(dataflowInvocation.getWorkflowId());
    Individual wfPlan = provModel.createWorkflow(URI.create(wfUri));
    provModel.setWasEnactedBy(wfProcess, tavernaAgent, wfPlan);
    provModel.setDescribedByWorkflow(wfProcess, wfPlan);

    provModel.setStartedAtTime(wfProcess, timestampToLiteral(dataflowInvocation.getInvocationStarted()));
    provModel.setEndedAtTime(wfProcess, timestampToLiteral(dataflowInvocation.getInvocationEnded()));

    // Workflow inputs and outputs
    storeEntitities(dataflowInvocation.getInputsDataBindingId(), wfProcess, Direction.INPUTS, true);
    // FIXME: These entities come out as "generated" by multiple processes
    storeEntitities(dataflowInvocation.getOutputsDataBindingId(), wfProcess, Direction.OUTPUTS, true);
    List<ProcessorEnactment> processorEnactments = provenanceAccess.getProcessorEnactments(getWorkflowRunId());
    // This will also include processor enactments in nested workflows
    for (ProcessorEnactment pe : processorEnactments) {
        String parentId = pe.getParentProcessorEnactmentId();
        URI parentURI;
        if (parentId == null) {
            // Top-level workflow
            parentURI = runURI;
        } else {
            // inside nested wf - this will be parent processenactment
            parentURI = URI.create(uriGenerator.makeProcessExecution(pe.getWorkflowRunId(),
                    pe.getParentProcessorEnactmentId()));

            // TODO: Find plan for nested workflow!
            // String wfUri = uriGenerator.makeWorkflowURI(nestedWfId);
            // Individual wfPlan =
            // provModel.createWorkflow(URI.create(wfUri));
            // provModel.setDescribedByWorkflow(wfProcess, wfPlan);
            // provModel.setWasEnactedBy(wfProcess, tavernaAgent, wfPlan);
        }

        URI processURI = URI
                .create(uriGenerator.makeProcessExecution(pe.getWorkflowRunId(), pe.getProcessEnactmentId()));

        Individual process = provModel.createProcessRun(processURI);
        Individual parentProcess = provModel.createWorkflowRun(parentURI);
        provModel.setWasPartOfWorkflowRun(process, parentProcess);

        provModel.setStartedAtTime(process, timestampToLiteral(pe.getEnactmentStarted()));
        provModel.setEndedAtTime(process, timestampToLiteral(pe.getEnactmentEnded()));

        ProvenanceProcessor provenanceProcessor = provenanceAccess.getProvenanceProcessor(pe.getProcessorId());

        URI processorURI = URI.create(uriGenerator.makeProcessorURI(provenanceProcessor.getProcessorName(),
                provenanceProcessor.getWorkflowId()));

        label(process, "Processor execution " + provenanceProcessor.getProcessorName());
        // The facade identifier is a bit too techie!
        // + " ("
        // + pe.getProcessIdentifier() + ")");
        Individual procPlan = provModel.createProcess(processorURI);
        label(procPlan, "Processor " + provenanceProcessor.getProcessorName());
        provModel.setWasEnactedBy(process, tavernaAgent, procPlan);
        provModel.setDescribedByProcess(process, procPlan);

        URI parentWfUri = URI.create(uriGenerator.makeWorkflowURI(provenanceProcessor.getWorkflowId()));

        Individual parentWf = provModel.createWorkflow(parentWfUri);
        provModel.addSubProcess(parentWf, procPlan);

        // TODO: How to link together iterations on a single processor and
        // the collections
        // they are iterating over and creating?
        // Need 'virtual' ProcessExecution for iteration?

        // TODO: Activity/service details from definition?

        // Inputs and outputs
        storeEntitities(pe.getInitialInputsDataBindingId(), process, Direction.INPUTS, false);
        storeEntitities(pe.getFinalOutputsDataBindingId(), process, Direction.OUTPUTS, false);
    }

    storeFileReferences();

    provModel.setEndedAtTime(storeProvenance, new GregorianCalendar());

    // provModel.model.write(outStream, "TURTLE",
    // provFileUri.toASCIIString());

    OntModel model = provModel.model;
    try (OutputStream outStream = Files.newOutputStream(provFile)) {
        WriterGraphRIOT writer = RDFDataMgr.createGraphWriter(RDFFormat.TURTLE_BLOCKS);
        writer.write(outStream, model.getBaseModel().getGraph(), RiotLib.prefixMap(model.getGraph()),
                provFileUri.toString(), new Context());
    } finally {
        // Avoid registering the RIOT readers/writers from ARQ, as that
        // won't
        // work within Raven or OSGi
        provModel.resetJena();
        logger.warn("Reset Jena readers and writers");
    }

    byte[] dataflow = getDataflow(dataflowInvocation);
    try {
        WorkflowBundle wfBundle = wfBundleIO.readBundle(new ByteArrayInputStream(dataflow),
                T2FlowReader.APPLICATION_VND_TAVERNA_T2FLOW_XML);
        writeBundle(wfBundle);
    } catch (ReaderException e) {
        logger.warn("Could not write bundle", e);
    }

}

From source file:org.lockss.util.UrlUtil.java

/** Resolve child relative to base */
// This version is a wrapper for java.net.URI.resolve().  Java class has
// two undesireable behaviors: it resolves ("http://foo.bar", "a.html")
// to "http://foo.bara.html" (fails to supply missing "/" to base with no
// path), and it resolves ("http://foo.bar/xxx.php", "?foo=bar") to
// "http://foo.bar/?foo=bar" (in accordance with RFC 2396), while all the
// browsers resolve it to "http://foo.bar/xxx.php?foo=bar" (in accordance
// with RFC 1808).  This mimics enough of the logic of
// java.net.URI.resolve(URI, URI) to detect those two cases, and defers
// to the URI code for other cases.

private static java.net.URI resolveUri0(java.net.URI base, java.net.URI child) throws MalformedURLException {

    // check if child is opaque first so that NPE is thrown 
    // if child is null.
    if (child.isOpaque() || base.isOpaque()) {
        return child;
    }//from   w  w w .j av  a  2s .com

    try {
        String scheme = base.getScheme();
        String authority = base.getAuthority();
        String path = base.getPath();
        String query = base.getQuery();
        String fragment = child.getFragment();

        // If base has null path, ensure authority is separated from path in
        // result.  (java.net.URI resolves ("http://foo.bar", "x.y") to
        // http://foo.barx.y)
        if (StringUtil.isNullString(base.getPath())) {
            path = "/";
            base = new java.net.URI(scheme, authority, path, query, fragment);
        }

        // Absolute child
        if (child.getScheme() != null)
            return child;

        if (child.getAuthority() != null) {
            // not relative, defer to URI
            return base.resolve(child);
        }

        // Fragment only, return base with this fragment
        if (child.getPath().equals("") && (child.getFragment() != null) && (child.getQuery() == null)) {
            if ((base.getFragment() != null) && child.getFragment().equals(base.getFragment())) {
                return base;
            }
            java.net.URI ru = new java.net.URI(scheme, authority, path, query, fragment);
            return ru;
        }

        query = child.getQuery();

        authority = base.getAuthority();

        if (StringUtil.isNullString(child.getPath())) {
            // don't truncate base path if child has no path
            path = base.getPath();
        } else if (child.getPath().charAt(0) == '/') {
            // Absolute child path
            path = child.getPath();
        } else {
            // normal relative path, defer to URI
            return base.resolve(child);
        }
        // create URI from relativized components
        java.net.URI ru = new java.net.URI(scheme, authority, path, query, fragment);
        return ru;
    } catch (URISyntaxException e) {
        throw newMalformedURLException(e);
    }
}

From source file:org.apache.streams.util.schema.SchemaStoreImpl.java

@Override
public synchronized Schema create(URI uri) {
    if (!getByUri(uri).isPresent()) {
        URI baseUri = UriUtil.removeFragment(uri);
        JsonNode baseNode = this.contentResolver.resolve(baseUri);
        if (uri.toString().contains("#") && !uri.toString().endsWith("#")) {
            Schema newSchema = new Schema(baseUri, baseNode, null, true);
            this.schemas.put(baseUri, newSchema);
            JsonNode childContent = this.fragmentResolver.resolve(baseNode,
                    '#' + StringUtils.substringAfter(uri.toString(), "#"));
            this.schemas.put(uri, new Schema(uri, childContent, newSchema, false));
        } else {/*from  w  w  w . j av a2 s  .  c  o m*/
            if (baseNode.has("extends") && baseNode.get("extends").isObject()) {
                URI ref = URI.create((baseNode.get("extends")).get("$ref").asText());
                URI absoluteUri;
                if (ref.isAbsolute()) {
                    absoluteUri = ref;
                } else {
                    absoluteUri = baseUri.resolve(ref);
                }
                JsonNode parentNode = this.contentResolver.resolve(absoluteUri);
                Schema parentSchema;
                if (this.schemas.get(absoluteUri) != null) {
                    parentSchema = this.schemas.get(absoluteUri);
                } else {
                    parentSchema = create(absoluteUri);
                }
                this.schemas.put(uri, new Schema(uri, baseNode, parentSchema, true));
            } else {
                this.schemas.put(uri, new Schema(uri, baseNode, null, true));
            }
        }
        List<JsonNode> refs = baseNode.findValues("$ref");
        for (JsonNode ref : refs) {
            if (ref.isValueNode()) {
                String refVal = ref.asText();
                URI refUri = null;
                try {
                    refUri = URI.create(refVal);
                } catch (Exception ex) {
                    LOGGER.info("Exception: {}", ex.getMessage());
                }
                if (refUri != null && !getByUri(refUri).isPresent()) {
                    if (refUri.isAbsolute()) {
                        create(refUri);
                    } else {
                        create(baseUri.resolve(refUri));
                    }
                }
            }
        }
    }

    return this.schemas.get(uri);
}

From source file:org.wrml.runtime.schema.DefaultSchemaLoader.java

private final URI getTypeUri(final String typeName, final boolean isChoices, final boolean cache) {

    if (_NativeTypeNameToUriBiMap.containsKey(typeName)) {
        return _NativeTypeNameToUriBiMap.get(typeName);
    }//from   ww w. ja  v  a 2s .co  m

    final URI baseSystemUri = (isChoices) ? SystemApi.Choices.getUri() : SystemApi.Schema.getUri();

    final String path = "/" + SchemaGenerator.externalTypeNameToInternalTypeName(typeName);

    final URI uri = baseSystemUri.resolve(path);

    if (cache) {
        _NativeTypeNameToUriBiMap.put(typeName, uri);
    }

    return uri;
}

From source file:com.collaborne.jsonschema.generator.driver.GeneratorDriver.java

/**
 * Create a {@link SchemaLoader} with the provided {@code rootUri} and {@code baseDirectory}.
 *
 * All schemas from {@code schemaFiles} are pre-loaded into the schema loader.
 *
 * @param rootUri/*ww w .j a va 2 s.  c  o m*/
 * @param baseDirectory
 * @param schemaFiles
 * @return
 * @throws IOException
 */
public SchemaLoader createSchemaLoader(URI rootUri, Path baseDirectory, List<Path> schemaFiles)
        throws IOException {
    URI baseDirectoryUri = baseDirectory.toAbsolutePath().normalize().toUri();

    // We're not adding a path redirection here, because that changes the path of the loaded schemas to the redirected location.
    // FIXME: This really looks like a bug in the SchemaLoader itself!
    URITranslatorConfiguration uriTranslatorConfiguration = URITranslatorConfiguration.newBuilder()
            .setNamespace(rootUri).freeze();

    LoadingConfigurationBuilder loadingConfigurationBuilder = LoadingConfiguration.newBuilder()
            .setURITranslatorConfiguration(uriTranslatorConfiguration);

    // ... instead, we use a custom downloader which executes the redirect
    Map<String, URIDownloader> downloaders = loadingConfigurationBuilder.freeze().getDownloaderMap();
    URIDownloader redirectingDownloader = new URIDownloader() {
        @Override
        public InputStream fetch(URI source) throws IOException {
            URI relativeSourceUri = rootUri.relativize(source);
            if (!relativeSourceUri.isAbsolute()) {
                // Apply the redirect
                source = baseDirectoryUri.resolve(relativeSourceUri);
            }

            URIDownloader wrappedDownloader = downloaders.get(source.getScheme());
            return wrappedDownloader.fetch(source);
        }
    };
    for (Map.Entry<String, URIDownloader> entry : downloaders.entrySet()) {
        loadingConfigurationBuilder.addScheme(entry.getKey(), redirectingDownloader);
    }

    JsonNodeReader reader = new JsonNodeReader(objectMapper);
    for (Path schemaFile : schemaFiles) {
        URI schemaFileUri = schemaFile.toAbsolutePath().normalize().toUri();
        URI relativeSchemaUri = baseDirectoryUri.relativize(schemaFileUri);
        URI schemaUri = rootUri.resolve(relativeSchemaUri);

        logger.info("{}: loading from {}", schemaUri, schemaFile);
        JsonNode schemaNode = reader.fromReader(Files.newBufferedReader(schemaFile));
        // FIXME: (upstream?): the preloaded map is accessed via the "real URI", so we need that one here as well
        //        This smells really wrong, after all we want all these to look like they came from rootUri()
        loadingConfigurationBuilder.preloadSchema(schemaFileUri.toASCIIString(), schemaNode);
    }

    return new SchemaLoader(loadingConfigurationBuilder.freeze());
}

From source file:de.betterform.xml.xforms.model.Model.java

private XSLoader getSchemaLoader()
        throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    // System.setProperty(DOMImplementationRegistry.PROPERTY,
    // "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    XSImplementation implementation = (XSImplementation) registry.getDOMImplementation("XS-Loader");
    XSLoader loader = implementation.createXSLoader(null);

    DOMConfiguration cfg = loader.getConfig();

    cfg.setParameter("resource-resolver", new LSResourceResolver() {
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            LSInput input = new LSInput() {
                String systemId;/*w  ww.  ja  v a 2 s .c o  m*/

                public void setSystemId(String systemId) {
                    this.systemId = systemId;
                }

                public void setStringData(String s) {
                }

                String publicId;

                public void setPublicId(String publicId) {
                    this.publicId = publicId;
                }

                public void setEncoding(String s) {
                }

                public void setCharacterStream(Reader reader) {
                }

                public void setCertifiedText(boolean flag) {
                }

                public void setByteStream(InputStream inputstream) {
                }

                String baseURI;

                public void setBaseURI(String baseURI) {
                    if (baseURI == null || "".equals(baseURI)) {
                        baseURI = getContainer().getProcessor().getBaseURI();
                    }
                    this.baseURI = baseURI;
                }

                public String getSystemId() {
                    return this.systemId;
                }

                public String getStringData() {
                    return null;
                }

                public String getPublicId() {
                    return this.publicId;
                }

                public String getEncoding() {
                    return null;
                }

                public Reader getCharacterStream() {
                    return null;
                }

                public boolean getCertifiedText() {
                    return false;
                }

                public InputStream getByteStream() {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("Schema resource\n\t\t publicId '" + publicId + "'\n\t\t systemId '"
                                + systemId + "' requested");
                    }
                    try {
                        String pathToSchema = null;
                        if ("http://www.w3.org/MarkUp/SCHEMA/xml-events-attribs-1.xsd".equals(systemId)) {
                            pathToSchema = "schema/xml-events-attribs-1.xsd";
                        } else if ("http://www.w3.org/2001/XMLSchema.xsd".equals(systemId)) {
                            pathToSchema = "schema/XMLSchema.xsd";
                        } else if ("-//W3C//DTD XMLSCHEMA 200102//EN".equals(publicId)) {
                            pathToSchema = "schema/XMLSchema.dtd";
                        } else if ("datatypes".equals(publicId)) {
                            pathToSchema = "schema/datatypes.dtd";
                        } else if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                            pathToSchema = "schema/xml.xsd";
                        }

                        // LOAD WELL KNOWN SCHEMA
                        if (pathToSchema != null) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("loading Schema '" + pathToSchema + "'\n\n");
                            }
                            return Thread.currentThread().getContextClassLoader()
                                    .getResourceAsStream(pathToSchema);
                        }
                        // LOAD SCHEMA THAT IS NOT(!) YET KNWON TO THE XFORMS PROCESSOR
                        else if (systemId != null && !"".equals(systemId)) {
                            URI schemaURI = new URI(baseURI);
                            schemaURI = schemaURI.resolve(systemId);

                            // ConnectorFactory.getFactory()
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("loading schema resource '" + schemaURI.toString() + "'\n\n");
                            }
                            return ConnectorFactory.getFactory().getHTTPResourceAsStream(schemaURI);

                        } else {
                            LOGGER.error("resource not known '" + systemId + "'\n\n");
                            return null;
                        }

                    } catch (XFormsException e) {
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                public String getBaseURI() {
                    return this.baseURI;
                }
            };
            input.setSystemId(systemId);
            input.setBaseURI(baseURI);
            input.setPublicId(publicId);
            return input;
        }
    });
    // END: Patch
    return loader;
}