Java - API Sample Code
Abstract
Java - API Sample Code
In this section you find code samples for an Apache HttpClient dependency and for suggesting a concept.
For the following code snippets Java 7 was used. You can use different implementations of HTTP clients in Java. See the following examples to find different approaches:
Suggest a New Concept
This example uses the PoolParty API Web Service Method: Suggest Concept
This example uses Apache HttpClient as dependency to build an HTTP client.
Maven Dependency Snippet
<dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> </dependencies>
Download: SuggestConceptSampleRequest.java
POST Suggest Concept Sample Code
package biz.poolparty.api.sample; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.logging.*; /** * Sample request to show functionality of PoolParty API in Java code. */ public class SuggestConceptSampleRequest { private static final Logger LOGGER = Logger.getAnonymousLogger(); public static void main(String[] args) { // logger setting, printing output to console LOGGER.setLevel(Level.ALL); ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(new VerySimpleFormatter()); handler.setLevel(Level.FINE); LOGGER.addHandler(handler); SuggestConceptSampleRequest suggestConceptSampleRequest = new SuggestConceptSampleRequest(); suggestConceptSampleRequest.suggestConcept( "user", "password", "https://rockefeller.poolparty.biz", "1DDF868D-B8E0-0001-C53B-AD39B7102A50", "Hello world", "en", "http://rockefeller.poolparty.biz/test/1"); } /** * Method to suggest a concept in a PoolParty project. * This example shows adding a concept sending a preferred label in default language, * providing an existing concept that can be used as future parent concept. * * @param username user - used for API credentials * @param password password - used for API credentials * @param server the target PoolParty server, e.g. https://rockefeller.poolparty.biz * @param projectUuid PoolParty project unique identifier * @param prefLabel label that should be suggested as new concept * @param defaultLanguage language the label * @param broaderConcept existing concept that should become parent */ public void suggestConcept(String username, String password, String server, String projectUuid, String prefLabel, String defaultLanguage, String broaderConcept){ // prepare HTTP client, providing credentials for basic auth CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); // prepare the request URL HttpPost httpPost = new HttpPost(server + "/PoolParty/api/thesaurus/" + projectUuid + "/suggestConcept"); // formulate JSON string as described in the documentation String requestJson = "{\n" + " \"prefLabels\": [\n" + " {\n" + " \"label\":\"" + prefLabel + "\",\n" + " \"language\":\"" + defaultLanguage + "\"\n" + " }\n" + " ],\n" + " \"broaderConcept\": [\n" + " {\n" + " \"uri\":\"" + broaderConcept + "\"\n" + " }\n" + " ],\n" + " \"checkForDuplicates\" : true\n" + "}"; StringEntity input; try { input = new StringEntity(requestJson); } catch (UnsupportedEncodingException e) { LOGGER.log(Level.SEVERE, "Provided JSON format could not be encoded.", e); return; } input.setContentType("application/json"); httpPost.setEntity(input); // output request to console LOGGER.log(Level.FINE, "Executing request: " + httpPost.getRequestLine()); // fire request CloseableHttpResponse response; try { response = httpClient.execute(httpPost); } catch (IOException e) { LOGGER.log(Level.SEVERE, "HTTP request execution failed.", e); return; } // present response LOGGER.log(Level.FINE, "- Response -"); LOGGER.log(Level.FINE, response.getStatusLine().toString()); try { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder responseContent = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { responseContent.append(line); } LOGGER.log(Level.FINE, responseContent.toString()); } catch (IOException e) { LOGGER.log(Level.WARNING, "Error during processing response content.", e); } finally { try { httpClient.close(); response.close(); } catch (IOException e) { // ignore } } LOGGER.log(Level.FINE, "Request processed"); } /** * Formatter for very simple log output. */ static class VerySimpleFormatter extends Formatter { public String format(LogRecord record) { StringBuilder builder = new StringBuilder(1000); builder.append(formatMessage(record)); builder.append("\n"); return builder.toString(); } public String getHead(Handler h) { return super.getHead(h); } public String getTail(Handler h) { return super.getTail(h); } } }