Package servlets

Source Code of servlets.Documento

package servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.DocumentoCreateExternoRequest;
import models.LoginResponse;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import base64.Base64Coder;

import com.google.gson.Gson;

import communication.Global;

/**
* Servlet implementation class Documento
*/
@WebServlet("/Documento")
public class Documento extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private static final String CAMINHO_API_DOCUMENTO = "api/documento/";
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Documento() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {

      if (request.getParameter("action") != null) {

        HttpSession session = request.getSession(true);
        LoginResponse login = (LoginResponse) session.getAttribute(Global.LOGIN);

        if (login != null) {

          //Busca o parametro enviado pelo form
          String action = request.getParameter("action").toLowerCase();
          HttpResponse httpResp = null;
         
          switch (action) {
          case "listbyusuario":
            if (request.getParameter("status") != null) {
              httpResp = listByUsuario(request.getParameter("status"), login);
            } else {
              response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }
           
            break;

          case "getbyid":
            if (request.getParameter("documento") != null) {
              httpResp = getById(request.getParameter("documento"), login);
            } else {
              response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }

            break;
          default:
            break;
          }
         
          if (httpResp != null){
            StatusLine statusLine = httpResp.getStatusLine();

            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
            String data = reader.readLine();

            response.setStatus(statusLine.getStatusCode());
            PrintWriter out = response.getWriter();
            out.print(data);
          }
        } else {
          response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }

      } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      }

    } catch (Exception e) {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * Submete o documento para assinatura
   * http://homolog.portaldeassinaturas.com.br/Help/Api/POST-Api-Documento-Create
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    try {
      Gson gson = new Gson();

      if (request.getParameter("documento") != null) {

        HttpSession session = request.getSession(true);
        LoginResponse login = (LoginResponse) session.getAttribute(Global.LOGIN);

        if (login != null) {

          //Busca o parametro enviado pelo form
          DocumentoCreateExternoRequest documento = gson.fromJson(request.getParameter("documento"), DocumentoCreateExternoRequest.class);

          //L� o arquivo enviado
          String fileDir = getFilePath(request, documento.getArquivoNome());

          byte[] fileBytes = Files.readAllBytes(Paths.get(fileDir));

          documento.setBytes(Base64Coder.encode(fileBytes));

          String apiName = CAMINHO_API_DOCUMENTO + "CreateExterno";

          HttpPost httpPost = new HttpPost(Global.ApiPortalBaseURL + apiName);

          httpPost.setHeader(Global.ACS_AUTH_CONTEXT_UID, login.getUidContextos(0));
          httpPost.setHeader(Global.ACS_AUTH_TOKEN, login.getToken());
          httpPost.setHeader(Global.ACS_AUTH_USER_UID, login.getUserInfo().getUid());

          StringEntity entity = new StringEntity(gson.toJson(documento), StandardCharsets.UTF_8);
          entity.setContentType("application/json");
          httpPost.setEntity(entity);

          CloseableHttpClient client = HttpClients.createDefault();

          HttpResponse httpResp = client.execute(httpPost);
          StatusLine statusLine = httpResp.getStatusLine();

          if (statusLine.getStatusCode() < 300) {
            response.setStatus(statusLine.getStatusCode());
          }
          else {
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
            String msg = reader.readLine();

            response.setContentType("application/json");
            response.setStatus(statusLine.getStatusCode());
           
            PrintWriter out = response.getWriter();
            out.print(msg);
          }
        }
        else {
          response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }

      }
      else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      }

    } catch (Exception e) {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
   
   
  }

  /**
   * Lista documentos de um usu�rio
   * http://homolog.portaldeassinaturas.com.br/Help/Api/POST-Api-Documento-ListByUsuario
   */
  private HttpResponse listByUsuario(String status, LoginResponse login) throws Exception {

    try {
       
      String apiName = CAMINHO_API_DOCUMENTO + "ListByStatusPeriodo?status="+status+"&inicio=&fim=&matrizId=";

      HttpGet httpget = new HttpGet(Global.ApiPortalBaseURL + apiName);
   
      httpget.setHeader(Global.ACS_AUTH_CONTEXT_UID, login.getUidContextos(0));
      httpget.setHeader(Global.ACS_AUTH_TOKEN, login.getToken());
      httpget.setHeader(Global.ACS_AUTH_USER_UID, login.getUserInfo().getUid());
     
      CloseableHttpClient client = HttpClients.createDefault();

      HttpResponse httpResp = client.execute(httpget);     
             
         
      return httpResp;

    } catch (Exception e) {
      throw e;
    }
 
  }
 
  private String getFilePath(HttpServletRequest request, String fileName) {
    String fileDir = request.getSession().getServletContext().getRealPath("/") + Global.FILE_DIR;
    if (fileDir.length() > 0 && fileDir.charAt(fileDir.length()-1)=='/') {
      fileDir = fileDir.substring(0, fileDir.length()-1) + "\\" + fileName;
    }
    return fileDir;
  }

  private HttpResponse getById(String idDoc, LoginResponse login) throws Exception {

    try {
     
      String apiName = CAMINHO_API_DOCUMENTO + "Get?Id=" + idDoc;

      HttpGet httpGet = new HttpGet(Global.ApiPortalBaseURL + apiName);

      httpGet.setHeader(Global.ACS_AUTH_CONTEXT_UID, login.getUidContextos(0));
      httpGet.setHeader(Global.ACS_AUTH_TOKEN, login.getToken());
      httpGet.setHeader(Global.ACS_AUTH_USER_UID, login.getUserInfo().getUid());

      //StringEntity entity = new StringEntity(gson.toJson(para), StandardCharsets.UTF_8);
      //entity.setContentType("application/json");
      //httpPost.setEntity(entity);

      CloseableHttpClient client = HttpClients.createDefault();

      HttpResponse httpResp = client.execute(httpGet);
     
      return httpResp;

    } catch (Exception e) {
      throw e;
    }
  }
 
}
TOP

Related Classes of servlets.Documento

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.