com.mama100.rs.client.RESTfulClient.java Source code

Java tutorial

Introduction

Here is the source code for com.mama100.rs.client.RESTfulClient.java

Source

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 com.mama100.rs.client;

import com.mama100.rs.common.Customer;
import com.mama100.rs.common.CustomerService;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;

import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.security.KeyStore;

public final class RESTfulClient {

    private static final String CLIENT_CONFIG_FILE = "ClientConfig.xml";
    private static final String BASE_SERVICE_URL = "https://localhost:9000/customerservice/customers";

    private RESTfulClient() {
        try {
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void callWebClient4get() {
        WebClient wc = WebClient.create(BASE_SERVICE_URL + "/123", CLIENT_CONFIG_FILE);
        Response resp = wc.get();

        System.out.println(" result status: " + resp.getStatus());
        System.out.println(" Sending HTTPS Get to update customer :" + resp.readEntity(Customer.class).toString());
    }

    public void callHttpClient() throws Exception {
        String keyStoreLoc = "clientKeystore.jks";

        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreLoc);
        if (is == null) {
            System.out.println("--------------------can't get the resource file " + keyStoreLoc);
        }
        keyStore.load(is, "cspass".toCharArray());
        /*
         * Send HTTP GET request to query customer info using portable HttpClient
         * object from Apache HttpComponents
         */
        SSLSocketFactory sf = new SSLSocketFactory(keyStore, "ckpass", keyStore);
        Scheme httpsScheme = new Scheme("https", 9000, sf);

        System.out.println("Sending HTTPS GET request to query customer info");
        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getConnectionManager().getSchemeRegistry().register(httpsScheme);
        HttpGet httpget = new HttpGet(BASE_SERVICE_URL + "/123");
        BasicHeader bh = new BasicHeader("Accept", "text/xml");
        httpget.addHeader(bh);

        HttpResponse response = httpclient.execute(httpget);
        System.out.println("-----" + response.getStatusLine().getStatusCode());
        HttpEntity entity = response.getEntity();
        entity.writeTo(System.out);
        httpclient.getConnectionManager().shutdown();
    }

    /**
     *  Send HTTP PUT request to update customer info, using CXF WebClient method
     *  Note: if need to use basic authentication, use the WebClient.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    public void callWebClient4Update() throws Exception {

        System.out.println("");
        Customer customer = new Customer();
        customer.setId(123);
        customer.setName("Mary");
        WebClient wc = WebClient.create(BASE_SERVICE_URL, CLIENT_CONFIG_FILE);
        Response resp = wc.put(customer);

        System.out.println(" result status: " + resp.getStatus());
        System.out.println(" Sending HTTPS PUT to update customer name." + resp.getEntity().toString());
    }

    /**
    *  Send HTTP POST request to add customer, using JAXRSClientProxy
    *  Note: if need to use basic authentication, use the JAXRSClientFactory.create(baseAddress,
    *  username,password,configFile) variant, where configFile can be null if you're
    *  not using certificates.
    */
    public void callWebClient4Addition() throws Exception {
        WebClient wc = WebClient.create(BASE_SERVICE_URL, CLIENT_CONFIG_FILE);
        Customer customer = new Customer();
        customer.setName("Jack");
        CustomerService proxy = JAXRSClientFactory.create(BASE_SERVICE_URL, CustomerService.class,
                CLIENT_CONFIG_FILE);
        Response resp = wc.post(customer);

        System.out.println("Sending HTTPS POST request to add customer, get result status :" + resp.getStatus()
                + ", result :" + resp.getHeaders().values().size());
    }

    final void init() throws Exception {
        callWebClient4get();
        callHttpClient();
        callWebClient4Update();
        callWebClient4Addition();
    }

    public static void main(String args[]) {
        new RESTfulClient();
    }
}