Java Code Examples for org.apache.commons.httpclient.methods.PostMethod#releaseConnection()
The following examples show how to use
org.apache.commons.httpclient.methods.PostMethod#releaseConnection() .
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: SolrWaveIndexerImpl.java From swellrt with Apache License 2.0 | 7 votes |
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 2
Source File: CatalogITCase.java From olat with Apache License 2.0 | 6 votes |
@Test public void testUpdateCatalogEntryQuery() throws IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry2.getKey().toString()).build(); final PostMethod method = createPost(uri, MediaType.APPLICATION_JSON, true); method.setQueryString(new NameValuePair[] { new NameValuePair("name", "Entry-2-b"), new NameValuePair("description", "Entry-description-2-b"), new NameValuePair("type", String.valueOf(CatalogEntry.TYPE_NODE)) }); final int code = c.executeMethod(method); assertEquals(200, code); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final CatalogEntryVO vo = parse(body, CatalogEntryVO.class); assertNotNull(vo); final CatalogEntry updatedEntry = catalogService.loadCatalogEntry(entry2); assertEquals("Entry-2-b", updatedEntry.getName()); assertEquals("Entry-description-2-b", updatedEntry.getDescription()); }
Example 3
Source File: JunkUtils.java From http4e with Apache License 2.0 | 6 votes |
public static String getHdToken(String url, String md){ final HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.setRequestHeader("content-type", "application/x-www-form-urlencoded"); post.setParameter("v", md); post.setApacheHttpListener(httpListener); try { HttpUtils.execute(client, post, responseReader); Header header = post.getResponseHeader("hd-token"); if(header != null){ // System.out.println("hd-token:" + header.getValue() + "'"); return header.getValue(); } } catch (Exception ignore) { ExceptionHandler.handle(ignore); } finally { if(post != null) post.releaseConnection(); } return null; }
Example 4
Source File: HeliumRestApiTest.java From zeppelin with Apache License 2.0 | 6 votes |
@Test public void testVisualizationPackageOrder() throws IOException { GetMethod get1 = httpGet("/helium/order/visualization"); assertThat(get1, isAllowed()); Map<String, Object> resp1 = gson.fromJson(get1.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() { }.getType()); List<Object> body1 = (List<Object>) resp1.get("body"); assertEquals(body1.size(), 0); //We assume allPackages list has been refreshed before sorting helium.getAllPackageInfo(); String postRequestJson = "[name2, name1]"; PostMethod post = httpPost("/helium/order/visualization", postRequestJson); assertThat(post, isAllowed()); post.releaseConnection(); GetMethod get2 = httpGet("/helium/order/visualization"); assertThat(get2, isAllowed()); Map<String, Object> resp2 = gson.fromJson(get2.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() { }.getType()); List<Object> body2 = (List<Object>) resp2.get("body"); assertEquals(body2.size(), 2); assertEquals(body2.get(0), "name2"); assertEquals(body2.get(1), "name1"); }
Example 5
Source File: CatalogITCase.java From olat with Apache License 2.0 | 6 votes |
@Test public void testUpdateCatalogEntryQuery() throws IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry2.getKey().toString()).build(); final PostMethod method = createPost(uri, MediaType.APPLICATION_JSON, true); method.setQueryString(new NameValuePair[] { new NameValuePair("name", "Entry-2-b"), new NameValuePair("description", "Entry-description-2-b"), new NameValuePair("type", String.valueOf(CatalogEntry.TYPE_NODE)) }); final int code = c.executeMethod(method); assertEquals(200, code); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final CatalogEntryVO vo = parse(body, CatalogEntryVO.class); assertNotNull(vo); final CatalogEntry updatedEntry = catalogService.loadCatalogEntry(entry2); assertEquals("Entry-2-b", updatedEntry.getName()); assertEquals("Entry-description-2-b", updatedEntry.getDescription()); }
Example 6
Source File: PropertyIntegrationForceSCAcceptedPropertyTestCase.java From micro-integrator with Apache License 2.0 | 6 votes |
@Test(groups = "wso2.esb", description = "Testing functionality of FORCE_SC_ACCEPTED " + "Enabled True - " + "Client should receive 202 message", dependsOnMethods = "testFORCE_SC_ACCEPTEDPropertyEnabledFalseScenario") public void testWithFORCE_SC_ACCEPTEDPropertyEnabledTrueScenario() throws Exception { int responseStatus = 0; String strXMLFilename = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "ESB" + File.separator + "mediatorconfig" + File.separator + "property" + File.separator + "PlaceOrder.xml"; File input = new File(strXMLFilename); PostMethod post = new PostMethod(getProxyServiceURLHttp("FORCE_SC_ACCEPTED_TrueTestProxy")); RequestEntity entity = new FileRequestEntity(input, "text/xml"); post.setRequestEntity(entity); post.setRequestHeader("SOAPAction", "placeOrder"); HttpClient httpclient = new HttpClient(); try { responseStatus = httpclient.executeMethod(post); } finally { post.releaseConnection(); } assertEquals(responseStatus, 202, "Response status should be 202"); }
Example 7
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java From product-ei with Apache License 2.0 | 6 votes |
@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 8
Source File: NotebookRestApiTest.java From zeppelin with Apache License 2.0 | 5 votes |
@Test public void testCloneNote() throws IOException { LOG.info("Running testCloneNote"); Note note1 = null; String clonedNoteId = null; try { note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous); PostMethod post = httpPost("/notebook/" + note1.getId(), ""); LOG.info("testCloneNote response\n" + post.getResponseBodyAsString()); assertThat(post, isAllowed()); Map<String, Object> resp = gson.fromJson(post.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {}.getType()); clonedNoteId = (String) resp.get("body"); post.releaseConnection(); GetMethod get = httpGet("/notebook/" + clonedNoteId); assertThat(get, isAllowed()); Map<String, Object> resp2 = gson.fromJson(get.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {}.getType()); Map<String, Object> resp2Body = (Map<String, Object>) resp2.get("body"); // assertEquals(resp2Body.get("name"), "Note " + clonedNoteId); get.releaseConnection(); } finally { // cleanup if (null != note1) { TestUtils.getInstance(Notebook.class).removeNote(note1, anonymous); } if (null != clonedNoteId) { Note clonedNote = TestUtils.getInstance(Notebook.class).getNote(clonedNoteId); if (clonedNote != null) { TestUtils.getInstance(Notebook.class).removeNote(clonedNote, anonymous); } } } }
Example 9
Source File: ApacheHttpClient3xPluginIT.java From glowroot with Apache License 2.0 | 5 votes |
@Override public void transactionMarker() throws Exception { HttpClient httpClient = new HttpClient(); PostMethod httpPost = new PostMethod("http://localhost:" + getPort() + "/hello1"); httpClient.executeMethod(httpPost); httpPost.releaseConnection(); if (httpPost.getStatusCode() != 200) { throw new IllegalStateException( "Unexpected response status code: " + httpPost.getStatusCode()); } }
Example 10
Source File: CourseGroupMgmtITCase.java From olat with Apache License 2.0 | 5 votes |
@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 11
Source File: SchemaUtils.java From incubator-pinot with Apache License 2.0 | 5 votes |
/** * Given host, port and schema, send a http POST request to upload the {@link Schema}. * * @return <code>true</code> on success. * <P><code>false</code> on failure. */ public static boolean postSchema(@Nonnull String host, int port, @Nonnull Schema schema) { Preconditions.checkNotNull(host); Preconditions.checkNotNull(schema); try { URL url = new URL("http", host, port, "/schemas"); PostMethod httpPost = new PostMethod(url.toString()); try { Part[] parts = {new StringPart(schema.getSchemaName(), schema.toSingleLineJsonString())}; MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, new HttpMethodParams()); httpPost.setRequestEntity(requestEntity); int responseCode = HTTP_CLIENT.executeMethod(httpPost); if (responseCode >= 400) { String response = httpPost.getResponseBodyAsString(); LOGGER.warn("Got error response code: {}, response: {}", responseCode, response); return false; } return true; } finally { httpPost.releaseConnection(); } } catch (Exception e) { LOGGER.error("Caught exception while posting the schema: {} to host: {}, port: {}", schema.getSchemaName(), host, port, e); return false; } }
Example 12
Source File: UcsHttpClient.java From cloudstack with Apache License 2.0 | 5 votes |
public String call(String xml) { PostMethod post = new PostMethod(url); post.setRequestEntity(new StringRequestEntity(xml)); post.setRequestHeader("Content-type", "text/xml"); //post.setFollowRedirects(true); try { int result = client.executeMethod(post); if (result == 302) { // Handle HTTPS redirect // Ideal way might be to configure from add manager API // for using either HTTP / HTTPS // Allow only one level of redirect String redirectLocation; Header locationHeader = post.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); } else { throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager"); } post.setURI(new URI(redirectLocation)); result = client.executeMethod(post); } // Check for errors if (result != 200) { throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString()); } String res = post.getResponseBodyAsString(); if (res.contains("errorCode")) { String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res); throw new CloudRuntimeException(err); } return res; } catch (Exception e) { throw new CloudRuntimeException(e.getMessage(), e); } finally { post.releaseConnection(); } }
Example 13
Source File: ZeppelinRestApiTest.java From zeppelin with Apache License 2.0 | 5 votes |
@Test public void testMoveParagraph() throws IOException { Note note = null; try { note = TestUtils.getInstance(Notebook.class).createNote("note1_testMoveParagraph", anonymous); Paragraph p = note.addNewParagraph(AuthenticationInfo.ANONYMOUS); p.setTitle("title1"); p.setText("text1"); Paragraph p2 = note.addNewParagraph(AuthenticationInfo.ANONYMOUS); p2.setTitle("title2"); p2.setText("text2"); TestUtils.getInstance(Notebook.class).saveNote(note, anonymous); PostMethod post = httpPost("/notebook/" + note.getId() + "/paragraph/" + p2.getId() + "/move/" + 0, ""); assertThat("Test post method: ", post, isAllowed()); post.releaseConnection(); Note retrNote = TestUtils.getInstance(Notebook.class).getNote(note.getId()); Paragraph paragraphAtIdx0 = retrNote.getParagraphs().get(0); assertEquals(p2.getId(), paragraphAtIdx0.getId()); assertEquals(p2.getTitle(), paragraphAtIdx0.getTitle()); assertEquals(p2.getText(), paragraphAtIdx0.getText()); PostMethod post2 = httpPost("/notebook/" + note.getId() + "/paragraph/" + p2.getId() + "/move/" + 10, ""); assertThat("Test post method: ", post2, isBadRequest()); post.releaseConnection(); } finally { //cleanup if (null != note) { TestUtils.getInstance(Notebook.class).removeNote(note, anonymous); } } }
Example 14
Source File: OnlyHttpClient3Upload.java From oim-fx with MIT License | 5 votes |
public String upload(String http, String tagName, File file, Map<String, String> dataMap) { String body = null; PostMethod filePost = new PostMethod(http); try { if (dataMap != null) { // 通过以下方法可以模拟页面参数提交 // filePost.setParameter("name", "中文"); Iterator<Map.Entry<String, String>> i = dataMap.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, String> entry = i.next(); String inputName = (String) entry.getKey(); String inputValue = (String) entry.getValue(); filePost.setParameter(inputName, inputValue); } } Part[] parts = { new FilePart(file.getName(), file) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); body = filePost.getResponseBodyAsString(); if (status == HttpStatus.SC_OK) {// 上传成功 } else {// 上传失败 } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } return body; }
Example 15
Source File: NotebookRestApiTest.java From zeppelin with Apache License 2.0 | 4 votes |
@Test public void testRunWithServerRestart() throws Exception { LOG.info("Running testRunWithServerRestart"); Note note1 = null; try { note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous); // 2 paragraphs // P1: // %python // from __future__ import print_function // import time // time.sleep(1) // user='abc' // P2: // %python // print(user) // Paragraph p1 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS); Paragraph p2 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS); p1.setText("%python from __future__ import print_function\nimport time\ntime.sleep(1)\nuser='abc'"); p2.setText("%python print(user)"); PostMethod post1 = httpPost("/notebook/job/" + note1.getId() + "?blocking=true", ""); assertThat(post1, isAllowed()); post1.releaseConnection(); PutMethod put = httpPut("/notebook/" + note1.getId() + "/clear", ""); LOG.info("test clear paragraph output response\n" + put.getResponseBodyAsString()); assertThat(put, isAllowed()); put.releaseConnection(); // restart server (while keeping interpreter configuration) AbstractTestRestApi.shutDown(false); startUp(NotebookRestApiTest.class.getSimpleName(), false); note1 = TestUtils.getInstance(Notebook.class).getNote(note1.getId()); p1 = note1.getParagraph(p1.getId()); p2 = note1.getParagraph(p2.getId()); PostMethod post2 = httpPost("/notebook/job/" + note1.getId() + "?blocking=true", ""); assertThat(post2, isAllowed()); Map<String, Object> resp = gson.fromJson(post2.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {}.getType()); assertEquals(resp.get("status"), "OK"); post2.releaseConnection(); assertEquals(Job.Status.FINISHED, p1.getStatus()); assertEquals(p2.getReturn().toString(), Job.Status.FINISHED, p2.getStatus()); assertNotNull(p2.getReturn()); assertEquals("abc\n", p2.getReturn().message().get(0).getData()); } finally { // cleanup if (null != note1) { TestUtils.getInstance(Notebook.class).removeNote(note1, anonymous); } } }
Example 16
Source File: NotebookRestApiTest.java From zeppelin with Apache License 2.0 | 4 votes |
@Test public void testRunNoteWithParams() throws IOException, InterruptedException { Note note1 = null; try { note1 = TestUtils.getInstance(Notebook.class).createNote("note1", anonymous); // 2 paragraphs // P1: // %python // name = z.input('name', 'world') // print(name) // P2: // %sh // echo ${name|world} // Paragraph p1 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS); Paragraph p2 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS); p1.setText("%python name = z.input('name', 'world')\nprint(name)"); p2.setText("%sh echo '${name=world}'"); Map<String, Object> paramsMap = new HashMap<>(); paramsMap.put("name", "zeppelin"); ParametersRequest parametersRequest = new ParametersRequest(paramsMap); PostMethod post = httpPost("/notebook/job/" + note1.getId() + "?blocking=false&isolated=true&", parametersRequest.toJson()); assertThat(post, isAllowed()); Map<String, Object> resp = gson.fromJson(post.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {}.getType()); assertEquals(resp.get("status"), "OK"); post.releaseConnection(); // wait for all the paragraphs are done while(note1.isRunning()) { Thread.sleep(1000); } assertEquals(Job.Status.FINISHED, p1.getStatus()); assertEquals(Job.Status.FINISHED, p2.getStatus()); assertEquals("zeppelin\n", p1.getReturn().message().get(0).getData()); assertEquals("zeppelin\n", p2.getReturn().message().get(0).getData()); // another attempt rest api call without params post = httpPost("/notebook/job/" + note1.getId() + "?blocking=false&isolated=true", ""); assertThat(post, isAllowed()); resp = gson.fromJson(post.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {}.getType()); assertEquals(resp.get("status"), "OK"); post.releaseConnection(); // wait for all the paragraphs are done while(note1.isRunning()) { Thread.sleep(1000); } assertEquals(Job.Status.FINISHED, p1.getStatus()); assertEquals(Job.Status.FINISHED, p2.getStatus()); assertEquals("world\n", p1.getReturn().message().get(0).getData()); assertEquals("world\n", p2.getReturn().message().get(0).getData()); } finally { // cleanup if (null != note1) { TestUtils.getInstance(Notebook.class).removeNote(note1, anonymous); } } }
Example 17
Source File: KafkaAvroSchemaRegistry.java From incubator-gobblin with Apache License 2.0 | 4 votes |
/** * Register a schema to the Kafka schema registry * * @param schema * @return schema ID of the registered schema * @throws SchemaRegistryException if registration failed */ @Override public synchronized String register(Schema schema) throws SchemaRegistryException { // Change namespace if override specified if (this.namespaceOverride.isPresent()) { schema = AvroUtils.switchNamespace(schema, this.namespaceOverride.get()); } LOG.info("Registering schema " + schema.toString()); PostMethod post = new PostMethod(url); post.addParameter("schema", schema.toString()); HttpClient httpClient = this.borrowClient(); try { LOG.debug("Loading: " + post.getURI()); int statusCode = httpClient.executeMethod(post); if (statusCode != HttpStatus.SC_CREATED) { throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode); } String response; response = post.getResponseBodyAsString(); if (response != null) { LOG.info("Received response " + response); } String schemaKey; Header[] headers = post.getResponseHeaders(SCHEMA_ID_HEADER_NAME); if (headers.length != 1) { throw new SchemaRegistryException( "Error reading schema id returned by registerSchema call: headers.length = " + headers.length); } else if (!headers[0].getValue().startsWith(SCHEMA_ID_HEADER_PREFIX)) { throw new SchemaRegistryException( "Error parsing schema id returned by registerSchema call: header = " + headers[0].getValue()); } else { LOG.info("Registered schema successfully"); schemaKey = headers[0].getValue().substring(SCHEMA_ID_HEADER_PREFIX.length()); } return schemaKey; } catch (Throwable t) { throw new SchemaRegistryException(t); } finally { post.releaseConnection(); this.httpClientPool.returnObject(httpClient); } }
Example 18
Source File: InterpreterRestApiTest.java From zeppelin with Apache License 2.0 | 4 votes |
@Test public void testCreatedInterpreterDependencies() throws IOException { // when: Create 2 interpreter settings `md1` and `md2` which have different dep. String md1Name = "md1"; String md2Name = "md2"; String md1Dep = "org.apache.drill.exec:drill-jdbc:jar:1.7.0"; String md2Dep = "org.apache.drill.exec:drill-jdbc:jar:1.6.0"; String reqBody1 = "{\"name\":\"" + md1Name + "\",\"group\":\"md\"," + "\"properties\":{\"propname\": {\"value\": \"propvalue\", \"name\": \"propname\", " + "\"type\": \"textarea\"}}," + "\"interpreterGroup\":[{\"class\":\"org.apache.zeppelin.markdown.Markdown\"," + "\"name\":\"md\"}]," + "\"dependencies\":[ {\n" + " \"groupArtifactVersion\": \"" + md1Dep + "\",\n" + " \"exclusions\":[]\n" + " }]," + "\"option\": { \"remote\": true, \"session\": false }}"; PostMethod post = httpPost("/interpreter/setting", reqBody1); assertThat("test create method:", post, isAllowed()); post.releaseConnection(); String reqBody2 = "{\"name\":\"" + md2Name + "\",\"group\":\"md\"," + "\"properties\": {\"propname\": {\"value\": \"propvalue\", \"name\": \"propname\", " + "\"type\": \"textarea\"}}," + "\"interpreterGroup\":[{\"class\":\"org.apache.zeppelin.markdown.Markdown\"," + "\"name\":\"md\"}]," + "\"dependencies\":[ {\n" + " \"groupArtifactVersion\": \"" + md2Dep + "\",\n" + " \"exclusions\":[]\n" + " }]," + "\"option\": { \"remote\": true, \"session\": false }}"; post = httpPost("/interpreter/setting", reqBody2); assertThat("test create method:", post, isAllowed()); post.releaseConnection(); // 1. Call settings API GetMethod get = httpGet("/interpreter/setting"); String rawResponse = get.getResponseBodyAsString(); get.releaseConnection(); // 2. Parsing to List<InterpreterSettings> JsonObject responseJson = gson.fromJson(rawResponse, JsonElement.class).getAsJsonObject(); JsonArray bodyArr = responseJson.getAsJsonArray("body"); List<InterpreterSetting> settings = new Gson().fromJson(bodyArr, new TypeToken<ArrayList<InterpreterSetting>>() { }.getType()); // 3. Filter interpreters out we have just created InterpreterSetting md1 = null; InterpreterSetting md2 = null; for (InterpreterSetting setting : settings) { if (md1Name.equals(setting.getName())) { md1 = setting; } else if (md2Name.equals(setting.getName())) { md2 = setting; } } // then: should get created interpreters which have different dependencies // 4. Validate each md interpreter has its own dependencies assertEquals(1, md1.getDependencies().size()); assertEquals(1, md2.getDependencies().size()); assertEquals(md1Dep, md1.getDependencies().get(0).getGroupArtifactVersion()); assertEquals(md2Dep, md2.getDependencies().get(0).getGroupArtifactVersion()); }
Example 19
Source File: ZeppelinRestApiTest.java From zeppelin with Apache License 2.0 | 4 votes |
@Test public void testImportNotebook() throws IOException { Note note = null; Note newNote = null; Map<String, Object> resp; String oldJson; String noteName; try { noteName = "source note for import"; LOG.info("testImportNote"); // create test note note = TestUtils.getInstance(Notebook.class).createNote("note1_testImportNotebook", anonymous); assertNotNull("can't create new note", note); note.setName(noteName); Paragraph paragraph = note.addNewParagraph(AuthenticationInfo.ANONYMOUS); Map config = paragraph.getConfig(); config.put("enabled", true); paragraph.setConfig(config); paragraph.setText("%md This is my new paragraph in my new note"); TestUtils.getInstance(Notebook.class).saveNote(note, anonymous); String sourceNoteId = note.getId(); // get note content as JSON oldJson = getNoteContent(sourceNoteId); // delete it first then import it TestUtils.getInstance(Notebook.class).removeNote(note, anonymous); // call note post PostMethod importPost = httpPost("/notebook/import/", oldJson); assertThat(importPost, isAllowed()); resp = gson.fromJson(importPost.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {}.getType()); String importId = (String) resp.get("body"); assertNotNull("Did not get back a note id in body", importId); newNote = TestUtils.getInstance(Notebook.class).getNote(importId); assertEquals("Compare note names", noteName, newNote.getName()); assertEquals("Compare paragraphs count", note.getParagraphs().size(), newNote.getParagraphs() .size()); importPost.releaseConnection(); } finally { if (null != note) { if (TestUtils.getInstance(Notebook.class).getNote(note.getId()) != null) { TestUtils.getInstance(Notebook.class).removeNote(note, anonymous); } } if (null != newNote) { if (TestUtils.getInstance(Notebook.class).getNote(newNote.getId()) != null) { TestUtils.getInstance(Notebook.class).removeNote(newNote, anonymous); } } } }
Example 20
Source File: ClusterEventTest.java From zeppelin with Apache License 2.0 | 4 votes |
@Test public void testInterpreterEvent() throws IOException, InterruptedException { // when: Create 1 interpreter settings `sh1` String md1Name = "sh1"; String md1Dep = "org.apache.drill.exec:drill-jdbc:jar:1.7.0"; String reqBody1 = "{\"name\":\"" + md1Name + "\",\"group\":\"sh\"," + "\"properties\":{\"propname\": {\"value\": \"propvalue\", \"name\": \"propname\", " + "\"type\": \"textarea\"}}," + "\"interpreterGroup\":[{\"class\":\"org.apache.zeppelin.shell.ShellInterpreter\"," + "\"name\":\"md\"}]," + "\"dependencies\":[ {\n" + " \"groupArtifactVersion\": \"" + md1Dep + "\",\n" + " \"exclusions\":[]\n" + " }]," + "\"option\": { \"remote\": true, \"session\": false }}"; PostMethod post = httpPost("/interpreter/setting", reqBody1); String postResponse = post.getResponseBodyAsString(); LOG.info("testCreatedInterpreterDependencies create response\n" + post.getResponseBodyAsString()); InterpreterSetting created = convertResponseToInterpreterSetting(postResponse); MatcherAssert.assertThat("test create method:", post, isAllowed()); post.releaseConnection(); // 1. Call settings API GetMethod get = httpGet("/interpreter/setting"); String rawResponse = get.getResponseBodyAsString(); get.releaseConnection(); // 2. Parsing to List<InterpreterSettings> JsonObject responseJson = gson.fromJson(rawResponse, JsonElement.class).getAsJsonObject(); JsonArray bodyArr = responseJson.getAsJsonArray("body"); List<InterpreterSetting> settings = new Gson().fromJson(bodyArr, new TypeToken<ArrayList<InterpreterSetting>>() { }.getType()); // 3. Filter interpreters out we have just created InterpreterSetting md1 = null; for (InterpreterSetting setting : settings) { if (md1Name.equals(setting.getName())) { md1 = setting; } } // then: should get created interpreters which have different dependencies // 4. Validate each md interpreter has its own dependencies assertEquals(1, md1.getDependencies().size()); assertEquals(md1Dep, md1.getDependencies().get(0).getGroupArtifactVersion()); Thread.sleep(1000); checkClusterIntpSettingEventListener(); // 2. test update Interpreter String rawRequest = "{\"name\":\"sh1\",\"group\":\"sh\"," + "\"properties\":{\"propname\": {\"value\": \"propvalue\", \"name\": \"propname\", " + "\"type\": \"textarea\"}}," + "\"interpreterGroup\":[{\"class\":\"org.apache.zeppelin.markdown.Markdown\"," + "\"name\":\"md\"}],\"dependencies\":[]," + "\"option\": { \"remote\": true, \"session\": false }}"; JsonObject jsonRequest = gson.fromJson(rawRequest, JsonElement.class).getAsJsonObject(); // when: call update setting API JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("name", "propname2"); jsonObject.addProperty("value", "this is new prop"); jsonObject.addProperty("type", "textarea"); jsonRequest.getAsJsonObject("properties").add("propname2", jsonObject); PutMethod put = httpPut("/interpreter/setting/" + created.getId(), jsonRequest.toString()); LOG.info("testSettingCRUD update response\n" + put.getResponseBodyAsString()); // then: call update setting API MatcherAssert.assertThat("test update method:", put, isAllowed()); put.releaseConnection(); Thread.sleep(1000); checkClusterIntpSettingEventListener(); // 3: call delete setting API DeleteMethod delete = httpDelete("/interpreter/setting/" + created.getId()); LOG.info("testSettingCRUD delete response\n" + delete.getResponseBodyAsString()); // then: call delete setting API MatcherAssert.assertThat("Test delete method:", delete, isAllowed()); delete.releaseConnection(); Thread.sleep(1000); checkClusterIntpSettingEventListener(); }