Example usage for org.apache.http.client.utils URIBuilder toString

List of usage examples for org.apache.http.client.utils URIBuilder toString

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder toString.

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:org.flowable.admin.service.engine.DeploymentService.java

public JsonNode listDeployments(ServerConfig serverConfig, Map<String, String[]> parameterMap) {

    URIBuilder builder = null;/*from w  w  w.j a  va  2s .c  o  m*/
    try {
        builder = new URIBuilder("repository/deployments");
    } catch (Exception e) {
        log.error("Error building uri", e);
        throw new FlowableServiceException("Error building uri", e);
    }

    for (String name : parameterMap.keySet()) {
        builder.addParameter(name, parameterMap.get(name)[0]);
    }
    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder.toString()));
    return clientUtil.executeRequest(get, serverConfig);
}

From source file:org.geosdi.geoplatform.experimental.openam.support.config.connector.crud.OpenAMCrudConnector.java

/**
 * @param userName/*w w w  .  j  a v a2 s  . com*/
 * @return {@link IOpenAMDeleteResponse}
 * @throws Exception
 */
@Override
public IOpenAMDeleteResponse deleteUser(String userName) throws Exception {
    IOpenAMAuthenticate openAMAuthenticate = null;
    try {
        Preconditions.checkNotNull(userName, "The UserName must not be null");
        logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TRYING TO Delete USER with UserName: {}  WITH "
                + "OPENAM_CONNECTOR_SETTINGS : {} \n", userName, this.openAMConnectorSettings);

        OpenAMDeleteUserRequest deleteUserRequest = this.openAMRequestMediator.getRequest(DELETE_USER);
        URIBuilder uriBuilder = this.buildURI(this.openAMConnectorSettings,
                deleteUserRequest.setExtraPathParam(userName));

        logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@OPENAM_DELETE_USER_CONNECTOR_URI : {}\n",
                URLDecoder.decode(uriBuilder.toString(), "UTF-8"));

        openAMAuthenticate = super.authenticate();
        logger.debug("::::::::::::::::::::::::::::::AUTHENTICATE_FOR_DELETE_USER : {}\n", openAMAuthenticate);

        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());
        httpDelete.addHeader(this.openAMCookieInfo.getOpenAMCookie(), openAMAuthenticate.getTokenId());

        CloseableHttpResponse response = this.httpClient.execute(httpDelete);
        if (response.getStatusLine().getStatusCode() == 404) {
            logger.debug("##############################OPENAM_USER with USER_NAME : {} - not exist\n",
                    userName);
            return new OpenAMDeleteResponse() {
                {
                    super.setSuccess(Boolean.TRUE);
                }
            };
        }

        if (response.getStatusLine().getStatusCode() != 200) {
            IOpenAMErrorResponse openAMErrorResponse = this.openAMReader
                    .readValue(response.getEntity().getContent(), OpenAMErrorResponse.class);
            throw new IllegalStateException("OpenAMUpdateUser Error Code : " + openAMErrorResponse.getCode()
                    + " - Reason : " + openAMErrorResponse.getReason() + " - Message : "
                    + openAMErrorResponse.getMessage());
        }
        return this.openAMReader.readValue(response.getEntity().getContent(), OpenAMDeleteResponse.class);
    } finally {
        if (openAMAuthenticate != null)
            super.logout(openAMAuthenticate.getTokenId());
    }
}

From source file:org.geosdi.geoplatform.experimental.openam.support.config.connector.crud.OpenAMCrudConnector.java

/**
 * @param openAMUser//from   www .  j a  v  a  2s  .  c om
 * @return {@link IOpenAMUserResponse}
 * @throws Exception
 */
@Override
public IOpenAMUserResponse updateUser(IOpenAMUser openAMUser) throws Exception {
    Preconditions.checkNotNull(openAMUser, "The OpenAMUser must not be null");
    Preconditions.checkArgument((openAMUser.getUserName() != null) && !(openAMUser.getUserName().isEmpty()),
            "The OpenAm UserName must not be null or an Empty String.");
    logger.debug(
            "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TRYING TO Update USER {}  WITH "
                    + "OPENAM_CONNECTOR_SETTINGS : {} \n",
            openAMUser.getUserName(), this.openAMConnectorSettings);

    OpenAMUpdateUserRequest updateUserRequest = this.openAMRequestMediator.getRequest(UPDATE_USER);
    URIBuilder updateURIBuilder = this.buildURI(this.openAMConnectorSettings,
            updateUserRequest.setExtraPathParam(openAMUser.getUserName()));

    logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@OPENAM_UPDATE_USER_CONNECTOR_URI : {}\n",
            URLDecoder.decode(updateURIBuilder.toString(), "UTF-8"));

    IOpenAMAuthenticate openAMAuthenticate = super.authenticate();
    logger.debug("::::::::::::::::::::::::::::::AUTHENTICATE_FOR_UPDATE_USER : {}\n", openAMAuthenticate);

    String openAMUserAsString = this.openAMReader.writeValueAsString(openAMUser);
    logger.debug("::::::::::::::::::::::::::OPENAM_UPDATE_USER_AS_STRING : {}\n", openAMUserAsString);

    HttpPut httpPut = new HttpPut(updateURIBuilder.build());
    httpPut.addHeader("Content-Type", "application/json");
    httpPut.addHeader(this.openAMCookieInfo.getOpenAMCookie(), openAMAuthenticate.getTokenId());
    httpPut.setEntity(new StringEntity(openAMUserAsString, ContentType.APPLICATION_JSON));

    CloseableHttpResponse response = this.httpClient.execute(httpPut);

    if (response.getStatusLine().getStatusCode() != 200) {
        IOpenAMErrorResponse openAMErrorResponse = this.openAMReader
                .readValue(response.getEntity().getContent(), OpenAMErrorResponse.class);
        throw new IllegalStateException(
                "OpenAMUpdateUser Error Code : " + openAMErrorResponse.getCode() + " - Reason : "
                        + openAMErrorResponse.getReason() + " - Message : " + openAMErrorResponse.getMessage());
    }
    this.logout(openAMAuthenticate.getTokenId());
    return this.openAMReader.readValue(response.getEntity().getContent(), OpenAMUserResponse.class);
}

From source file:org.flowable.admin.service.engine.EventSubscriptionService.java

public JsonNode listEventSubscriptions(ServerConfig serverConfig, Map<String, String[]> parameterMap) {

    URIBuilder builder = null;
    try {/*from   w w  w. j a  v  a 2  s.co m*/
        builder = new URIBuilder("runtime/event-subscriptions");
    } catch (Exception e) {
        log.error("Error building uri", e);
        throw new FlowableServiceException("Error building uri", e);
    }

    for (String name : parameterMap.keySet()) {
        builder.addParameter(name, parameterMap.get(name)[0]);
    }
    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder.toString()));
    return clientUtil.executeRequest(get, serverConfig);
}

From source file:com.nexmo.client.voice.endpoints.ListCallsMethod.java

@Override
public RequestBuilder makeRequest(CallsFilter filter)
        throws NexmoClientException, UnsupportedEncodingException {
    URIBuilder uriBuilder;
    try {//from w  w  w  .  j a va2s .  c om
        uriBuilder = new URIBuilder(this.uri);
    } catch (URISyntaxException e) {
        throw new NexmoUnexpectedException("Could not parse URI: " + this.uri);
    }
    if (filter != null) {
        List<NameValuePair> params = filter.toUrlParams();
        for (NameValuePair param : params) {
            uriBuilder.setParameter(param.getName(), param.getValue());
        }
    }
    return RequestBuilder.get().setUri(uriBuilder.toString());
}

From source file:com.activiti.service.activiti.ProcessDefinitionService.java

public JsonNode listProcesDefinitions(ServerConfig serverConfig, Map<String, String[]> parameterMap,
        boolean latest) {

    URIBuilder builder = null;
    try {/*  ww  w  .  j  ava2 s.co m*/
        builder = new URIBuilder("repository/process-definitions");
    } catch (Exception e) {
        log.error("Error building uri", e);
        throw new ActivitiServiceException("Error building uri", e);
    }

    for (String name : parameterMap.keySet()) {
        builder.addParameter(name, parameterMap.get(name)[0]);
    }
    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder.toString()));
    return clientUtil.executeRequest(get, serverConfig);
}

From source file:org.flowable.admin.service.engine.ProcessDefinitionService.java

public JsonNode listProcesDefinitions(ServerConfig serverConfig, Map<String, String[]> parameterMap,
        boolean latest) {

    URIBuilder builder = null;
    try {//from   w w w  .j a va  2  s. c  o  m
        builder = new URIBuilder("repository/process-definitions");
    } catch (Exception e) {
        log.error("Error building uri", e);
        throw new FlowableServiceException("Error building uri", e);
    }

    for (String name : parameterMap.keySet()) {
        builder.addParameter(name, parameterMap.get(name)[0]);
    }
    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder.toString()));
    return clientUtil.executeRequest(get, serverConfig);
}

From source file:gov.medicaid.screening.dao.impl.MedicalPracticeLicenseDAOBean.java

/**
 * Performs a search for all possible results.
 *
 * @param criteria The search criteria.// ww w .  j a v  a  2 s.  co m
 * @param byName flag indicating it is a search by name.
 * @return the search result for licenses
 * @throws URISyntaxException if an error occurs while building the URL.
 * @throws ClientProtocolException if client does not support protocol used.
 * @throws IOException if an error occurs while parsing response.
 * @throws ParseException if an error occurs while parsing response.
 * @throws ServiceException for any other problems encountered
 */
private SearchResult<License> getAllResults(MedicalPracticeLicenseSearchCriteria criteria, boolean byName)
        throws URISyntaxException, ClientProtocolException, IOException, ParseException, ServiceException {

    DefaultHttpClient client = new DefaultHttpClient();

    URIBuilder builder = new URIBuilder(getSearchURL()).setPath("/BMP/DesktopModules/ServiceForm.aspx");
    String hostId = builder.toString();
    builder.setParameter("svid", "30").setParameter("mid", "176");

    HttpGet httpget = new HttpGet(builder.build());
    HttpResponse landing = client.execute(httpget);
    Document document = Jsoup.parse(EntityUtils.toString(landing.getEntity()));

    HttpPost httppost = new HttpPost(builder.build());

    HttpEntity entity = postForm(hostId, client, httppost,
            new String[][] {
                    { "__EVENTTARGET", byName ? "_ctl7_rblSearchOption_0" : "_ctl7_rblSearchOption_1" },
                    { "__EVENTARGUMENT", "" }, { "_ctl7:rblSearchOption", byName ? "Name" : "Specialty" },
                    { "__VIEWSTATE", document.select("#Form1 input[name=__VIEWSTATE]").first().val() } },
            true);

    document = Jsoup.parse(EntityUtils.toString(entity));
    httppost.releaseConnection();

    if (byName) {
        entity = postForm(hostId, client, httppost,
                new String[][] { { "__EVENTTARGET", "" }, { "__EVENTARGUMENT", "" },
                        { "_ctl7:cmdSearch", "Search" }, { "_ctl7:rblSearchOption", "Name" },
                        { "_ctl7:txtCity", Util.defaultString(criteria.getCity()) },
                        { "_ctl7:txtFirstName", Util.defaultString(criteria.getFirstName()) },
                        { "_ctl7:txtLastName", Util.defaultString(criteria.getLastName()) },
                        { "_ctl7:txtLicNbr", Util.defaultString(criteria.getIdentifier()) },
                        { "__VIEWSTATE", document.select("#Form1 input[name=__VIEWSTATE]").first().val() } },
                true);
    } else {

        String code = matchSpecialtyCode(criteria, document);
        entity = postForm(hostId, client, httppost,
                new String[][] { { "__EVENTTARGET", "" }, { "__EVENTARGUMENT", "" },
                        { "_ctl7:cmdSearchSpecialty", "Search" }, { "_ctl7:ddlbSpecialty", code },
                        { "_ctl7:rblSearchOption", "Specialty" },
                        { "_ctl7:txtSpecialtyCity", Util.defaultString(criteria.getCity()) },
                        { "_ctl7:txtSpecialtyZip", Util.defaultString(criteria.getZipcode()) },
                        { "__VIEWSTATE", document.select("#Form1 input[name=__VIEWSTATE]").first().val() } },
                true);
    }

    // licenses list
    List<License> licenseList = new ArrayList<License>();
    if (entity != null) {
        String result = EntityUtils.toString(entity);
        document = Jsoup.parse(result);
        Elements rows = document.select(
                "#_ctl7_grdSearchResults tr.TableItem, #_ctl7_grdSearchResults tr.TableAlternatingItem");
        for (Element row : rows) {
            String href = row.select("a[name=Hyperlink1]").first().attr("href");
            String city = row.select("td:eq(4)").text();

            String detailsLink = getSearchURL() + "/BMP/DesktopModules/" + href.replaceAll(" ", "%20");
            HttpGet detailsGet = new HttpGet(detailsLink);
            HttpResponse detailsResponse = client.execute(detailsGet);
            HttpEntity detailsEntity = detailsResponse.getEntity();
            if (detailsEntity != null) {
                Document details = Jsoup.parse(EntityUtils.toString(detailsEntity));
                licenseList.add(parseLicense(city, details));
            }
        }
    }

    SearchResult<License> result = new SearchResult<License>();
    result.setItems(licenseList);
    return result;
}

From source file:org.opennms.netmgt.poller.monitors.HttpPostMonitor.java

/**
 * {@inheritDoc}/*from  w  ww  .j  a  v  a2 s  . co  m*/
 *
 * Poll the specified address for service availability.
 *
 * During the poll an attempt is made to execute the named method (with optional input) connect on the specified port. If
 * the exec on request is successful, the banner line generated by the
 * interface is parsed and if the banner text indicates that we are talking
 * to Provided that the interface's response is valid we set the service
 * status to SERVICE_AVAILABLE and return.
 */
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    NetworkInterface<InetAddress> iface = svc.getNetInterface();

    // Process parameters

    // Get interface address from NetworkInterface
    if (iface.getType() != NetworkInterface.TYPE_INET)
        throw new NetworkInterfaceNotSupportedException(
                "Unsupported interface type, only TYPE_INET currently supported");

    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);

    // Port
    int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);

    //URI
    String strURI = ParameterMap.getKeyedString(parameters, PARAMETER_URI, DEFAULT_URI);

    //Username
    String strUser = ParameterMap.getKeyedString(parameters, PARAMETER_USERNAME, null);

    //Password
    String strPasswd = ParameterMap.getKeyedString(parameters, PARAMETER_PASSWORD, null);

    //BannerMatch
    String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);

    //Scheme
    String strScheme = ParameterMap.getKeyedString(parameters, PARAMETER_SCHEME, DEFAULT_SCHEME);

    //Payload
    String strPayload = ParameterMap.getKeyedString(parameters, PARAMETER_PAYLOAD, null);

    //Mimetype
    String strMimetype = ParameterMap.getKeyedString(parameters, PARAMETER_MIMETYPE, DEFAULT_MIMETYPE);

    //Charset
    String strCharset = ParameterMap.getKeyedString(parameters, PARAMETER_CHARSET, DEFAULT_CHARSET);

    //SSLFilter
    boolean boolSSLFilter = ParameterMap.getKeyedBoolean(parameters, PARAMETER_SSLFILTER, DEFAULT_SSLFILTER);

    // Get the address instance.
    InetAddress ipv4Addr = (InetAddress) iface.getAddress();

    final String hostAddress = InetAddressUtils.str(ipv4Addr);

    LOG.debug("poll: address = " + hostAddress + ", port = " + port + ", " + tracker);

    // Give it a whirl
    PollStatus serviceStatus = PollStatus.unavailable();

    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        HttpClientWrapper clientWrapper = null;
        try {
            tracker.startAttempt();

            clientWrapper = HttpClientWrapper.create().setConnectionTimeout(tracker.getSoTimeout())
                    .setSocketTimeout(tracker.getSoTimeout()).setRetries(DEFAULT_RETRY);

            if (boolSSLFilter) {
                clientWrapper.trustSelfSigned(strScheme);
            }
            HttpEntity postReq;

            if (strUser != null && strPasswd != null) {
                clientWrapper.addBasicCredentials(strUser, strPasswd);
            }

            try {
                postReq = new StringEntity(strPayload, ContentType.create(strMimetype, strCharset));
            } catch (final UnsupportedCharsetException e) {
                serviceStatus = PollStatus
                        .unavailable("Unsupported encoding encountered while constructing POST body " + e);
                break;
            }

            URIBuilder ub = new URIBuilder();
            ub.setScheme(strScheme);
            ub.setHost(hostAddress);
            ub.setPort(port);
            ub.setPath(strURI);

            LOG.debug("HttpPostMonitor: Constructed URL is " + ub.toString());

            HttpPost post = new HttpPost(ub.build());
            post.setEntity(postReq);
            CloseableHttpResponse response = clientWrapper.execute(post);

            LOG.debug("HttpPostMonitor: Status Line is " + response.getStatusLine());

            if (response.getStatusLine().getStatusCode() > 399) {
                LOG.info("HttpPostMonitor: Got response status code "
                        + response.getStatusLine().getStatusCode());
                LOG.debug("HttpPostMonitor: Received server response: " + response.getStatusLine());
                LOG.debug("HttpPostMonitor: Failing on bad status code");
                serviceStatus = PollStatus
                        .unavailable("HTTP(S) Status code " + response.getStatusLine().getStatusCode());
                break;
            }

            LOG.debug("HttpPostMonitor: Response code is valid");
            double responseTime = tracker.elapsedTimeInMillis();

            HttpEntity entity = response.getEntity();
            InputStream responseStream = entity.getContent();
            String Strresponse = IOUtils.toString(responseStream);

            if (Strresponse == null)
                continue;

            LOG.debug("HttpPostMonitor: banner = " + Strresponse);
            LOG.debug("HttpPostMonitor: responseTime= " + responseTime + "ms");

            //Could it be a regex?
            if (strBannerMatch.charAt(0) == '~') {
                if (!Strresponse.matches(strBannerMatch.substring(1))) {
                    serviceStatus = PollStatus
                            .unavailable("Banner does not match Regex '" + strBannerMatch + "'");
                    break;
                } else {
                    serviceStatus = PollStatus.available(responseTime);
                }
            } else {
                if (Strresponse.indexOf(strBannerMatch) > -1) {
                    serviceStatus = PollStatus.available(responseTime);
                } else {
                    serviceStatus = PollStatus
                            .unavailable("Did not find expected Text '" + strBannerMatch + "'");
                    break;
                }
            }

        } catch (final URISyntaxException e) {
            final String reason = "URISyntaxException for URI: " + strURI + " " + e.getMessage();
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } catch (final Exception e) {
            final String reason = "Exception: " + e.getMessage();
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } finally {
            IOUtils.closeQuietly(clientWrapper);
        }
    }

    // return the status of the service
    return serviceStatus;
}