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

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

Introduction

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

Prototype

public URI build() throws URISyntaxException 

Source Link

Document

Builds a URI instance.

Usage

From source file:oracle.custom.ui.servlet.ConfigInputCheck.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w  . j  ava  2 s  . c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("processing ConfigInputCheck request");
    try {
        PrintWriter out = response.getWriter();

        String whichform = request.getParameter("whichform");

        String domain = request.getParameter("domain");
        String idcsUrl = request.getParameter("idcsUrl");
        String myUrl = request.getParameter("myUrl");

        String clientId = request.getParameter("clientId");
        String clientSecret = request.getParameter("clientSecret");

        String appId = request.getParameter("appId");
        String appSecret = request.getParameter("appSecret");
        switch (whichform) {
        case "checkOpenID":
            OpenIdConfiguration openidConf = OpenIdConfiguration.getButDontSave(idcsUrl);

            URIBuilder builder = new URIBuilder(openidConf.getAuthzEndpoint());
            builder.addParameter("client_id", clientId);
            builder.addParameter("response_type", "code");
            builder.addParameter("redirect_uri", myUrl + "atreturn/");
            builder.addParameter("scope", "urn:opc:idm:t.user.me openid urn:opc:idm:__myscopes__");
            builder.addParameter("nonce", UUID.randomUUID().toString());

            URI url = builder.build();

            System.out.println("URL: " + url.toString());

            // now go get it
            HttpClient client = ServerUtils.getClient();

            HttpGet get = new HttpGet(url);
            HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getScheme());
            HttpResponse httpResponse = client.execute(host, get);
            try {
                // IDCS behavior has changed.
                // older versions returned 303 with a Location: header
                // current version returns 200 with HTML

                if ((httpResponse.getStatusLine().getStatusCode() == 303)
                        || (httpResponse.getStatusLine().getStatusCode() == 200)) {
                    System.out.println("Request seems to have worked");
                    out.print("Success?");
                } else
                    throw new ServletException("Invalid status from OAuth AZ URL. Expected 303, got "
                            + httpResponse.getStatusLine().getStatusCode());

            } finally {
                if (response instanceof CloseableHttpResponse) {
                    ((CloseableHttpResponse) response).close();
                }
            }
            break;

        default:
            throw new Exception("Invalid request");
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new ServletException("Error.");
    }
}

From source file:org.zaizi.manifoldcf.authorities.authorities.alfresco.AlfrescoAuthorityConnector.java

/**
 * Check connection for sanity.//w  ww  . j a  v a  2  s.c o m
 */
@Override
public String check() throws ManifoldCFException {
    URIBuilder uri = new URIBuilder();
    uri.setScheme(protocol);
    uri.setHost(server);
    uri.setPort(Integer.parseInt(port));
    uri.setPath(path + USER_AUTHORITIES_URI);

    try {
        HttpResponse response = httpClient.execute(new HttpGet(uri.build()));
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != 200) {
            return "Connection not working! Check Configuration";
        }
    } catch (Exception e) {
        return "Connection not working! Check Configuration";
    }

    return super.check();
}

From source file:com.grameenfoundation.ictchallenge.controllers.ConnectedAppREST.java

private JSONObject getFarmerById(String instanceUrl, String accessToken, String id)
        throws ServletException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet();

    //add key and value
    httpGet.addHeader("Authorization", "OAuth " + accessToken);

    try {//  w w w. ja va  2 s  .  c  o m

        URIBuilder builder = new URIBuilder(instanceUrl + "/services/data/v30.0/query");
        //builder.setParameter("q", "SELECT Name, Id from Account LIMIT 100");
        builder.setParameter("q",
                "SELECT Name__c,Date_Of_Birth__c,Land_size__c,Farmer_I_D__c,Picture__c from Farmer__c "
                        + " WHERE Farmer_I_D__c=" + "'" + id + "'");

        httpGet.setURI(builder.build());

        CloseableHttpResponse closeableresponse = httpclient.execute(httpGet);
        System.out.println("Response Status line :" + closeableresponse.getStatusLine());

        if (closeableresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Now lets use the standard java json classes to work with the
            // results
            try {

                // Do the needful with entity.  
                HttpEntity entity = closeableresponse.getEntity();
                InputStream rstream = entity.getContent();
                JSONObject authResponse = new JSONObject(new JSONTokener(rstream));

                log.log(Level.INFO, "Query response: {0}", authResponse.toString(2));

                log.log(Level.INFO, "{0} record(s) returned\n\n", authResponse.getInt("totalSize"));

                return authResponse;

            } catch (JSONException e) {
                e.printStackTrace();

            }
        }
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException ex) {
        Logger.getLogger(ConnectedAppREST.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        httpclient.close();
    }

    return null;
}

From source file:com.mollie.api.resource.BaseResource.java

/**
 * Creates a valid query string from the supplied options that can be used
 * as url parameters. The method returns null if there was an error building
 * the query string./*from  w  w  w.  ja v a  2 s  . c  o m*/
 * 
 * @param options options to build a query string from
 * @return a valid query string or null.
 */
private String buildQueryFromMap(Map<String, String> options) {
    URIBuilder ub = null;
    String queryString = null;

    try {
        ub = new URIBuilder();

        for (Map.Entry<String, String> entry : options.entrySet()) {
            ub.addParameter(entry.getKey(), entry.getValue());
        }

        queryString = ub.build().getQuery();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    return queryString;
}

From source file:com.jaspersoft.studio.server.protocol.restv2.RestV2Connection.java

@Override
public List<ResourceDescriptor> list(IProgressMonitor monitor, ResourceDescriptor rd) throws Exception {
    List<ResourceDescriptor> rds = new ArrayList<ResourceDescriptor>();
    if (rd.getWsType().equals(ResourceDescriptor.TYPE_REPORTUNIT)) {
        rd = get(monitor, rd, null);//  www .  j a  v a 2s  . c  o m
        return rd.getChildren();
    } else {
        URIBuilder ub = new URIBuilder(url("resources"));
        ub.addParameter("folderUri", rd.getUriString());
        ub.addParameter("recursive", "false");
        ub.addParameter("sortBy", "label");
        ub.addParameter("limit", Integer.toString(Integer.MAX_VALUE));

        ClientResourceListWrapper resources = toObj(HttpUtils.get(ub.build().toASCIIString(), sp),
                ClientResourceListWrapper.class, monitor);
        if (resources != null)
            for (ClientResourceLookup crl : resources.getResourceLookups())
                rds.add(Rest2Soap.getRDLookup(this, crl));
    }
    return rds;
}

From source file:org.aicer.hibiscus.http.client.HttpClient.java

private String getNameValuePairsAsString() {

    String query = "";

    if (nameValuePairs.size() == 0) {
        return query;
    }//w w w .j a  v  a 2  s .  c o  m

    URIBuilder builder = new URIBuilder().setScheme(SCHEME_HTTP).setHost(DEFAULT_HOST).setPath(DEFAULT_PATH);

    for (final BasicNameValuePair nvp : nameValuePairs) {
        builder.setParameter(nvp.getName(), nvp.getValue());
    }

    try {
        query = builder.build().getRawQuery();
    } catch (URISyntaxException e) {
        log.debug("Error while attempting to build NVP entity", e);
    }

    return query;
}

From source file:com.collective.celos.CelosClient.java

public void iterateScheduler(ScheduledTime scheduledTime, Set<WorkflowID> workflowIDs) throws Exception {
    URIBuilder uriBuilder = new URIBuilder(address);
    uriBuilder.setPath(uriBuilder.getPath() + SCHEDULER_PATH);
    if (!workflowIDs.isEmpty()) {
        uriBuilder.addParameter(IDS_PARAM, StringUtils.join(workflowIDs, ","));
    }//from w  w  w.  j  a v a  2 s  .c o  m
    uriBuilder.addParameter(TIME_PARAM, timeFormatter.formatPretty(scheduledTime));
    executePost(uriBuilder.build());
}

From source file:org.pentaho.reporting.libraries.pensol.vfs.LocalFileModel.java

public void refresh() throws IOException {
    getDescriptionEntries().clear();/*from w w  w .  j  a va2 s . c om*/

    final Configuration configuration = LibPensolBoot.getInstance().getGlobalConfig();
    final String service = configuration
            .getConfigProperty("org.pentaho.reporting.libraries.pensol.web.LoadRepositoryDoc");

    URI uri;
    String baseUrl = url + service;
    try {
        URIBuilder builder = new URIBuilder(baseUrl);
        logger.debug("Connecting to '" + baseUrl + '\'');
        if (username != null) {
            builder.setParameter("userid", username);
        }
        if (password != null) {
            builder.setParameter("password", password);
        }
        uri = builder.build();
    } catch (URISyntaxException e) {
        throw new IOException("Provided URL is invalid: " + baseUrl);
    }
    final HttpPost filePost = new HttpPost(uri);
    filePost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

    HttpResponse httpResponse = client.execute(filePost, context);
    final int lastStatus = httpResponse.getStatusLine().getStatusCode();
    if (lastStatus == HttpStatus.SC_UNAUTHORIZED) {
        throw new IOException("401: User authentication failed.");
    } else if (lastStatus == HttpStatus.SC_NOT_FOUND) {
        throw new IOException("404: Repository service not found on server.");
    } else if (lastStatus != HttpStatus.SC_OK) {
        throw new IOException("Server error: HTTP lastStatus code " + lastStatus);
    }

    final InputStream postResult = httpResponse.getEntity().getContent();
    try {
        setRoot(performParse(postResult));
    } finally {
        postResult.close();
    }
}

From source file:org.dspace.submit.lookup.PubmedService.java

public List<Record> getByPubmedIDs(List<String> pubmedIDs)
        throws HttpException, IOException, ParserConfigurationException, SAXException {
    List<Record> results = new ArrayList<Record>();
    HttpGet method = null;/*  w  ww  .  j  a v  a  2s.co m*/
    try {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5 * timeout);

        try {
            URIBuilder uriBuilder = new URIBuilder("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi");
            uriBuilder.addParameter("db", "pubmed");
            uriBuilder.addParameter("retmode", "xml");
            uriBuilder.addParameter("rettype", "full");
            uriBuilder.addParameter("id", StringUtils.join(pubmedIDs.iterator(), ","));
            method = new HttpGet(uriBuilder.build());
        } catch (URISyntaxException ex) {
            throw new RuntimeException("Request not sent", ex);
        }

        // Execute the method.
        HttpResponse response = client.execute(method);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            throw new RuntimeException("WS call failed: " + statusLine);
        }

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document inDoc = builder.parse(response.getEntity().getContent());

        Element xmlRoot = inDoc.getDocumentElement();
        List<Element> pubArticles = XMLUtils.getElementList(xmlRoot, "PubmedArticle");

        for (Element xmlArticle : pubArticles) {
            Record pubmedItem = null;
            try {
                pubmedItem = PubmedUtils.convertPubmedDomToRecord(xmlArticle);
                results.add(pubmedItem);
            } catch (Exception e) {
                throw new RuntimeException("PubmedID is not valid or not exist: " + e.getMessage(), e);
            }
        }

        return results;
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}