List of usage examples for org.apache.http.client.utils URIUtils createURI
@Deprecated public static URI createURI(final String scheme, final String host, final int port, final String path, final String query, final String fragment) throws URISyntaxException
From source file:com.healthcit.cacure.dao.CouchDBDao.java
public void deleteDoc(String docId, String docRev) throws IOException, URISyntaxException { // send//from w w w.jav a 2s.c o m URI uri = URIUtils.createURI("http", host, port, "/" + getDbName() + "/" + docId, "rev=" + docRev, null); HttpDelete httpDel = new HttpDelete(uri); String response = doHttp(httpDel); }
From source file:com.healthcit.cacure.dao.CouchDBDao.java
public JSONArray getAnswersByOwnerAndQuestion(JSONArray key) throws IOException, URISyntaxException { String keyString = key.toString(); String encodedURL = URLEncoder.encode(keyString, "UTF-8"); String viewURL = constructViewURL("GetAnswersByOwnerAndQuestion"); URI uri = URIUtils.createURI("http", host, port, viewURL, "key=" + encodedURL, null); HttpGet httpGet = new HttpGet(uri); String response = doHttp(httpGet); JSONObject json = JSONObject.fromObject(response); JSONArray answers = null;//from ww w. j a va2 s. co m if (json.containsKey("rows")) { JSONArray objects = json.getJSONArray("rows"); if (objects != null && objects.size() > 0) { JSONObject row = objects.getJSONObject(0); answers = row.getJSONArray("value"); } } return answers; }
From source file:com.healthcit.cacure.dao.CouchDBDao.java
public JSONObject readObject(String id) throws IOException, URISyntaxException { URI uri = URIUtils.createURI("http", host, port, "/" + getDbName() + "/", "id=" + id, null); HttpGet httpGet = new HttpGet(uri); String response = doHttp(httpGet); JSONObject json = JSONObject.fromObject(response); return json;//from www. java 2 s. co m }
From source file:com.healthcit.cacure.dao.CouchDBDao.java
public String saveForm(JSONObject jsonDoc, JSONArray key) throws IOException, URISyntaxException { JSONObject object = getFormByOwnerIdAndFormId(key); String id, rev;//ww w .j a v a 2 s. c o m if (object != null) { id = object.getString("_id"); rev = object.getString("_rev"); jsonDoc.put("_id", id); jsonDoc.put("_rev", rev); } else { id = getDocId(); } String jsonStr = jsonDoc.toString(); //URI uri = URIUtils.createURI("http", DB_HOST, DB_PORT, "/" + DB_NAME + "/" + getDocId(), URI uri = URIUtils.createURI("http", host, port, "/" + getDbName() + "/" + id, null, null); String response = runPutQuery(uri, jsonStr); return response; }
From source file:com.healthcit.cacure.dao.CouchDBDao.java
public String addAttachment(String attachmentName, JSONObject attachment, String dbName, String designDocName) throws IOException, URISyntaxException { String revision = getCouchDbRevisionNumber(dbName, designDocName); URI uri = URIUtils .createURI(/* ww w . java2 s . c o m*/ "http", host, port, "/" + dbName + "/" + DESIGN_DOC_PREFIX + "/" + designDocName + "/" + attachmentName + (StringUtils.isEmpty(revision) ? "" : "?rev=" + revision), null, null); String response = runPutQuery(uri, attachment.toString()); return response; }
From source file:com.healthcit.cacure.dao.CouchDBDao.java
public String getAttachment(String attachmentName, String dbName, String designDocName) { String response = null;//w ww .j ava 2 s . c om try { URI uri = URIUtils.createURI("http", host, port, "/" + dbName + "/" + DESIGN_DOC_PREFIX + "/" + designDocName + "/" + attachmentName, null, null); response = doHttp(new HttpGet(uri)); } catch (Exception ex) { log.error("Could not read the attachment " + attachmentName + " in the database " + dbName); log.error(ExceptionUtils.getFullStackTrace(ex)); } return response; }
From source file:com.healthcit.cacure.dao.CouchDBDao.java
public JSONArray getAllDbs() throws URISyntaxException, IOException { URI uri = URIUtils.createURI("http", host, port, "/" + ALL_DBS_URL_SUFFIX, null, null); String response = runGetQuery(uri); JSONArray dbs = JSONArray.fromObject(response); return dbs;//from w ww .j a va 2 s . c o m }
From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java
@Override public String obtainOauth2Data(String destinationUrl) throws IllegalArgumentException { // get the auth code... Context ctxt = getStateContext(ctxtKey); String code = (String) ctxt.getContext("code"); {//from w ww.java 2 s . com // convert the auth code into an auth token URI nakedUri; try { nakedUri = new URI(tokenUrl); } catch (URISyntaxException e2) { e2.printStackTrace(); logger.error(e2.toString()); return getSelfUrl(); } // DON'T NEED clientId on the toke request... // addCredentials(clientId, clientSecret, nakedUri.getHost()); // setup request interceptor to do preemptive auth // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0); HttpClientFactory factory = new GaeHttpClientFactoryImpl(); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS); HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(httpParams, true); // support authenticating HttpClientParams.setAuthenticating(httpParams, true); httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1); httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // setup client HttpClient client = factory.createHttpClient(httpParams); HttpPost httppost = new HttpPost(nakedUri); logger.info(httppost.getURI().toString()); // THESE ARE POST BODY ARGS... List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("grant_type", "authorization_code")); qparams.add(new BasicNameValuePair("client_id", CLIENT_ID)); qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET)); qparams.add(new BasicNameValuePair("code", code)); qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl())); UrlEncodedFormEntity postentity; try { postentity = new UrlEncodedFormEntity(qparams, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); logger.error(e1.toString()); throw new IllegalArgumentException("Unexpected"); } httppost.setEntity(postentity); HttpResponse response = null; try { response = client.execute(httppost, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("not 200: " + statusCode); return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase() + " status code: " + statusCode; } else { HttpEntity entity = response.getEntity(); if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) { ObjectMapper mapper = new ObjectMapper(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); Map<String, Object> userData = mapper.readValue(reader, Map.class); // stuff the map in the Context... for (Map.Entry<String, Object> e : userData.entrySet()) { ctxt.putContext(e.getKey(), e.getValue()); } } else { logger.error("unexpected body"); return "Error with Oauth2 token request - unexpected body"; } } } catch (IOException e) { throw new IllegalArgumentException(e.toString()); } } // OK if we got here, we have a valid token. // Issue the request... { URI nakedUri; try { nakedUri = new URI(destinationUrl); } catch (URISyntaxException e2) { e2.printStackTrace(); logger.error(e2.toString()); return getSelfUrl(); } List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token"))); URI uri; try { uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(), nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null); } catch (URISyntaxException e1) { e1.printStackTrace(); logger.error(e1.toString()); return getSelfUrl(); } // DON'T NEED clientId on the toke request... // addCredentials(clientId, clientSecret, nakedUri.getHost()); // setup request interceptor to do preemptive auth // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0); HttpClientFactory factory = new GaeHttpClientFactoryImpl(); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS); HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(httpParams, true); // support authenticating HttpClientParams.setAuthenticating(httpParams, true); httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1); httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // setup client HttpClient client = factory.createHttpClient(httpParams); HttpGet httpget = new HttpGet(uri); logger.info(httpget.getURI().toString()); HttpResponse response = null; try { response = client.execute(httpget, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("not 200: " + statusCode); return "Error"; } else { HttpEntity entity = response.getEntity(); if (entity != null) { String contentType = entity.getContentType().getValue(); if (contentType.toLowerCase().contains("xml")) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuilder b = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { b.append(line); } String value = b.toString(); return value; } else { logger.error("unexpected body"); return "Error"; } } else { logger.error("unexpected missing body"); return "Error"; } } } catch (IOException e) { throw new IllegalArgumentException(e.toString()); } } }
From source file:org.dataconservancy.dcs.integration.lineage.HttpLineageServiceIT.java
/** * Builds an HttpGet to use in the test given the argument and the id. /*from w w w .j a v a2s . c o m*/ * @param argument should be one of latest, original, search. * @param id The lineage or entity id of the object * @param optionalArgument can be if-modified-since or accept * @return The completed http request that can be passed to HttpClient * @throws UnsupportedEncodingException * @throws URISyntaxException */ private HttpGet buildRequest(String argument, String id, String... optionalArguments) throws UnsupportedEncodingException, URISyntaxException { HttpGet request = null; String arguments = "/lineage"; if (argument != null && !argument.isEmpty()) { arguments += "/" + argument; } if (id != null && !id.isEmpty()) { arguments += "/" + id; } List<NameValuePair> params = new ArrayList<NameValuePair>(); String headerName = ""; String headerValue = ""; for (int i = 0; i < optionalArguments.length; i = i + 2) { if (!optionalArguments[i].isEmpty()) { if (optionalArguments[i].equalsIgnoreCase("if-modified-since")) { headerName = optionalArguments[i]; headerValue = optionalArguments[i + 1]; } else { params.add(new BasicNameValuePair(optionalArguments[i], optionalArguments[i + 1])); } } } URI uri = URIUtils.createURI("http", "localhost", 8080, arguments, URLEncodedUtils.format(params, "UTF-8"), null); request = new HttpGet(uri); if (headerName != null && !headerName.isEmpty() && headerValue != null && !headerValue.isEmpty()) { headerValue = DateUtility.toRfc822(Long.valueOf(headerValue)); request.setHeader(headerName, headerValue); } return request; }
From source file:org.soyatec.windowsazure.internal.util.HttpUtilities.java
/** * Create a request URI./*from w w w. j av a 2 s . c o m*/ * * @param baseUri * @param usePathStyleUris * @param accountName * @param containerName * @param blobName * @param timeout * @param queryParameters * @param uriComponents * @param appendQuery * @return URI */ public static URI createRequestUri(URI baseUri, boolean usePathStyleUris, String accountName, String containerName, String blobName, TimeSpan timeout, NameValueCollection queryParameters, ResourceUriComponents uriComponents, String appendQuery) { URI uri = HttpRequestAccessor.constructResourceUri(baseUri, uriComponents, usePathStyleUris); if (queryParameters != null) { if (queryParameters.get(QueryParams.QueryParamTimeout) == null && timeout != null) { queryParameters.put(QueryParams.QueryParamTimeout, timeout.toSeconds()); } StringBuilder sb = new StringBuilder(); boolean firstParam = true; boolean appendBlockAtTail = false; for (Object key : queryParameters.keySet()) { String queryKey = (String) key; if (queryKey.equalsIgnoreCase(QueryParams.QueryParamBlockId)) { appendBlockAtTail = true; continue; } if (!firstParam) { sb.append("&"); } sb.append(Utilities.encode(queryKey)); sb.append('='); sb.append(Utilities.encode(queryParameters.getSingleValue(queryKey))); firstParam = false; } /* * You shuold add blockid as the last query parameters for put block * request, or an exception you will get. */ if (appendBlockAtTail) { String queryKey = QueryParams.QueryParamBlockId; sb.append("&"); sb.append(Utilities.encode(queryKey)); sb.append('='); sb.append(Utilities.encode(queryParameters.getSingleValue(queryKey))); } if (!Utilities.isNullOrEmpty(appendQuery)) { if (sb.length() > 0) { sb.append("&"); } // @NOTE: escape char sb.append(appendQuery.replaceAll(" ", "%20")); } if (sb.length() > 0) { try { String p = getNormalizePath(uri).replaceAll(" ", "%20"); return URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), p, (uri.getQuery() == null ? Utilities.emptyString() : uri.getQuery()) + sb.toString(), uri.getFragment()); } catch (URISyntaxException e) { Logger.error("", e); } } return uri; } else { return uri; } }