List of usage examples for org.apache.http.client.utils URIBuilder setScheme
public URIBuilder setScheme(final String scheme)
From source file:com.xively.client.http.DefaultRequestHandler.java
private URIBuilder buildUri(HttpMethod requestMethod, String appPath, Map<String, Object> params, AcceptedMediaType mediaType) {//from ww w.j a v a 2s . com URIBuilder uriBuilder = new URIBuilder(); String path = appPath; if (HttpMethod.GET == requestMethod) { path = appPath.concat(".").concat(mediaType.name()); } uriBuilder.setScheme("http").setHost(baseURI).setPath(path); if (params != null && !params.isEmpty()) { for (Entry<String, Object> param : params.entrySet()) { uriBuilder.addParameter(param.getKey(), StringUtil.toString(param.getValue())); } } return uriBuilder; }
From source file:com.simple.toadiot.rtinfosdk.http.DefaultRequestHandler.java
private URIBuilder buildUri(HttpMethod method, String path, Map<String, Object> params, AcceptedMediaType mediaType) {//w ww .j a va 2 s .c o m URIBuilder uriBuilder = new URIBuilder(); // if (HttpMethod.GET == method) { // path = path.concat(".").concat(mediaType.name()); // } uriBuilder.setScheme("http").setHost(AppConfig.getBaseURI()).setPath("/" + AppConfig.getVersion() + path); if (params != null && !params.isEmpty()) { for (Entry<String, Object> param : params.entrySet()) { uriBuilder.addParameter(param.getKey(), StringUtil.toString(param.getValue())); } } return uriBuilder; }
From source file:org.zaizi.manifoldcf.authorities.authorities.alfresco.AlfrescoAuthorityConnector.java
/** * Check connection for sanity.//w w w . j a v a 2 s. c om */ @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:org.opennms.netmgt.poller.monitors.HttpPostMonitor.java
/** * {@inheritDoc}/*w ww. j a v a2 s.c om*/ * * 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; }
From source file:it.txt.ens.core.impl.BasicENSResource.java
/** * /*from w w w . j av a 2 s.c o m*/ * @param host * @param path * @param namespace * @param pattern * @throws IllegalArgumentException if at least one parameter is <code>null</code> or an empty string. * @throws URIBuildingException if an error occurs while building the URI */ /*private*/ BasicENSResource(String host, String path, String namespace, String pattern) throws IllegalArgumentException, URIBuildingException { if (host == null) throw new IllegalArgumentException("The host cannot be null"); if (host.length() == 0) throw new IllegalArgumentException("The host cannot be an empty string"); if (path == null) throw new IllegalArgumentException("The path cannot be null"); if (path.length() == 0) throw new IllegalArgumentException("The path cannot be an empty string"); if (namespace == null) throw new IllegalArgumentException("The namespace cannot be null"); if (namespace.length() == 0) throw new IllegalArgumentException("The namespace cannot be an empty string"); if (pattern == null) throw new IllegalArgumentException("The pattern cannot be null"); if (pattern.length() == 0) throw new IllegalArgumentException("The pattern cannot be an empty string"); this.host = host; this.namespace = namespace; if (path.startsWith(SLASH)) this.path = path; else this.path = SLASH + path; this.pattern = pattern; URIBuilder uriBuilder = new URIBuilder(); uriBuilder.addParameter(NAMESPACE_PARAMETER_NAME, this.namespace); uriBuilder.addParameter(PATTERN_PARAMETER_NAME, this.pattern); uriBuilder.setHost(this.host); uriBuilder.setPath(this.path); uriBuilder.setScheme(URI_SCHEME); try { this.uri = uriBuilder.build(); } catch (URISyntaxException e) { throw new URIBuildingException("getURI.URISyntaxException.log", e); } }
From source file:com.softinstigate.restheart.integrationtest.GetDocumentIT.java
private void testGetDocument(URI uri) throws Exception { Response resp = adminExecutor.execute(Request.Get(uri)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp);//from w ww . j ava 2 s .com HttpEntity entity = httpResp.getEntity(); assertNotNull(entity); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode()); assertNotNull("content type not null", entity.getContentType()); assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue()); String content = EntityUtils.toString(entity); assertNotNull("", content); JsonObject json = null; try { json = JsonObject.readFrom(content); } catch (Throwable t) { fail("parsing received json"); } assertNotNull("check json not null", json); assertNotNull("check not null @etag property", json.get("_etag")); assertNotNull("check not null @lastupdated_on property", json.get("_lastupdated_on")); assertNotNull("check not null @created_on property", json.get("_created_on")); assertNotNull("check not null @_id property", json.get("_id")); assertEquals("check @_id value", document1Id, json.get("_id").asString()); assertNotNull("check not null a", json.get("a")); assertEquals("check a value", 1, json.get("a").asInt()); assertNotNull("check not null mtm links", json.get("_links").asObject().get("mtm")); assertNotNull("check not null mto links", json.get("_links").asObject().get("mto")); assertNotNull("check not null otm links", json.get("_links").asObject().get("otm")); assertNotNull("check not null oto links", json.get("_links").asObject().get("oto")); assertTrue("check mtm link", json.get("_links").asObject().get("mtm").asObject().get("href").asString() .endsWith("?filter={'mtm':{'$in':['doc2']}}")); assertTrue("check mto link", json.get("_links").asObject().get("mto").asObject().get("href").asString().endsWith("/doc2")); assertTrue("check otm link", json.get("_links").asObject().get("otm").asObject().get("href").asString() .endsWith("?filter={'otm':{'$in':['doc2']}}")); assertTrue("check oto link", json.get("_links").asObject().get("oto").asObject().get("href").asString().endsWith("/doc2")); String mtm = json.get("_links").asObject().get("mtm").asObject().get("href").asString(); String mto = json.get("_links").asObject().get("mto").asObject().get("href").asString(); String otm = json.get("_links").asObject().get("otm").asObject().get("href").asString(); String oto = json.get("_links").asObject().get("oto").asObject().get("href").asString(); URIBuilder ub = new URIBuilder(); String[] mtms = mtm.split("\\?"); String[] mtos = mtm.split("\\?"); String[] otms = mtm.split("\\?"); String[] otos = mtm.split("\\?"); URI _mtm = ub.setScheme(uri.getScheme()).setHost(uri.getHost()).setPort(uri.getPort()).setPath(mtms[0]) .setCustomQuery(mtms[1]).build(); URI _mto = ub.setScheme(uri.getScheme()).setHost(uri.getHost()).setPort(uri.getPort()).setPath(mtos[0]) .setCustomQuery(mtos[1]).build(); URI _otm = ub.setScheme(uri.getScheme()).setHost(uri.getHost()).setPort(uri.getPort()).setPath(otms[0]) .setCustomQuery(otms[1]).build(); URI _oto = ub.setScheme(uri.getScheme()).setHost(uri.getHost()).setPort(uri.getPort()).setPath(otos[0]) .setCustomQuery(otos[1]).build(); Response respMtm = adminExecutor.execute(Request.Get(_mtm)); HttpResponse httpRespMtm = respMtm.returnResponse(); assertNotNull("check not null get mtm response", httpRespMtm); assertEquals("check get mtm response status code", HttpStatus.SC_OK, httpRespMtm.getStatusLine().getStatusCode()); Response respMto = adminExecutor.execute(Request.Get(_mto)); HttpResponse httpRespMto = respMto.returnResponse(); assertNotNull("check not null get mto response", httpRespMto); assertEquals("check get mto response status code", HttpStatus.SC_OK, httpRespMto.getStatusLine().getStatusCode()); Response respOtm = adminExecutor.execute(Request.Get(_otm)); HttpResponse httpRespOtm = respOtm.returnResponse(); assertNotNull("check not null get otm response", httpRespOtm); assertEquals("check get otm response status code", HttpStatus.SC_OK, httpRespOtm.getStatusLine().getStatusCode()); Response respOto = adminExecutor.execute(Request.Get(_oto)); HttpResponse httpRespOto = respOto.returnResponse(); assertNotNull("check not null get oto response", httpRespOto); assertEquals("check get oto response status code", HttpStatus.SC_OK, httpRespOto.getStatusLine().getStatusCode()); }
From source file:com.liferay.ide.core.remote.RemoteConnection.java
protected Object httpJSONAPI(Object... args) throws APIException { if (!(args[0] instanceof HttpRequestBase)) { throw new IllegalArgumentException("First argument must be a HttpRequestBase."); //$NON-NLS-1$ }//from w w w .j av a 2s . com Object retval = null; String api = null; Object[] params = new Object[0]; final HttpRequestBase request = (HttpRequestBase) args[0]; final boolean isPostRequest = request instanceof HttpPost; if (args[1] instanceof String) { api = args[1].toString(); } else if (args[1] instanceof Object[]) { params = (Object[]) args[1]; api = params[0].toString(); } else { throw new IllegalArgumentException("2nd argument must be either String or Object[]"); //$NON-NLS-1$ } try { final URIBuilder builder = new URIBuilder(); builder.setScheme("http"); //$NON-NLS-1$ builder.setHost(getHost()); builder.setPort(getHttpPort()); builder.setPath(api); List<NameValuePair> postParams = new ArrayList<NameValuePair>(); if (params.length >= 3) { for (int i = 1; i < params.length; i += 2) { String name = null; String value = StringPool.EMPTY; if (params[i] != null) { name = params[i].toString(); } if (params[i + 1] != null) { value = params[i + 1].toString(); } if (isPostRequest) { postParams.add(new BasicNameValuePair(name, value)); } else { builder.setParameter(name, value); } } } if (isPostRequest) { HttpPost postRequest = ((HttpPost) request); if (postRequest.getEntity() == null) { postRequest.setEntity(new UrlEncodedFormEntity(postParams)); } } request.setURI(builder.build()); String response = getHttpResponse(request); if (response != null && response.length() > 0) { Object jsonResponse = getJSONResponse(response); if (jsonResponse == null) { throw new APIException(api, "Unable to get response: " + response); //$NON-NLS-1$ } else { retval = jsonResponse; } } } catch (APIException e) { throw e; } catch (Exception e) { throw new APIException(api, e); } finally { try { request.releaseConnection(); } finally { // no need to log error } } return retval; }
From source file:org.restheart.test.integration.GetDocumentIT.java
private void testGetDocument(URI uri) throws Exception { Response resp = adminExecutor.execute(Request.Get(uri)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp);/*from www . j av a 2 s.c om*/ HttpEntity entity = httpResp.getEntity(); assertNotNull(entity); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode()); assertNotNull("content type not null", entity.getContentType()); assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue()); String content = EntityUtils.toString(entity); assertNotNull("", content); JsonObject json = null; try { json = JsonObject.readFrom(content); } catch (Throwable t) { fail("parsing received json"); } assertNotNull("check json not null", json); assertNotNull("check not null _etag property", json.get("_etag")); assertNotNull("check not null _lastupdated_on property", json.get("_lastupdated_on")); if (ObjectId.isValid(json.get("_id").asString())) assertNotNull("check not null _created_on property", json.get("_created_on")); else assertNull("check null _created_on property", json.get("_created_on")); assertNotNull("check not null _id property", json.get("_id")); assertEquals("check _id value", document1Id, json.get("_id").asString()); assertNotNull("check not null a", json.get("a")); assertEquals("check a value", 1, json.get("a").asInt()); assertNotNull("check not null mtm links", json.get("_links").asObject().get("mtm")); assertNotNull("check not null mto links", json.get("_links").asObject().get("mto")); assertNotNull("check not null otm links", json.get("_links").asObject().get("otm")); assertNotNull("check not null oto links", json.get("_links").asObject().get("oto")); assertTrue("check mtm link", json.get("_links").asObject().get("mtm").asObject().get("href").asString() .endsWith("?filter={'_id':{'$in':['doc2']}}")); assertTrue("check mto link", json.get("_links").asObject().get("mto").asObject().get("href").asString().endsWith("/doc2")); assertTrue("check otm link", json.get("_links").asObject().get("otm").asObject().get("href").asString() .endsWith("?filter={'_id':{'$in':['doc2']}}")); assertTrue("check oto link", json.get("_links").asObject().get("oto").asObject().get("href").asString().endsWith("/doc2")); String mtm = json.get("_links").asObject().get("mtm").asObject().get("href").asString(); String mto = json.get("_links").asObject().get("mto").asObject().get("href").asString(); String otm = json.get("_links").asObject().get("otm").asObject().get("href").asString(); String oto = json.get("_links").asObject().get("oto").asObject().get("href").asString(); URIBuilder ub = new URIBuilder(); String[] mtms = mtm.split("\\?"); String[] mtos = mtm.split("\\?"); String[] otms = mtm.split("\\?"); String[] otos = mtm.split("\\?"); URI _mtm = ub.setScheme(uri.getScheme()).setHost(uri.getHost()).setPort(uri.getPort()).setPath(mtms[0]) .setCustomQuery(mtms[1]).build(); URI _mto = ub.setScheme(uri.getScheme()).setHost(uri.getHost()).setPort(uri.getPort()).setPath(mtos[0]) .setCustomQuery(mtos[1]).build(); URI _otm = ub.setScheme(uri.getScheme()).setHost(uri.getHost()).setPort(uri.getPort()).setPath(otms[0]) .setCustomQuery(otms[1]).build(); URI _oto = ub.setScheme(uri.getScheme()).setHost(uri.getHost()).setPort(uri.getPort()).setPath(otos[0]) .setCustomQuery(otos[1]).build(); Response respMtm = adminExecutor.execute(Request.Get(_mtm)); HttpResponse httpRespMtm = respMtm.returnResponse(); assertNotNull("check not null get mtm response", httpRespMtm); assertEquals("check get mtm response status code", HttpStatus.SC_OK, httpRespMtm.getStatusLine().getStatusCode()); Response respMto = adminExecutor.execute(Request.Get(_mto)); HttpResponse httpRespMto = respMto.returnResponse(); assertNotNull("check not null get mto response", httpRespMto); assertEquals("check get mto response status code", HttpStatus.SC_OK, httpRespMto.getStatusLine().getStatusCode()); Response respOtm = adminExecutor.execute(Request.Get(_otm)); HttpResponse httpRespOtm = respOtm.returnResponse(); assertNotNull("check not null get otm response", httpRespOtm); assertEquals("check get otm response status code", HttpStatus.SC_OK, httpRespOtm.getStatusLine().getStatusCode()); Response respOto = adminExecutor.execute(Request.Get(_oto)); HttpResponse httpRespOto = respOto.returnResponse(); assertNotNull("check not null get oto response", httpRespOto); assertEquals("check get oto response status code", HttpStatus.SC_OK, httpRespOto.getStatusLine().getStatusCode()); }
From source file:org.zaizi.manifoldcf.authorities.authorities.alfresco.AlfrescoAuthorityConnector.java
/** * Obtain the access tokens for a given user name. * /*from ww w.j a v a 2s .c o m*/ * @param userName is the user name or identifier. * @return the response tokens (according to the current authority). (Should throws an exception only when a * condition cannot be properly described within the authorization response object.) */ @Override public AuthorizationResponse getAuthorizationResponse(String userName) throws ManifoldCFException { // String[] tokens = new String[] { userName }; // return new AuthorizationResponse(tokens, AuthorizationResponse.RESPONSE_OK); List<String> tokens = new ArrayList<String>(); try { URIBuilder uri = new URIBuilder(); uri.setScheme(protocol); uri.setHost(server); uri.setPort(Integer.parseInt(port)); uri.setPath(path + USER_AUTHORITIES_URI); uri.setParameter(USERNAME_PARAM, userName); HttpGet get = new HttpGet(uri.build()); HttpResponse response = httpClient.execute(get); JSONObject json = new JSONObject(EntityUtils.toString(response.getEntity(), UTF8)); JSONArray auths = (JSONArray) json.get(AUTHORITIES_JSON); if (auths != null) { int len = auths.length(); for (int i = 0; i < len; i++) { tokens.add(auths.get(i).toString()); } } EntityUtils.consume(response.getEntity()); } catch (Exception e) { return new AuthorizationResponse(null, AuthorizationResponse.RESPONSE_UNREACHABLE); } return new AuthorizationResponse(tokens.toArray(new String[] {}), AuthorizationResponse.RESPONSE_OK); }