Example usage for java.net URI getAuthority

List of usage examples for java.net URI getAuthority

Introduction

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

Prototype

public String getAuthority() 

Source Link

Document

Returns the decoded authority component of this URI.

Usage

From source file:com.hortonworks.registries.schemaregistry.webservice.SchemaRegistryResource.java

/**
 * Checks whether the current instance is a leader. If so, it invokes the given {@code supplier}, else current
 * request is redirected to the leader node in registry cluster.
 *
 * @param uriInfo/*w  w  w.j  a v a2 s.  c o m*/
 * @param supplier
 * @return
 */
private Response handleLeaderAction(UriInfo uriInfo, Supplier<Response> supplier) {
    LOG.info("URI info [{}]", uriInfo.getRequestUri());
    if (!leadershipParticipant.get().isLeader()) {
        URI location = null;
        try {
            String currentLeaderLoc = leadershipParticipant.get().getCurrentLeader();
            URI leaderServerUrl = new URI(currentLeaderLoc);
            URI requestUri = uriInfo.getRequestUri();
            location = new URI(leaderServerUrl.getScheme(), leaderServerUrl.getAuthority(),
                    requestUri.getPath(), requestUri.getQuery(), requestUri.getFragment());
            LOG.info("Redirecting to URI [{}] as this instance is not the leader", location);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Response.temporaryRedirect(location).build();
    } else {
        LOG.info("Invoking here as this instance is the leader");
        return supplier.get();
    }
}

From source file:eu.planets_project.tb.impl.system.batch.backends.ifwee.TestbedWEEBatchProcessor.java

private WorkflowResult fetchWFResultFromDR(String job_key) throws Exception {
    //2. get the data registry manager and fetch the digital object containing the wfResult
    URI drManagerID = DataRegistryFactory.createDataRegistryIdFromName("/experiment-files/executions/")
            .normalize();//from   w  ww. j  a  v  a2 s.c  o  m
    DigitalObjectManager drExpResults = DataRegistryFactory.getDataRegistry()
            .getDigitalObjectManager(drManagerID);
    URI wfResultstorageURI = new URI(drManagerID.getScheme(), drManagerID.getAuthority(),
            drManagerID.getPath() + "/" + job_key + "/wfResult-id-" + job_key + ".xml", null, null).normalize();
    DigitalObject doWFResult = drExpResults.retrieve(wfResultstorageURI);
    if (doWFResult.getContent() == null) {
        throw new Exception("No workflow xml content available.");
    }
    //3. now read the stream into a String and unmarshall the WorkflwoResult object           
    StringBuilder sb = new StringBuilder();
    String line;

    InputStream fis = doWFResult.getContent().getInputStream();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));

        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
    } finally {
        fis.close();
    }

    //4. call unmarshall xml->WorkflowResult object
    return WFResultUtil.unmarshalWorkflowResult(sb.toString());
}

From source file:org.wso2.carbon.ml.core.impl.BAMInputAdapter.java

/**
 * Set the size of the sample to be retrieved from BAM, and return the new URI.
 * //from www  .  j a  v a  2 s  .  c om
 * @param uri           URI of the BAM Data Source
 * @param sampleSize    Size of the sample needed.
 * @return              New URI having the sample size set.
 * @throws              URISyntaxException
 * @throws              MLInputAdapterException
 */
private URI getUriWithSampleSize(URI uri, int sampleSize) throws URISyntaxException, MLInputAdapterException {
    if (uriResourceParameters.length == 1) {
        uri = new URI(uri.toString() + "/-1/-1/0/" + sampleSize);
    } else if (uriResourceParameters.length == 2) {
        uri = new URI(uri.toString() + "/-1/0/" + sampleSize);
    } else if (uriResourceParameters.length == 3) {
        uri = new URI(uri.toString() + "/0/" + sampleSize);
    } else if (uriResourceParameters.length == 4) {
        uri = new URI(uri.toString() + "/" + sampleSize);
    } else if (uriResourceParameters.length == 5) {
        uri = new URI(uri.getScheme() + "://" + uri.getAuthority() + "/analytics/tables/"
                + uriResourceParameters[0] + "/" + uriResourceParameters[1] + "/" + uriResourceParameters[2]
                + "/" + uriResourceParameters[3] + "/" + sampleSize);
    } else {
        throw new MLInputAdapterException("Invalid data source URI: " + uri);
    }
    return uri.normalize();
}

From source file:com.tesora.dve.common.PEUrl.java

private PEUrl parseURL(String urlString) throws PEException {

    try {//  www . jav  a 2s . c  o  m
        URI parser = new URI(urlString.trim());
        final String protocol = parser.getScheme();

        parser = URI.create(parser.getSchemeSpecificPart());
        final String subProtocol = parser.getScheme();
        final String authority = parser.getAuthority();

        if ((protocol == null) || (subProtocol == null)) {
            throw new PEException("Malformed URL '" + urlString + "' - incomplete protocol");
        } else if (authority == null) {
            throw new PEException("Malformed URL '" + urlString + "' - invalid authority");
        }

        this.setProtocol(protocol);
        this.setSubProtocol(subProtocol);

        final String host = parser.getHost();
        if (host != null) {
            this.setHost(host);
        }

        final int port = parser.getPort();
        if (port != -1) {
            this.setPort(port);
        }

        final String query = parser.getQuery();
        if (query != null) {
            this.setQuery(query);
        }

        final String path = parser.getPath();
        if ((path != null) && !path.isEmpty()) {
            this.setPath(path.startsWith("/") ? path.substring(1) : path);
        }

        return this;
    } catch (final URISyntaxException | IllegalArgumentException e) {
        throw new PEException("Malformed URL '" + urlString + "'", e);
    }
}

From source file:org.structr.crawler.SourcePattern.java

private void extractAndSetValue(final NodeInterface obj, final Document doc, final String selector,
        final String mappedType, final String mappedAttribute, final String mappedAttributeFunction,
        final SourcePage subPage) throws FrameworkException {

    // If the sub pattern has a mapped attribute, set the extracted value
    if (StringUtils.isNotEmpty(mappedAttribute)) {

        // Extract the value for this sub pattern's selector
        final String ex = doc.select(selector).text();
        final PropertyKey key = StructrApp.key(type(mappedType), mappedAttribute);

        if (StringUtils.isNotBlank(ex) && key != null) {

            Object convertedValue = ex;

            if (StringUtils.isNotBlank(mappedAttributeFunction)) {

                // input transformation requested
                ActionContext ctx = new ActionContext(securityContext);
                ctx.setConstant("input", convertedValue);
                convertedValue = Scripting.evaluate(ctx, null, "${" + mappedAttributeFunction + "}",
                        " virtual property " + mappedAttribute);

            } else {

                // if no custom transformation is given, try input converter
                final PropertyConverter inputConverter = key.inputConverter(securityContext);

                if (inputConverter != null) {
                    convertedValue = inputConverter.convert(convertedValue);
                }//w  w w  . ja  va2 s.  co m
            }

            obj.setProperty(key, convertedValue);
        }

        // If the sub pattern has no mapped attribute but a sub page defined, query the patterns of the sub page
    } else if (subPage != null) {

        final String pageUrl = subPage.getProperty(SourcePage.url);
        final URI uri;

        try {
            uri = new URI(pageUrl);
        } catch (URISyntaxException ex) {
            throw new FrameworkException(422, "Unable to parse sub page url: " + pageUrl);
        }

        // This is the URL of the linked page derived from the enclosing selector
        final String subUrl = uri.getScheme() + "://" + uri.getAuthority() + doc.select(selector).attr("href");

        // Extract the content of the linked page
        final String subContent = getContent(subUrl);

        // Parse the content into a document
        final Document subDoc = Jsoup.parse(subContent);

        final List<SourcePattern> subPagePatterns = subPage.getProperty(SourcePage.patterns);

        // Loop through all patterns of the sub page
        for (final SourcePattern subPagePattern : subPagePatterns) {

            final Map<String, Object> params = new HashMap<>();
            params.put("document", subDoc);
            params.put("object", obj);

            subPagePattern.extract(params);

            //            final String subPagePatternSelector = subPagePattern.getProperty(SourcePattern.selectorProperty);
            //
            //
            //            // Extract
            //            final String subEx = subDoc.select(subPagePatternSelector).text();
            //            final String subPagePatternType = subPagePattern.getProperty(SourcePattern.mappedTypeProperty);
            //
            //            if (subPagePatternType != null) {
            //
            //
            //               final Elements subParts = subDoc.select(subPagePatternSelector);
            //
            //               final Long j = 1L;
            //
            //               for (final Element subPart : subParts) {
            //
            //                  final NodeInterface subObj = create(subPagePatternType);
            //
            //                  final List<SourcePattern> subPagePatternPatterns = subPagePattern.getProperty(SourcePattern.subPatternsProperty);
            //
            //                  for (final SourcePattern subPageSubPattern : subPagePatternPatterns) {
            //
            //
            //                     final String subPagePatternSelector = subPageSubPattern.getProperty(SourcePattern.selectorProperty);
            //
            //
            //
            //                     final String subPageSubPatternSelector = subPagePatternSelector + ":nth-child(" + j + ") > " + subPagePatternSelector;
            //
            //                     extractAndSetValue(subObj, subDoc, subSelector, mappedType, subPatternMappedAttribute);
            //
            //
            //                     final String subSubEx = subDoc.select(subPageSubPatternSelector).text();
            //
            //                     if (subSubEx != null && subSubEx != = '' && subPageSubPattern.mappedAttribute != null) {
            //
            //                     final PropertyKey key = StructrApp.key(type(mappedType), subPatternMappedAttribute);
            //                     if (key != null) {
            //
            //                        subObj.setProperty(key, subSubEx);
            //                     }
            //
            //                  }
            //
            //                  final String subPagePatternMappedAttribute = subPagePattern.getProperty(SourcePattern.mappedAttributeProperty);
            //
            //                  final PropertyKey key = StructrApp.key(type(mappedType), subPagePatternMappedAttribute);
            //                  if (key != null) {
            //
            //                     obj.setProperty(key, subSubEx);
            //                  }
            //
            //               }
            //
            //            } else {
            //
            //               if (subEx != null && subEx != = '' && subPagePattern.mappedAttribute != null) {
            //                  obj[subPagePattern.mappedAttribute] = subEx;
            //               }
        }
    }
}

From source file:org.eclipse.orion.server.git.GitFileDecorator.java

private void addGitLinks(HttpServletRequest request, URI location, JSONObject representation, URI cloneLocation,
        Repository db, RemoteBranch defaultRemoteBranch, String branchName)
        throws URISyntaxException, JSONException {
    if (db == null)
        return;//from ww  w  .j av a  2 s .c o m
    IPath targetPath = new Path(location.getPath());

    JSONObject gitSection = new JSONObject();

    // add Git Diff URI
    IPath path = new Path(GitServlet.GIT_URI + '/' + Diff.RESOURCE + '/' + GitConstants.KEY_DIFF_DEFAULT)
            .append(targetPath);
    URI link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_DIFF, link);

    // add Git Status URI
    path = new Path(GitServlet.GIT_URI + '/' + Status.RESOURCE).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_STATUS, link);

    // add Git Index URI
    path = new Path(GitServlet.GIT_URI + '/' + Index.RESOURCE).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_INDEX, link);

    // add Git HEAD URI
    path = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(Constants.HEAD).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_HEAD, link);

    // add Git Commit URI
    path = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(GitUtils.encode(branchName))
            .append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_COMMIT, link);

    // add Git Remote URI
    path = new Path(GitServlet.GIT_URI + '/' + Remote.RESOURCE).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_REMOTE, link);

    // add Git Clone Config URI
    path = new Path(GitServlet.GIT_URI + '/' + ConfigOption.RESOURCE + '/' + Clone.RESOURCE).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_CONFIG, link);

    // add Git Default Remote Branch URI 
    gitSection.put(GitConstants.KEY_DEFAULT_REMOTE_BRANCH, defaultRemoteBranch.getLocation());

    // add Git Tag URI
    path = new Path(GitServlet.GIT_URI + '/' + Tag.RESOURCE).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_TAG, link);

    // add Git Blame URI
    path = new Path(GitServlet.GIT_URI + '/' + Blame.RESOURCE).append(Constants.HEAD).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_BLAME, link);

    // add Git Clone URI
    gitSection.put(GitConstants.KEY_CLONE, cloneLocation);

    representation.put(GitConstants.KEY_GIT, gitSection);
}

From source file:org.eclipse.e4.tools.services.impl.ResourceBundleHelper.java

/**
 * Parses the specified contributor URI and loads the {@link ResourceBundle} for the specified {@link Locale}
 * out of an OSGi {@link Bundle}.//w w  w. j ava  2s.co m
 * <p>Following URIs are supported:
 * <ul>
 * <li>platform:/[plugin|fragment]/[Bundle-SymbolicName]<br>
 * Load the OSGi resource bundle out of the bundle/fragment named [Bundle-SymbolicName]</li>
 * <li>platform:/[plugin|fragment]/[Bundle-SymbolicName]/[Path]/[Basename]<br>
 * Load the resource bundle specified by [Path] and [Basename] out of the bundle/fragment named [Bundle-SymbolicName].</li>
 * <li>bundleclass://[plugin|fragment]/[Full-Qualified-Classname]<br>
 * Instantiate the class specified by [Full-Qualified-Classname] out of the bundle/fragment named [Bundle-SymbolicName].
 * Note that the class needs to be a subtype of {@link ResourceBundle}.</li>
 * </ul>
 * </p>
 * @param contributorURI The URI that points to a {@link ResourceBundle}
 * @param locale The {@link Locale} to use for loading the {@link ResourceBundle}
 * @param localization The service for retrieving a {@link ResourceBundle} for a given {@link Locale} out of
 *          the given {@link Bundle} which is specified by URI.
 * @return
 */
public static ResourceBundle getResourceBundleForUri(String contributorURI, Locale locale,
        BundleLocalization localization) {
    if (contributorURI == null)
        return null;

    LogService logService = ToolsServicesActivator.getDefault().getLogService();

    URI uri;
    try {
        uri = new URI(contributorURI);
    } catch (URISyntaxException e) {
        if (logService != null)
            logService.log(LogService.LOG_ERROR, "Invalid contributor URI: " + contributorURI); //$NON-NLS-1$
        return null;
    }

    String bundleName = null;
    Bundle bundle = null;
    String resourcePath = null;
    String classPath = null;

    //the uri follows the platform schema, so we search for .properties files in the bundle
    if (PLATFORM_SCHEMA.equals(uri.getScheme())) {
        bundleName = uri.getPath();
        if (bundleName.startsWith(PLUGIN_SEGMENT))
            bundleName = bundleName.substring(PLUGIN_SEGMENT.length());
        else if (bundleName.startsWith(FRAGMENT_SEGMENT))
            bundleName = bundleName.substring(FRAGMENT_SEGMENT.length());

        resourcePath = ""; //$NON-NLS-1$
        if (bundleName.contains(PATH_SEPARATOR)) {
            resourcePath = bundleName.substring(bundleName.indexOf(PATH_SEPARATOR) + 1);
            bundleName = bundleName.substring(0, bundleName.indexOf(PATH_SEPARATOR));
        }
    } else if (BUNDLECLASS_SCHEMA.equals(uri.getScheme())) {
        if (uri.getAuthority() == null) {
            if (logService != null)
                logService.log(LogService.LOG_ERROR, "Failed to get bundle for: " + contributorURI); //$NON-NLS-1$
        }
        bundleName = uri.getAuthority();
        //remove the leading /
        classPath = uri.getPath().substring(1);
    }

    ResourceBundle result = null;

    if (bundleName != null) {
        bundle = getBundleForName(bundleName);

        if (bundle != null) {
            if (resourcePath == null && classPath != null) {
                //the URI points to a class within the bundle classpath
                //therefore we are trying to instantiate the class
                try {
                    Class<?> resourceBundleClass = bundle.loadClass(classPath);
                    result = getEquinoxResourceBundle(classPath, locale, resourceBundleClass.getClassLoader());
                } catch (Exception e) {
                    if (logService != null)
                        logService.log(LogService.LOG_ERROR,
                                "Failed to load specified ResourceBundle: " + contributorURI, e); //$NON-NLS-1$
                }
            } else if (resourcePath.length() > 0) {
                //the specified URI points to a resource 
                //therefore we try to load the .properties files into a ResourceBundle
                result = getEquinoxResourceBundle(resourcePath.replace('.', '/'), locale, bundle);
            } else {
                //there is no class and no special resource specified within the URI 
                //therefore we load the OSGi resource bundle out of the specified Bundle
                //for the current Locale
                result = localization.getLocalization(bundle, locale.toString());
            }
        }
    }

    return result;
}

From source file:org.apache.hadoop.hdfs.web.WebHdfsFileSystem.java

@Override
public synchronized void initialize(URI uri, Configuration conf) throws IOException {
    super.initialize(uri, conf);
    setConf(conf);//www  . ja v a  2 s.c  o m

    this.nnAddr = NetUtils.createSocketAddr(uri.getAuthority(), getDefaultPort());
    this.workingDir = getHomeDirectory();

    if (UserGroupInformation.isSecurityEnabled()) {
        initDelegationToken();
    }
}

From source file:org.apache.hadoop.hive.metastore.HiveAlterHandler.java

/**
 * Uses the scheme and authority of the object's current location and the path constructed
 * using the object's new name to construct a path for the object's new location.
 *//*from   w  w  w . java  2 s  .  c  o  m*/
private Path constructRenamedPath(Path defaultNewPath, Path currentPath) {
    URI currentUri = currentPath.toUri();

    return new Path(currentUri.getScheme(), currentUri.getAuthority(), defaultNewPath.toUri().getPath());
}

From source file:org.apache.falcon.hadoop.JailedFileSystem.java

@Override
public void initialize(URI name, Configuration conf) throws IOException {
    super.initialize(name, conf);
    setConf(conf);//from w ww.  j  av  a 2s  .c  o  m
    localFS.initialize(LocalFileSystem.getDefaultUri(conf), conf);
    String base = name.getHost();
    if (base == null) {
        throw new IOException("Incomplete Jail URI, no jail base: " + name);
    }
    basePath = new Path(
            conf.get("jail.base",
                    System.getProperty("hadoop.tmp.dir", System.getProperty("user.dir")
                            + "/target/falcon/tmp-hadoop-" + System.getProperty("user.name")))
                    + "/jail-fs/" + base).toUri().getPath();
    this.uri = URI.create(name.getScheme() + "://" + name.getAuthority());
}