public String doPut(String url, String charset, String jsonObj) { String resStr = null; HttpClient htpClient = new HttpClient(); PutMethod putMethod = new PutMethod(url); putMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, charset); try { putMethod.setRequestEntity(new StringRequestEntity(jsonObj, "application/json", charset)); int statusCode = htpClient.executeMethod(putMethod); if (statusCode != HttpStatus.SC_OK) { log.error("Method failed: " + putMethod.getStatusLine()); return null; } byte[] responseBody = putMethod.getResponseBody(); resStr = new String(responseBody, charset); } catch (Exception e) { e.printStackTrace(); } finally { putMethod.releaseConnection(); } return resStr; }
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); }
private static void updateAccount() throws HttpException, IOException { System.out.println("Sent HTTP PUT request to update Account"); File input = new File(testFolder + "Account.xml"); PutMethod put = new PutMethod(cadURL + "/object/User?_type=xml&externalServiceType=FBMC&externalUsername=8x8webservice&externalPassword=E4qtjWZLYKre"); put.addRequestHeader("Content-Type", "application/xml"); RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); put.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); try { int result = httpclient.executeMethod(put); System.out.println("Response status code: " + result); System.out.println("Response body: " + put.getResponseBodyAsString()); } finally { put.releaseConnection(); } }
private static void updateCustomer() throws HttpException, IOException { System.out.println("Sent HTTP PUT request to update Customer"); File input = new File(testFolder + "Customer.xml"); PutMethod put = new PutMethod(cadURL + "/object/customer?_type=xml"); put.addRequestHeader("Content-Type", "application/xml"); RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); put.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); try { System.out.println("URI: " + put.getURI()); int result = httpclient.executeMethod(put); System.out.println("Response status code: " + result); System.out.println("Response body: " + put.getResponseBodyAsString()); } finally { put.releaseConnection(); } }
private static void updateContact() throws HttpException, IOException { System.out.println("Sent HTTP POST request to createContact"); File input = new File(testFolder + "Contact.xml"); PutMethod put = new PutMethod(cadURL + "/object/oltp?_type=xml"); put.addRequestHeader("Content-Type", "application/xml"); RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); put.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); try { System.out.println("URI: " + put.getURI()); int result = httpclient.executeMethod(put); System.out.println("Response status code: " + result); System.out.println("Response body: " + put.getResponseBodyAsString()); } finally { put.releaseConnection(); } }
private static void updateUser() throws HttpException, IOException { File input = new File(testFolder + "User.xml"); PutMethod put = new PutMethod(cadURL + "/object/user?_type=xml"); put.addRequestHeader("Content-Type", "application/xml"); RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); put.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); try { System.out.println("URI: " + put.getURI()); int result = httpclient.executeMethod(put); System.out.println("Response status code: " + result); System.out.println("Response body: " + put.getResponseBodyAsString()); } finally { put.releaseConnection(); } }
private static void updateCase() throws HttpException, IOException { File input = new File(testFolder + "Case.xml"); PutMethod post = new PutMethod(cadURL + "/object/oltp?_type=xml"); post.addRequestHeader("Content-Type", "application/xml"); RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); try { System.out.println("URI: " + post.getURI()); int result = httpclient.executeMethod(post); System.out.println("Response status code: " + result); System.out.println("Response body: " + post.getResponseBodyAsString()); } finally { post.releaseConnection(); } }
private static void updateFollowup() throws HttpException, IOException { File input = new File(testFolder + "Followup.xml"); PutMethod post = new PutMethod(cadURL + "/object/oltp?_type=xml"); post.addRequestHeader("Content-Type", "application/xml"); RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); try { System.out.println("URI: " + post.getURI()); int result = httpclient.executeMethod(post); System.out.println("Response status code: " + result); System.out.println("Response body: " + post.getResponseBodyAsString()); } finally { post.releaseConnection(); } }
/** * Factory method to create a {@link HttpMethod}-object according to the * given String <code>httpMethod</codde> * * @param httpMethodString the name of the {@link HttpMethod} to create * @param url * * @return an object of type {@link GetMethod}, {@link PutMethod}, * {@link PostMethod} or {@link DeleteMethod} * @throws IllegalArgumentException if <code>httpMethod</code> is none of * <code>GET</code>, <code>PUT</code>, <code>POST</POST> or <code>DELETE</code> */ public static HttpMethod createHttpMethod(String httpMethodString, String url) { if ("GET".equals(httpMethodString)) { return new GetMethod(url); } else if ("PUT".equals(httpMethodString)) { return new PutMethod(url); } else if ("POST".equals(httpMethodString)) { return new PostMethod(url); } else if ("DELETE".equals(httpMethodString)) { return new DeleteMethod(url); } else { throw new IllegalArgumentException("given httpMethod '" + httpMethodString + "' is unknown"); } }
/** * 处理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); }
@Test public void testUpdateParagraphConfig() throws IOException { Note note = ZeppelinServer.notebook.createNote(anonymous); String noteId = note.getId(); Paragraph p = note.addNewParagraph(AuthenticationInfo.ANONYMOUS); assertNull(p.getConfig().get("colWidth")); String paragraphId = p.getId(); String jsonRequest = "{\"colWidth\": 6.0}"; PutMethod put = httpPut("/notebook/" + noteId + "/paragraph/" + paragraphId +"/config", jsonRequest); assertThat("test testUpdateParagraphConfig:", put, isAllowed()); Map<String, Object> resp = gson.fromJson(put.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() { }.getType()); Map<String, Object> respBody = (Map<String, Object>) resp.get("body"); Map<String, Object> config = (Map<String, Object>) respBody.get("config"); put.releaseConnection(); assertEquals(config.get("colWidth"), 6.0); note = ZeppelinServer.notebook.getNote(noteId); assertEquals(note.getParagraph(paragraphId).getConfig().get("colWidth"), 6.0); //cleanup ZeppelinServer.notebook.removeNote(noteId, anonymous); }
@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"); }
@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 = ZeppelinServer.notebook.getNote(noteId); assertNull("Deleted note should be null", deletedNote); }
@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); }
@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()); }
@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); }
@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); }
@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); }
@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); }
@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); }
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"); }
/** * This method implements the HTTP Put Method * * @param uri * Resource URI * @param requestPayload * Content which has to be put into the Resource * @return ResponseCode of HTTP Interaction */ @SuppressWarnings("deprecation") public static HttpResponseMessage Put(String uri, String requestPayload, String acceptHeaderValue) { PutMethod method = new PutMethod(uri); // requestPayload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + // requestPayload; HighLevelRestApi.setAcceptHeader(method, acceptHeaderValue); method.setRequestBody(requestPayload); HttpResponseMessage responseMessage = LowLevelRestApi .executeHttpMethod(method); // kill <?xml... in front of response HighLevelRestApi.cleanResponseBody(responseMessage); return responseMessage; }
/** * Create a Commons HttpMethodBase object for the given HTTP method * and URI specification. * @param httpMethod the HTTP method * @param uri the URI * @return the Commons HttpMethodBase object */ protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String uri) { switch (httpMethod) { case GET: return new GetMethod(uri); case DELETE: return new DeleteMethod(uri); case HEAD: return new HeadMethod(uri); case OPTIONS: return new OptionsMethod(uri); case POST: return new PostMethod(uri); case PUT: return new PutMethod(uri); case TRACE: return new TraceMethod(uri); case PATCH: throw new IllegalArgumentException( "HTTP method PATCH not available before Apache HttpComponents HttpClient 4.2"); default: throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } }
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(); } }
public PutMethod getSendByteArrayMethod(byte[] content, String service) throws Exception { // Prepare HTTP put // String urlString = constructUrl(service); log.logDebug(toString(), Messages.getString("SlaveServer.DEBUG_ConnectingTo", urlString)); //$NON-NLS-1$ PutMethod putMethod = new PutMethod(urlString); // Request content will be retrieved directly from the input stream // RequestEntity entity = new ByteArrayRequestEntity(content); putMethod.setRequestEntity(entity); putMethod.setDoAuthentication(true); putMethod.addRequestHeader(new Header("Content-Type", "text/xml;charset=" + Const.XML_ENCODING)); return putMethod; }
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"); } }
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; }
@Test(expected = BigSwitchBcfApiException.class) public void testExecuteUpdateObjectFailure() throws BigSwitchBcfApiException, IOException { NetworkData network = new NetworkData(); _method = mock(PutMethod.class); when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); Header header = mock(Header.class); when(header.getValue()).thenReturn("text/html"); when(_method.getResponseHeader("Content-type")).thenReturn(header); when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); when(_method.isRequestSent()).thenReturn(true); try { _api.executeUpdateObject(network, "/", Collections.<String, String> emptyMap()); } finally { verify(_method, times(1)).releaseConnection(); } }
/** * Saves a stream into a file in the repository. * * @param text * Stream to be stored. * @param url * URL to the file that will be created. */ public void saveStream(InputStream stream, String url) throws IOException { PutMethod putMethod = new PutMethod(url); putMethod.setRequestEntity(new InputStreamRequestEntity(stream)); try { client.executeMethod(putMethod); putMethod.releaseConnection(); } catch (IOException e) { throw new IOException(e); } finally { stream.close(); } }
@Test public void testRetrieveTextFile() throws HttpException, IOException { DavHandler dav = new DavHandler(folders); InputStream stream = new ByteArrayInputStream("some text".getBytes()); PutMethod putMethod = new PutMethod( "http://localhost:9002/parent/child/textToRetrieve.txt"); putMethod.setRequestEntity(new InputStreamRequestEntity(stream)); HttpClient client = new HttpClient(); client.executeMethod(putMethod); stream.close(); putMethod.releaseConnection(); String retrieved = dav.retrieveTextFile("http://localhost:9002/parent/child/textToRetrieve.txt"); assertEquals("some text", retrieved); }
private String sendPostData(HttpMethod method) throws IOException { String form; if (useAuthHeader) { form = nonOAuthParams.get(0).getValue(); } else { form = OAuth.formEncode(message.getParameters()); } method.addRequestHeader(HEADER_CONTENT_LENGTH, form.length() + ""); //$NON-NLS-1$ if (method instanceof PostMethod || method instanceof PutMethod) { StringRequestEntity requestEntity = new StringRequestEntity(form); ((EntityEnclosingMethod)method).setRequestEntity(requestEntity); } else { log.error("Logic error, method must be POST or PUT to send body"); //$NON-NLS-1$ } return form; }