org.apache.commons.httpclient.methods.PostMethod Java Examples

The following examples show how to use org.apache.commons.httpclient.methods.PostMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReplaceJSONPayloadTestcase.java    From micro-integrator with Apache License 2.0 8 votes vote down vote up
private String httpClient(String proxyLocation, String xml) {
    try {
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(proxyLocation);

        post.setRequestEntity(new StringRequestEntity(xml));
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        post.setRequestHeader("SOAPAction", "urn:mediate");
        httpclient.executeMethod(post);

        InputStream in = post.getResponseBodyAsStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
            buffer.append("\n");
        }
        reader.close();
        return buffer.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: RestClient.java    From maven-framework-project with MIT License 7 votes vote down vote up
public Book getBook(String bookName) throws Exception {

        String output = null;
        try{
            String url = "http://localhost:8080/bookservice/getbook/";

            url = url + URLEncoder.encode(bookName, "UTF-8");

            HttpClient client = new HttpClient();
            PostMethod mPost = new PostMethod(url);
            client.executeMethod( mPost );
            Header mtHeader = new Header();
            mtHeader.setName("content-type");
            mtHeader.setValue("application/x-www-form-urlencoded");
            mtHeader.setName("accept");
            mtHeader.setValue("application/xml");
            mPost.addRequestHeader(mtHeader);
            client.executeMethod(mPost);
            output = mPost.getResponseBodyAsString( );
            mPost.releaseConnection( );
            System.out.println("out : " + output);
        }catch(Exception e){
            throw new Exception("Exception in retriving group page info : " + e);
        }
        return null;
    }
 
Example #3
Source File: RemoteConnectorRequestImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected static HttpMethodBase buildHttpClientMethod(String url, String method)
{
    if ("GET".equals(method))
    {
        return new GetMethod(url);
    }
    if ("POST".equals(method))
    {
        return new PostMethod(url);
    }
    if ("PUT".equals(method))
    {
        return new PutMethod(url);
    }
    if ("DELETE".equals(method))
    {
        return new DeleteMethod(url);
    }
    if (TestingMethod.METHOD_NAME.equals(method))
    {
        return new TestingMethod(url);
    }
    throw new UnsupportedOperationException("Method '"+method+"' not supported");
}
 
Example #4
Source File: PropertyIntegrationForceSCAcceptedPropertyTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Testing functionality of FORCE_SC_ACCEPTED " + "- Enabled False")
public void testFORCE_SC_ACCEPTEDPropertyEnabledFalseScenario() throws Exception {
    int responseStatus = 0;

    String strXMLFilename =
            FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "ESB" + File.separator
                    + "mediatorconfig" + File.separator + "property" + File.separator + "GetQuoteRequest.xml";

    File input = new File(strXMLFilename);
    PostMethod post = new PostMethod(getProxyServiceURLHttp("FORCE_SC_ACCEPTED_FalseTestProxy"));
    RequestEntity entity = new FileRequestEntity(input, "text/xml");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "getQuote");

    HttpClient httpclient = new HttpClient();

    try {
        responseStatus = httpclient.executeMethod(post);
    } finally {
        post.releaseConnection();
    }

    assertEquals(responseStatus, 200, "Response status should be 200");

}
 
Example #5
Source File: PropertyIntegrationForceSCAcceptedPropertyTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Testing functionality of FORCE_SC_ACCEPTED " + "Enabled True  - "
        + "Client should receive 202 message", dependsOnMethods = "testFORCE_SC_ACCEPTEDPropertyEnabledFalseScenario")
public void testWithFORCE_SC_ACCEPTEDPropertyEnabledTrueScenario() throws Exception {
    int responseStatus = 0;

    String strXMLFilename =
            FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "ESB" + File.separator
                    + "mediatorconfig" + File.separator + "property" + File.separator + "PlaceOrder.xml";

    File input = new File(strXMLFilename);
    PostMethod post = new PostMethod(getProxyServiceURLHttp("FORCE_SC_ACCEPTED_TrueTestProxy"));
    RequestEntity entity = new FileRequestEntity(input, "text/xml");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "placeOrder");

    HttpClient httpclient = new HttpClient();

    try {
        responseStatus = httpclient.executeMethod(post);
    } finally {
        post.releaseConnection();
    }

    assertEquals(responseStatus, 202, "Response status should be 202");
}
 
Example #6
Source File: HttpSOAPClient.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Processes a SOAP fault, as determined by an HTTP 500 status code, response.
 * 
 * @param httpMethod the HTTP method used to send the request and receive the response
 * @param messageContext current messages context
 * 
 * @throws SOAPClientException thrown if the response can not be read from the {@link PostMethod}
 * @throws SOAPFaultException an exception containing the SOAP fault
 */
protected void processFaultResponse(PostMethod httpMethod, SOAPMessageContext messageContext)
        throws SOAPClientException, SOAPFaultException {
    try {
        Envelope response = unmarshallResponse(httpMethod.getResponseBodyAsStream());
        messageContext.setInboundMessage(response);

        List<XMLObject> faults = response.getBody().getUnknownXMLObjects(Fault.DEFAULT_ELEMENT_NAME);
        if (faults.size() < 1) {
            throw new SOAPClientException("HTTP status code was 500 but SOAP response did not contain a Fault");
        }
        Fault fault = (Fault) faults.get(0);

        log.debug("SOAP fault code {} with message {}", fault.getCode().getValue(), fault.getMessage().getValue());
        SOAPFaultException faultException = new SOAPFaultException("SOAP Fault: " + fault.getCode().getValue()
                + " Fault Message: " + fault.getMessage().getValue());
        faultException.setFault(fault);
        throw faultException;
    } catch (IOException e) {
        throw new SOAPClientException("Unable to read response", e);
    }
}
 
Example #7
Source File: HeliumRestApiTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testVisualizationPackageOrder() throws IOException {
  GetMethod get1 = httpGet("/helium/order/visualization");
  assertThat(get1, isAllowed());
  Map<String, Object> resp1 = gson.fromJson(get1.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() { }.getType());
  List<Object> body1 = (List<Object>) resp1.get("body");
  assertEquals(body1.size(), 0);

  //We assume allPackages list has been refreshed before sorting
  helium.getAllPackageInfo();

  String postRequestJson = "[name2, name1]";
  PostMethod post = httpPost("/helium/order/visualization", postRequestJson);
  assertThat(post, isAllowed());
  post.releaseConnection();

  GetMethod get2 = httpGet("/helium/order/visualization");
  assertThat(get2, isAllowed());
  Map<String, Object> resp2 = gson.fromJson(get2.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() { }.getType());
  List<Object> body2 = (List<Object>) resp2.get("body");
  assertEquals(body2.size(), 2);
  assertEquals(body2.get(0), "name2");
  assertEquals(body2.get(1), "name1");
}
 
Example #8
Source File: RestUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static HttpMethodBase getMethod(HttpMethod method, String address) {
	String addr = address;
	if (method.equals(HttpMethod.Delete)) {
		return new DeleteMethod(addr);
	}
	if (method.equals(HttpMethod.Post)) {
		return new PostMethod(addr);
	}
	if (method.equals(HttpMethod.Get)) {
		return new GetMethod(addr);
	}
	if (method.equals(HttpMethod.Put)) {
		return new PutMethod(addr);
	}
	Assert.assertUnreachable("method doesn't exist");
	return null;
}
 
Example #9
Source File: VmRuntimeJettyKitchenSink2Test.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Test that blob upload requests are intercepted by the blob upload filter.
 *
 * @throws Exception
 */
public void testBlobUpload() throws Exception {
  String postData = "--==boundary\r\n" + "Content-Type: message/external-body; "
          + "charset=ISO-8859-1; blob-key=\"blobkey:blob-0\"\r\n" + "Content-Disposition: form-data; "
          + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "Content-Type: image/jpeg\r\n"
          + "Content-Length: 1024\r\n" + "X-AppEngine-Upload-Creation: 2009-04-30 17:12:51.675929\r\n"
          + "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n"
          + "\r\n" + "--==boundary\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n"
          + "Content-Disposition: form-data; name=text1\r\n" + "Content-Length: 10\r\n" + "\r\n"
          + "Testing.\r\n" + "\r\n" + "\r\n" + "--==boundary--";

  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  PostMethod blobPost = new PostMethod(createUrl("/upload-blob").toString());
  blobPost.addRequestHeader("Content-Type", "multipart/form-data; boundary=\"==boundary\"");
  blobPost.addRequestHeader("X-AppEngine-BlobUpload", "true");
  blobPost.setRequestBody(postData);
  int httpCode = httpClient.executeMethod(blobPost);

  assertEquals(302, httpCode);
  Header redirUrl = blobPost.getResponseHeader("Location");
  assertEquals("http://" + getServerHost() + "/serve-blob?key=blobkey:blob-0",
          redirUrl.getValue());
}
 
Example #10
Source File: ChatterCommands.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <p>This creates a HttpMethod with the message as its payload and image attachment. The message should be a properly formatted JSON
 * String (No validation is done on this).</p>
 *
 * <p>The message can be easily created using the {@link #getJsonPayload(Message)} method.</p>
 *
 * @param uri The full URI which we will post to
 * @param message A properly formatted JSON message. UTF-8 is expected
 * @param image A complete instance of ImageAttachment object
 * @throws IOException
 */
public HttpMethod getJsonPostForMultipartRequestEntity(String uri, String message, ImageAttachment image) throws IOException {
    PostMethod post = new PostMethod(uri);

    StringPart bodyPart = new StringPart("json", message);
    bodyPart.setContentType("application/json");

    FilePart filePart= new FilePart("feedItemFileUpload", image.retrieveObjectFile());
    filePart.setContentType(image.retrieveContentType());

    Part[] parts = {
            bodyPart,
            filePart,
    };

    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    return post;
}
 
Example #11
Source File: BusinessJob.java    From http4e with Apache License 2.0 6 votes vote down vote up
private void addParams( PostMethod postMethod, Map<String, String> parameterizedMap){
   for (Iterator it = model.getParameters().entrySet().iterator(); it.hasNext();) {
      Map.Entry me = (Map.Entry) it.next();
      String key = (String) me.getKey();
      List values = (List) me.getValue();
      StringBuilder sb = new StringBuilder();
      int cnt = 0;
      for (Iterator it2 = values.iterator(); it2.hasNext();) {
         String val = (String) it2.next();
         if (cnt != 0) {
            sb.append(",");
         }
         sb.append(val);
         cnt++;
      }

      String parameterizedVal = ParseUtils.getParametizedArg(sb.toString(), parameterizedMap);
      postMethod.setParameter(key, parameterizedVal);
   }
}
 
Example #12
Source File: OAuth2Client.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public String getAccessToken(String username, String password) {
	logger.debug("IN");
	try {
		PostMethod httppost = createPostMethodForAccessToken();
		httppost.setParameter("grant_type", "password");
		httppost.setParameter("username", username);
		httppost.setParameter("password", password);
		httppost.setParameter("client_id", config.getProperty("CLIENT_ID"));

		return sendHttpPost(httppost);
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("Error while trying to get access token from OAuth2 provider", e);
	} finally {
		logger.debug("OUT");
	}
}
 
Example #13
Source File: HttpUtils.java    From Java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 设置请求参数
 * @param method
 * @param params
 */
private static void setParams(PostMethod method,Map<String, String> params) {

	//校验参数
	if(params==null||params.size()==0){
		return;
	}
	
	Set<String> paramsKeys = params.keySet();
	Iterator<String> iterParams = paramsKeys.iterator();
	while(iterParams.hasNext()){
		String key = iterParams.next();
		method.addParameter(key, params.get(key));
	}
	
}
 
Example #14
Source File: HttpUtil.java    From OfficeAutomatic-System with Apache License 2.0 6 votes vote down vote up
public static String sendPost(String urlParam) throws HttpException, IOException {
    // 创建httpClient实例对象
    HttpClient httpClient = new HttpClient();
    // 设置httpClient连接主机服务器超时时间:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建post请求方法实例对象
    PostMethod postMethod = new PostMethod(urlParam);
    // 设置post请求超时时间
    postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    postMethod.addRequestHeader("Content-Type", "application/json");

    httpClient.executeMethod(postMethod);

    String result = postMethod.getResponseBodyAsString();
    postMethod.releaseConnection();
    return result;
}
 
Example #15
Source File: CatalogITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateCatalogEntryQuery() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry2.getKey().toString()).build();
    final PostMethod method = createPost(uri, MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("name", "Entry-2-b"), new NameValuePair("description", "Entry-description-2-b"),
            new NameValuePair("type", String.valueOf(CatalogEntry.TYPE_NODE)) });

    final int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final CatalogEntryVO vo = parse(body, CatalogEntryVO.class);
    assertNotNull(vo);

    final CatalogEntry updatedEntry = catalogService.loadCatalogEntry(entry2);
    assertEquals("Entry-2-b", updatedEntry.getName());
    assertEquals("Entry-description-2-b", updatedEntry.getDescription());
}
 
Example #16
Source File: AbstractTest4.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
public static void callAPI(String url, String user, String uToken) throws HttpException, IOException {
	if(url.indexOf("?") < 0) {
		url += "?uName=" +user+ "&uToken=" + uToken;
	}
	else {
		url += "&uName=" +user+ "&uToken=" + uToken;
	}
	PostMethod postMethod = new PostMethod(url);
	postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

    // 最后生成一个HttpClient对象,并发出postMethod请求
    HttpClient httpClient = new HttpClient();
    int statusCode = httpClient.executeMethod(postMethod);
    if(statusCode == 200) {
        System.out.print("返回结果: ");
        String soapResponseData = postMethod.getResponseBodyAsString();
        System.out.println(soapResponseData);     
    }
    else {
        System.out.println("调用失败!错误码:" + statusCode);
    }
}
 
Example #17
Source File: RestClient.java    From maven-framework-project with MIT License 6 votes vote down vote up
public void addBook(String bookName, String author) throws Exception {

        String output = null;
        try{
            String url = "http://localhost:8080/bookservice/addbook";
            HttpClient client = new HttpClient();
            PostMethod mPost = new PostMethod(url);
            mPost.addParameter("name", "Naked Sun");
            mPost.addParameter("author", "Issac Asimov");
            Header mtHeader = new Header();
            mtHeader.setName("content-type");
            mtHeader.setValue("application/x-www-form-urlencoded");
            mtHeader.setName("accept");
            mtHeader.setValue("application/xml");
            //mtHeader.setValue("application/json");
            mPost.addRequestHeader(mtHeader);
            client.executeMethod(mPost);
            output = mPost.getResponseBodyAsString( );
            mPost.releaseConnection( );
            System.out.println("output : " + output);
        }catch(Exception e){
            throw new Exception("Exception in adding bucket : " + e);
        }

    }
 
Example #18
Source File: RefreshTokenAuthenticationTest.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(expected = UnauthenticatedSessionException.class)
public void testBadResponseCode() throws HttpException, IOException, UnauthenticatedSessionException,
    AuthenticationException {
    IChatterData data = getMockedChatterData();

    RefreshTokenAuthentication auth = new RefreshTokenAuthentication(data);

    HttpClient mockHttpClient = mock(HttpClient.class);
    when(mockHttpClient.executeMethod(any(PostMethod.class))).thenAnswer(
        new ExecuteMethodAnswer("400 Bad Request", HttpStatus.SC_BAD_REQUEST));

    auth.setHttpClient(mockHttpClient);

    auth.authenticate();
    fail();
}
 
Example #19
Source File: OldHttpClientApi.java    From javabase with Apache License 2.0 6 votes vote down vote up
public void  post(){
    String requesturl = "http://www.tuling123.com/openapi/api";
    PostMethod postMethod = new PostMethod(requesturl);
    String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0";
    String INFO ="北京时间";
    NameValuePair nvp1=new NameValuePair("key",APIKEY);
    NameValuePair nvp2=new NameValuePair("info",INFO);
    NameValuePair[] data = new NameValuePair[2];
    data[0]=nvp1;
    data[1]=nvp2;

    postMethod.setRequestBody(data);
    postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
    try {
        byte[] responseBody = executeMethod(postMethod,10000);
        String content=new String(responseBody ,"utf-8");
        log.info(content);
    }catch (Exception e){
       log.error(""+e.getLocalizedMessage());
    }finally {
        postMethod.releaseConnection();
    }
}
 
Example #20
Source File: PublicApiHttpClient.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId,
            final String relationCollectionName, final Object relationshipEntityId, final String body, String contentType, final Map<String, String> params) throws IOException
{
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName,
                relationshipEntityId, params);
    String url = endpoint.getUrl();

    PostMethod req = new PostMethod(url.toString());
    if (body != null)
    {
        if (contentType == null || contentType.isEmpty())
        {
            contentType = "application/json";
        }
        StringRequestEntity requestEntity = new StringRequestEntity(body, contentType, "UTF-8");
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}
 
Example #21
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Test create target.
 * 
 * @throws Exception
 */
public void testSuccessfulVerifyTargetOverHttp() throws Exception
{
    //Stub HttpClient so that executeMethod returns a 200 response
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(200);
    
    //Call verifyTarget
    transmitter.verifyTarget(target);
    
    ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
    ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
    ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
    
    verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
    
    assertTrue("post method", httpMethod.getValue() instanceof PostMethod);
    assertEquals("host name", TARGET_HOST, hostConfig.getValue().getHost());
    assertEquals("port", HTTP_PORT, hostConfig.getValue().getPort());
    assertEquals("protocol", HTTP_PROTOCOL.toLowerCase(), 
            hostConfig.getValue().getProtocol().getScheme().toLowerCase());
    assertEquals("path", TRANSFER_SERVICE_PATH + "/test", httpMethod.getValue().getPath());
}
 
Example #22
Source File: BigSwitchBcfApi.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
protected HttpMethod createMethod(final String type, final String uri, final int port) throws BigSwitchBcfApiException {
    String url;
    try {
        url = new URL(S_PROTOCOL, host, port, uri).toString();
    } catch (MalformedURLException e) {
        S_LOGGER.error("Unable to build Big Switch API URL", e);
        throw new BigSwitchBcfApiException("Unable to build Big Switch API URL", e);
    }

    if ("post".equalsIgnoreCase(type)) {
        return new PostMethod(url);
    } else if ("get".equalsIgnoreCase(type)) {
        return new GetMethod(url);
    } else if ("delete".equalsIgnoreCase(type)) {
        return new DeleteMethod(url);
    } else if ("put".equalsIgnoreCase(type)) {
        return new PutMethod(url);
    } else {
        throw new BigSwitchBcfApiException("Requesting unknown method type");
    }
}
 
Example #23
Source File: PropertyIntegrationHTTP_SCTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Getting HTTP status code number ")
public void testHttpResponseCode() throws Exception {

    int responseStatus = 0;

    String strXMLFilename = FrameworkPathUtil.getSystemResourceLocation() + "artifacts"
                            + File.separator + "ESB" + File.separator + "mediatorconfig" +
                            File.separator + "property" + File.separator + "GetQuoteRequest.xml";

    File input = new File(strXMLFilename);
    PostMethod post = new PostMethod(getProxyServiceURLHttp("HTTP_SCTestProxy"));
    RequestEntity entity = new FileRequestEntity(input, "text/xml");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "getQuote");

    HttpClient httpclient = new HttpClient();

    try {
        responseStatus = httpclient.executeMethod(post);
    } finally {
        post.releaseConnection();
    }

    assertEquals(responseStatus, 404, "Response status should be 404");
}
 
Example #24
Source File: ESBJAVA2615TestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private String httpClient(String proxyLocation, String xml) {
    try {
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(proxyLocation);

        post.setRequestEntity(new StringRequestEntity(xml));
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        post.setRequestHeader("SOAPAction", "urn:mediate");
        httpclient.executeMethod(post);

        InputStream in = post.getResponseBodyAsStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
            buffer.append("\n");
        }
        reader.close();
        return buffer.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
Source File: CourseGroupMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateCourseGroup() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GroupVO vo = new GroupVO();
    vo.setKey(g1.getKey());
    vo.setName("rest-g1-mod");
    vo.setDescription("rest-g1 description");
    vo.setMinParticipants(g1.getMinParticipants());
    vo.setMaxParticipants(g1.getMaxParticipants());
    vo.setType(g1.getType());

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/repo/courses/" + course.getResourceableId() + "/groups/" + g1.getKey();
    final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);
    method.releaseConnection();
    assertTrue(code == 200 || code == 201);

    final BusinessGroup bg = businessGroupService.loadBusinessGroup(g1.getKey(), false);
    assertNotNull(bg);
    assertEquals(bg.getKey(), vo.getKey());
    assertEquals("rest-g1-mod", bg.getName());
    assertEquals("rest-g1 description", bg.getDescription());
}
 
Example #26
Source File: CrucibleSessionImpl.java    From Crucible4IDEA with MIT License 5 votes vote down vote up
@Override
public void completeReview(@NotNull String reviewId) {
  final String url = getHostUrl() + REVIEW_SERVICE + "/" + reviewId + COMPLETE;
  try {
    final PostMethod method = new PostMethod(url);
    executeHttpMethod(method);
  }
  catch (IOException e) {
    LOG.warn(e.getMessage());
  }
}
 
Example #27
Source File: CreateRouteCommand.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected ServerStatus _doIt() {
	try {
		/* create cloud foundry application */
		URI targetURI = URIUtil.toURI(target.getUrl());
		URI routesURI = targetURI.resolve("/v2/routes"); //$NON-NLS-1$

		PostMethod createRouteMethod = new PostMethod(routesURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(createRouteMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;

		/* set request body */
		JSONObject routeRequest = new JSONObject();
		routeRequest.put(CFProtocolConstants.V2_KEY_SPACE_GUID, target.getSpace().getCFJSON().getJSONObject(CFProtocolConstants.V2_KEY_METADATA).getString(CFProtocolConstants.V2_KEY_GUID));
		routeRequest.put(CFProtocolConstants.V2_KEY_HOST, hostName);
		routeRequest.put(CFProtocolConstants.V2_KEY_DOMAIN_GUID, domain.getGuid());
		createRouteMethod.setRequestEntity(new StringRequestEntity(routeRequest.toString(), "application/json", "utf-8")); //$NON-NLS-1$//$NON-NLS-2$
		createRouteMethod.setQueryString("inline-relations-depth=1"); //$NON-NLS-1$

		ServerStatus createRouteStatus = HttpUtil.executeMethod(createRouteMethod);
		if (!createRouteStatus.isOK())
			return createRouteStatus;

		route = new Route().setCFJSON(createRouteStatus.getJsonData());

		return createRouteStatus;
	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
		logger.error(msg, e);
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
	}
}
 
Example #28
Source File: CSP.java    From scim2-compliance-test-suite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public String getAccessToken() {
    if (this.oAuth2AccessToken != null) {
        return this.oAuth2AccessToken;
    }

    try {
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(this.getUsername(), this.getPassword());
        client.getState().setCredentials(AuthScope.ANY, defaultcreds);

        PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
        method.setRequestBody("grant_type=client_credentials");
        int responseCode = client.executeMethod(method);
        if (responseCode != 200) {

            throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
                    + ", got response code " + responseCode);
        }
        String responseBody = method.getResponseBodyAsString();
        JSONObject accessResponse = new JSONObject(responseBody);
        accessResponse.getString("access_token");
        return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
    } catch (Exception e) {
        throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
    }
}
 
Example #29
Source File: ErrorReportSender.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
protected void addHttpPostParams(Map<String, String> values, PostMethod method) {
  for (String key : values.keySet()) {
    String parameterValue = values.get(key);
    parameterValue = parameterValue != null ? parameterValue : NULL;
    method.setParameter(key, parameterValue);
  }
}
 
Example #30
Source File: OAuth2Client.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getAccessToken(String code) {
	logger.debug("IN");
	try {
		PostMethod httppost = createPostMethodForAccessToken();
		httppost.setParameter("grant_type", "authorization_code");
		httppost.setParameter("code", code);
		httppost.setParameter("redirect_uri", config.getProperty("REDIRECT_URI"));

		return sendHttpPost(httppost);
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("Error while trying to get access token from OAuth2 provider", e);
	} finally {
		logger.debug("OUT");
	}
}