List of usage examples for org.apache.commons.httpclient.methods PutMethod PutMethod
public PutMethod(String paramString)
From source file:com.github.pires.example.tests.UserServiceIntegrationTest.java
@Test public void shouldCreateAndRetriveUserWithREST() throws Exception { String payload = "{ " + "\"name\": \"manel joao\", " + "\"properties\": {" + "\"value\": {" + "\"num1\":{" + "\"type\":\"number\", " + "\"value\":\"1\", " + "\"mandatory\":\"false\"}, " + "\"string1\":{" + "\"type\":\"string\", " + "\"value\":\"teste\", " + "\"mandatory\":\"false\"}" + "}}}"; try {//from w w w . ja va2 s . c om //create user PutMethod put = new PutMethod(USER_MANAGER_URL); put.addRequestHeader("Accept", "application/json"); RequestEntity entity = new StringRequestEntity(payload, "application/json", "UTF-8"); put.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); int result = 0; try { result = httpclient.executeMethod(put); //System.err.println(result); assertTrue(result == 204); } catch (Exception e) { org.junit.Assert.fail("Unable to create user"); } finally { put.releaseConnection(); } //get user URL url = new URL(USER_MANAGER_URL); InputStream in = null; try { in = url.openStream(); } catch (Exception e) { org.junit.Assert.fail("Connection error"); } String res = getStringFromInputStream(in); System.err.println(res); assertTrue(res.contains("\"name\":\"manel joao\"") && res.contains("\"string1\":{") && res.contains("\"num1\":{")); } catch (Exception e) { System.err.println(e.getMessage()); org.junit.Assert.fail("test failed"); } }
From source file:com.zimbra.cs.dav.client.DavRequest.java
public HttpMethod getHttpMethod(String baseUrl) { String url = mRedirectUrl;/*www .j av a 2 s . c o m*/ if (url == null) { // Normally, mUri is a relative URL but sometimes it is a full URL. // For instance iCloud currently specifies a full URL instead of a relative one for calendar-home-set // in a PROPFIND result, even though it specifies relative ones for schedule-inbox-URL and // schedule-outbox-URL in the same report. try { new URL(mUri); // This will throw an exception when the URL is a relative one. url = mUri; } catch (MalformedURLException e) { url = baseUrl + mUri; } } if (mDoc == null) return new GetMethod(url) { @Override public String getName() { return mMethod; } }; PutMethod m = new PutMethod(url) { RequestEntity re; @Override public String getName() { return mMethod; } @Override protected RequestEntity generateRequestEntity() { return re; } @Override public void setRequestEntity(RequestEntity requestEntity) { re = requestEntity; super.setRequestEntity(requestEntity); } }; DocumentRequestEntity re = new DocumentRequestEntity(mDoc); m.setRequestEntity(re); return m; }
From source file:com.owncloud.android.lib.resources.shares.UpdateRemoteShareOperation.java
@Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; int status = -1; /// prepare array of parameters to update List<Pair<String, String>> parametersToUpdate = new ArrayList<Pair<String, String>>(); if (mPassword != null) { parametersToUpdate.add(new Pair<String, String>(PARAM_PASSWORD, mPassword)); }/* www .j a va2 s. c o m*/ if (mExpirationDateInMillis < 0) { // clear expiration date parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, "")); } else if (mExpirationDateInMillis > 0) { // set expiration date DateFormat dateFormat = new SimpleDateFormat(FORMAT_EXPIRATION_DATE); Calendar expirationDate = Calendar.getInstance(); expirationDate.setTimeInMillis(mExpirationDateInMillis); String formattedExpirationDate = dateFormat.format(expirationDate.getTime()); parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, formattedExpirationDate)); } // else, ignore - no update /* TODO complete rest of parameters if (mPermissions > 0) { parametersToUpdate.add(new Pair("permissions", Integer.toString(mPermissions))); } if (mPublicUpload != null) { parametersToUpdate.add(new Pair("publicUpload", mPublicUpload.toString()); } */ /// perform required PUT requests PutMethod put = null; String uriString = null; try { Uri requestUri = client.getBaseUri(); Uri.Builder uriBuilder = requestUri.buildUpon(); uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH.substring(1)); uriBuilder.appendEncodedPath(Long.toString(mRemoteId)); uriString = uriBuilder.build().toString(); for (Pair<String, String> parameter : parametersToUpdate) { if (put != null) { put.releaseConnection(); } put = new PutMethod(uriString); put.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); put.setRequestEntity(new StringRequestEntity(parameter.first + "=" + parameter.second, ENTITY_CONTENT_TYPE, ENTITY_CHARSET)); status = client.executeMethod(put); if (status == HttpStatus.SC_OK) { String response = put.getResponseBodyAsString(); // Parse xml response ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser( new ShareXMLParser()); parser.setOwnCloudVersion(client.getOwnCloudVersion()); parser.setServerBaseUri(client.getBaseUri()); result = parser.parse(response); } else { result = new RemoteOperationResult(false, status, put.getResponseHeaders()); } } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Exception while updating remote share ", e); if (put != null) { put.releaseConnection(); } } finally { if (put != null) { put.releaseConnection(); } } return result; }
From source file:eu.learnpad.core.impl.cw.XwikiBridgeInterfaceRestResource.java
@Override public void notifyRecommendations(String modelSetId, String simulationid, String userId, Recommendations rec) throws LpRestException { String contentType = "application/xml"; HttpClient httpClient = this.getClient(); String uri = String.format("%s/learnpad/cw/bridge/notify/%s", DefaultRestResource.REST_URI, modelSetId); PutMethod putMethod = new PutMethod(uri); putMethod.addRequestHeader("Accept", contentType); NameValuePair[] queryString = new NameValuePair[2]; queryString[0] = new NameValuePair("simulationid", simulationid); queryString[1] = new NameValuePair("userid", userId); putMethod.setQueryString(queryString); try {/*from w ww .j a v a 2 s . co m*/ JAXBContext jc = JAXBContext.newInstance(Recommendations.class); Writer recWriter = new StringWriter(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(rec, recWriter); RequestEntity requestEntity = new StringRequestEntity(recWriter.toString(), contentType, "UTF-8"); putMethod.setRequestEntity(requestEntity); httpClient.executeMethod(putMethod); } catch (JAXBException | IOException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } }
From source file:com.intuit.tank.http.BaseRequest.java
/** * Execute the post. Use this to force the type of response * /*from w ww . j a v a2 s .co m*/ * @param newResponse * The response object to populate */ public void doPut(BaseResponse response) { PutMethod httpput = null; try { URL url = BaseRequestHandler.buildUrl(protocol, host, port, path, urlVariables); httpput = new PutMethod(url.toString()); String requestBody = this.getBody(); // Multiple calls can be // expensive, so get it once StringRequestEntity entity; entity = new StringRequestEntity(requestBody, getContentType(), contentTypeCharSet); httpput.setRequestEntity(entity); sendRequest(response, httpput, requestBody); } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (null != httpput) httpput.releaseConnection(); } }
From source file:eu.learnpad.core.impl.me.XwikiController.java
@Override public MVResults checkModelSetVerification(String verificationProcessId) throws LpRestExceptionImpl { MVResults result = mvResults.get(verificationProcessId); if (result != null) { MVResults toReturn = new MVResults(result); if (result.getStatus().equals("inprogress")) { mvResults.get(verificationProcessId).terminate(); } else {//from w ww. ja v a 2s .c o m mvResults.remove(verificationProcessId); } if (toReturn.getStatus().equals("finished")) { // Notify CW about a new model set imported HttpClient httpClient = RestResource.getClient(); String uri = String.format("%s/learnpad/cw/bridge/modelsetimported/%s", RestResource.REST_URI, toReturn.getModelSetId()); PutMethod putMethod = new PutMethod(uri); putMethod.addRequestHeader("Accept", "application/xml"); NameValuePair[] queryString = new NameValuePair[1]; queryString[0] = new NameValuePair("type", toReturn.getType()); putMethod.setQueryString(queryString); try { httpClient.executeMethod(putMethod); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Notify OR about a new model set imported httpClient = RestResource.getClient(); uri = String.format("%s/learnpad/or/bridge/modelsetimported/%s", RestResource.REST_URI, toReturn.getModelSetId()); PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader("Accept", "application/xml"); queryString = new NameValuePair[1]; queryString[0] = new NameValuePair("type", toReturn.getType()); postMethod.setQueryString(queryString); try { httpClient.executeMethod(postMethod); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return toReturn; } else { return null; } }
From source file:com.moss.bdbadmin.client.service.BdbClient.java
public void put(IdProof assertion, String path, BdbResourceHandle handle) throws ServiceException { try {//ww w.ja v a2 s. c o m PutMethod method = new PutMethod(baseUrl + "/" + path); method.setRequestHeader(AuthenticationHeader.HEADER_NAME, AuthenticationHeader.encode(assertion)); method.setRequestEntity(new InputStreamRequestEntity(handle.read())); int result = httpClient.executeMethod(method); if (result != 200) { throw new ServiceException(result); } } catch (IOException ex) { throw new ServiceFailure(ex); } }
From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (servletRequest.getUserPrincipal() == null) { servletResponse.sendError(403, "User is not logged in"); return;/*from w ww . j a va 2s . c o m*/ } if (!servletRequest.isUserInRole("HOPS_ADMIN")) { servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(), "You don't have the access right for this service"); return; } if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); } if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // Make the Request // note: we won't transfer the protocol version because I'm not // sure it would truly be compatible String proxyRequestUri = rewriteUrlFromRequest(servletRequest); try { // Execute the request HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); HostConfiguration config = new HostConfiguration(); InetAddress localAddress = InetAddress.getLocalHost(); config.setLocalAddress(localAddress); String method = servletRequest.getMethod(); HttpMethod m; if (method.equalsIgnoreCase("PUT")) { m = new PutMethod(proxyRequestUri); RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(), servletRequest.getContentType()); ((PutMethod) m).setRequestEntity(requestEntity); } else { m = new GetMethod(proxyRequestUri); } Enumeration<String> names = servletRequest.getHeaderNames(); while (names.hasMoreElements()) { String headerName = names.nextElement(); String value = servletRequest.getHeader(headerName); if (PASS_THROUGH_HEADERS.contains(headerName)) { //yarn does not send back the js if encoding is not accepted //but we don't want to accept encoding for the html because we //need to be able to parse it if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null || !servletRequest.getPathInfo().contains(".js"))) { continue; } else { m.setRequestHeader(headerName, value); } } } String user = servletRequest.getRemoteUser(); if (user != null && !user.isEmpty()) { m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII")); } client.executeMethod(config, m); // Process the response int statusCode = m.getStatusCode(); // Pass the response code. This method with the "reason phrase" is //deprecated but it's the only way to pass the reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase()); copyResponseHeaders(m, servletRequest, servletResponse); // Send the content to the client copyResponseEntity(m, servletResponse); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } }
From source file:eu.impact_project.resultsrepository.DavHandler.java
/** * Saves a stream into a file in the repository. * /*from w ww .ja v a 2s. c o m*/ * @param text * Stream to be stored. * @param url * URL to the file that will be created. */ public void saveStream(InputStream stream, String url) throws IOException { PutMethod putMethod = new PutMethod(url); putMethod.setRequestEntity(new InputStreamRequestEntity(stream)); try { client.executeMethod(putMethod); putMethod.releaseConnection(); } catch (IOException e) { throw new IOException(e); } finally { stream.close(); } }
From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java
/** * Determines the HttpClient's request method from the HTTPMethod enum. * * @param method the HTTPCache enum that determines * @param requestURI the request URI./*from w w w. j av a2 s .c o m*/ * @return a new HttpMethod subclass. */ protected HttpMethod getMethod(HTTPMethod method, URI requestURI) { if (CONNECT.equals(method)) { HostConfiguration config = new HostConfiguration(); config.setHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme()); return new ConnectMethod(config); } else if (DELETE.equals(method)) { return new CustomHttpMethod(HTTPMethod.DELETE.name(), requestURI.toString()); } else if (GET.equals(method)) { return new GetMethod(requestURI.toString()); } else if (HEAD.equals(method)) { return new HeadMethod(requestURI.toString()); } else if (OPTIONS.equals(method)) { return new OptionsMethod(requestURI.toString()); } else if (POST.equals(method)) { return new PostMethod(requestURI.toString()); } else if (PUT.equals(method)) { return new PutMethod(requestURI.toString()); } else if (TRACE.equals(method)) { return new TraceMethod(requestURI.toString()); } else { return new CustomHttpMethod(method.name(), requestURI.toString()); } }