Example usage for java.net URI getUserInfo

List of usage examples for java.net URI getUserInfo

Introduction

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

Prototype

public String getUserInfo() 

Source Link

Document

Returns the decoded user-information component of this URI.

Usage

From source file:eu.planets_project.tb.impl.data.util.DataHandlerImpl.java

public URI storeDigitalObject(DigitalObject dob, Experiment exp) {
    URI defaultDomUri = this.dataReg.getDefaultDigitalObjectManagerId();
    this.log.info("Attempting to store in data registry: " + defaultDomUri);
    UserBean currentUser = (UserBean) JSFUtil.getManagedObject("UserBean");
    String userid = ".";
    if (currentUser != null && currentUser.getUserid() != null) {
        userid = currentUser.getUserid();
    }/*from  w ww  .  j a v a2  s  .com*/

    // Store new DO in the user space, with path based on experiment details.
    URI baseUri = null;
    try {
        if (exp == null) {
            baseUri = new URI(defaultDomUri.toString() + "/testbed/users/" + userid + "/digitalobjects/");
        } else {
            baseUri = new URI(
                    defaultDomUri.toString() + "/testbed/experiments/experiment-" + exp.getEntityID() + "/");
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return null;
    }
    log.info("Attempting to store in: " + baseUri);

    // Pick a name for the object.
    String name = dob.getTitle();
    if (name == null || "".equals(name)) {
        UUID randomSequence = UUID.randomUUID();
        name = exp.getExperimentSetup().getBasicProperties().getExperimentName() + "-" + randomSequence
                + ".digitalObject";
    }

    // look at the location and pick a unique name.
    URI dobUri;
    try {
        dobUri = new URI(baseUri.getScheme(), baseUri.getUserInfo(), baseUri.getHost(), baseUri.getPort(),
                baseUri.getPath() + name, null, null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        return null;
    }
    log.info("Calling Data Registry List for " + baseUri);
    List<URI> storedDobs = dataReg.list(baseUri);
    if (storedDobs != null) {
        int unum = 1;
        while (storedDobs.contains(dobUri)) {
            try {
                dobUri = new URI(baseUri.getScheme(), baseUri.getUserInfo(), baseUri.getHost(),
                        baseUri.getPort(), baseUri.getPath() + unum + "-" + name, null, null);
            } catch (URISyntaxException e) {
                e.printStackTrace();
                return null;
            }
            unum++;
        }
    }

    log.info("Attempting to store at: " + dobUri);

    try {
        dobUri = this.storeDigitalObject(dobUri, dob);
    } catch (DigitalObjectNotStoredException e) {
        log.error("Store failed! " + e);
        e.printStackTrace();
        return null;
    }

    log.info("Was store at: " + dobUri);

    return dobUri;
}

From source file:org.apache.hadoop.fs.s3r.S3RFileSystem.java

/** Called after a new FileSystem instance is constructed.
 * @param name a uri whose authority section names the host, port, etc.
 *   for this FileSystem/* ww w  .ja va  2s  .c  om*/
 * @param conf the configuration
 */
public void initialize(URI name, Configuration conf) throws IOException {
    super.initialize(name, conf);

    uri = URI.create(name.getScheme() + "://" + name.getAuthority());
    workingDir = new Path("/user", System.getProperty("user.name")).makeQualified(this.uri,
            this.getWorkingDirectory());

    // Try to get our credentials or just connect anonymously
    String accessKey = conf.get(ACCESS_KEY, null);
    String secretKey = conf.get(SECRET_KEY, null);

    String userInfo = name.getUserInfo();
    if (userInfo != null) {
        int index = userInfo.indexOf(':');
        if (index != -1) {
            accessKey = userInfo.substring(0, index);
            secretKey = userInfo.substring(index + 1);
        } else {
            accessKey = userInfo;
        }
    }

    AWSCredentialsProviderChain credentials = new AWSCredentialsProviderChain(
            new BasicAWSCredentialsProvider(accessKey, secretKey), new InstanceProfileCredentialsProvider(),
            new AnonymousAWSCredentialsProvider());

    bucket = name.getHost();

    ClientConfiguration awsConf = new ClientConfiguration();
    awsConf.setMaxConnections(conf.getInt(MAXIMUM_CONNECTIONS, DEFAULT_MAXIMUM_CONNECTIONS));
    boolean secureConnections = conf.getBoolean(SECURE_CONNECTIONS, DEFAULT_SECURE_CONNECTIONS);
    awsConf.setProtocol(secureConnections ? Protocol.HTTPS : Protocol.HTTP);
    awsConf.setMaxErrorRetry(conf.getInt(MAX_ERROR_RETRIES, DEFAULT_MAX_ERROR_RETRIES));
    awsConf.setConnectionTimeout(conf.getInt(ESTABLISH_TIMEOUT, DEFAULT_ESTABLISH_TIMEOUT));
    awsConf.setSocketTimeout(conf.getInt(SOCKET_TIMEOUT, DEFAULT_SOCKET_TIMEOUT));

    String proxyHost = conf.getTrimmed(PROXY_HOST, "");
    int proxyPort = conf.getInt(PROXY_PORT, -1);
    if (!proxyHost.isEmpty()) {
        awsConf.setProxyHost(proxyHost);
        if (proxyPort >= 0) {
            awsConf.setProxyPort(proxyPort);
        } else {
            if (secureConnections) {
                LOG.warn("Proxy host set without port. Using HTTPS default 443");
                awsConf.setProxyPort(443);
            } else {
                LOG.warn("Proxy host set without port. Using HTTP default 80");
                awsConf.setProxyPort(80);
            }
        }
        String proxyUsername = conf.getTrimmed(PROXY_USERNAME);
        String proxyPassword = conf.getTrimmed(PROXY_PASSWORD);
        if ((proxyUsername == null) != (proxyPassword == null)) {
            String msg = "Proxy error: " + PROXY_USERNAME + " or " + PROXY_PASSWORD + " set without the other.";
            LOG.error(msg);
            throw new IllegalArgumentException(msg);
        }
        awsConf.setProxyUsername(proxyUsername);
        awsConf.setProxyPassword(proxyPassword);
        awsConf.setProxyDomain(conf.getTrimmed(PROXY_DOMAIN));
        awsConf.setProxyWorkstation(conf.getTrimmed(PROXY_WORKSTATION));
        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    "Using proxy server {}:{} as user {} with password {} on " + "domain {} as workstation {}",
                    awsConf.getProxyHost(), awsConf.getProxyPort(), String.valueOf(awsConf.getProxyUsername()),
                    awsConf.getProxyPassword(), awsConf.getProxyDomain(), awsConf.getProxyWorkstation());
        }
    } else if (proxyPort >= 0) {
        String msg = "Proxy error: " + PROXY_PORT + " set without " + PROXY_HOST;
        LOG.error(msg);
        throw new IllegalArgumentException(msg);
    }

    s3 = new AmazonS3Client(credentials, awsConf);
    String endPoint = conf.getTrimmed(ENDPOINT, "");
    if (!endPoint.isEmpty()) {
        try {
            s3.setEndpoint(endPoint);
        } catch (IllegalArgumentException e) {
            String msg = "Incorrect endpoint: " + e.getMessage();
            LOG.error(msg);
            throw new IllegalArgumentException(msg, e);
        }
    }

    maxKeys = conf.getInt(MAX_PAGING_KEYS, DEFAULT_MAX_PAGING_KEYS);
    partSize = conf.getLong(MULTIPART_SIZE, DEFAULT_MULTIPART_SIZE);
    multiPartThreshold = conf.getInt(MIN_MULTIPART_THRESHOLD, DEFAULT_MIN_MULTIPART_THRESHOLD);

    if (partSize < 5 * 1024 * 1024) {
        LOG.error(MULTIPART_SIZE + " must be at least 5 MB");
        partSize = 5 * 1024 * 1024;
    }

    if (multiPartThreshold < 5 * 1024 * 1024) {
        LOG.error(MIN_MULTIPART_THRESHOLD + " must be at least 5 MB");
        multiPartThreshold = 5 * 1024 * 1024;
    }

    int maxThreads = conf.getInt(MAX_THREADS, DEFAULT_MAX_THREADS);
    int coreThreads = conf.getInt(CORE_THREADS, DEFAULT_CORE_THREADS);
    if (maxThreads == 0) {
        maxThreads = Runtime.getRuntime().availableProcessors() * 8;
    }
    if (coreThreads == 0) {
        coreThreads = Runtime.getRuntime().availableProcessors() * 8;
    }
    long keepAliveTime = conf.getLong(KEEPALIVE_TIME, DEFAULT_KEEPALIVE_TIME);
    LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(
            maxThreads * conf.getInt(MAX_TOTAL_TASKS, DEFAULT_MAX_TOTAL_TASKS));
    threadPoolExecutor = new ThreadPoolExecutor(coreThreads, maxThreads, keepAliveTime, TimeUnit.SECONDS,
            workQueue, newDaemonThreadFactory("s3a-transfer-shared-"));
    threadPoolExecutor.allowCoreThreadTimeOut(true);

    TransferManagerConfiguration transferConfiguration = new TransferManagerConfiguration();
    transferConfiguration.setMinimumUploadPartSize(partSize);
    transferConfiguration.setMultipartUploadThreshold(multiPartThreshold);

    transfers = new TransferManager(s3, threadPoolExecutor);
    transfers.setConfiguration(transferConfiguration);

    String cannedACLName = conf.get(CANNED_ACL, DEFAULT_CANNED_ACL);
    if (!cannedACLName.isEmpty()) {
        cannedACL = CannedAccessControlList.valueOf(cannedACLName);
    } else {
        cannedACL = null;
    }

    if (!s3.doesBucketExist(bucket)) {
        throw new IOException("Bucket " + bucket + " does not exist");
    }

    boolean purgeExistingMultipart = conf.getBoolean(PURGE_EXISTING_MULTIPART,
            DEFAULT_PURGE_EXISTING_MULTIPART);
    long purgeExistingMultipartAge = conf.getLong(PURGE_EXISTING_MULTIPART_AGE,
            DEFAULT_PURGE_EXISTING_MULTIPART_AGE);

    if (purgeExistingMultipart) {
        Date purgeBefore = new Date(new Date().getTime() - purgeExistingMultipartAge * 1000);

        transfers.abortMultipartUploads(bucket, purgeBefore);
    }

    serverSideEncryptionAlgorithm = conf.get(SERVER_SIDE_ENCRYPTION_ALGORITHM);

    setConf(conf);
}

From source file:org.apache.nifi.web.api.VersionsResource.java

private String lockVersionControl(final URI originalUri, final String groupId) throws URISyntaxException {
    final URI createRequestUri = new URI(originalUri.getScheme(), originalUri.getUserInfo(),
            originalUri.getHost(), originalUri.getPort(), "/nifi-api/versions/active-requests", null,
            originalUri.getFragment());//  w w w. j  a  v a 2s .c o m

    final NodeResponse clusterResponse;
    try {
        // create an active request entity to indicate the group id
        final CreateActiveRequestEntity activeRequestEntity = new CreateActiveRequestEntity();
        activeRequestEntity.setProcessGroupId(groupId);

        final Map<String, String> headers = new HashMap<>();
        headers.put("content-type", MediaType.APPLICATION_JSON);

        if (getReplicationTarget() == ReplicationTarget.CLUSTER_NODES) {
            clusterResponse = getRequestReplicator()
                    .replicate(HttpMethod.POST, createRequestUri, activeRequestEntity, headers)
                    .awaitMergedResponse();
        } else {
            clusterResponse = getRequestReplicator().forwardToCoordinator(getClusterCoordinatorNode(),
                    HttpMethod.POST, createRequestUri, activeRequestEntity, headers).awaitMergedResponse();
        }
    } catch (final InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(
                "Interrupted while updating Version Control Information for Process Group with ID " + groupId
                        + ".",
                ie);
    }

    if (clusterResponse.getStatus() != Status.OK.getStatusCode()) {
        final String errorResponse = getResponseEntity(clusterResponse, String.class);
        throw new IllegalStateException(
                "Failed to create a Version Control Request across all nodes in the cluster. Received response code "
                        + clusterResponse.getStatus() + " with content: " + errorResponse);
    }

    final String requestId = getResponseEntity(clusterResponse, String.class);
    return requestId;
}

From source file:org.apache.nifi.web.api.VersionsResource.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//  w w  w  . j av  a2  s .co m
@Produces(MediaType.APPLICATION_JSON)
@Path("process-groups/{id}")
@ApiOperation(value = "Save the Process Group with the given ID", response = VersionControlInformationEntity.class, notes = "Begins version controlling the Process Group with the given ID or commits changes to the Versioned Flow, "
        + "depending on if the provided VersionControlInformation includes a flowId. "
        + NON_GUARANTEED_ENDPOINT, authorizations = { @Authorization(value = "Read - /process-groups/{uuid}"),
                @Authorization(value = "Write - /process-groups/{uuid}"),
                @Authorization(value = "Read - /{component-type}/{uuid} - For all encapsulated components"),
                @Authorization(value = "Read - any referenced Controller Services by any encapsulated components - /controller-services/{uuid}") })
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
        @ApiResponse(code = 401, message = "Client could not be authenticated."),
        @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
        @ApiResponse(code = 404, message = "The specified resource could not be found."),
        @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") })
public Response saveToFlowRegistry(@ApiParam("The process group id.") @PathParam("id") final String groupId,
        @ApiParam(value = "The versioned flow details.", required = true) final StartVersionControlRequestEntity requestEntity) {

    // Verify the request
    final RevisionDTO revisionDto = requestEntity.getProcessGroupRevision();
    if (revisionDto == null) {
        throw new IllegalArgumentException("Process Group Revision must be specified");
    }

    final VersionedFlowDTO versionedFlowDto = requestEntity.getVersionedFlow();
    if (versionedFlowDto == null) {
        throw new IllegalArgumentException("Version Control Information must be supplied.");
    }
    if (StringUtils.isEmpty(versionedFlowDto.getBucketId())) {
        throw new IllegalArgumentException("The Bucket ID must be supplied.");
    }
    if (StringUtils.isEmpty(versionedFlowDto.getFlowName())
            && StringUtils.isEmpty(versionedFlowDto.getFlowId())) {
        throw new IllegalArgumentException("The Flow Name or Flow ID must be supplied.");
    }
    if (versionedFlowDto.getFlowName() != null && versionedFlowDto.getFlowName().length() > 1000) {
        throw new IllegalArgumentException("The Flow Name cannot exceed 1,000 characters");
    }
    if (StringUtils.isEmpty(versionedFlowDto.getRegistryId())) {
        throw new IllegalArgumentException("The Registry ID must be supplied.");
    }
    if (versionedFlowDto.getDescription() != null && versionedFlowDto.getDescription().length() > 65535) {
        throw new IllegalArgumentException("Flow Description cannot exceed 65,535 characters");
    }
    if (versionedFlowDto.getComments() != null && versionedFlowDto.getComments().length() > 65535) {
        throw new IllegalArgumentException("Comments cannot exceed 65,535 characters");
    }

    if (isDisconnectedFromCluster()) {
        verifyDisconnectedNodeModification(requestEntity.isDisconnectedNodeAcknowledged());
    }

    // ensure we're not attempting to version the root group
    final ProcessGroupEntity root = serviceFacade.getProcessGroup(FlowManager.ROOT_GROUP_ID_ALIAS);
    if (root.getId().equals(groupId)) {
        throw new IllegalArgumentException("The Root Process Group cannot be versioned.");
    }

    if (isReplicateRequest()) {
        // We first have to obtain a "lock" on all nodes in the cluster so that multiple Version Control requests
        // are not being made simultaneously. We do this by making a POST to /nifi-api/versions/active-requests.
        // The Response gives us back the Request ID.
        final URI requestUri;
        try {
            final URI originalUri = getAbsolutePath();
            final String requestId = lockVersionControl(originalUri, groupId);

            requestUri = new URI(originalUri.getScheme(), originalUri.getUserInfo(), originalUri.getHost(),
                    originalUri.getPort(), "/nifi-api/versions/active-requests/" + requestId, null,
                    originalUri.getFragment());
        } catch (final URISyntaxException e) {
            throw new RuntimeException(e);
        }

        // Now that we have the Request, we know that no other thread is updating the Flow Registry. So we can now
        // create the Flow in the Flow Registry and push the Process Group as the first version of the Flow. Once we've
        // succeeded with that, we need to update all nodes' Process Group to contain the new Version Control Information.
        // Finally, we can delete the Request.
        try {
            final VersionControlComponentMappingEntity mappingEntity = serviceFacade
                    .registerFlowWithFlowRegistry(groupId, requestEntity);
            replicateVersionControlMapping(mappingEntity, requestEntity, requestUri, groupId);

            final VersionControlInformationEntity responseEntity = serviceFacade
                    .getVersionControlInformation(groupId);
            return generateOkResponse(responseEntity).build();
        } finally {
            unlockVersionControl(requestUri, groupId);
        }
    }

    // Perform local task. If running in a cluster environment, we will never get to this point. This is because
    // in the above block, we check if (isReplicate()) and if true, we implement the 'cluster logic', but this
    // does not involve replicating the actual request, because we only want a single node to handle the logic of
    // creating the flow in the Registry.
    final Revision groupRevision = new Revision(revisionDto.getVersion(), revisionDto.getClientId(), groupId);
    return withWriteLock(serviceFacade, requestEntity, groupRevision, lookup -> {
        final ProcessGroupAuthorizable groupAuthorizable = lookup.getProcessGroup(groupId);
        final Authorizable processGroup = groupAuthorizable.getAuthorizable();

        // require write to this group
        processGroup.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());

        // require read to this group and all descendants
        authorizeProcessGroup(groupAuthorizable, authorizer, lookup, RequestAction.READ, true, false, true,
                true);
    }, () -> {
        final VersionedFlowDTO versionedFlow = requestEntity.getVersionedFlow();
        final String registryId = versionedFlow.getRegistryId();
        final String bucketId = versionedFlow.getBucketId();
        final String flowId = versionedFlow.getFlowId();
        serviceFacade.verifyCanSaveToFlowRegistry(groupId, registryId, bucketId, flowId);
    }, (rev, flowEntity) -> {
        // Register the current flow with the Flow Registry.
        final VersionControlComponentMappingEntity mappingEntity = serviceFacade
                .registerFlowWithFlowRegistry(groupId, flowEntity);

        // Update the Process Group's Version Control Information
        final VersionControlInformationEntity responseEntity = serviceFacade.setVersionControlInformation(rev,
                groupId, mappingEntity.getVersionControlInformation(),
                mappingEntity.getVersionControlComponentMapping());
        return generateOkResponse(responseEntity).build();
    });
}

From source file:it.infn.ct.futuregateway.apiserver.inframanager.SessionBuilder.java

/**
 * Read the proxy certificate from a remote location.
 * The location is retrieved from the parameters.
 *
 * @return A string representation of the proxy
 * @throws InfrastructureException If the proxy for the infrastructure
 * cannot be retrieved for problems with the parameters
 */// w ww.  j av a  2s  .  com
protected final String readRemoteProxy() throws InfrastructureException {
    URL proxy;
    if (params.getProperty("proxyurl") == null && params.getProperty("etokenserverurl") == null) {
        throw new InfrastructureException(
                "No proxy location in " + "configuration parameters for " + infrastructure.getId());
    }
    if (params.getProperty("proxyurl") != null) {
        try {
            proxy = new URL(params.getProperty("proxyurl"));
        } catch (MalformedURLException mue) {
            throw new InfrastructureException("URL for the proxy is not " + "valid, infrastructure "
                    + infrastructure.getId() + " is not accessible");
        }
    } else {
        try {
            URI etokenurl = new URI(params.getProperty("etokenserverurl"));
            StringBuilder queryURI = new StringBuilder();
            StringBuilder pathURI = new StringBuilder();
            String oldPath = etokenurl.getPath();
            if (oldPath != null) {
                pathURI.append(oldPath);
                if (!oldPath.endsWith("/")) {
                    pathURI.append('/');
                }
                pathURI.append(params.getProperty("etokenid", ""));
            } else {
                pathURI.append('/').append(params.getProperty("etokenid", ""));
            }
            String oldQuery = etokenurl.getQuery();
            if (oldQuery != null) {
                queryURI.append(oldQuery).append('&');
            }
            queryURI.append("voms=").append(params.getProperty("vo", "")).append(':')
                    .append(params.getProperty("voroles", "")).append('&');
            queryURI.append("proxy-renewal=").append(params.getProperty("proxyrenewal", Defaults.PROXYRENEWAL))
                    .append('&');
            queryURI.append("disable-voms-proxy=")
                    .append(params.getProperty("disablevomsproxy", Defaults.DISABLEVOMSPROXY)).append('&');
            queryURI.append("rfc-proxy=").append(params.getProperty("rfcproxy", Defaults.RFCPROXY)).append('&');
            queryURI.append("cn-label=");
            if (user != null) {
                queryURI.append("eToken:").append(user);
            }
            etokenurl = new URI(etokenurl.getScheme(), etokenurl.getUserInfo(), etokenurl.getHost(),
                    etokenurl.getPort(), pathURI.toString(), queryURI.toString(), etokenurl.getFragment());
            proxy = etokenurl.toURL();
        } catch (MalformedURLException | URISyntaxException use) {
            throw new InfrastructureException("etokenserverurl not " + "properly configured for infrastructure "
                    + getInfrastructure().getId());
        }
    }
    StringBuilder strProxy = new StringBuilder();
    log.debug("Accessing the proxy " + proxy.toString());
    try {
        String lnProxy;
        BufferedReader fileProxy = new BufferedReader(new InputStreamReader(proxy.openStream()));
        while ((lnProxy = fileProxy.readLine()) != null) {
            strProxy.append(lnProxy);
            strProxy.append("\n");
        }
    } catch (IOException ioer) {
        log.error("Impossible to retrieve the remote proxy certificate from" + ": " + proxy.toString());
    }
    log.debug("Proxy:\n\n" + strProxy.toString() + "\n\n");
    return strProxy.toString();
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

private URI buildUri(HttpRequest request, Joiner joiner) {
    URI requestUri = request.getUri();

    Map<String, Collection<String>> queryParams = request.getQueryParams();
    if (queryParams != null && !queryParams.isEmpty()) {
        URIBuilder uriBuilder = new URIBuilder();
        StringBuilder queryStringBuilder = new StringBuilder();
        boolean hasQuery = !queryParams.isEmpty();
        for (Map.Entry<String, Collection<String>> stringCollectionEntry : queryParams.entrySet()) {
            String key = stringCollectionEntry.getKey();
            Collection<String> queryParamsValueList = stringCollectionEntry.getValue();
            if (request.isQueryParamsParseAsMultiValue()) {
                for (String queryParamsValue : queryParamsValueList) {
                    uriBuilder.addParameter(key, queryParamsValue);
                    queryStringBuilder.append(key).append("=").append(queryParamsValue).append("&");
                }/*from  www . j ava 2s  .c om*/
            } else {
                String value = joiner.join(queryParamsValueList);
                uriBuilder.addParameter(key, value);
                queryStringBuilder.append(key).append("=").append(value).append("&");
            }
        }
        uriBuilder.setFragment(requestUri.getFragment());
        uriBuilder.setHost(requestUri.getHost());
        uriBuilder.setPath(requestUri.getPath());
        uriBuilder.setPort(requestUri.getPort());
        uriBuilder.setScheme(requestUri.getScheme());
        uriBuilder.setUserInfo(requestUri.getUserInfo());
        try {

            if (!autoEncodeUri) {
                String urlPath = "";
                if (requestUri.getRawPath() != null && requestUri.getRawPath().startsWith("/")) {
                    urlPath = requestUri.getRawPath();
                } else {
                    urlPath = "/" + requestUri.getRawPath();
                }

                if (hasQuery) {
                    String query = queryStringBuilder.substring(0, queryStringBuilder.length() - 1);
                    requestUri = new URI(requestUri.getScheme() + "://" + requestUri.getHost() + ":"
                            + requestUri.getPort() + urlPath + "?" + query);
                } else {
                    requestUri = new URI(requestUri.getScheme() + "://" + requestUri.getHost() + ":"
                            + requestUri.getPort() + urlPath);
                }
            } else {
                requestUri = uriBuilder.build();
            }
        } catch (URISyntaxException e) {
            LOGGER.warn("could not update uri: {}", requestUri);
        }
    }
    return requestUri;
}

From source file:com.epam.reportportal.apache.http.impl.execchain.ProtocolExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final HttpRequest original = request.getOriginal();
    URI uri = null;
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {/*w w w .j  a va  2s .c  o m*/
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    request.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(request, route);

    final HttpParams params = request.getParams();
    HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST);
    // HTTPCLIENT-1092 - add the port if necessary
    if (virtualHost != null && virtualHost.getPort() == -1) {
        final int port = route.getTargetHost().getPort();
        if (port != -1) {
            virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Using virtual host" + virtualHost);
        }
    }

    HttpHost target = null;
    if (virtualHost != null) {
        target = virtualHost;
    } else {
        if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
            target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        }
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            CredentialsProvider credsProvider = context.getCredentialsProvider();
            if (credsProvider == null) {
                credsProvider = new BasicCredentialsProvider();
                context.setCredentialsProvider(credsProvider);
            }
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    // Run request protocol interceptors
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);

    this.httpProcessor.process(request, context);

    final CloseableHttpResponse response = this.requestExecutor.execute(route, request, context, execAware);
    try {
        // Run response protocol interceptors
        context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
        this.httpProcessor.process(response, context);
        return response;
    } catch (final RuntimeException ex) {
        response.close();
        throw ex;
    } catch (final IOException ex) {
        response.close();
        throw ex;
    } catch (final HttpException ex) {
        response.close();
        throw ex;
    }
}

From source file:org.apache.nifi.registry.web.api.ApplicationResource.java

protected URI getBaseUri() {
    final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
    URI uri = uriBuilder.build();
    try {// w  w  w.ja v a  2 s  . co m

        // check for proxy settings
        final String scheme = getFirstHeaderValue(PROXY_SCHEME_HTTP_HEADER, FORWARDED_PROTO_HTTP_HEADER);
        final String host = getFirstHeaderValue(PROXY_HOST_HTTP_HEADER, FORWARDED_HOST_HTTP_HEADER);
        final String port = getFirstHeaderValue(PROXY_PORT_HTTP_HEADER, FORWARDED_PORT_HTTP_HEADER);
        String baseContextPath = getFirstHeaderValue(PROXY_CONTEXT_PATH_HTTP_HEADER,
                FORWARDED_CONTEXT_HTTP_HEADER);

        // if necessary, prepend the context path
        String resourcePath = uri.getPath();
        if (baseContextPath != null) {
            // normalize context path
            if (!baseContextPath.startsWith("/")) {
                baseContextPath = "/" + baseContextPath;
            }

            if (baseContextPath.endsWith("/")) {
                baseContextPath = StringUtils.substringBeforeLast(baseContextPath, "/");
            }

            // determine the complete resource path
            resourcePath = baseContextPath + resourcePath;
        }

        // determine the port uri
        int uriPort = uri.getPort();
        if (port != null) {
            if (StringUtils.isWhitespace(port)) {
                uriPort = -1;
            } else {
                try {
                    uriPort = Integer.parseInt(port);
                } catch (final NumberFormatException nfe) {
                    logger.warn(String.format(
                            "Unable to parse proxy port HTTP header '%s'. Using port from request URI '%s'.",
                            port, uriPort));
                }
            }
        }

        // construct the URI
        uri = new URI((StringUtils.isBlank(scheme)) ? uri.getScheme() : scheme, uri.getUserInfo(),
                (StringUtils.isBlank(host)) ? uri.getHost() : host, uriPort, resourcePath, uri.getQuery(),
                uri.getFragment());

    } catch (final URISyntaxException use) {
        throw new UriBuilderException(use);
    }
    return uri;
}

From source file:org.apache.http.HC4.impl.execchain.ProtocolExec.java

@Override
public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final HttpRequest original = request.getOriginal();
    URI uri = null;
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {//from w w  w . ja  v a2s  .c o m
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    request.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(request, route);

    final HttpParams params = request.getParams();
    HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST);
    // HTTPCLIENT-1092 - add the port if necessary
    if (virtualHost != null && virtualHost.getPort() == -1) {
        final int port = route.getTargetHost().getPort();
        if (port != -1) {
            virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Using virtual host" + virtualHost);
        }
    }

    HttpHost target = null;
    if (virtualHost != null) {
        target = virtualHost;
    } else {
        if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
            target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        }
    }
    if (target == null) {
        target = request.getTarget();
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            CredentialsProvider credsProvider = context.getCredentialsProvider();
            if (credsProvider == null) {
                credsProvider = new BasicCredentialsProvider();
                context.setCredentialsProvider(credsProvider);
            }
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    // Run request protocol interceptors
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);

    this.httpProcessor.process(request, context);

    final CloseableHttpResponse response = this.requestExecutor.execute(route, request, context, execAware);
    try {
        // Run response protocol interceptors
        context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
        this.httpProcessor.process(response, context);
        return response;
    } catch (final RuntimeException ex) {
        response.close();
        throw ex;
    } catch (final IOException ex) {
        response.close();
        throw ex;
    } catch (final HttpException ex) {
        response.close();
        throw ex;
    }
}

From source file:org.eclipse.orion.server.useradmin.servlets.UserHandlerV1.java

private JSONObject formJson(User user, IOrionUserProfileNode userProfile, URI location, String contextPath)
        throws JSONException, CoreException {
    JSONObject json = new JSONObject();
    json.put(UserConstants.KEY_UID, user.getUid());
    json.put(ProtocolConstants.KEY_LOCATION, location);
    json.put(ProtocolConstants.KEY_NAME, user.getName());
    json.put(UserConstants.KEY_LOGIN, user.getLogin());
    json.put(UserConstants.KEY_EMAIL, user.getEmail());
    json.put(UserConstants.KEY_EMAIL_CONFIRMED, user.isEmailConfirmed());
    json.put(UserConstants.KEY_HAS_PASSWORD, user.getPassword() == null ? false : true);

    JSONObject properties = new JSONObject();
    Enumeration<?> userProperties = user.getProperties().keys();
    while (userProperties.hasMoreElements()) {
        String property = (String) userProperties.nextElement();
        properties.put(property, user.getProperty(property));
    }/*from   ww w . j  ava 2  s.  c  o m*/
    json.put(UserConstants.KEY_PROPERTIES, properties);

    if (userProfile != null) {
        json.put(UserConstants.KEY_LAST_LOGIN_TIMESTAMP,
                userProfile.get(IOrionUserProfileConstants.LAST_LOGIN_TIMESTAMP, ""));
        json.put("GitMail", userProfile.get("GitMail", null));
        json.put("GitName", userProfile.get("GitName", null));
    }

    JSONArray plugins = new JSONArray();
    try {
        JSONObject plugin = new JSONObject();
        URI result = user.getPassword() == null
                ? new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                        contextPath + "/plugins/user/nopasswordProfilePlugin.html", null, null)
                : new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                        contextPath + "/plugins/user/userProfilePlugin.html", null, null);
        plugin.put(UserConstants.KEY_PLUGIN_LOCATION, result);
        plugins.put(plugin);
    } catch (URISyntaxException e) {
        LogHelper.log(e);
    }

    return json;
}