Java tutorial
/* * Dashboard * Copyright 2014 Christian Robert * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.perdian.apps.dashboard.support.clients; import java.util.Map; import java.util.Properties; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.BasicHttpContext; import org.codehaus.jackson.JsonNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.perdian.apps.dashboard.DashboardException; /** * Abstract implementation of a client that establishes a connection to a remote * system and is able to retrieve JSON data from that remote system. * * @author Christian Robert */ public class JsonClient implements AutoCloseable { private static final Logger log = LoggerFactory.getLogger(JsonClient.class); private String username = null; private String password = null; private Properties defaultHeaders = null; private CloseableHttpClient httpClient = null; public JsonClient(String username, String password) { this(username, password, 1000 * 10); } public JsonClient(String username, String password, int timeout) { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder.setConnectTimeout(timeout); requestBuilder.setSocketTimeout(timeout); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultRequestConfig(requestBuilder.build()); this.setHttpClient(clientBuilder.build()); this.setDefaultHeaders(new Properties()); this.setUsername(username); this.setPassword(password); } @Override @SuppressWarnings("resource") public void close() { CloseableHttpClient currentClient = this.getHttpClient(); if (currentClient != null) { try { currentClient.close(); } catch (Exception e) { log.trace("Cannot close HttpClient", e); } } } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(this.getClass().getSimpleName()); result.append("[httpClient=").append(this.getHttpClient()); return result.append("]").toString(); } /** * Executes the given job and return the response * * @param requestUri * the URI to which the request should be sent * @return * the JSON result */ public JsonNode sendRequest(CharSequence requestUri) { try { HttpGet httpGet = new HttpGet(requestUri.toString()); if (this.getUsername() != null && this.getPassword() != null) { httpGet.addHeader(new BasicScheme().authenticate( new UsernamePasswordCredentials(this.getUsername(), this.getPassword()), httpGet, new BasicHttpContext())); } for (Map.Entry<Object, Object> defaultHeaderEntry : this.getDefaultHeaders().entrySet()) { httpGet.addHeader((String) defaultHeaderEntry.getKey(), (String) defaultHeaderEntry.getValue()); } String httpResponseString = this.getHttpClient().execute(httpGet, new BasicResponseHandler()); return JsonUtil.fromJsonString(httpResponseString); } catch (Exception e) { StringBuilder errorMessage = new StringBuilder(); errorMessage.append("Cannot send HTTP request [").append(requestUri); errorMessage.append("] using client [").append(this).append("]"); log.debug(errorMessage.toString(), e); throw new DashboardException(errorMessage.toString(), e); } } // ------------------------------------------------------------------------- // --- Property access methods --------------------------------------------- // ------------------------------------------------------------------------- private CloseableHttpClient getHttpClient() { return this.httpClient; } private void setHttpClient(CloseableHttpClient httpClient) { this.httpClient = httpClient; } public String getUsername() { return this.username; } private void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } private void setPassword(String password) { this.password = password; } public Properties getDefaultHeaders() { return this.defaultHeaders; } public void setDefaultHeaders(Properties defaultHeaders) { this.defaultHeaders = defaultHeaders; } }