List of usage examples for org.apache.commons.httpclient.methods PutMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:org.sonatype.nexus.restlight.testharness.PUTFixtureTest.java
@Test public void testPUT() throws Exception { Document doc = new Document().setRootElement(new Element("root")); fixture.setRequestDocument(doc);// w w w .j av a 2 s.c o m String url = "http://localhost:" + fixture.getPort(); HttpClient client = new HttpClient(); setupAuthentication(client); PutMethod put = new PutMethod(url); XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat()); put.setRequestEntity(new StringRequestEntity(outputter.outputString(doc), "application/xml", "UTF-8")); client.executeMethod(put); String statusText = put.getStatusText(); System.out.println(statusText); put.releaseConnection(); assertEquals(HttpServletResponse.SC_OK, put.getStatusCode()); }
From source file:org.talend.mdm.bulkload.client.BulkloadClientUtil.java
public static void bulkload(String url, String cluster, String concept, String datamodel, boolean validate, boolean smartpk, boolean insertonly, InputStream itemdata, String username, String password, String transactionId, String sessionId, String universe, String tokenKey, String tokenValue) throws Exception { HostConfiguration config = new HostConfiguration(); URI uri = new URI(url, false, "UTF-8"); //$NON-NLS-1$ config.setHost(uri);//from w w w .ja va 2 s . c o m NameValuePair[] parameters = { new NameValuePair("cluster", cluster), //$NON-NLS-1$ new NameValuePair("concept", concept), //$NON-NLS-1$ new NameValuePair("datamodel", datamodel), //$NON-NLS-1$ new NameValuePair("validate", String.valueOf(validate)), //$NON-NLS-1$ new NameValuePair("action", "load"), //$NON-NLS-1$ //$NON-NLS-2$ new NameValuePair("smartpk", String.valueOf(smartpk)), //$NON-NLS-1$ new NameValuePair("insertonly", String.valueOf(insertonly)) }; //$NON-NLS-1$ HttpClient client = new HttpClient(); String user = universe == null || universe.trim().length() == 0 ? username : universe + "/" + username; //$NON-NLS-1$ client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); HttpClientParams clientParams = client.getParams(); clientParams.setAuthenticationPreemptive(true); clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); PutMethod putMethod = new PutMethod(); // This setPath call is *really* important (if not set, request will be sent to the JBoss root '/') putMethod.setPath(url); String responseBody; try { // Configuration putMethod.setRequestHeader("Content-Type", "text/xml; charset=utf8"); //$NON-NLS-1$ //$NON-NLS-2$ if (transactionId != null) { putMethod.setRequestHeader("transaction-id", transactionId); //$NON-NLS-1$ } if (sessionId != null) { putMethod.setRequestHeader("Cookie", STICKY_SESSION + "=" + sessionId); //$NON-NLS-1$ //$NON-NLS-2$ } if (tokenKey != null && tokenValue != null) { putMethod.setRequestHeader(tokenKey, tokenValue); } putMethod.setQueryString(parameters); putMethod.setContentChunked(true); // Set the content of the PUT request putMethod.setRequestEntity(new InputStreamRequestEntity(itemdata)); client.executeMethod(config, putMethod); responseBody = putMethod.getResponseBodyAsString(); if (itemdata instanceof InputStreamMerger) { ((InputStreamMerger) itemdata).setAlreadyProcessed(true); } } catch (Exception e) { throw new RuntimeException(e); } finally { putMethod.releaseConnection(); } int statusCode = putMethod.getStatusCode(); if (statusCode >= 500) { throw new BulkloadException(responseBody); } else if (statusCode >= 400) { throw new BulkloadException("Could not send data to MDM (HTTP status code: " + statusCode + ")."); //$NON-NLS-1$ //$NON-NLS-2$ } }
From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java
private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl) throws IOException { final String methodName = hsRequest.getMethod(); final HttpMethod method; if ("POST".equalsIgnoreCase(methodName)) { PostMethod postMethod = new PostMethod(); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity( hsRequest.getInputStream()); postMethod.setRequestEntity(inputStreamRequestEntity); method = postMethod;/*from ww w .j a va2s .c o m*/ } else if ("GET".equalsIgnoreCase(methodName)) { method = new GetMethod(); } else if ("PUT".equalsIgnoreCase(methodName)) { PutMethod putMethod = new PutMethod(); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity( hsRequest.getInputStream()); putMethod.setRequestEntity(inputStreamRequestEntity); method = putMethod; } else if ("DELETE".equalsIgnoreCase(methodName)) { method = new DeleteMethod(); } else { log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod()); return null; } method.setFollowRedirects(false); method.setPath(targetUrl.getPath()); method.setQueryString(targetUrl.getQuery()); Enumeration e = hsRequest.getHeaderNames(); if (e != null) { while (e.hasMoreElements()) { String headerName = (String) e.nextElement(); if ("host".equalsIgnoreCase(headerName)) { //the host value is set by the http client continue; } else if ("content-length".equalsIgnoreCase(headerName)) { //the content-length is managed by the http client continue; } else if ("accept-encoding".equalsIgnoreCase(headerName)) { //the accepted encoding should only be those accepted by the http client. //The response stream should (afaik) be deflated. If our http client does not support //gzip then the response can not be unzipped and is delivered wrong. continue; } else if (headerName.toLowerCase().startsWith("cookie")) { //fixme : don't set any cookies in the proxied request, this needs a cleaner solution continue; } Enumeration values = hsRequest.getHeaders(headerName); while (values.hasMoreElements()) { String headerValue = (String) values.nextElement(); log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue); method.addRequestHeader(headerName, headerValue); } } } if (log.isInfoEnabled()) log.info("proxy query string " + method.getQueryString()); return method; }
From source file:org.ws4d.pipes.modules.http.Put.java
public void doWork() { // execute base module doWork() super.doWork(); /* wait for input */ final PortValue bodyV = getWiredOrConfiguredValue(PORT_BODY); final PortValue contentTypeV = getWiredOrConfiguredValue(PORT_CONTENTTYPE); // check if we can terminate if (canClose()) { closeAllPorts();// w ww . j a v a 2 s . co m return; } // if body is string if (bodyV.isString()) { try { body = bodyV.getString().getBytes("utf-8"); } catch (UnsupportedEncodingException e) { getLogger().log(Level.SEVERE, "Can't convert string", e); body = null; } } // if body is byte array if (bodyV.isByteArray()) { body = bodyV.getByteArray(); } // get content type if (contentTypeV.isString()) { contentType = contentTypeV.getString(); } if ((getUrl() != null) && (body != null)) { final PutMethod method = new PutMethod(getUrl()); try { method.setRequestEntity(new ByteArrayRequestEntity(body, contentType)); } catch (Exception e) { getLogger().log(Level.SEVERE, "Can't create request entity", e); return; } try { getClient().executeMethod(method); setOutData(BaseModule.PORT_STATUSCODE, method.getStatusCode()); setOutData(BaseModule.PORT_STATUSLINE, method.getStatusLine()); } catch (Exception e) { getLogger().log(Level.SEVERE, "Can't execute http put request", e); } finally { method.releaseConnection(); } } }
From source file:org.wso2.carbon.identity.scim.common.impl.ProvisioningClient.java
public void provisionUpdateUser() throws IdentitySCIMException { String userName = null;/* ww w . j a va 2 s .c o m*/ try { //get provider details String userEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USER_ENDPOINT); userName = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USERNAME); String password = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_PASSWORD); String contentType = provider.getProperty(SCIMConstants.CONTENT_TYPE_HEADER); if (contentType == null) { contentType = SCIMConstants.APPLICATION_JSON; } /*get the userId of the user being provisioned from the particular provider by filtering with user name*/ GetMethod getMethod = new GetMethod(userEPURL); //add filter query parameter getMethod.setQueryString(USER_FILTER + ((User) scimObject).getUserName()); //add authorization headers getMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER, BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password)); //create http client HttpClient httpFilterClient = new HttpClient(); //send the request int responseStatus = httpFilterClient.executeMethod(getMethod); String response = getMethod.getResponseBodyAsString(); if (logger.isDebugEnabled()) { logger.debug("SCIM - filter operation inside 'delete user' provisioning " + "returned with response code: " + responseStatus); logger.debug("Filter User Response: " + response); } SCIMClient scimClient = new SCIMClient(); if (scimClient.evaluateResponseStatus(responseStatus)) { //decode the response to extract the userId. ListedResource listedResource = scimClient.decodeSCIMResponseWithListedResource(response, SCIMConstants.identifyFormat(contentType), objectType); List<SCIMObject> users = listedResource.getScimObjects(); String userId = null; //we expect only one user in the list for (SCIMObject user : users) { userId = ((User) user).getId(); if (userId == null) { logger.error("Trying to update a user entry which doesn't support SCIM. " + "Usually internal carbon User entries such as admin role doesn't support SCIM attributes."); return; } } String url = userEPURL + "/" + userId; //now send the update request. PutMethod putMethod = new PutMethod(url); putMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER, BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password)); String encodedUser = scimClient.encodeSCIMObject((AbstractSCIMObject) scimObject, SCIMConstants.identifyFormat(contentType)); RequestEntity putRequestEntity = new StringRequestEntity(encodedUser, contentType, null); putMethod.setRequestEntity(putRequestEntity); HttpClient httpUpdateClient = new HttpClient(); int updateResponseStatus = httpUpdateClient.executeMethod(putMethod); String updateResponse = putMethod.getResponseBodyAsString(); logger.info("SCIM - update user operation returned with response code: " + updateResponseStatus); if (!scimClient.evaluateResponseStatus(updateResponseStatus)) { //decode scim exception and extract the specific error message. AbstractCharonException exception = scimClient.decodeSCIMException(updateResponse, SCIMConstants.identifyFormat(contentType)); logger.error(exception.getDescription()); } } else { //decode scim exception and extract the specific error message. AbstractCharonException exception = scimClient.decodeSCIMException(response, SCIMConstants.identifyFormat(contentType)); logger.error(exception.getDescription()); } } catch (CharonException e) { throw new IdentitySCIMException("Error in provisioning 'update user' operation for user :" + userName); } catch (HttpException e) { throw new IdentitySCIMException("Error in provisioning 'update user' operation for user :" + userName); } catch (IOException e) { throw new IdentitySCIMException("Error in provisioning 'update user' operation for user :" + userName); } catch (BadRequestException e) { throw new IdentitySCIMException("Error in provisioning 'update user' operation for user :" + userName); } }
From source file:org.wso2.carbon.identity.scim.common.impl.ProvisioningClient.java
public void provisionUpdateGroup() throws IdentitySCIMException { String userName = null;//w w w. j a va2 s. co m try { //get provider details String groupEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_GROUP_ENDPOINT); String userEPURL = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USER_ENDPOINT); userName = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_USERNAME); String password = provider.getProperty(SCIMConfigConstants.ELEMENT_NAME_PASSWORD); String contentType = provider.getProperty(SCIMConstants.CONTENT_TYPE_HEADER); if (contentType == null) { contentType = SCIMConstants.APPLICATION_JSON; } /*get the groupId of the group being provisioned from the particular provider by filtering with display name*/ GetMethod getMethod = new GetMethod(groupEPURL); //add filter query parameter //check if role name is updated if (additionalProvisioningInformation != null && (Boolean) additionalProvisioningInformation .get(SCIMCommonConstants.IS_ROLE_NAME_CHANGED_ON_UPDATE)) { getMethod.setQueryString( GROUP_FILTER + additionalProvisioningInformation.get(SCIMCommonConstants.OLD_GROUP_NAME)); } else { getMethod.setQueryString(GROUP_FILTER + ((Group) scimObject).getDisplayName()); } //add authorization headers getMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER, BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password)); //create http client HttpClient httpFilterClient = new HttpClient(); //send the request int responseStatus = httpFilterClient.executeMethod(getMethod); String response = getMethod.getResponseBodyAsString(); if (logger.isDebugEnabled()) { logger.debug("SCIM - filter operation inside 'update group' provisioning " + "returned with response code: " + responseStatus); logger.debug("Filter Group Response: " + response); } SCIMClient scimClient = new SCIMClient(); if (scimClient.evaluateResponseStatus(responseStatus)) { //decode the response to extract the groupId. ListedResource listedResource = scimClient.decodeSCIMResponseWithListedResource(response, SCIMConstants.identifyFormat(contentType), objectType); List<SCIMObject> groups = listedResource.getScimObjects(); String groupId = null; //we expect only one user in the list for (SCIMObject group : groups) { groupId = ((Group) group).getId(); } String url = groupEPURL + "/" + groupId; //now start sending the update request. //get list of users in the group, if any, by userNames List<String> users = ((Group) scimObject).getMembersWithDisplayName(); Group copiedGroup = null; if (CollectionUtils.isNotEmpty(users)) { //create a deep copy of the group since we are going to update the member ids copiedGroup = (Group) CopyUtil.deepCopy(scimObject); //delete existing members in the group since we are going to update it with copiedGroup.deleteAttribute(SCIMConstants.GroupSchemaConstants.MEMBERS); //create http client HttpClient httpFilterUserClient = new HttpClient(); //create get method for filtering GetMethod getUserMethod = new GetMethod(userEPURL); getUserMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER, BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password)); //get corresponding userIds for (String user : users) { String filter = USER_FILTER + user; getUserMethod.setQueryString(filter); int responseCode = httpFilterUserClient.executeMethod(getUserMethod); String filterUserResponse = getUserMethod.getResponseBodyAsString(); if (logger.isDebugEnabled()) { logger.debug("SCIM - 'filter user' operation inside 'update group' provisioning " + "returned with response code: " + responseCode); logger.debug("Filter User Response: " + filterUserResponse); } //check for success of the response if (scimClient.evaluateResponseStatus(responseCode)) { ListedResource listedUserResource = scimClient.decodeSCIMResponseWithListedResource( filterUserResponse, SCIMConstants.identifyFormat(contentType), SCIMConstants.USER_INT); List<SCIMObject> filteredUsers = listedUserResource.getScimObjects(); String userId = null; for (SCIMObject filteredUser : filteredUsers) { //we expect only one result here userId = ((User) filteredUser).getId(); } copiedGroup.setGroupMember(userId, user); } else { //decode scim exception and extract the specific error message. AbstractCharonException exception = scimClient.decodeSCIMException(filterUserResponse, SCIMConstants.identifyFormat(contentType)); logger.error(exception.getDescription()); } } } //now send the update request. PutMethod putMethod = new PutMethod(url); putMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER, BasicAuthUtil.getBase64EncodedBasicAuthHeader(userName, password)); String encodedGroup = scimClient.encodeSCIMObject((AbstractSCIMObject) scimObject, SCIMConstants.identifyFormat(contentType)); RequestEntity putRequestEntity = new StringRequestEntity(encodedGroup, contentType, null); putMethod.setRequestEntity(putRequestEntity); HttpClient httpUpdateClient = new HttpClient(); int updateResponseStatus = httpUpdateClient.executeMethod(putMethod); String updateResponse = putMethod.getResponseBodyAsString(); logger.info("SCIM - update group operation returned with response code: " + updateResponseStatus); if (!scimClient.evaluateResponseStatus(updateResponseStatus)) { //decode scim exception and extract the specific error message. AbstractCharonException exception = scimClient.decodeSCIMException(updateResponse, SCIMConstants.identifyFormat(contentType)); logger.error(exception.getDescription()); } } else { //decode scim exception and extract the specific error message. AbstractCharonException exception = scimClient.decodeSCIMException(response, SCIMConstants.identifyFormat(contentType)); logger.error(exception.getDescription()); } } catch (CharonException | IOException | BadRequestException e) { throw new IdentitySCIMException("Error in provisioning 'delete group' operation for user :" + userName, e); } }
From source file:org.wso2.carbon.oc.agent.publisher.rt.RTPublisher.java
/** * @param url String - operations center url * @param request String - json string request message * @param expected int - expected http status code * @return String - response json string * @throws IOException - sever connect problem *///from w w w.j av a 2 s . c o m public String sendPutRequest(String url, String request, int expected) throws IOException { PutMethod putMethod = new PutMethod(url); try { RequestEntity entity = new StringRequestEntity(request, CONTENT_TYPE, CHARACTER_SET); putMethod.setRequestEntity(entity); if (logger.isTraceEnabled()) { logger.trace("Sending PUT request. " + request); } int statusCode = httpClient.executeMethod(putMethod); if (statusCode == expected) { String responseBody = putMethod.getResponseBodyAsString(); if (logger.isTraceEnabled()) { logger.trace("Response received. " + responseBody); } return responseBody; } else { logger.debug("Request failed with status Code : " + statusCode); throw new IOException(); } } catch (UnsupportedEncodingException e) { if (logger.isDebugEnabled()) { logger.error("Failed to sync data with Operations Center", e); } } finally { putMethod.releaseConnection(); } return null; }
From source file:org.wso2.iot.integration.common.IOTHttpClient.java
public IOTResponse put(String endpoint, String body) { HttpClient client = new HttpClient(); try {//w w w.ja va 2 s . c om ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory(); Protocol https = new Protocol(Constants.HTTPS, socketFactory, Constants.HTTPS_GATEWAY_PORT); Protocol.registerProtocol(Constants.HTTPS, https); String url = backEndUrl + endpoint; PutMethod method = new PutMethod(url); method.setRequestHeader(AUTHORIZATION, authorizationString); StringRequestEntity requestEntity = new StringRequestEntity(body, requestHeaders.get(Constants.CONTENT_TYPE), Constants.UTF8); method.setRequestEntity(requestEntity); IOTResponse iotResponse = new IOTResponse(); iotResponse.setStatus(client.executeMethod(method)); iotResponse.setBody(method.getResponseBodyAsString()); return iotResponse; } catch (GeneralSecurityException e) { log.error("Failure occurred at IOTResponse put for GeneralSecurityException", e); } catch (IOException e) { log.error("Failure occurred at IOTResponse put for IO Exception", e); } return null; }
From source file:org.wso2.mdm.integration.common.MDMHttpClient.java
public MDMResponse put(String endpoint, String body) { HttpClient client = new HttpClient(); try {/*w ww .j av a 2 s .c om*/ ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory(); Protocol https = new Protocol("https", socketFactory, 9443); Protocol.registerProtocol("https", https); String url = backEndUrl + endpoint; PutMethod method = new PutMethod(url); method.setRequestHeader(AUTHORIZATION, authrizationString); StringRequestEntity requestEntity = new StringRequestEntity(body, requestHeaders.get(Constants.CONTENT_TYPE), Constants.UTF8); method.setRequestEntity(requestEntity); MDMResponse mdmResponse = new MDMResponse(); mdmResponse.setStatus(client.executeMethod(method)); mdmResponse.setBody(method.getResponseBodyAsString()); return mdmResponse; } catch (GeneralSecurityException e) { log.error("Failure occurred at MDMResponse put for GeneralSecurityException", e); } catch (IOException e) { log.error("Failure occurred at MDMResponse put for IO Exception", e); } return null; }
From source file:org.wso2.scim.sample.group.UpdateGroup.java
public static void main(String[] args) { try {/*from w w w . j a va 2 s. co m*/ //load sample configuration SCIMSamplesUtils.loadConfiguration(); //set the keystore SCIMSamplesUtils.setKeyStore(); //create SCIM client SCIMClient scimClient = new SCIMClient(); //create a user according to SCIM User Schema Group scimGroup = scimClient.createGroup(); //scimGroup.setExternalId(SCIMSamplesUtils.groupDisplayNameToCreateGroup); scimGroup.setDisplayName(SCIMSamplesUtils.updatedGroupDisplayName); //encode the user in JSON format String encodedGroup = scimClient.encodeSCIMObject(scimGroup, SCIMConstants.JSON); String groupId = getSCIMIdOfGroup(SCIMSamplesUtils.groupDisplayNameToCreateGroup); System.out.println(""); System.out.println(""); System.out.println("/******Updated Group in json format: " + encodedGroup + "******/"); System.out.println(""); String url = SCIMSamplesUtils.groupEndpointURL + "/" + groupId; //now send the update request. PutMethod putMethod = new PutMethod(url); //add authorization header String authHeader = SCIMSamplesUtils.getAuthorizationHeader(); putMethod.addRequestHeader(SCIMConstants.AUTHORIZATION_HEADER, authHeader); RequestEntity putRequestEntity = new StringRequestEntity(encodedGroup, SCIMSamplesUtils.CONTENT_TYPE, null); putMethod.setRequestEntity(putRequestEntity); HttpClient httpUpdateClient = new HttpClient(); int updateResponseStatus = httpUpdateClient.executeMethod(putMethod); String updateResponse = putMethod.getResponseBodyAsString(); System.out.println(""); System.out.println(""); System.out.println("/******SCIM group update response status: " + updateResponseStatus); System.out.println("SCIM group update response data: " + updateResponse + "******/"); System.out.println(""); } catch (CharonException e) { e.printStackTrace(); } catch (HttpException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }