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:org.mariotaku.twidere.util.net.HttpClientImpl.java

@Override
public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException {
    try {//w w  w .  ja  va  2s.  c  o m
        HttpRequestBase commonsRequest;

        final HostAddressResolver resolver = conf.getHostAddressResolver();
        final String urlString = req.getURL();
        final URI urlOrig;
        try {
            urlOrig = new URI(urlString);
        } catch (final URISyntaxException e) {
            throw new TwitterException(e);
        }
        final String host = urlOrig.getHost(), authority = urlOrig.getAuthority();
        final String resolvedHost = resolver != null ? resolver.resolve(host) : null;
        final String resolvedUrl = !isEmpty(resolvedHost)
                ? urlString.replace("://" + host, "://" + resolvedHost)
                : urlString;

        final RequestMethod method = req.getMethod();
        if (method == RequestMethod.GET) {
            commonsRequest = new HttpGet(resolvedUrl);
        } else if (method == RequestMethod.POST) {
            final HttpPost post = new HttpPost(resolvedUrl);
            // parameter has a file?
            boolean hasFile = false;
            final HttpParameter[] params = req.getParameters();
            if (params != null) {
                for (final HttpParameter param : params) {
                    if (param.isFile()) {
                        hasFile = true;
                        break;
                    }
                }
                if (!hasFile) {
                    if (params.length > 0) {
                        post.setEntity(new UrlEncodedFormEntity(params));
                    }
                } else {
                    final MultipartEntity me = new MultipartEntity();
                    for (final HttpParameter param : params) {
                        if (param.isFile()) {
                            final ContentBody body;
                            if (param.getFile() != null) {
                                body = new FileBody(param.getFile(), param.getContentType());
                            } else {
                                body = new InputStreamBody(param.getFileBody(), param.getFileName(),
                                        param.getContentType());
                            }
                            me.addPart(param.getName(), body);
                        } else {
                            final ContentBody body = new StringBody(param.getValue(),
                                    "text/plain; charset=UTF-8", Charset.forName("UTF-8"));
                            me.addPart(param.getName(), body);
                        }
                    }
                    post.setEntity(me);
                }
            }
            post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
            commonsRequest = post;
        } else if (method == RequestMethod.DELETE) {
            commonsRequest = new HttpDelete(resolvedUrl);
        } else if (method == RequestMethod.HEAD) {
            commonsRequest = new HttpHead(resolvedUrl);
        } else if (method == RequestMethod.PUT) {
            commonsRequest = new HttpPut(resolvedUrl);
        } else
            throw new TwitterException("Unsupported request method " + method);
        final Map<String, String> headers = req.getRequestHeaders();
        for (final String headerName : headers.keySet()) {
            commonsRequest.addHeader(headerName, headers.get(headerName));
        }
        final Authorization authorization = req.getAuthorization();
        final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req)
                : null;
        if (authorizationHeader != null) {
            commonsRequest.addHeader("Authorization", authorizationHeader);
        }
        if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) {
            commonsRequest.addHeader("Host", authority);
        }

        final ApacheHttpClientHttpResponseImpl res;
        try {
            res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf);
        } catch (final IllegalStateException e) {
            throw new TwitterException("Please check your API settings.", e);
        } catch (final NullPointerException e) {
            // Bug http://code.google.com/p/android/issues/detail?id=5255
            throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e);
        } catch (final OutOfMemoryError e) {
            // I don't know why OOM thown, but it should be catched.
            System.gc();
            throw new TwitterException("Unknown error", e);
        }
        final int statusCode = res.getStatusCode();
        if (statusCode < OK || statusCode > ACCEPTED)
            throw new TwitterException(res.asString(), req, res);
        return res;
    } catch (final IOException e) {
        throw new TwitterException(e);
    }
}

From source file:org.apache.falcon.entity.FileSystemStorage.java

/**
 * Create an instance from the URI Template that was generated using
 * the getUriTemplate() method./* w  w w  . ja v a 2 s.co m*/
 *
 * @param uriTemplate the uri template from org.apache.falcon.entity.FileSystemStorage#getUriTemplate
 * @throws URISyntaxException
 */
protected FileSystemStorage(String uriTemplate) throws URISyntaxException {
    if (uriTemplate == null || uriTemplate.length() == 0) {
        throw new IllegalArgumentException("URI template cannot be null or empty");
    }

    String rawStorageUrl = null;
    List<Location> rawLocations = new ArrayList<Location>();
    String[] feedLocs = uriTemplate.split(FEED_PATH_SEP);
    for (String rawPath : feedLocs) {
        String[] typeAndPath = rawPath.split(LOCATION_TYPE_SEP);
        final String processed = typeAndPath[1]
                .replaceAll(DOLLAR_EXPR_START_REGEX, DOLLAR_EXPR_START_NORMALIZED)
                .replaceAll("}", EXPR_CLOSE_NORMALIZED);
        URI uri = new URI(processed);
        if (rawStorageUrl == null) {
            rawStorageUrl = uri.getScheme() + "://" + uri.getAuthority();
        }

        String path = uri.getPath();
        final String finalPath = path.replaceAll(DOLLAR_EXPR_START_NORMALIZED, DOLLAR_EXPR_START_REGEX)
                .replaceAll(EXPR_CLOSE_NORMALIZED, EXPR_CLOSE_REGEX);

        Location location = new Location();
        location.setPath(finalPath);
        location.setType(LocationType.valueOf(typeAndPath[0]));
        rawLocations.add(location);
    }

    this.storageUrl = rawStorageUrl;
    this.locations = rawLocations;
}

From source file:org.apache.hadoop.hbase.master.replication.ReplicationPeerManager.java

private void checkPeerConfigForSyncReplication(ReplicationPeerConfig peerConfig) throws DoNotRetryIOException {
    // This is used to reduce the difficulty for implementing the sync replication state transition
    // as we need to reopen all the related regions.
    // TODO: Add namespace, replicat_all flag back
    if (peerConfig.replicateAllUserTables()) {
        throw new DoNotRetryIOException("Only support replicated table config for sync replication peer");
    }/* w w w . j a va2s.c  om*/
    if (peerConfig.getNamespaces() != null && !peerConfig.getNamespaces().isEmpty()) {
        throw new DoNotRetryIOException("Only support replicated table config for sync replication peer");
    }
    if (peerConfig.getTableCFsMap() == null || peerConfig.getTableCFsMap().isEmpty()) {
        throw new DoNotRetryIOException("Need config replicated tables for sync replication peer");
    }
    for (List<String> cfs : peerConfig.getTableCFsMap().values()) {
        if (cfs != null && !cfs.isEmpty()) {
            throw new DoNotRetryIOException("Only support replicated table config for sync replication peer");
        }
    }

    Path remoteWALDir = new Path(peerConfig.getRemoteWALDir());
    if (!remoteWALDir.isAbsolute()) {
        throw new DoNotRetryIOException(
                "The remote WAL directory " + peerConfig.getRemoteWALDir() + " is not absolute");
    }
    URI remoteWALDirUri = remoteWALDir.toUri();
    if (remoteWALDirUri.getScheme() == null || remoteWALDirUri.getAuthority() == null) {
        throw new DoNotRetryIOException("The remote WAL directory " + peerConfig.getRemoteWALDir()
                + " is not qualified, you must provide scheme and authority");
    }
}

From source file:com.microsoft.tfs.client.common.ui.protocolhandler.ProtocolHandler.java

private boolean tryParseTfsLink(final String tfsLink) {
    final String decodedTfsLink;
    try {/* www.  ja v  a  2  s. c o m*/
        decodedTfsLink = new String(Base64.decodeBase64(tfsLink), "UTF-8"); //$NON-NLS-1$
    } catch (final UnsupportedEncodingException e) {
        log.error("Incorrectly encoded the tfslink query parameter in the protocol handler URI", e); //$NON-NLS-1$
        return false;
    }

    final String[] tfsLinkItems = decodedTfsLink.split("&"); //$NON-NLS-1$
    Map<String, AtomicReference<String>> tfsLinkItemMap = prepareTfsLinkItemMap();

    for (final String tfsLinkItem : tfsLinkItems) {
        final int idx = tfsLinkItem.indexOf("="); //$NON-NLS-1$

        final String itemName;
        final String itemValue;
        if (idx < 0) {
            itemName = tfsLinkItem;
            itemValue = StringUtil.EMPTY;
        } else {
            itemName = tfsLinkItem.substring(0, idx);
            itemValue = tfsLinkItem.substring(idx + 1);
        }

        if (tfsLinkItemMap.containsKey(itemName)) {
            log.info(MessageFormat.format("                          {0}={1}", //$NON-NLS-1$
                    itemName, itemValue));

            tfsLinkItemMap.get(itemName).set(itemValue);
        }
    }

    if (tfsLinkItemMap.get(PROTOCOL_HANDLER_SERVER_URL_ITEM).get() != null) {
        /*
         * A temporary patch. Should be removed after the TFS server is
         * fixed and sends a collection URL instead of server URL and
         * collection ID.
         */
        final URI cloneUrl = URIUtils.newURI(tfsLinkItemMap.get(PROTOCOL_HANDLER_CLONE_URL_ITEM).get());
        if (ServerURIUtils.isHosted(cloneUrl)) {
            final URI uriCandidate = URIUtils.newURI(cloneUrl.getScheme(), cloneUrl.getAuthority());
            tfsLinkItemMap.get(PROTOCOL_HANDLER_COLLECTION_URL_ITEM).set(uriCandidate.toASCIIString());
        }
    }

    if (tfsLinkItemMap.get(PROTOCOL_HANDLER_COLLECTION_URL_ITEM).get() == null) {
        tfsLinkItemMap.remove(PROTOCOL_HANDLER_COLLECTION_URL_ITEM);
        isCollectionUrlAvailable = false;
    } else {
        tfsLinkItemMap.remove(PROTOCOL_HANDLER_COLLECTION_ID_ITEM);
        tfsLinkItemMap.remove(PROTOCOL_HANDLER_SERVER_URL_ITEM);
        isCollectionUrlAvailable = true;
    }

    for (final AtomicReference<String> value : tfsLinkItemMap.values()) {
        if (value.get() == null) {
            return false;
        }
    }

    return true;
}

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

private Path makeExternalScratchDir(URI extURI) throws IOException {
    while (true) {
        String extPath = scratchPath + File.separator + HiveConf.getVar(conf, HiveConf.ConfVars.HIVEQUERYID)
                + "_" + Integer.toString(Math.abs(rand.nextInt()));
        Path extScratchDir = new Path(extURI.getScheme(), extURI.getAuthority(), extPath);

        FileSystem fs = extScratchDir.getFileSystem(conf);
        if (fs.mkdirs(extScratchDir)) {
            allScratchDirs.add(extScratchDir);
            return extScratchDir;
        }//from ww w.  j a  v a  2  s.  c  o m
    }
}

From source file:nl.kpmg.lcm.server.backend.AbstractBackend.java

protected String getStorageName(String key) {
    DataItemsDescriptor dynamicDataDescriptor = metaDataWrapper.getDynamicData().getDynamicDataDescriptor(key);
    String unparesURI = dynamicDataDescriptor.getURI();
    URI parsedUri;
    try {//from w w w .jav  a2s.  c  o m
        parsedUri = new URI(unparesURI);
    } catch (URISyntaxException ex) {
        LOGGER.error("unable to parse uri " + unparesURI + " for key:" + key);
        return null;
    }

    String storageName = parsedUri.getHost() != null ? parsedUri.getHost() : parsedUri.getAuthority();

    return storageName;
}

From source file:org.apache.jxtadoop.fs.FileSystem.java

/** Returns the FileSystem for this URI's scheme and authority.  The scheme
 * of the URI determines a configuration property name,
 * <tt>fs.<i>scheme</i>.class</tt> whose value names the FileSystem class.
 * The entire URI is passed to the FileSystem instance's initialize method.
 *///from  w ww .  j a v  a2  s. c  om
public static FileSystem get(URI uri, Configuration conf) throws IOException {
    String scheme = uri.getScheme();
    String authority = uri.getAuthority();

    if (scheme == null) { // no scheme: use default FS
        return get(conf);
    }

    if (authority == null) { // no authority
        URI defaultUri = getDefaultUri(conf);
        if (scheme.equals(defaultUri.getScheme()) // if scheme matches default
                && defaultUri.getAuthority() != null) { // & default has authority
            return get(defaultUri, conf); // return default
        }
    }

    return CACHE.get(uri, conf);
}

From source file:com.reelfx.model.PostProcessor.java

/**
 * s// w  w w.  jav  a 2  s. com
 * 
 * @param url
 */
private void setPostURI(String url) {
    try {
        URI given = new URI(url);
        String query = given.getQuery() == null ? "" : given.getQuery();
        query = query + (query.isEmpty() ? "" : "&")
                + (Applet.API_KEY.isEmpty() ? "" : "api_key=" + Applet.API_KEY);
        postUrl = new URI(given.getScheme(), given.getAuthority(), given.getPath(), query, given.getFragment());
    } catch (Exception e) {
        logger.error("Error occurred while processing the post URL (received: " + url + ")", e);
        fireProcessUpdate(POST_FAILED);
    }
}

From source file:com.navercorp.pinpoint.plugin.httpclient4.interceptor.HttpClientExecuteMethodWithHttpUriRequestInterceptor.java

/**
 * copy/* w ww.ja v  a 2  s .co  m*/
 * org.apache.http.client.utils.URIUtils#extractHost(java.net.URI)
 * @param uri
 * @return
 */
private NameIntValuePair<String> extractHost(final URI uri) {
    if (uri == null) {
        return null;
    }
    NameIntValuePair<String> target = null;
    if (uri.isAbsolute()) {
        int port = uri.getPort(); // may be overridden later
        String host = uri.getHost();
        if (host == null) { // normal parse failed; let's do it ourselves
            // authority does not seem to care about the valid character-set
            // for host names
            host = uri.getAuthority();
            if (host != null) {
                // Strip off any leading user credentials
                int at = host.indexOf('@');
                if (at >= 0) {
                    if (host.length() > at + 1) {
                        host = host.substring(at + 1);
                    } else {
                        host = null; // @ on its own
                    }
                }
                // Extract the port suffix, if present
                if (host != null) {
                    int colon = host.indexOf(':');
                    if (colon >= 0) {
                        int pos = colon + 1;
                        int len = 0;
                        for (int i = pos; i < host.length(); i++) {
                            if (Character.isDigit(host.charAt(i))) {
                                len++;
                            } else {
                                break;
                            }
                        }
                        if (len > 0) {
                            try {
                                port = Integer.parseInt(host.substring(pos, pos + len));
                            } catch (NumberFormatException ignore) {
                                // skip
                            }
                        }
                        host = host.substring(0, colon);
                    }
                }
            }
        }
        if (host != null) {
            target = new NameIntValuePair<String>(host, port);
        }
    }
    return target;
}

From source file:org.apache.hadoop.fs.redfish.RedfishFileSystem.java

@Override
public void initialize(URI uri, Configuration conf) throws IOException {
    String configFile = conf.get("fs.redfish.configFile", "");
    if (configFile == "") {
        throw new IOException(
                "You must set fs.redfish.configFile to the " + "path to a valid Redfish configuration file");
    }//from  ww w  .  j  a va2s  . c  o  m
    String userName = System.getProperty("user.name");
    this.m_client = new RedfishClient(configFile, userName);
    this.m_uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
    this.m_cwd = new Path("/user", System.getProperty("user.name")).makeQualified(this).toUri().getPath();
    setConf(conf);
}