com.image32.demo.simpleapi.ContentHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.image32.demo.simpleapi.ContentHandler.java

Source

/*
 * The MIT License (MIT)
    
Copyright (c) 2014 Interconnect Medical, Inc.
    
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
    
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
    
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
    
 */

package com.image32.demo.simpleapi;

import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.handler.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

public class ContentHandler extends AbstractHandler {

    static Logger logger = LoggerFactory.getLogger(ContentHandler.class.getName());

    private void httpHeaderNoCache(HttpServletResponse response) {
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
    }

    ///////// Server handlers for embedded Jetty  

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
            throws IOException, ServletException {
        HttpSession session = request.getSession();
        response.setStatus(HttpServletResponse.SC_OK);
        httpHeaderNoCache(response);

        ((Request) request).setHandled(true);

        if (request.getMethod().equals("POST") && target.equals("/login")) {
            response.setContentType("application/json;charset=utf-8");
            String requestToken = request.getParameter("requestToken");
            String demoPass = request.getParameter("demoPass");
            logger.info("logging in with requestToken:" + requestToken + " demoPass:" + demoPass);
            Image32APIAuthResponse responseObj = null;
            HashMap<String, String> out = new HashMap<String, String>();

            if (demoPass != null && (demoPass.equals("admin"))) { //has no security for this demo.
                session.setAttribute("adminRole", true);
                //authenticate with image32 api
                DefaultHttpClient httpclient = new DefaultHttpClient();//
                HttpPost httpPost = new HttpPost(SimpleApiDemo.image32ApiAuthUrl);
                try {
                    String body = "{\"client_id\": \"" + SimpleApiDemo.image32ApiClientId
                            + "\",\"client_secret\":\"" + SimpleApiDemo.image32ApiSecrect
                            + "\",\"auth_request_token\":\"" + requestToken + "\",";
                    body += "\"scopes\":[";
                    body += "{\"type\":\"user-id\",\"id\":\"abc_user_001\",\"permission\":\"view\"},"; //give access to all studies
                    body += "{\"type\":\"case-id\",\"id\":\"abc\",\"permission\":\"full\"}"; //give full access to case/folder 'abc'
                    body += "]}";
                    HttpEntity entity = new ByteArrayEntity(body.getBytes("UTF-8"));
                    httpPost.setEntity(entity);
                    HttpResponse apiResponse = httpclient.execute(httpPost);
                    String result = EntityUtils.toString(apiResponse.getEntity());
                    logger.info("image32 api response:" + result);
                    EntityUtils.consume(entity);
                    //parse response
                    Gson gson = new Gson();
                    responseObj = gson.fromJson(result, Image32APIAuthResponse.class);
                    session.setAttribute("responseObj", responseObj);

                    if (responseObj != null && responseObj.getRedirect_url() != null) {
                        out.put("confirmUrl", responseObj.getRedirect_url());
                    }

                } catch (ParseException e) {
                    logger.warn(e.getMessage());

                } finally {
                    httpPost.releaseConnection();
                }
                out.put("result", "true");

                //print journal entries
                Gson gson = new Gson();

                //print response
                String outStr = gson.toJson(out);
                response.getWriter().println(outStr);
            } else {
                response.getWriter().println("{\"result\":false}");//role is not valid
            }

            return;

        }
        //      else if (request.getMethod().equals("POST") && target.equals("/getStudies") && isWriter(session)) {
        //         //get all available studies for current session
        //         response.setContentType("application/json;charset=utf-8");
        //         logger.info("getStudies");
        //         
        //         Image32APIAuthResponse responseObj = (Image32APIAuthResponse)session.getAttribute("responseObj");
        //         if(responseObj!=null){
        //            //get all studies
        //            HttpGet httpGet = new HttpGet(SimpleApiDemo.image32ApiGetStudiesUrl);
        //            
        //            try {
        //               httpGet.setHeader("Authorization", "Bearer "+responseObj.getAccess_token());
        //               DefaultHttpClient httpclient = new DefaultHttpClient();
        //               HttpResponse apiResponse = httpclient.execute(httpGet);
        //               String result = EntityUtils.toString(apiResponse.getEntity());
        //               EntityUtils.consume(apiResponse.getEntity());
        //               response.getWriter().println(result);
        //               logger.info("image32 api response:" + result);
        //               
        //            } catch (ParseException e) {
        //               logger.warn(e.getMessage());
        //               
        //            }finally{
        //               httpGet.releaseConnection();
        //            }
        //         }
        //      }
    }

    class Image32APIAuthResponse {
        String access_token;
        long expires_in;
        String redirect_url;

        public String getAccess_token() {
            return access_token;
        }

        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }

        public long getExpires_in() {
            return expires_in;
        }

        public void setExpires_in(long expires_in) {
            this.expires_in = expires_in;
        }

        public String getRedirect_url() {
            return redirect_url;
        }

        public void setRedirect_url(String redirect_url) {
            this.redirect_url = redirect_url;
        }

    }
}