List of usage examples for org.apache.http.client.utils URIBuilder URIBuilder
public URIBuilder(final URI uri)
From source file:org.dspace.submit.lookup.PubmedService.java
public List<Record> search(String query) throws IOException, HttpException { List<Record> results = new ArrayList<>(); if (!ConfigurationManager.getBooleanProperty(SubmissionLookupService.CFG_MODULE, "remoteservice.demo")) { HttpGet method = null;//w ww.java 2 s . c o m try { HttpClient client = new DefaultHttpClient(); client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); URIBuilder uriBuilder = new URIBuilder("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"); uriBuilder.addParameter("db", "pubmed"); uriBuilder.addParameter("datetype", "edat"); uriBuilder.addParameter("retmax", "10"); uriBuilder.addParameter("term", query); method = new HttpGet(uriBuilder.build()); // 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; try { builder = factory.newDocumentBuilder(); Document inDoc = builder.parse(response.getEntity().getContent()); Element xmlRoot = inDoc.getDocumentElement(); Element idList = XMLUtils.getSingleElement(xmlRoot, "IdList"); List<String> pubmedIDs = XMLUtils.getElementValueList(idList, "Id"); results = getByPubmedIDs(pubmedIDs); } catch (ParserConfigurationException e1) { log.error(e1.getMessage(), e1); } catch (SAXException e1) { log.error(e1.getMessage(), e1); } } catch (Exception e1) { log.error(e1.getMessage(), e1); } finally { if (method != null) { method.releaseConnection(); } } } else { InputStream stream = null; try { File file = new File(ConfigurationManager.getProperty("dspace.dir") + "/config/crosswalks/demo/pubmed-search.xml"); stream = new FileInputStream(file); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document inDoc = builder.parse(stream); Element xmlRoot = inDoc.getDocumentElement(); Element idList = XMLUtils.getSingleElement(xmlRoot, "IdList"); List<String> pubmedIDs = XMLUtils.getElementValueList(idList, "Id"); results = getByPubmedIDs(pubmedIDs); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } } return results; }
From source file:ezbake.azkaban.manager.ScheduleManager.java
/** * Class for scheduling a flow in Azkaban * * @param azkabanUri The Azkaban URL/*w ww .ja v a 2 s. c o m*/ * @param username The username to use * @param password The password for the username */ public ScheduleManager(URI azkabanUri, String username, String password) { try { this.schedulerUri = new URIBuilder(azkabanUri).setPath("/schedule").build(); } catch (URISyntaxException e) { e.printStackTrace(); } final AuthenticationManager azkabanAuthenticator = new AuthenticationManager(schedulerUri, username, password); final AuthenticationResult result = azkabanAuthenticator.login(); if (result.hasError()) { throw new IllegalStateException(result.getError()); } this.sessionId = result.getSessionId(); }
From source file:com.esri.geoportal.commons.ckan.client.Client.java
private URI createListPackagesUri(long rows, long start) throws IOException, URISyntaxException { return new URIBuilder(url.toURI().resolve(PACKAGE_LIST_URL)).addParameter("rows", Long.toString(rows)) .addParameter("start", Long.toString(start)).build(); }
From source file:io.gravitee.gateway.standalone.QueryParametersTest.java
@Test public void call_get_query_accent() throws Exception { String query = "poupe"; URI target = new URIBuilder("http://localhost:8082/test/my_team").addParameter("q", query).build(); Response response = Request.Get(target).execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); String responseContent = StringUtils.copy(returnResponse.getEntity().getContent()); assertEquals(query, responseContent); }
From source file:com.kurtraschke.wmata.gtfsrealtime.services.WMATAAPIService.java
public Routes downloadRouteList() throws WMATAAPIException { try {/*from www . j a v a 2 s . c om*/ URIBuilder b = new URIBuilder("http://api.wmata.com/Bus.svc/json/JRoutes"); b.addParameter(API_KEY_PARAM_NAME, _apiKey); return mapUrl(b.build(), true, Routes.class, _jsonMapper); } catch (Exception e) { throw new WMATAAPIException(e); } }
From source file:org.mitre.openid.connect.client.service.impl.SignedAuthRequestUrlBuilder.java
@Override public String buildAuthRequestUrl(ServerConfiguration serverConfig, RegisteredClient clientConfig, String redirectUri, String nonce, String state, Map<String, String> options, String loginHint) { // create our signed JWT for the request object JWTClaimsSet.Builder claims = new JWTClaimsSet.Builder(); //set parameters to JwtClaims claims.claim("response_type", "code"); claims.claim("client_id", clientConfig.getClientId()); claims.claim("scope", Joiner.on(" ").join(clientConfig.getScope())); // build our redirect URI claims.claim("redirect_uri", redirectUri); // this comes back in the id token claims.claim("nonce", nonce); // this comes back in the auth request return claims.claim("state", state); // Optional parameters for (Entry<String, String> option : options.entrySet()) { claims.claim(option.getKey(), option.getValue()); }/*from www. java2s . co m*/ // if there's a login hint, send it if (!Strings.isNullOrEmpty(loginHint)) { claims.claim("login_hint", loginHint); } JWSAlgorithm alg = clientConfig.getRequestObjectSigningAlg(); if (alg == null) { alg = signingAndValidationService.getDefaultSigningAlgorithm(); } SignedJWT jwt = new SignedJWT(new JWSHeader(alg), claims.build()); signingAndValidationService.signJwt(jwt, alg); try { URIBuilder uriBuilder = new URIBuilder(serverConfig.getAuthorizationEndpointUri()); uriBuilder.addParameter("request", jwt.serialize()); // build out the URI return uriBuilder.build().toString(); } catch (URISyntaxException e) { throw new AuthenticationServiceException("Malformed Authorization Endpoint Uri", e); } }
From source file:org.wso2.carbon.apimgt.authenticator.oidc.ui.common.Util.java
/** * Building authentication request/*from ww w . j av a 2s .c o m*/ * @param nonce cryptographically random nonce * @param state cryptographically random state * @return url */ public static String buildAuthRequestUrl(String nonce, String state) { try { log.debug("Building Authentication request..."); URIBuilder uriBuilder = new URIBuilder(authorizationEndpointURI); uriBuilder.addParameter(OIDCConstants.PARAM_RESPONSE_TYPE, responseType); uriBuilder.addParameter(OIDCConstants.PARAM_CLIENT_ID, clientId); uriBuilder.addParameter(OIDCConstants.PARAM_SCOPE, scope); uriBuilder.addParameter(OIDCConstants.PARAM_REDIRECT_URI, redirectURI); uriBuilder.addParameter(OIDCConstants.PARAM_NONCE, nonce); uriBuilder.addParameter(OIDCConstants.PARAM_STATE, state); return uriBuilder.build().toString(); } catch (URISyntaxException e) { log.error("Build Auth Request Failed", e); } return null; }
From source file:com.epam.ngb.cli.manager.command.handler.http.DatasetDeletionHandler.java
@Override protected void runDeletion(Long id) { String url = String.format(getRequestUrl(), id); try {//from w ww . j av a 2 s. c o m URIBuilder requestBuilder = new URIBuilder(String.format(url, projectId)); requestBuilder.setParameter("force", String.valueOf(force)); HttpRequestBase request = getRequest(requestBuilder.build().toString()); setDefaultHeader(request); if (isSecure()) { addAuthorizationToRequest(request); } String result = RequestManager.executeRequest(request); ResponseResult response = getMapper().readValue(result, getMapper().getTypeFactory().constructType(ResponseResult.class)); LOGGER.info(response.getStatus() + "\t" + response.getMessage()); } catch (IOException | URISyntaxException e) { throw new ApplicationException(e.getMessage(), e); } }
From source file:com.lonepulse.zombielink.request.QueryParamProcessor.java
/** * <p>Accepts the {@link InvocationContext} along with an {@link HttpRequestBase} and creates a * <a href="http://en.wikipedia.org/wiki/Query_string">query string</a> using arguments annotated * with @{@link QueryParam} and @{@link QueryParams}; which is subsequently appended to the URI.</p> * /*from w ww . j a va2s .c om*/ * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p> * * @param context * the {@link InvocationContext} which is used to discover annotated query parameters * <br><br> * @param request * prefers an instance of {@link HttpGet} so as to conform with HTTP 1.1; however, other * request types will be entertained to allow compliance with unusual endpoint definitions * <br><br> * @return the same instance of {@link HttpRequestBase} which was given for processing query parameters * <br><br> * @throws RequestProcessorException * if the creation of a query string failed due to an unrecoverable errorS * <br><br> * @since 1.3.0 */ @Override protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) { try { URIBuilder uriBuilder = new URIBuilder(request.getURI()); //add static name and value pairs List<Param> constantQueryParams = RequestUtils.findStaticQueryParams(context); for (Param param : constantQueryParams) { uriBuilder.setParameter(param.name(), param.value()); } //add individual name and value pairs List<Entry<QueryParam, Object>> queryParams = Metadata.onParams(QueryParam.class, context); for (Entry<QueryParam, Object> entry : queryParams) { String name = entry.getKey().value(); Object value = entry.getValue(); if (!(value instanceof CharSequence)) { StringBuilder errorContext = new StringBuilder().append("Query parameters can only be of type ") .append(CharSequence.class.getName()) .append(". Please consider implementing CharSequence ") .append("and providing a meaningful toString() representation for the ") .append("<name> of the query parameter. "); throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString())); } uriBuilder.setParameter(name, ((CharSequence) value).toString()); } //add batch name and value pairs (along with any static params) List<Entry<QueryParams, Object>> queryParamMaps = Metadata.onParams(QueryParams.class, context); for (Entry<QueryParams, Object> entry : queryParamMaps) { Param[] constantParams = entry.getKey().value(); if (constantParams != null && constantParams.length > 0) { for (Param param : constantParams) { uriBuilder.setParameter(param.name(), param.value()); } } Object map = entry.getValue(); if (!(map instanceof Map)) { StringBuilder errorContext = new StringBuilder() .append("@QueryParams can only be applied on <java.util.Map>s. ") .append("Please refactor the method to provide a Map of name and value pairs. "); throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString())); } Map<?, ?> nameAndValues = (Map<?, ?>) map; for (Entry<?, ?> nameAndValue : nameAndValues.entrySet()) { Object name = nameAndValue.getKey(); Object value = nameAndValue.getValue(); if (!(name instanceof CharSequence && (value instanceof CharSequence || value instanceof Collection))) { StringBuilder errorContext = new StringBuilder().append( "The <java.util.Map> identified by @QueryParams can only contain mappings of type ") .append("<java.lang.CharSequence, java.lang.CharSequence> or ") .append("<java.lang.CharSequence, java.util.Collection<? extends CharSequence>>"); throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString())); } if (value instanceof CharSequence) { uriBuilder.addParameter(((CharSequence) name).toString(), ((CharSequence) value).toString()); } else { //add multi-valued query params Collection<?> multivalues = (Collection<?>) value; for (Object multivalue : multivalues) { if (!(multivalue instanceof CharSequence)) { StringBuilder errorContext = new StringBuilder().append( "Values for the <java.util.Map> identified by @QueryParams can only contain collections ") .append("of type java.util.Collection<? extends CharSequence>"); throw new RequestProcessorException( new IllegalArgumentException(errorContext.toString())); } uriBuilder.addParameter(((CharSequence) name).toString(), ((CharSequence) multivalue).toString()); } } } } request.setURI(uriBuilder.build()); return request; } catch (Exception e) { throw (e instanceof RequestProcessorException) ? (RequestProcessorException) e : new RequestProcessorException(context, getClass(), e); } }