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:org.apache.synapse.transport.nhttp.ClientWorker.java

/**
 * Create the thread that would process the response message received for the outgoing message
 * context sent//from w w  w. j  a  v a 2  s.co m
 * @param cfgCtx the Axis2 configuration context
 * @param in the InputStream to read the body of the response message received
 * @param response HTTP response received from the server
 * @param outMsgCtx the original outgoing message context (i.e. corresponding request)
 * @param endpointURLPrefix The endpoint URL prefix
 */
public ClientWorker(ConfigurationContext cfgCtx, InputStream in, HttpResponse response,
        MessageContext outMsgCtx, String endpointURLPrefix) {

    this.cfgCtx = cfgCtx;
    this.in = in;
    this.response = response;
    this.endpointURLPrefix = endpointURLPrefix;
    this.outMsgCtx = outMsgCtx;

    try {
        responseMsgCtx = outMsgCtx.getOperationContext().getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
        // fix for RM to work because of a soapAction and wsaAction conflict
        if (responseMsgCtx != null) {
            responseMsgCtx.setSoapAction("");
        }
    } catch (AxisFault af) {
        log.error("Error getting IN message context from the operation context", af);
        return;
    }

    // this conditional block is to support Sandesha, as it uses an out-in mep, but without
    // creating the message context to write the response and adding it into the operation
    // context, as it may get a 202 accepted or 200. So if the operation is complete ignore
    // this message, else, create a new message context and handle this
    if (responseMsgCtx == null && outMsgCtx.getOperationContext().isComplete()) {

        if (log.isDebugEnabled()) {
            log.debug("Error getting IN message context from the operation context. "
                    + "Possibly an RM terminate sequence message");
        }

    } else {
        if (responseMsgCtx == null) {
            responseMsgCtx = new MessageContext();
            responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext());
        }

        responseMsgCtx.setProperty(MessageContext.IN_MESSAGE_CONTEXT, outMsgCtx);
        responseMsgCtx.setServerSide(true);
        responseMsgCtx.setDoingREST(outMsgCtx.isDoingREST());
        responseMsgCtx.setProperty(MessageContext.TRANSPORT_IN,
                outMsgCtx.getProperty(MessageContext.TRANSPORT_IN));
        responseMsgCtx.setTransportIn(outMsgCtx.getTransportIn());
        responseMsgCtx.setTransportOut(outMsgCtx.getTransportOut());

        // set any transport headers received
        Header[] headers = response.getAllHeaders();
        if (headers != null && headers.length > 0) {

            Map<String, String> headerMap = new TreeMap<String, String>(new Comparator<String>() {
                public int compare(String o1, String o2) {
                    return o1.compareToIgnoreCase(o2);
                }
            });

            String servicePrefix = (String) outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX);
            for (int i = 0; i < headers.length; i++) {
                Header header = headers[i];

                // if this header is already added
                if (headerMap.containsKey(header.getName())) {
                    /* this is a multi-value header */
                    // generate the key
                    String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
                    // get the old value
                    String oldValue = headerMap.get(header.getName());
                    // adds additional values to a list in a property of
                    // message context
                    Map map;
                    if (responseMsgCtx.getProperty(key) != null) {
                        map = (Map) responseMsgCtx.getProperty(key);
                        map.put(header.getName(), oldValue);
                    } else {
                        map = new MultiValueMap();
                        map.put(header.getName(), oldValue);
                        // set as a property in message context
                        responseMsgCtx.setProperty(key, map);
                    }

                }

                if ("Location".equals(header.getName()) && endpointURLPrefix != null && servicePrefix != null) {
                    //Here, we are changing only the host name and the port of the new URI - value of the Location
                    //header.
                    //If the new URI is again referring to a resource in the server to which the original request
                    //is sent, then replace the hostname and port of the URI with the hostname and port of synapse
                    //We are not changing the request url here, only the host name and the port.
                    try {
                        URI serviceURI = new URI(servicePrefix);
                        URI endpointURI = new URI(endpointURLPrefix);
                        URI locationURI = new URI(header.getValue());

                        if ((locationURI.getHost().equalsIgnoreCase(endpointURI.getHost()))
                                && (locationURI.getPort() == endpointURI.getPort())) {
                            URI newURI = new URI(locationURI.getScheme(), locationURI.getUserInfo(),
                                    serviceURI.getHost(), serviceURI.getPort(), locationURI.getPath(),
                                    locationURI.getQuery(), locationURI.getFragment());
                            headerMap.put(header.getName(), newURI.toString());
                            responseMsgCtx.setProperty(NhttpConstants.SERVICE_PREFIX,
                                    outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX));
                        } else {
                            headerMap.put(header.getName(), header.getValue());
                        }
                    } catch (URISyntaxException e) {
                        log.error(e.getMessage(), e);
                    }
                } else {
                    headerMap.put(header.getName(), header.getValue());
                }
            }
            responseMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
        }

        responseMsgCtx.setAxisMessage(outMsgCtx.getOperationContext().getAxisOperation()
                .getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE));
        responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext());
        responseMsgCtx.setConfigurationContext(outMsgCtx.getConfigurationContext());
        responseMsgCtx.setTo(null);

        // Ensure MessageContext has a ClientConnectionDebug attached before we start streaming
        ClientConnectionDebug cd = (ClientConnectionDebug) outMsgCtx
                .getProperty(ClientHandler.CLIENT_CONNECTION_DEBUG);
        if (cd != null) {
            responseMsgCtx.setProperty(ClientHandler.CLIENT_CONNECTION_DEBUG, cd);
        }
    }
    setServerContextAttribute(NhttpConstants.CLIENT_WORKER_INIT_TIME, System.currentTimeMillis(), outMsgCtx);
}

From source file:org.opendatakit.aggregate.externalservice.AbstractExternalService.java

protected HttpResponse sendHttpRequest(String method, String url, HttpEntity entity,
        List<NameValuePair> qparams, CallingContext cc) throws IOException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);

    // setup client
    HttpClientFactory factory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
    HttpClient client = factory.createHttpClient(httpParams);

    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    // redirect limit is set to some unreasonably high number
    // resets of the socket cause a retry up to MAX_REDIRECTS times,
    // so we should be careful not to set this too high...
    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 32);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // context holds authentication state machine, so it cannot be
    // shared across independent activities.
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

    HttpUriRequest request = null;/*from w w w  .ja va 2  s  . com*/
    if (entity == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("No body supplied for POST, PATCH or PUT request");
    } else if (entity != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("Body was supplied for GET or DELETE request");
    }

    URI nakedUri;
    try {
        nakedUri = new URI(url);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException(e);
    }

    if (qparams == null) {
        qparams = new ArrayList<NameValuePair>();
    }
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, HtmlConsts.UTF8_ENCODE), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new IllegalStateException(e1);
    }
    System.out.println(uri.toString());

    if (GET.equals(method)) {
        HttpGet get = new HttpGet(uri);
        request = get;
    } else if (DELETE.equals(method)) {
        HttpDelete delete = new HttpDelete(uri);
        request = delete;
    } else if (PATCH.equals(method)) {
        HttpPatch patch = new HttpPatch(uri);
        patch.setEntity(entity);
        request = patch;
    } else if (POST.equals(method)) {
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);
        request = post;
    } else if (PUT.equals(method)) {
        HttpPut put = new HttpPut(uri);
        put.setEntity(entity);
        request = put;
    } else {
        throw new IllegalStateException("Unexpected request method");
    }

    HttpResponse resp = client.execute(request);
    return resp;
}

From source file:org.eclipse.orion.server.git.objects.Diff.java

private URI getNewLocation(URI location, IPath path) throws URISyntaxException {
    String scope = path.segment(0);
    if (scope.contains("..")) { //$NON-NLS-1$
        String[] commits = scope.split("\\.\\."); //$NON-NLS-1$
        if (commits.length != 2) {
            throw new IllegalArgumentException(
                    NLS.bind("Illegal scope format, expected {old}..{new}, was {0}", scope));
        }//ww  w .  j  ava 2s.  c o  m
        IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(commits[1])
                .append(path.removeFirstSegments(1));
        return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                p.toString(), "parts=body", null); //$NON-NLS-1$
    } else if (scope.equals(GitConstants.KEY_DIFF_CACHED)) {
        IPath p = new Path(GitServlet.GIT_URI + '/' + Index.RESOURCE).append(path.removeFirstSegments(1));
        return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                p.toString(), null, null);
    } else {
        /* including scope.equals(GitConstants.KEY_DIFF_DEFAULT */
        return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                path.removeFirstSegments(1).makeAbsolute().toString(), null, null);
    }
}

From source file:org.eclipse.orion.server.git.servlets.GitCloneHandlerV1.java

private boolean handlePost(HttpServletRequest request, HttpServletResponse response, String pathString)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException, NoHeadException,
        NoMessageException, ConcurrentRefUpdateException, WrongRepositoryStateException {
    // make sure required fields are set
    JSONObject toAdd = OrionServlet.readJSONRequest(request);
    if (toAdd.optBoolean(GitConstants.KEY_PULL, false)) {
        GitUtils.createGitCredentialsProvider(toAdd);
        GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(toAdd);
        boolean force = toAdd.optBoolean(GitConstants.KEY_FORCE, false);
        return pull(request, response, cp, pathString, force);
    }//from   w w  w .  j a v  a 2  s.  c o  m

    Clone clone = new Clone();
    String url = toAdd.optString(GitConstants.KEY_URL, null);
    // method handles repository clone or just repository init
    // decision is based on existence of GitUrl argument
    boolean initOnly;
    if (url == null || url.isEmpty())
        initOnly = true;
    else {
        initOnly = false;
        if (!validateCloneUrl(url, request, response))
            return true;
        clone.setUrl(new URIish(url));
    }
    String cloneName = toAdd.optString(ProtocolConstants.KEY_NAME, null);
    if (cloneName == null)
        cloneName = request.getHeader(ProtocolConstants.HEADER_SLUG);
    // expected path /workspace/{workspaceId}
    String workspacePath = ServletResourceHandler.toOrionLocation(request,
            toAdd.optString(ProtocolConstants.KEY_LOCATION, null));
    // expected path /file/{workspaceId}/{projectName}[/{path}]
    String filePathString = ServletResourceHandler.toOrionLocation(request,
            toAdd.optString(ProtocolConstants.KEY_PATH, null));
    IPath filePath = filePathString == null ? null : new Path(filePathString);
    if (filePath != null && filePath.segmentCount() < 3)
        filePath = null;
    if (filePath == null && workspacePath == null) {
        String msg = NLS.bind("Either {0} or {1} should be provided: {2}",
                new Object[] { ProtocolConstants.KEY_PATH, ProtocolConstants.KEY_LOCATION, toAdd });
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
    }
    // only during init operation filePath or cloneName must be provided
    // during clone operation, name can be obtained from URL
    if (initOnly && filePath == null && cloneName == null) {
        String msg = NLS.bind("Either {0} or {1} should be provided: {2}",
                new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_NAME, toAdd });
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
    }
    if (!validateCloneName(cloneName, request, response))
        return true;

    // prepare the WebClone object, create a new project if necessary
    ProjectInfo project = null;
    boolean webProjectExists = false;
    if (filePath != null) {
        //path format is /file/{workspaceId}/{projectName}/[filePath]
        clone.setId(filePath.toString());
        project = GitUtils.projectFromPath(filePath);
        //workspace path format needs to be used if project does not exist
        if (project == null) {
            String msg = NLS.bind("Specified project does not exist: {0}", filePath.segment(2));
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
        webProjectExists = true;
        clone.setContentLocation(
                project.getProjectStore().getFileStore(filePath.removeFirstSegments(3)).toURI());
        if (cloneName == null)
            cloneName = filePath.segmentCount() > 2 ? filePath.lastSegment() : project.getFullName();
    } else if (workspacePath != null) {
        IPath path = new Path(workspacePath);
        // TODO: move this to CloneJob
        // if so, modify init part to create a new project if necessary
        final IMetaStore metaStore = OrionConfiguration.getMetaStore();
        WorkspaceInfo workspace = metaStore.readWorkspace(path.segment(1));
        if (cloneName == null)
            cloneName = new URIish(url).getHumanishName();
        cloneName = getUniqueProjectName(workspace, cloneName);
        webProjectExists = false;
        project = new ProjectInfo();
        project.setFullName(cloneName);
        project.setWorkspaceId(workspace.getUniqueId());

        try {
            //creating project in the backing store will assign a project id
            metaStore.createProject(project);
        } catch (CoreException e) {
            return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error persisting project state", e));
        }
        try {
            WorkspaceResourceHandler.computeProjectLocation(request, project, null, false);
            metaStore.updateProject(project);
        } catch (CoreException e) {
            //delete the project so we don't end up with a project in a bad location
            try {
                metaStore.deleteProject(workspace.getUniqueId(), project.getFullName());
            } catch (CoreException e1) {
                //swallow secondary error
                LogHelper.log(e1);
            }
            //we are unable to write in the platform location!
            String msg = NLS.bind("Failed to create project: {0}", project.getFullName());
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
        }

        URI baseLocation = getURI(request);
        baseLocation = new URI(baseLocation.getScheme(), baseLocation.getUserInfo(), baseLocation.getHost(),
                baseLocation.getPort(), workspacePath, baseLocation.getQuery(), baseLocation.getFragment());
        clone.setId(GitUtils.pathFromProject(workspace, project).toString());
        clone.setContentLocation(project.getProjectStore().toURI());
    }
    clone.setName(cloneName);
    clone.setBaseLocation(getURI(request));
    JSONObject cloneObject = clone.toJSON();
    String cloneLocation = cloneObject.getString(ProtocolConstants.KEY_LOCATION);

    String gitUserName = toAdd.optString(GitConstants.KEY_NAME, null);
    String gitUserMail = toAdd.optString(GitConstants.KEY_MAIL, null);
    Boolean initProject = toAdd.optBoolean(GitConstants.KEY_INIT_PROJECT, false);
    if (initOnly) {
        // git init
        InitJob job = new InitJob(clone, TaskJobHandler.getUserId(request), request.getRemoteUser(),
                cloneLocation, gitUserName, gitUserMail);
        return TaskJobHandler.handleTaskJob(request, response, job, statusHandler);
    }
    // git clone
    // prepare creds
    GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(toAdd);
    cp.setUri(new URIish(clone.getUrl()));

    // if all went well, clone
    CloneJob job = new CloneJob(clone, TaskJobHandler.getUserId(request), cp, request.getRemoteUser(),
            cloneLocation,
            webProjectExists ? null : project /* used for cleaning up, so null when not needed */, gitUserName,
            gitUserMail, initProject);
    return TaskJobHandler.handleTaskJob(request, response, job, statusHandler);
}

From source file:org.eclipse.orion.server.git.objects.Diff.java

private URI getOldLocation(URI location, IPath path) throws URISyntaxException {
    String scope = path.segment(0);
    if (scope.contains("..")) { //$NON-NLS-1$
        String[] commits = scope.split("\\.\\."); //$NON-NLS-1$
        if (commits.length != 2) {
            throw new IllegalArgumentException(
                    NLS.bind("Illegal scope format, expected {old}..{new}, was {0}", scope));
        }//from w  ww . j  a  v  a 2 s .c  o m
        IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(commits[0])
                .append(path.removeFirstSegments(1));
        return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                p.toString(), "parts=body", null); //$NON-NLS-1$
    } else if (scope.equals(GitConstants.KEY_DIFF_CACHED)) {
        IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(Constants.HEAD)
                .append(path.removeFirstSegments(1));
        return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                p.toString(), "parts=body", null); //$NON-NLS-1$
    } else if (scope.equals(GitConstants.KEY_DIFF_DEFAULT)) {
        IPath p = new Path(GitServlet.GIT_URI + '/' + Index.RESOURCE).append(path.removeFirstSegments(1));
        return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                p.toString(), null, null);
    } else {
        IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(scope)
                .append(path.removeFirstSegments(1));
        return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                p.toString(), "parts=body", null); //$NON-NLS-1$
    }
}

From source file:org.cryptomator.frontend.webdav.mount.WindowsWebDavMounter.java

@Override
public WebDavMount mount(URI uri, Map<MountParam, Optional<String>> mountParams) throws CommandFailedException {
    final String driveLetter = mountParams.getOrDefault(MountParam.WIN_DRIVE_LETTER, Optional.empty())
            .orElse(AUTO_ASSIGN_DRIVE_LETTER);
    if (driveLetters.getOccupiedDriveLetters().contains(CharUtils.toChar(driveLetter))) {
        throw new CommandFailedException("Drive letter occupied.");
    }/*  w ww . j  av a  2s .c  om*/

    final String hostname = mountParams.getOrDefault(MountParam.HOSTNAME, Optional.empty()).orElse(LOCALHOST);
    try {
        final URI adjustedUri = new URI(uri.getScheme(), uri.getUserInfo(), hostname, uri.getPort(),
                uri.getPath(), uri.getQuery(), uri.getFragment());
        CommandResult mountResult = mount(adjustedUri, driveLetter);
        return new WindowsWebDavMount(
                AUTO_ASSIGN_DRIVE_LETTER.equals(driveLetter) ? getDriveLetter(mountResult.getStdOut())
                        : driveLetter);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid host: " + hostname);
    }
}

From source file:org.dcache.srm.client.HttpClientSender.java

/**
 * Creates the HttpContext for a particular call to a SOAP server.
 *
 * Called once per session./*from   w  ww . j  a va 2s . c o m*/
 */
protected HttpClientContext createHttpContext(MessageContext msgContext, URI uri) {
    HttpClientContext context = new HttpClientContext(new BasicHttpContext());
    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();
    if ((userID == null) && (uri.getUserInfo() != null)) {
        String info = uri.getUserInfo();
        int sep = info.indexOf(':');
        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf('\\');
        if (domainIndex > 0 && userID.length() > domainIndex + 1) {
            String domain = userID.substring(0, domainIndex);
            String user = userID.substring(domainIndex + 1);
            credsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain));
        } else {
            credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userID, passwd));
        }
        context.setCredentialsProvider(credsProvider);
    }
    context.setAttribute(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS,
            msgContext.getProperty(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS));
    return context;
}

From source file:com.mcxiaoke.next.http.util.URIBuilder.java

private void digestURI(final URI uri) {
    this.scheme = uri.getScheme();
    this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
    this.encodedAuthority = uri.getRawAuthority();
    this.host = uri.getHost();
    this.port = uri.getPort();
    this.encodedUserInfo = uri.getRawUserInfo();
    this.userInfo = uri.getUserInfo();
    this.encodedPath = uri.getRawPath();
    this.path = uri.getPath();
    this.encodedQuery = uri.getRawQuery();
    this.queryParams = parseQuery(uri.getRawQuery(), Charsets.UTF_8);
    this.encodedFragment = uri.getRawFragment();
    this.fragment = uri.getFragment();
}

From source file:org.callimachusproject.webdriver.helpers.BrowserFunctionalTestCase.java

private void recordTest(String jobId, String data, int retry) {
    String remotewebdriver = System.getProperty("org.callimachusproject.test.remotewebdriver");
    if (remotewebdriver != null && remotewebdriver.contains("saucelabs.com")) {
        URI uri = URI.create(remotewebdriver);
        CloseableHttpClient client = HttpClientBuilder.create().useSystemProperties()
                .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(5000).build()).build();
        try {//from   w w w. j a  v a2s.  c  om
            try {
                String info = uri.getUserInfo();
                putTestData(info, jobId, data, client);
            } finally {
                client.close();
            }
        } catch (IOException ex) {
            if (retry > 0) {
                logger.warn(ex.toString(), ex);
                recordTest(jobId, data, retry - 1);
            } else {
                logger.error(ex.toString(), ex);
            }
        } catch (RuntimeException ex) {
            logger.error(ex.toString(), ex);
        }
    }
}

From source file:com.dhenton9000.birt.configs.DatabaseConfig.java

@Bean
public DataSource dataSource() {
    URI dbUrl = null;
    String dbString = env.getProperty("DATABASE_URL");
    log.debug("database string " + dbString);
    try {//from ww  w .ja va 2 s  .  c  o m

        dbUrl = new URI(dbString);

    } catch (URISyntaxException ex) {

        throw new RuntimeException(ex.getMessage());
    }

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.postgresql.Driver");
    String url = "jdbc:postgresql://" + dbUrl.getHost() + ":" + dbUrl.getPort() + dbUrl.getPath();
    // log.debug("url "+url);
    dataSource.setUrl(url);
    // log.debug("info user "+dbUrl.getUserInfo());
    dataSource.setUsername(dbUrl.getUserInfo().split(":")[0]);
    dataSource.setPassword(dbUrl.getUserInfo().split(":")[1]);
    return dataSource;
}