List of usage examples for org.apache.commons.httpclient.methods PutMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:cz.muni.fi.pa165.creatures.rest.client.services.impl.RegionCRUDServiceImpl.java
@Override public void update(RegionDTO dto) { PutMethod putMethod = new PutMethod(uri); StringWriter writer = new StringWriter(); try {// w w w . ja v a 2 s. c o m context.createMarshaller().marshal(regionMapping.DTOtoEntity(dto), writer); } catch (JAXBException ex) { logger.log(Level.INFO, "Unable to marshall RegionDTO {0}", dto); return; } RequestEntity entity = new InputStreamRequestEntity(new ByteArrayInputStream(writer.toString().getBytes())); putMethod.setRequestEntity(entity); CRUDServiceHelper.send(putMethod); }
From source file:cz.muni.fi.pa165.creatures.rest.client.services.impl.WeaponCRUDServiceImpl.java
@Override public void update(WeaponDTO dto) { PutMethod putMethod = new PutMethod(uri); StringWriter writer = new StringWriter(); try {//www . j a va2s.co m context.createMarshaller().marshal(weaponMapping.DTOtoEntity(dto), writer); } catch (JAXBException ex) { logger.log(Level.INFO, "Unable to marshall WeaponDTO {0}", dto); return; } RequestEntity entity = new InputStreamRequestEntity(new ByteArrayInputStream(writer.toString().getBytes())); putMethod.setRequestEntity(entity); CRUDServiceHelper.send(putMethod); }
From source file:com.bdaum.juploadr.uploadapi.smugrest.upload.SmugmugUpload.java
@Override public boolean execute() throws ProtocolException, CommunicationException { HttpClient client = HttpClientFactory.getHttpClient(session.getAccount()); this.monitor.uploadStarted(new UploadEvent(image, 0, true, false)); SortedMap<String, String> params = getParams(); String name = params.get(X_SMUG_FILE_NAME); PutMethod put = new PutMethod(URL + name); for (Map.Entry<String, String> entry : params.entrySet()) put.addRequestHeader(entry.getKey(), entry.getValue()); File file = new File(image.getImagePath()); Asset asset = image.getAsset();//from w ww. java 2s . c om FileRequestEntity entity = new FileRequestEntity(file, asset.getMimeType()); put.setRequestEntity(entity); try { int status = client.executeMethod(put); if (status == HttpStatus.SC_OK) { // deal with the response try { String response = put.getResponseBodyAsString(); put.releaseConnection(); boolean success = parseResponse(response); if (success) { image.setState(UploadImage.STATE_UPLOADED); ImageUploadResponse resp = new ImageUploadResponse(handler.getPhotoID(), handler.getKey(), handler.getUrl()); this.monitor.uploadFinished(new UploadCompleteEvent(resp, image)); } else { throw new UploadFailedException(Messages.getString("juploadr.ui.error.status")); //$NON-NLS-1$ } } catch (IOException e) { // TODO: Is it safe to assume the upload failed here? this.fail(Messages.getString("juploadr.ui.error.response.unreadable") //$NON-NLS-1$ + e.getMessage(), e); } } else { this.fail(Messages.getString("juploadr.ui.error.bad.http.response", status), null); //$NON-NLS-1$ } } catch (ConnectException ce) { this.fail(Messages.getString("juploadr.ui.error.unable.to.connect"), ce); //$NON-NLS-1$ } catch (NoRouteToHostException route) { this.fail(Messages.getString("juploadr.ui.error.no.internet"), route); //$NON-NLS-1$ } catch (UnknownHostException uhe) { this.fail(Messages.getString("juploadr.ui.error.unknown.host"), uhe); //$NON-NLS-1$ } catch (HttpException e) { this.fail(Messages.getString("juploadr.ui.error.http.exception") + e, e); //$NON-NLS-1$ } catch (IOException e) { this.fail(Messages.getString("juploadr.ui.error.simple.ioexception") + e.getMessage() + "" //$NON-NLS-1$ //$NON-NLS-2$ + e, e); } return true; }
From source file:com.zimbra.cs.zimlet.ProxyServlet.java
private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException { ZimbraLog.clearContext();//from w w w. ja v a 2 s.c om boolean isAdmin = isAdminRequest(req); AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true) : getAuthTokenFromCookie(req, resp, true); if (authToken == null) { String zAuthToken = req.getParameter(QP_ZAUTHTOKEN); if (zAuthToken != null) { try { authToken = AuthProvider.getAuthToken(zAuthToken); if (authToken.isExpired()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired"); return; } if (!authToken.isRegistered()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid"); return; } if (isAdmin && !authToken.isAdmin()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied"); return; } } catch (AuthTokenException e) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken"); return; } } } if (authToken == null) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie"); return; } // get the posted body before the server read and parse them. byte[] body = copyPostedData(req); // sanity check String target = req.getParameter(TARGET_PARAM); if (target == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // check for permission URL url = new URL(target); if (!isAdmin && !checkPermissionOnTarget(url, authToken)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // determine whether to return the target inline or store it as an upload String uploadParam = req.getParameter(UPLOAD_PARAM); boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true")); HttpMethod method = null; try { HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient(); HttpProxyUtil.configureProxy(client); String reqMethod = req.getMethod(); if (reqMethod.equalsIgnoreCase("GET")) { method = new GetMethod(target); } else if (reqMethod.equalsIgnoreCase("POST")) { PostMethod post = new PostMethod(target); if (body != null) post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType())); method = post; } else if (reqMethod.equalsIgnoreCase("PUT")) { PutMethod put = new PutMethod(target); if (body != null) put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType())); method = put; } else if (reqMethod.equalsIgnoreCase("DELETE")) { method = new DeleteMethod(target); } else { ZimbraLog.zimlet.info("unsupported request method: " + reqMethod); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } // handle basic auth String auth, user, pass; auth = req.getParameter(AUTH_PARAM); user = req.getParameter(USER_PARAM); pass = req.getParameter(PASS_PARAM); if (auth != null && user != null && pass != null) { if (!auth.equals(AUTH_BASIC)) { ZimbraLog.zimlet.info("unsupported auth type: " + auth); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass)); client.setState(state); method.setDoAuthentication(true); } Enumeration headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String hdr = (String) headers.nextElement(); ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr)); if (canProxyHeader(hdr)) { ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr)); if (hdr.equalsIgnoreCase("x-host")) method.getParams().setVirtualHost(req.getHeader(hdr)); else method.addRequestHeader(hdr, req.getHeader(hdr)); } } try { if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) { method.setFollowRedirects(true); } HttpClientUtil.executeMethod(client, method); } catch (HttpException ex) { ZimbraLog.zimlet.info("exception while proxying " + target, ex); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : method.getStatusCode(); // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line Header ctHeader = method.getResponseHeader("Content-Type"); String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE : ctHeader.getValue(); InputStream targetResponseBody = method.getResponseBodyAsStream(); if (asUpload) { String filename = req.getParameter(FILENAME_PARAM); if (filename == null || filename.equals("")) filename = new ContentType(contentType).getParameter("name"); if ((filename == null || filename.equals("")) && method.getResponseHeader("Content-Disposition") != null) filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue()) .getParameter("filename"); if (filename == null || filename.equals("")) filename = "unknown"; List<Upload> uploads = null; if (targetResponseBody != null) { try { Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType, authToken.getAccountId()); uploads = Arrays.asList(up); } catch (ServiceException e) { if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED)) status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE; else status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } resp.setStatus(status); FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null); } else { resp.setStatus(status); resp.setContentType(contentType); for (Header h : method.getResponseHeaders()) if (canProxyHeader(h.getName())) resp.addHeader(h.getName(), h.getValue()); if (targetResponseBody != null) ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true); } } finally { if (method != null) method.releaseConnection(); } }
From source file:com.cloud.network.bigswitch.BigSwitchVnsApi.java
protected <T> void executeUpdateObject(T newObject, String uri, Map<String, String> parameters) throws BigSwitchVnsApiException { if (_host == null || _host.isEmpty()) { throw new BigSwitchVnsApiException("Hostname is null or empty"); }/* www . ja va 2 s .com*/ Gson gson = new Gson(); PutMethod pm = (PutMethod) createMethod("put", uri, 80); pm.setRequestHeader(CONTENT_TYPE, CONTENT_JSON); pm.setRequestHeader(ACCEPT, CONTENT_JSON); pm.setRequestHeader(HTTP_HEADER_INSTANCE_ID, CLOUDSTACK_INSTANCE_ID); try { pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null)); } catch (UnsupportedEncodingException e) { throw new BigSwitchVnsApiException("Failed to encode json request body", e); } executeMethod(pm); if (pm.getStatusCode() != HttpStatus.SC_OK) { String errorMessage = responseToErrorMessage(pm); pm.releaseConnection(); s_logger.error("Failed to update object : " + errorMessage); throw new BigSwitchVnsApiException("Failed to update object : " + errorMessage); } pm.releaseConnection(); }
From source file:eu.learnpad.core.impl.or.XwikiCoreFacadeRestResource.java
@Override public void pushKPIValues(String modelSetId, KPIValuesFormat format, String businessActorId, InputStream cockpitContent) throws LpRestException { String contentType = "application/xml"; HttpClient httpClient = this.getAnonymousClient(); String uri = String.format("%s/learnpad/or/corefacade/pushkpivalues/%s", DefaultRestResource.REST_URI, modelSetId);/*from w w w . j a v a 2s.c o m*/ PutMethod putMethod = new PutMethod(uri); putMethod.addRequestHeader("Content-Type", contentType); NameValuePair[] queryString = new NameValuePair[2]; queryString[0] = new NameValuePair("format", format.toString()); queryString[1] = new NameValuePair("businessactor", businessActorId); putMethod.setQueryString(queryString); RequestEntity requestEntity = new InputStreamRequestEntity(cockpitContent); putMethod.setRequestEntity(requestEntity); try { httpClient.executeMethod(putMethod); } catch (IOException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e); } }
From source file:com.gisgraphy.rest.RestClient.java
private HttpMethod createPutMethod(String url, Map<String, Object> map) throws RestClientException { PutMethod httpMethod = new PutMethod(url); StringBuilder responseBody = new StringBuilder(); if (map != null) { for (String key : map.keySet()) { if (map.get(key) != null) { responseBody.append(format("%s=%s\n", key, map.get(key).toString())); }/*from w w w. j a va 2 s. c om*/ } } String responseBodyAsString = responseBody.toString(); httpMethod.setRequestEntity( new StringRequestEntity(responseBodyAsString.substring(0, responseBody.length()))); httpMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); return httpMethod; }
From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java
@Override public void setUserAttribute(Long userId, String key, String value) { String resource = String.format(baseUrl + USER_ATTRIBUTES + "/" + key, userId); PutMethod method = new PutMethod(resource); try {// w w w .j a va2s .co m method.setRequestEntity(new StringRequestEntity(value, "text/plain", "UTF-8")); // Execute the HTTP Call int statusCode = getClient().executeMethod(method); if (statusCode == HttpStatus.SC_NOT_FOUND) { return; } assertResponseCodeOK(method, statusCode); } catch (Exception e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } }
From source file:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java
@Override public void updateOperator(OperatorDTO operator) { PutMethod method = new PutMethod(baseUrl + UPDATE_OPERATOR); prepareMethod(method);/*from ww w . j a v a 2 s .c om*/ try { String data = serialize(operator); method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8")); // Execute the method. int statusCode = getClient().executeMethod(method); if (statusCode == HttpStatus.SC_NOT_FOUND) { return; } assertResponseCodeOK(method, statusCode); } catch (Exception e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } }
From source file:eu.impact_project.resultsrepository.DavHandler.java
/** * Copies one file./*from w w w . ja v a2 s.co m*/ * * @param sourceUrl * The remote URL of the file. * @param targetUrl * URL in the repository. */ private void copyFile(String sourceUrl, String targetUrl) throws HttpException, IOException { if (sourceUrl != null && !sourceUrl.equals("")) { GetMethod getMethod = new GetMethod(sourceUrl); PutMethod putMethod = new PutMethod(targetUrl); client.executeMethod(getMethod); downloadedFile = getMethod.getResponseBody(); InputStream stream = null; try { stream = new ByteArrayInputStream(downloadedFile); putMethod.setRequestEntity(new InputStreamRequestEntity(stream)); client.executeMethod(putMethod); } finally { stream.close(); } getMethod.releaseConnection(); putMethod.releaseConnection(); } else { throw new IOException("A tool did not return a URL. The target URL would have been: " + targetUrl); } }