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

The following examples show how to use org.apache.commons.httpclient.methods.PutMethod. 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: CoursesFoldersITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadFile() throws IOException, URISyntaxException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getNodeURI()).path("files").build();

    // create single page
    final URL fileUrl = RepositoryEntriesITCase.class.getResource("singlepage.html");
    assertNotNull(fileUrl);
    final File file = new File(fileUrl.toURI());

    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", file), new StringPart("filename", file.getName()) };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    final int code = c.executeMethod(method);
    assertEquals(code, 200);

    final OlatNamedContainerImpl folder = BCCourseNode.getNodeFolderContainer((BCCourseNode) bcNode, course1.getCourseEnvironment());
    final VFSItem item = folder.resolve(file.getName());
    assertNotNull(item);
}
 
Example #2
Source File: MapRouteCommand.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected ServerStatus _doIt() {
	try {

		/* attach route to application */
		URI targetURI = URIUtil.toURI(target.getUrl());
		PutMethod attachRouteMethod = new PutMethod(targetURI.resolve("/v2/apps/" + application.getGuid() + "/routes/" + routeGUID).toString()); //$NON-NLS-1$//$NON-NLS-2$
		ServerStatus confStatus = HttpUtil.configureHttpMethod(attachRouteMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;
		
		return HttpUtil.executeMethod(attachRouteMethod);

	} 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 #3
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 #4
Source File: RestClient.java    From Kylin with Apache License 2.0 6 votes vote down vote up
public void wipeCache(String type, String action, String name) throws IOException {
    String url = baseUrl + "/cache/" + type + "/" + name + "/" + action;
    HttpMethod request = new PutMethod(url);

    try {
        int code = client.executeMethod(request);
        String msg = Bytes.toString(request.getResponseBody());

        if (code != 200)
            throw new IOException("Invalid response " + code + " with cache wipe url " + url + "\n" + msg);

    } catch (HttpException ex) {
        throw new IOException(ex);
    } finally {
        request.releaseConnection();
    }
}
 
Example #5
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 #6
Source File: CoursesITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateEmptyCourse() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("repo").path("courses").queryParam("shortTitle", "course3").queryParam("title", "course3 long name")
            .build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);

    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final CourseVO course = parse(body, CourseVO.class);
    assertNotNull(course);
    assertEquals("course3", course.getTitle());
    // check repository entry
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(course.getRepoEntryKey());
    assertNotNull(re);
    assertNotNull(re.getOlatResource());
    assertNotNull(re.getOwnerGroup());
}
 
Example #7
Source File: CoursesITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateEmptyCourse() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("repo").path("courses").queryParam("shortTitle", "course3").queryParam("title", "course3 long name")
            .build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);

    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final CourseVO course = parse(body, CourseVO.class);
    assertNotNull(course);
    assertEquals("course3", course.getTitle());
    // check repository entry
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(course.getRepoEntryKey());
    assertNotNull(re);
    assertNotNull(re.getOlatResource());
    assertNotNull(re.getOwnerGroup());
}
 
Example #8
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 #9
Source File: DavExchangeSession.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
protected PutMethod internalCreateOrUpdate(String encodedHref, byte[] mimeContent) throws IOException {
    PutMethod putmethod = new PutMethod(encodedHref);
    putmethod.setRequestHeader("Translate", "f");
    putmethod.setRequestHeader("Overwrite", "f");
    if (etag != null) {
        putmethod.setRequestHeader("If-Match", etag);
    }
    if (noneMatch != null) {
        putmethod.setRequestHeader("If-None-Match", noneMatch);
    }
    putmethod.setRequestHeader("Content-Type", "message/rfc822");
    putmethod.setRequestEntity(new ByteArrayRequestEntity(mimeContent, "message/rfc822"));
    try {
        httpClient.executeMethod(putmethod);
    } finally {
        putmethod.releaseConnection();
    }
    return putmethod;
}
 
Example #10
Source File: CoursesContactElementITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testBareBoneConfig() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    // create an contact node
    final URI newContactUri = getElementsUri(course1).path("contact").queryParam("parentNodeId", rootNodeId).queryParam("position", "0")
            .queryParam("shortTitle", "Contact-0").queryParam("longTitle", "Contact-long-0").queryParam("objectives", "Contact-objectives-0").build();
    final PutMethod method = createPut(newContactUri, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();

    assertEquals(200, code);
    final CourseNodeVO contactNode = parse(body, CourseNodeVO.class);
    assertNotNull(contactNode);
    assertNotNull(contactNode.getId());
    assertEquals(contactNode.getShortTitle(), "Contact-0");
    assertEquals(contactNode.getLongTitle(), "Contact-long-0");
    assertEquals(contactNode.getLearningObjectives(), "Contact-objectives-0");
    assertEquals(contactNode.getParentId(), rootNodeId);
}
 
Example #11
Source File: CourseITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddAuthor() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String uri = "/repo/courses/" + course1.getResourceableId() + "/authors/" + auth0.getKey();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);

    // is auth0 author
    final SecurityGroup authorGroup = securityManager.findSecurityGroupByName(Constants.GROUP_AUTHORS);
    final boolean isAuthor = securityManager.isIdentityInSecurityGroup(auth0, authorGroup);
    DBFactory.getInstance().intermediateCommit();
    assertTrue(isAuthor);

    // is auth0 owner
    final RepositoryService rm = RepositoryServiceImpl.getInstance();
    final RepositoryEntry repositoryEntry = rm.lookupRepositoryEntry(course1, true);
    final SecurityGroup ownerGroup = repositoryEntry.getOwnerGroup();
    final boolean isOwner = securityManager.isIdentityInSecurityGroup(auth0, ownerGroup);
    DBFactory.getInstance().intermediateCommit();
    assertTrue(isOwner);
}
 
Example #12
Source File: PublicApiHttpClient.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public HttpResponse putBinary(final RequestContext rq, final String scope, final int version, final String entityCollectionName,
            final Object entityId, final String relationCollectionName, final Object relationshipEntityId, final BinaryPayload payload,
            final Map<String, String> params) throws IOException
{
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName,
                relationshipEntityId, params);
    String url = endpoint.getUrl();

    PutMethod req = new PutMethod(url);
    if (payload != null)
    {
        BinaryRequestEntity requestEntity = new BinaryRequestEntity(payload.getFile(), payload.getMimeType(), payload.getCharset());
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}
 
Example #13
Source File: CatalogITCase.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-catalog-two", "A6B7C8");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("name", "Not-sub-entry-3"), new NameValuePair("description", "Not-sub-entry-description-3"),
            new NameValuePair("type", String.valueOf(CatalogEntry.TYPE_NODE)) });

    final int code = c.executeMethod(method);
    assertEquals(401, code);
    method.releaseConnection();

    final List<CatalogEntry> children = catalogService.getChildrenOf(entry1);
    boolean saved = false;
    for (final CatalogEntry child : children) {
        if ("Not-sub-entry-3".equals(child.getName())) {
            saved = true;
            break;
        }
    }

    assertFalse(saved);
}
 
Example #14
Source File: NotebookSecurityRestApiTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatWriterCannotRemoveNote() throws IOException {
  String noteId = createNoteForUser("test", "admin", "password1");
  
  //set permission
  String payload = "{ \"owners\": [\"admin\", \"user1\"], \"readers\": [\"user2\"], " +
          "\"runners\": [\"user2\"], \"writers\": [\"user2\"] }";
  PutMethod put = httpPut("/notebook/" + noteId + "/permissions", payload , "admin", "password1");
  assertThat("test set note permission method:", put, isAllowed());
  put.releaseConnection();
  
  userTryRemoveNote(noteId, "user2", "password3", isForbidden());
  userTryRemoveNote(noteId, "user1", "password2", isAllowed());
  
  Note deletedNote = TestUtils.getInstance(Notebook.class).getNote(noteId);
  assertNull("Deleted note should be null", deletedNote);
}
 
Example #15
Source File: NotebookSecurityRestApiTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatOtherUserCannotAccessNoteIfPermissionSet() throws IOException {
  String noteId = createNoteForUser("test", "admin", "password1");
  
  //set permission
  String payload = "{ \"owners\": [\"admin\"], \"readers\": [\"user2\"], " +
          "\"runners\": [\"user2\"], \"writers\": [\"user2\"] }";
  PutMethod put = httpPut("/notebook/" + noteId + "/permissions", payload , "admin", "password1");
  assertThat("test set note permission method:", put, isAllowed());
  put.releaseConnection();
  
  userTryGetNote(noteId, "user1", "password2", isForbidden());
  
  userTryGetNote(noteId, "user2", "password3", isAllowed());
  
  deleteNoteForUser(noteId, "admin", "password1");
}
 
Example #16
Source File: NotebookRestApiTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testRenameNote() throws IOException {
  LOG.info("Running testRenameNote");
  Note note = null;
  try {
    String oldName = "old_name";
    note = TestUtils.getInstance(Notebook.class).createNote(oldName, anonymous);
    assertEquals(note.getName(), oldName);
    String noteId = note.getId();

    final String newName = "testName";
    String jsonRequest = "{\"name\": " + newName + "}";

    PutMethod put = httpPut("/notebook/" + noteId + "/rename/", jsonRequest);
    assertThat("test testRenameNote:", put, isAllowed());
    put.releaseConnection();

    assertEquals(note.getName(), newName);
  } finally {
    // cleanup
    if (null != note) {
      TestUtils.getInstance(Notebook.class).removeNote(note, anonymous);
    }
  }
}
 
Example #17
Source File: CatalogITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddOwner() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).path("owners").path(id1.getKey().toString()).build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);

    final int code = c.executeMethod(method);
    method.releaseConnection();
    assertEquals(200, code);

    final CatalogEntry entry = catalogService.loadCatalogEntry(entry1.getKey());
    final List<Identity> identities = securityManager.getIdentitiesOfSecurityGroup(entry.getOwnerGroup());
    boolean found = false;
    for (final Identity identity : identities) {
        if (identity.getKey().equals(id1.getKey())) {
            found = true;
        }
    }
    assertTrue(found);
}
 
Example #18
Source File: HttpUtils.java    From Java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 处理Put请求
 * @param url
 * @param headers
 * @param object
 * @param property
 * @return
 */
public static JSONObject doPut(String url, Map<String, String> headers,String jsonString) {

	HttpClient httpClient = new HttpClient();
	
	PutMethod putMethod = new PutMethod(url);
	
	//设置header
	setHeaders(putMethod,headers);
	
	//设置put传递的json数据
	if(jsonString!=null&&!"".equals(jsonString)){
		putMethod.setRequestEntity(new ByteArrayRequestEntity(jsonString.getBytes()));
	}
	
	String responseStr = "";
	
	try {
		httpClient.executeMethod(putMethod);
		responseStr = putMethod.getResponseBodyAsString();
	} catch (Exception e) {
		log.error(e);
		responseStr="{status:0}";
	} 
	return JSONObject.parseObject(responseStr);
}
 
Example #19
Source File: CatalogITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddOwner() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).path("owners").path(id1.getKey().toString()).build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);

    final int code = c.executeMethod(method);
    method.releaseConnection();
    assertEquals(200, code);

    final CatalogEntry entry = catalogService.loadCatalogEntry(entry1.getKey());
    final List<Identity> identities = securityManager.getIdentitiesOfSecurityGroup(entry.getOwnerGroup());
    boolean found = false;
    for (final Identity identity : identities) {
        if (identity.getKey().equals(id1.getKey())) {
            found = true;
        }
    }
    assertTrue(found);
}
 
Example #20
Source File: S3SignedUrlFileUploader.java    From teamcity-s3-artifact-storage-plugin with Apache License 2.0 6 votes vote down vote up
private void uploadArtifact(@NotNull final String artifactPath, @NotNull final URL uploadUrl, @NotNull final File file, @NotNull final HttpClient awsHttpClient)
  throws IOException {
  try {
    final PutMethod putMethod = new PutMethod(uploadUrl.toString());
    putMethod.addRequestHeader("User-Agent", "TeamCity Agent");
    putMethod.setRequestEntity(new FileRequestEntity(file, S3Util.getContentType(file)));
    HttpClientCloseUtil.executeAndReleaseConnection(awsHttpClient, putMethod);
    LOG.debug(String.format("Successfully uploaded artifact %s to %s", artifactPath, uploadUrl));
  } catch (HttpClientCloseUtil.HttpErrorCodeException e) {
    final String msg;
    if (e.getResponseCode() == HttpStatus.SC_FORBIDDEN) {
      msg = "Failed to upload artifact " + artifactPath + ": received response code HTTP 403. Ensure that the credentials in S3 storage profile are correct.";
    } else {
      msg = "Failed to upload artifact " + artifactPath + " to " + uploadUrl + ": received response code HTTP " + e.getResponseCode() + ".";
    }
    LOG.info(msg);
    throw new IOException(msg);
  }
}
 
Example #21
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 #22
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportQuestionnaire() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("questionnaire-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "questionnaire-demo.zip"), new StringPart("resourcename", "Questionnaire demo"),
            new StringPart("displayname", "Questionnaire demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("Questionnaire demo", re.getDisplayname());
    log.info(re.getOlatResource().getResourceableTypeName());
}
 
Example #23
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportTest() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("qti-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "qti-demo.zip"), new StringPart("resourcename", "QTI demo"),
            new StringPart("displayname", "QTI demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("QTI demo", re.getDisplayname());
    log.info(re.getOlatResource().getResourceableTypeName());
}
 
Example #24
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutCategoryJson() throws IOException {
    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);
    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);
    boolean saved = false;
    for (final CatalogEntry child : children) {
        if (vo.getKey().equals(child.getKey())) {
            saved = true;
            break;
        }
    }

    assertTrue(saved);
}
 
Example #25
Source File: ChatRoomDecorator.java    From Spark with Apache License 2.0 5 votes vote down vote up
private void uploadFile(File file, UploadRequest response, ChatRoom room, Message.Type type)
{
    Log.warning("uploadFile request " + room.getRoomJid() + " " + response.putUrl);
    URLConnection urlconnection = null;

    try {
        PutMethod put = new PutMethod(response.putUrl);
        int port = put.getURI().getPort();
        if (port > 0)
        {
            Protocol.registerProtocol( "https", new Protocol( "https", new EasySSLProtocolSocketFactory(), port ) );
        }
        
        HttpClient client = new HttpClient();
        RequestEntity entity = new FileRequestEntity(file, "application/binary");
        put.setRequestEntity(entity);
        put.setRequestHeader("User-Agent", "Spark HttpFileUpload");
        client.executeMethod(put);

        int statusCode = put.getStatusCode();
        String responseBody = put.getResponseBodyAsString();

        Log.warning("uploadFile response " + statusCode + " " + responseBody);

        if ((statusCode >= 200) && (statusCode <= 202))
        {
            broadcastUploadUrl(room.getRoomJid(), response.getUrl, type);
        }

    } catch (Exception e) {
        Log.error("uploadFile error", e);
    }
}
 
Example #26
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 #27
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportCp() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("cp-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "cp-demo.zip"), new StringPart("resourcename", "CP demo"),
            new StringPart("displayname", "CP demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("CP demo", re.getDisplayname());
}
 
Example #28
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutCatalogEntryQuery() throws IOException {
    final RepositoryEntry re = createRepository("put-cat-entry-query", 6458439l);

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

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("name", "Sub-entry-2"), new NameValuePair("description", "Sub-entry-description-2"),
            new NameValuePair("type", String.valueOf(CatalogEntry.TYPE_NODE)), new NameValuePair("repoEntryKey", re.getKey().toString()) });

    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());
}
 
Example #29
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportBlog() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("blog-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "blog-demo.zip"), new StringPart("resourcename", "Blog demo"),
            new StringPart("displayname", "Blog demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("Blog demo", re.getDisplayname());
    log.info(re.getOlatResource().getResourceableTypeName());
}
 
Example #30
Source File: ClientEntry.java    From rome with Apache License 2.0 5 votes vote down vote up
/**
 * Update entry by posting new representation of entry to server. Note that you should not
 * attempt to update entries that you get from iterating over a collection they may be "partial"
 * entries. If you want to update an entry, you must get it via one of the
 * <code>getEntry()</code> methods in {@link com.rometools.rome.propono.atom.common.Collection}
 * or {@link com.rometools.rome.propono.atom.common.AtomService}.
 *
 * @throws ProponoException If entry is a "partial" entry.
 */
public void update() throws ProponoException {
    if (partial) {
        throw new ProponoException("ERROR: attempt to update partial entry");
    }
    final EntityEnclosingMethod method = new PutMethod(getEditURI());
    addAuthentication(method);
    final StringWriter sw = new StringWriter();
    final int code = -1;
    try {
        Atom10Generator.serializeEntry(this, sw);
        method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null));
        method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8");
        getHttpClient().executeMethod(method);
        final InputStream is = method.getResponseBodyAsStream();
        if (method.getStatusCode() != 200 && method.getStatusCode() != 201) {
            throw new ProponoException("ERROR HTTP status=" + method.getStatusCode() + " : " + Utilities.streamToString(is));
        }

    } catch (final Exception e) {
        final String msg = "ERROR: updating entry, HTTP code: " + code;
        LOG.debug(msg, e);
        throw new ProponoException(msg, e);
    } finally {
        method.releaseConnection();
    }
}