Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

Usually service integrations are via posting JSON or XML. I had a need to integrate with a service that used an HTTP form post. Wait, what? How do you do that? Springframework provides a MultiValueMap interface that is posted as form data. LinkedMultiValueMap is an implementation of the MultiValueMap interface. The MultiValueMap is backed by a LinkedHashMap as opposed to a Map. Hence, it uses add instead of put.

Let’s see it in some code…

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
// properties that identify our system, etc
map.add("username", username);
map.add("password", password);
map.add("ageToCheck", ageToCheck);
map.add("firstName", kycModel.getFirstName());
map.add("lastName", kycModel.getLastName());
map.add("address", kycModel.getAddress());
map.add("city", kycModel.getCity());
map.add("state", kycModel.getState());
map.add("zip", kycModel.getZip());
map.add("dobMonth", kycModel.getDobMonth());
map.add("dobDay", kycModel.getDobDay());
map.add("dobYear", kycModel.getDobYear());
map.add("ssnLast4", kycModel.getSsnLast4());

Response response = restTemplate.postForObject(url, map, Response.class);

From there on, the RestTemplate works as it normally does.

September 22nd, 2015

Posted In: Java, java ninja, Javaninja, Spring

Tags: , , , ,

Leave a Comment

There are several times when you need to specify a location in a Springframework configuration. An example is

<util:properties id="gsiProperties" location="classpath:gaming-adapter-default.properties"/>

A location is represented as a Resource. There are several ways to specify where to find the resource.

  • classpath: This represents a resource that should be retrieved from the classpath. It works the way a normal classloader does. The first match wins. Package names can also be represented as file directories (e.g. /this/that/my.properties
  • classpath:* This means that ALL resources that match the given name must be obtained, then merged to form a single resource. Meaning multiple property files could be mapped to. The sum of them would be used to supply the properties.
  • file: This is used to access a file system resource. This can be an absolute path or relative path.
  • http: This is used to access resources via HTTP protocol with a URL.
  • ftp: this is used to access a resource via FTP protocol.
  • blank This relies upon the implementation of the underlying context. For web applications, this utilizes the Servlet context.

July 28th, 2015

Posted In: java ninja, Javaninja, Spring

Tags: , , , , ,

Leave a Comment

In a previous post HttpClient 4 Json Post I showed how to post a Json object to a URL. That was useful, but required writing a method for each type of object you needed posted. A cleaner way is to use Java Generics to make a method that can accept multiple types of objects and can even return specific objects instead of a Json string.

    /**
     * Returns the http response as the specified object.
     * @param url the url to request
     * @param object the object to convert to the json payload
     * @param responseType the object type to convert the json response into
     * @throws IOException
     */
    public static <T> T postForObject(String url, Object object, Class<T> responseType) throws IOException {
        log.debug("Post: " + url);
        String response = "";
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(JsonUtils.toJson(object));
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-type", "application/json");
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            response = httpclient.execute(httpPost, responseHandler);
        } catch (IOException e) {
            log.error("IOException from " + url + " with " + object , e);
            throw e;
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return JsonUtils.toObject(response, responseType);
    }

The method return type is modified to return T and the method signature is changed to include Class responseType. Then responseType is used to tell the Json library what type of object is desired.

Here is a simple usage of the post method.

            AccountResponse accountResponse =
                    HttpUtils.postForObject(Server.IGP_ADAPTER_URL + "/accountBalances",
                            accountRequest,
                            AccountResponse.class);

December 11th, 2014

Posted In: Java

Tags: , , , , , , ,

Leave a Comment

Posting JSON to a URL is a common use case. Here is a follow-on to HttpClient Post for a String.

    /**
     * Performs HTTP post.
     * @param url http resource to post
     * @return string response
     */
    protected String post(String url, MyJsonObject myJsonObject) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(JsonUtils.toJson(myJsonObject));
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-type", "application/json");
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            responseBody = httpclient.execute(httpPost, responseHandler);
        } catch (IOException e) {
            log.error("IOException from " + url + " with " + object , e);
            throw e;
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return responseBody;
    }

Line 13 and 14 convert the object to be posted into a Json string and set it as the payload to be sent to the URL.
Line 15 sets the content type so the URL knows that you can accept JSON as a response.

December 11th, 2014

Posted In: Java

Tags: , , , ,

5 Comments

Continuing from my Http Get Example, here is an example of an HttpClient4 String post example.

    /**
     * Performs HTTP post.
     * @param url http resource to post
     * @return string response
     */
    protected String post(String url) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = null;
        try {
            responseBody = httpClient.execute(httpPost, responseHandler);
        } catch (IOException e) {
            log.error("IOException", e);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();
        }
        return responseBody;
    }

December 11th, 2014

Posted In: Java

Tags: , , , , , , , ,

One Comment

LinkedIn Auto Publish Powered By : XYZScripts.com