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

The following examples show how to use org.apache.commons.httpclient.methods.StringRequestEntity. 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: SolrWaveIndexerImpl.java    From swellrt with Apache License 2.0 7 votes vote down vote up
private void postUpdateToSolr(ReadableWaveletData wavelet, JsonArray docsJson) {
  PostMethod postMethod =
      new PostMethod(solrBaseUrl + "/update/json?commit=true");
  try {
    RequestEntity requestEntity =
        new StringRequestEntity(docsJson.toString(), "application/json", "UTF-8");
    postMethod.setRequestEntity(requestEntity);

    HttpClient httpClient = new HttpClient();
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
      throw new IndexException(wavelet.getWaveId().serialise());
    }
  } catch (IOException e) {
    throw new IndexException(String.valueOf(wavelet.getWaveletId()), e);
  } finally {
    postMethod.releaseConnection();
  }
}
 
Example #3
Source File: GroupMgmtITCase.java    From olat with Apache License 2.0 6 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 = "/groups/" + g1.getKey();
    final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final BusinessGroup bg = businessGroupService.loadBusinessGroup(g1.getKey(), false);
    assertNotNull(bg);
    assertEquals(bg.getKey(), vo.getKey());
    assertEquals(bg.getName(), "rest-g1-mod");
    assertEquals(bg.getDescription(), "rest-g1 description");
}
 
Example #4
Source File: BigSwitchBcfApi.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
protected <T> String executeUpdateObject(final T newObject, final String uri,
        final Map<String, String> parameters) throws BigSwitchBcfApiException,
IllegalArgumentException{
    checkInvariants();

    PutMethod pm = (PutMethod)createMethod("put", uri, _port);

    setHttpHeader(pm);

    try {
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null));
    } catch (UnsupportedEncodingException e) {
        throw new BigSwitchBcfApiException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    String hash = checkResponse(pm, "BigSwitch HTTP update failed: ");

    pm.releaseConnection();

    return hash;
}
 
Example #5
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 #6
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message")
public void sendingHTTP11Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched");
}
 
Example #7
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 #8
Source File: SolrWaveIndexerImpl.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
private void postUpdateToSolr(ReadableWaveletData wavelet, JsonArray docsJson) {
  PostMethod postMethod =
      new PostMethod(solrBaseUrl + "/update/json?commit=true");
  try {
    RequestEntity requestEntity =
        new StringRequestEntity(docsJson.toString(), "application/json", "UTF-8");
    postMethod.setRequestEntity(requestEntity);

    HttpClient httpClient = new HttpClient();
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
      throw new IndexException(wavelet.getWaveId().serialise());
    }
  } catch (IOException e) {
    throw new IndexException(String.valueOf(wavelet.getWaveletId()), e);
  } finally {
    postMethod.releaseConnection();
  }
}
 
Example #9
Source File: TestRailClient.java    From testrail-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
private TestRailResponse httpPostInt(String path, String payload)
        throws UnsupportedEncodingException, IOException, HTTPException {
    TestRailResponse result;
    PostMethod post = new PostMethod(host + "/" + path);
    HttpClient httpclient = setUpHttpClient(post);

    try {
        StringRequestEntity requestEntity = new StringRequestEntity(
                payload,
                "application/json",
                "UTF-8"
        );
        post.setRequestEntity(requestEntity);
        Integer status = httpclient.executeMethod(post);
        String body = new String(post.getResponseBody(), post.getResponseCharSet());
        result = new TestRailResponse(status, body);
    } finally {
        post.releaseConnection();
    }

    return result;
}
 
Example #10
Source File: S3SignedUrlFileUploader.java    From teamcity-s3-artifact-storage-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
private static Map<String, URL> fetchUploadUrlFromServer(@NotNull final HttpClient httpClient,
                                                         @NotNull final AgentRunningBuild build,
                                                         @NotNull final Collection<String> s3ObjectKeys) throws IOException {
  try {
    final PostMethod post = new PostMethod(targetUrl(build));
    post.addRequestHeader("User-Agent", "TeamCity Agent");
    post.setRequestEntity(new StringRequestEntity(S3PreSignUrlHelper.writeS3ObjectKeys(s3ObjectKeys), APPLICATION_XML, UTF_8));
    post.setDoAuthentication(true);
    final String responseBody = HttpClientCloseUtil.executeReleasingConnectionAndReadResponseBody(httpClient, post);
    return S3PreSignUrlHelper.readPreSignUrlMapping(responseBody);
  } catch (HttpClientCloseUtil.HttpErrorCodeException e) {
    LOG.debug("Failed resolving S3 pre-signed URL for build " + build.describe(false) + " . Response code " + e.getResponseCode());
    return Collections.emptyMap();
  }
}
 
Example #11
Source File: ReplaceJSONPayloadTestcase.java    From product-ei 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 #12
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message")
public void sendingHTTP11Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched");
}
 
Example #13
Source File: CourseGroupMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicSecurityPutCall() throws IOException {
    final HttpClient c = loginWithCookie("rest-c-g-3", "A6B7C8");

    final GroupVO vo = new GroupVO();
    vo.setName("hello dont put");
    vo.setDescription("hello description dont put");
    vo.setMinParticipants(new Integer(-1));
    vo.setMaxParticipants(new Integer(-1));

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);

    assertEquals(401, code);
}
 
Example #14
Source File: BotecoMessage.java    From build-notifications-plugin with MIT License 6 votes vote down vote up
@Override
public void send() {
  HttpClient client = new HttpClient();
  PostMethod post = new PostMethod(endpoint);
  post.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  Map<String, String> values = new HashMap<String, String>();
  values.put("title", title);
  values.put("text", content + "\n\n" + extraMessage);
  values.put("url", url);
  values.put("priority", priority);
  try {
    post.setRequestEntity(new StringRequestEntity(JSONObject.fromObject(values).toString(),
        "application/json", "UTF-8"));
    client.executeMethod(post);
  } catch (IOException e) {
    LOGGER.severe("Error while sending notification: " + e.getMessage());
    e.printStackTrace();
  }
}
 
Example #15
Source File: HttpStatsReporterService.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
@Override
public void sendStats(Map<String, Long> stats, String uuid, String olvVersion, String javaVersion) {
  String r = stats
    .entrySet()
    .stream()
    .sorted(Comparator.comparing(Map.Entry::getKey))
    .map(kv -> kv.getKey() + "=" + kv.getValue()).collect(Collectors.joining("\n"));

  HttpClient httpClient = new HttpClient();
  PostMethod method = new PostMethod(SEND_URL);
  try {
    method.setRequestEntity(new StringRequestEntity(r, "text/plain", "UTF-8"));
    method.addRequestHeader("uuid", uuid);
    method.addRequestHeader("olvVersion", olvVersion);
    method.addRequestHeader("javaVersion", javaVersion);
    httpClient.executeMethod(method);
  } catch (Exception e) {
    //User is not interested in issues with sending report
    LOGGER.warn("Can't send stats to server", e);
  }
}
 
Example #16
Source File: Simulator.java    From realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
private static void sendMessage() throws IOException, JsonProcessingException, JsonGenerationException,
            JsonMappingException, UnsupportedEncodingException, HttpException {
        ObjectMapper mapper = new ObjectMapper();

        Map<String, Object> m = new HashMap<String, Object>();

        m.put("si", "12345");
        m.put("ct", System.currentTimeMillis());
        
        String payload = mapper.writeValueAsString(m);
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod("http://localhost:8080/tracking/ingest/PulsarRawEvent");
//      method.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
        method.setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8"));
        int status = client.executeMethod(method);
        System.out.println(Arrays.toString(method.getResponseHeaders()));
        System.out.println("Status code: " + status + ", Body: " +  method.getResponseBodyAsString());
    }
 
Example #17
Source File: GroupMgmtITCase.java    From olat with Apache License 2.0 6 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 = "/groups/" + g1.getKey();
    final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final BusinessGroup bg = businessGroupService.loadBusinessGroup(g1.getKey(), false);
    assertNotNull(bg);
    assertEquals(bg.getKey(), vo.getKey());
    assertEquals(bg.getName(), "rest-g1-mod");
    assertEquals(bg.getDescription(), "rest-g1 description");
}
 
Example #18
Source File: CourseGroupMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicSecurityPutCall() throws IOException {
    final HttpClient c = loginWithCookie("rest-c-g-3", "A6B7C8");

    final GroupVO vo = new GroupVO();
    vo.setName("hello dont put");
    vo.setDescription("hello description dont put");
    vo.setMinParticipants(new Integer(-1));
    vo.setMaxParticipants(new Integer(-1));

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);

    assertEquals(401, code);
}
 
Example #19
Source File: ESBJAVA2615TestCase.java    From product-ei 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 #20
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Sending HTTP1.0 message")
public void sendingHTTP10Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_0);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_0.toString(), "Http version mismatched");

}
 
Example #21
Source File: CourseGroupMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutCourseGroup() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GroupVO vo = new GroupVO();
    vo.setName("hello");
    vo.setDescription("hello description");
    vo.setMinParticipants(new Integer(-1));
    vo.setMaxParticipants(new Integer(-1));

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);

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

    final BusinessGroup bg = businessGroupService.loadBusinessGroup(responseVo.getKey(), false);
    assertNotNull(bg);
    assertEquals(bg.getKey(), responseVo.getKey());
    assertEquals(bg.getName(), vo.getName());
    assertEquals(bg.getDescription(), vo.getDescription());
    assertEquals(new Integer(0), bg.getMinParticipants());
    assertEquals(new Integer(0), bg.getMaxParticipants());
}
 
Example #22
Source File: SecurityGroupHttpClient.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public SecurityGroupRuleAnswer call(String agentIp, SecurityGroupRulesCmd cmd) {
    PostMethod post = new PostMethod(String.format(
            "http://%s:%s", agentIp, getPort()));
    try {
        SecurityGroupVmRuleSet rset = new SecurityGroupVmRuleSet();
        rset.getEgressRules().addAll(generateRules(cmd.getEgressRuleSet()));
        rset.getIngressRules().addAll(
                generateRules(cmd.getIngressRuleSet()));
        rset.setVmName(cmd.getVmName());
        rset.setVmIp(cmd.getGuestIp());
        rset.setVmMac(cmd.getGuestMac());
        rset.setVmId(cmd.getVmId());
        rset.setSignature(cmd.getSignature());
        rset.setSequenceNumber(cmd.getSeqNum());
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(rset, writer);
        String xmlContents = writer.toString();
        logger.debug(xmlContents);

        post.addRequestHeader("command", "set_rules");
        StringRequestEntity entity = new StringRequestEntity(xmlContents);
        post.setRequestEntity(entity);
        if (httpClient.executeMethod(post) != 200) {
            return new SecurityGroupRuleAnswer(cmd, false,
                    post.getResponseBodyAsString());
        } else {
            return new SecurityGroupRuleAnswer(cmd);
        }
    } catch (Exception e) {
        return new SecurityGroupRuleAnswer(cmd, false, e.getMessage());
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}
 
Example #23
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 #24
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateCatalogEntryJson() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final CatalogEntryVO entry = new CatalogEntryVO();
    entry.setName("Entry-1-b");
    entry.setDescription("Entry-description-1-b");
    entry.setType(CatalogEntry.TYPE_NODE);
    final String entity = stringuified(entry);

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).build();
    final PostMethod method = createPost(uri, MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.APPLICATION_JSON);
    final RequestEntity requestEntity = new StringRequestEntity(entity, MediaType.APPLICATION_JSON, "UTF-8");
    method.setRequestEntity(requestEntity);

    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(entry1);
    assertEquals("Entry-1-b", updatedEntry.getName());
    assertEquals("Entry-description-1-b", updatedEntry.getDescription());
}
 
Example #25
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateUser() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final UserVO vo = new UserVO();
    final String username = UUID.randomUUID().toString();
    vo.setLogin(username);
    vo.setFirstName("John");
    vo.setLastName("Smith");
    vo.setEmail(username + "@frentix.com");
    vo.putProperty("telOffice", "39847592");
    vo.putProperty("telPrivate", "39847592");
    vo.putProperty("telMobile", "39847592");
    vo.putProperty("gender", "Female");// male or female
    vo.putProperty("birthDay", "12/12/2009");

    final String stringuifiedAuth = stringuified(vo);
    final PutMethod method = createPut("/users", MediaType.APPLICATION_JSON, true);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    method.setRequestEntity(entity);
    method.addRequestHeader("Accept-Language", "en");

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final UserVO savedVo = parse(body, UserVO.class);

    final Identity savedIdent = securityManager.findIdentityByName(username);

    assertNotNull(savedVo);
    assertNotNull(savedIdent);
    assertEquals(savedVo.getKey(), savedIdent.getKey());
    assertEquals(savedVo.getLogin(), savedIdent.getName());
    assertEquals("Female", userService.getUserProperty(savedIdent.getUser(), UserConstants.GENDER, Locale.ENGLISH));
    assertEquals("39847592", userService.getUserProperty(savedIdent.getUser(), UserConstants.TELPRIVATE, Locale.ENGLISH));
    assertEquals("12/12/09", userService.getUserProperty(savedIdent.getUser(), UserConstants.BIRTHDAY, Locale.ENGLISH));
}
 
Example #26
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Test machine format for gender and date
 */
@Test
public void testCreateUser2() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final UserVO vo = new UserVO();
    final String username = UUID.randomUUID().toString();
    vo.setLogin(username);
    vo.setFirstName("John");
    vo.setLastName("Smith");
    vo.setEmail(username + "@frentix.com");
    vo.putProperty("telOffice", "39847592");
    vo.putProperty("telPrivate", "39847592");
    vo.putProperty("telMobile", "39847592");
    vo.putProperty("gender", "female");// male or female
    vo.putProperty("birthDay", "20091212");

    final String stringuifiedAuth = stringuified(vo);
    final PutMethod method = createPut("/users", MediaType.APPLICATION_JSON, true);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    method.setRequestEntity(entity);
    method.addRequestHeader("Accept-Language", "en");

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final UserVO savedVo = parse(body, UserVO.class);

    final Identity savedIdent = securityManager.findIdentityByName(username);

    assertNotNull(savedVo);
    assertNotNull(savedIdent);
    assertEquals(savedVo.getKey(), savedIdent.getKey());
    assertEquals(savedVo.getLogin(), savedIdent.getName());
    assertEquals("Female", userService.getUserProperty(savedIdent.getUser(), UserConstants.GENDER, Locale.ENGLISH));
    assertEquals("39847592", userService.getUserProperty(savedIdent.getUser(), UserConstants.TELPRIVATE, Locale.ENGLISH));
    assertEquals("12/12/09", userService.getUserProperty(savedIdent.getUser(), UserConstants.BIRTHDAY, Locale.ENGLISH));
}
 
Example #27
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateUserWithValidationError() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final UserVO vo = new UserVO();
    vo.setLogin("rest-809");
    vo.setFirstName("John");
    vo.setLastName("Smith");
    vo.setEmail("");
    vo.putProperty("gender", "lu");

    final String stringuifiedAuth = stringuified(vo);
    final PutMethod method = createPut("/users", MediaType.APPLICATION_JSON, true);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    method.setRequestEntity(entity);

    final int code = c.executeMethod(method);
    assertTrue(code == 406);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<ErrorVO> errors = parseErrorArray(body);
    assertNotNull(errors);
    assertFalse(errors.isEmpty());
    assertTrue(errors.size() >= 2);
    assertNotNull(errors.get(0).getCode());
    assertNotNull(errors.get(0).getTranslation());
    assertNotNull(errors.get(1).getCode());
    assertNotNull(errors.get(1).getTranslation());

    final Identity savedIdent = securityManager.findIdentityByName("rest-809");
    assertNull(savedIdent);
}
 
Example #28
Source File: CrucibleApi.java    From Crucible4IDEA with MIT License 5 votes vote down vote up
public static RequestEntity createCommentRequest(@NotNull Comment comment, boolean isGeneral) throws UnsupportedEncodingException {
  BaseComment raw;
  if (isGeneral) {
    raw = new GeneralComment();
  }
  else if (comment.getParentCommentId() != null) {
    raw = new ReplyComment();
  }
  else {
    raw = new TopLevelComment();
  }

  raw.message = comment.getMessage();
  raw.draft = comment.isDraft();
  raw.deleted = false;
  raw.defectRaised = false;

  if (!isGeneral && comment.getParentCommentId() == null) {
    raw.reviewItemId = new IdHolder(comment.getReviewItemId());
    raw.toLineRange = comment.getLine();
  }

  if (comment.getParentCommentId() != null) {
    raw.parentCommentId = new IdHolder(comment.getParentCommentId());
  }

  String requestString = gson.toJson(raw);
  return new StringRequestEntity(requestString, "application/json", "UTF-8");
}
 
Example #29
Source File: CourseGroupMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutCourseGroup() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GroupVO vo = new GroupVO();
    vo.setName("hello");
    vo.setDescription("hello description");
    vo.setMinParticipants(new Integer(-1));
    vo.setMaxParticipants(new Integer(-1));

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);

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

    final BusinessGroup bg = businessGroupService.loadBusinessGroup(responseVo.getKey(), false);
    assertNotNull(bg);
    assertEquals(bg.getKey(), responseVo.getKey());
    assertEquals(bg.getName(), vo.getName());
    assertEquals(bg.getDescription(), vo.getDescription());
    assertEquals(new Integer(0), bg.getMinParticipants());
    assertEquals(new Integer(0), bg.getMaxParticipants());
}
 
Example #30
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutCatalogEntryJson() throws IOException {
    final RepositoryEntry re = createRepository("put-cat-entry-json", 6458438l);

    final HttpClient c = loginWithCookie("administrator", "olat");

    final CatalogEntryVO subEntry = new CatalogEntryVO();
    subEntry.setName("Sub-entry-1");
    subEntry.setDescription("Sub-entry-description-1");
    subEntry.setType(CatalogEntry.TYPE_NODE);
    subEntry.setRepositoryEntryKey(re.getKey());
    final String entity = stringuified(subEntry);

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.APPLICATION_JSON);
    final RequestEntity requestEntity = new StringRequestEntity(entity, MediaType.APPLICATION_JSON, "UTF-8");
    method.setRequestEntity(requestEntity);

    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 List<CatalogEntry> children = catalogService.getChildrenOf(entry1);
    CatalogEntry ce = null;
    for (final CatalogEntry child : children) {
        if (vo.getKey().equals(child.getKey())) {
            ce = child;
            break;
        }
    }

    assertNotNull(ce);
    assertNotNull(ce.getRepositoryEntry());
    assertEquals(re.getKey(), ce.getRepositoryEntry().getKey());
}