
/*
 *  Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
*/
package oracle.jcs.ws.sample.oauth.client;

import java.util.*;
import java.io.*;
import java.lang.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.ClientFilter;
import com.sun.jersey.api.client.filter.LoggingFilter;

import oracle.wsm.agent.handler.jaxrs.RESTClientFilter;

import com.sun.jersey.api.client.ClientResponse;

import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;


public class HelloWorldClientServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException,
                                                              IOException {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        String BASE_URI =request.getParameter("address");
        ClientConfig cc = new DefaultClientConfig();
        Client client = Client.create(cc);
        RESTClientFilter filter = new RESTClientFilter();
        client.addFilter(filter);
        client.addFilter(new LoggingFilter(System.out));
        try{
            WebResource webResource = client.resource(BASE_URI);
            ClientResponse res = webResource.get(ClientResponse.class);
            int status = res.getStatus();
            String reasonPhrase = res.getClientResponseStatus().getReasonPhrase();
            String textEntity = res.getEntity(String.class);
            out.println("Response status :" + status);
            out.println("Reason Phrase :" + reasonPhrase);
            out.println("Response :" + textEntity);
        } catch(Exception e){
            String[] messages = getAllInnerErrorMessages(e);
            int count = 0;
            String allMsg = null;
            for (String mes : messages) {
                if (count != 0) {
                    allMsg += "\n|";
                    allMsg = allMsg + "\n+" + (getString("-", count * 3) + "-> Caused By : " + mes);
                } else {
                    allMsg = mes;
                }
                count++;
            }
            out.println("The client was not able to call the service using OAuth. The exception causes are: \n" + allMsg);
        }  
        out.close();
    }
    
    private String[] getAllInnerErrorMessages(Throwable th) {
        List<String> all = new ArrayList<String>();
        boolean msgFound = false;
        while (th != null) {
            if (th.getMessage() != null && !th.getMessage().trim().equals("")) {
                if (!msgFound && all.size() > 0) {
                    all.add(0, th.getMessage());
                }
                all.add(th.getMessage());
                msgFound = true;
            } else {
                all.add(th.getClass().getName());
            }
            th = th.getCause();
        }
        return all.toArray(new String[0]);
    }
    
    private String getString(String sp, int count){
        StringBuffer ret = new StringBuffer();
        for (int i = 0; i < count; i++){
            ret.append(sp);
        }
        return ret.toString();
    }
        
}
