Enviar archivo .zip, encriptado.

Cuando encriptamos archivos y los comprimimos en un zip

Desde la aplicacion Web hacemos el envio

Modificamos la aplicacion anterior para incluir el envio de archivos zip.

FileController.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bpbonline.sendweb;

import com.avbravo.jmoordbutils.JsfUtil;
import com.avbravo.jmoordbutils.jaxrs.Microservices;
import java.io.Serializable;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.ws.rs.core.Response;

/**
 *
 * @author avbravo
 */
@Named
@ViewScoped
public class FileController implements Serializable {

    private String directory = JsfUtil.userHome() + JsfUtil.fileSeparator() + "fiscalprinter" + JsfUtil.fileSeparator() + "license" + JsfUtil.fileSeparator();

    
    // <editor-fold defaultstate="collapsed" desc="String send()">
    public String send() {

        try {
            //--Files to send 
          Response response  =Microservices.sendFileWithJaxRsHeaders(directory, "license.enc", "http://localhost:8080/serverfiles/resources/file", "upload"
                  ,"folder","license");
        Response responseivEnc =  Microservices.sendFileWithJaxRsHeaders(directory, "licenseiv.enc", "http://localhost:8080/serverfiles/resources/file", "upload"
                ,"folder","license");
       Response responseDes   =  Microservices.sendFileWithJaxRsHeaders(directory, "license.des", "http://localhost:8080/serverfiles/resources/file", "upload"
              ,"folder" ,"license");
               
           String mensajeExistoso="";
           String mensajeFallido="";
            if (response.getStatus() == 200 && responseivEnc.getStatus() == 200 &&  responseDes.getStatus() == 200)  {
              JsfUtil.infoDialog("Envio existoso"," Se enviaron exitosamente los archivos: licemse.emc, licenseiv.enc, license.des");
            } else{
                         if (response.getStatus() == 200){
                             mensajeExistoso+=" license.enc";
                         }else{
                             mensajeFallido=" license.enc";
                         }
                         if (responseivEnc.getStatus() == 200){
                             mensajeExistoso+=" licenseiv.enc";
                         }else{
                             mensajeFallido+=" licenseiv.enc";
                         }
                         
                         if (responseDes.getStatus() == 200){
                             mensajeExistoso+=" license.des";
                         }else{
                             mensajeFallido+=" license.desc";
                         }
                        JsfUtil.infoDialog("Proceso terminado","Exitosos:"+mensajeExistoso +  "    Fallidps: "+mensajeFallido);     
                         
            }
    

        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.errorDialog("send)=", e.getLocalizedMessage());
        }
        return "";
    }
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="String sendZip()">
    public String sendZip() {

        try {
            //--Files to send 
          Response response  =Microservices.sendFileWithJaxRs(directory, "authorizedlicense.zip", "http://localhost:8080/serverfiles/resources/zip", "upload");
     
               
            System.out.println("response.getStatus() "+response.getStatus());
            System.out.println("response.getStatusInfo() "+response.getStatusInfo());
            if (response.getStatus() == 200 )  {
              JsfUtil.infoDialog("Envio existoso"," Se enviaron exitosamente el archivo authorizedlicense.zip");
            } else{
                       
                       JsfUtil.warningDialog("Envio errado","  No Se envio el archivo authorizedlicense.zip");
                         
            }
    

        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.errorDialog("sendZip()", e.getLocalizedMessage());
        }
        return "";
    }
    // <editor-fold defaultstate="collapsed" desc="method()">
 
}
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:p="http://primefaces.org/ui">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:form id="form" prependId="false">
            <h1><p:outputLabel value="Sendwebfile"/></h1>
            <p:outputLabel value="Envia un archivo desde el controller al microservices"/>
            <br></br>
            <p:outputLabel value="Pasos:"/>
            <br></br>
            <p:outputLabel value="1.Ejecute serverfiles.jar primero"/>


            <p:growl id="growl"></p:growl>
           
            
            
            
            
               <p:fieldset legend="ENVIAR ARCHIVOs" style="margin-bottom:20px" toggleable="true" collapsed="true">
               <p:panelGrid columns="2">

                <p:outputLabel value="Nota"/>

                <p:outputLabel value="Copie los archivos en /fiscalprinter/license"/>
                <p:outputLabel value="Archivos"/>
                <p:outputLabel value="license.enc, licenseiv.enc, license.desc"/>




            </p:panelGrid>

            <p:commandButton value="Send File"
                             action="#{fileController.send()}"
                             update=":form"
                             />
            </p:fieldset>
            
               <p:fieldset legend="ENVIAR .ZIP" style="margin-bottom:20px" toggleable="true" collapsed="true">
               <p:panelGrid columns="2">

                <p:outputLabel value="Nota"/>

                <p:outputLabel value="Copie el archivo /fiscalprinter/license/authorizedlicense.zip"/>
              
            </p:panelGrid>

                   <p:commandButton value="Send Zip"
                             action="#{fileController.sendZip()}"
                             update=":form"
                             />
            </p:fieldset>


        </h:form>
    </h:body>
</html>

En el proyecto serverfiles

Creamoa la clase ZipServices.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bpbonline.serverfiles.resources;


import com.avbravo.jmoordbutils.JsfUtil;
import com.avbravo.jmoordbutils.fileencripter.FileDecryption;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

/**
 *
 * @author avbravo
 */
@Path("/zip")
public class ZipService {

    private String directory = JsfUtil.userHome() + JsfUtil.fileSeparator() + "fiscalserver" + JsfUtil.fileSeparator() + "license";

    @POST
    @Path("/upload")
    @Consumes(MediaType.APPLICATION_OCTET_STREAM)
    @Produces(MediaType.TEXT_PLAIN)
    public Response reciveFile(@Context HttpHeaders headers, InputStream fileInputStream) {
        MultivaluedMap<String, String> map = headers.getRequestHeaders();
 
        //getFileName
        String fileName = getFileName(map);

//        //get folder
//        String folder = getFolder(map);

        
        OutputStream out = null;

        File directorio = new File(directory);
        if (!directorio.exists()) {
            //Crear el directorio
            if (directorio.mkdirs()) {
              System.out.println("---> creado el directorio");
//
          } else {
                System.out.println("---> no se creo el directorio");
            }
        }

        String filePath = directory + JsfUtil.fileSeparator() + fileName;
        try {
            out = new FileOutputStream(new File(filePath));
            byte[] buf = new byte[1024];
            int len;
            while ((len = fileInputStream.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            
            //Desencripta el archivo
           
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        //UNZIP ARCHIVO .ZIP
           if(JsfUtil.unzipFileToDirectory(filePath, JsfUtil.pathOfFile(filePath))){
            // Despues de descomprimir se desencriptar  
                  desencriptarFile();
           }
      
             
        return Response.status(Response.Status.OK).entity("File '" + filePath + "' uploaded successfully")
                .type(MediaType.TEXT_PLAIN).build();
    }

    private String getFileName(MultivaluedMap<String, String> headers) {
        try {
           String[] contentDisposition = headers.getFirst("Content-Disposition").split(";");
        for (String filename : contentDisposition) {
            if ((filename.trim().startsWith("filename"))) {
                String[] name = filename.split("=");
                String finalFileName = name[1].trim().replaceAll("\"", "");
                return finalFileName;
            }
        }  
        } catch (Exception e) {
            System.out.println("getFileName() "+e.getLocalizedMessage());
        }
       
        return "";
    }
    
//    private String getFolder(MultivaluedMap<String, String> headers) {
//        try {
//             String[] folder = headers.getFirst("folder").split(";");
//        for (String filename : folder) {
//            if ((filename.trim().startsWith("folder"))) {
//                String[] name = filename.split("=");
//                String finalFileName = name[1].trim().replaceAll("\"", "");
//                return finalFileName;
//            }
//        }
//        } catch (Exception e) {
//            System.out.println(" getFolder() "+e.getLocalizedMessage());
//        }
//       
//        return "";
//    }
    
    
    // <editor-fold defaultstate="collapsed" desc="desencriptarFile()">
     public String desencriptarFile(){
        try{
            String fileEnc = directory+JsfUtil.fileSeparator()+"authorizedlicense"+ JsfUtil.fileSeparator()+"license"+ JsfUtil.fileSeparator()+"license.enc"; 
     
            String fileIvEnc= directory+JsfUtil.fileSeparator()+"authorizedlicense"+ JsfUtil.fileSeparator()+"license"+  JsfUtil.fileSeparator()+"licenseiv.enc";
            String fileDes= directory+JsfUtil.fileSeparator()+"authorizedlicense"+ JsfUtil.fileSeparator()+"license"+  JsfUtil.fileSeparator()+"license.des";
            
          
            String keyDesCifrado="MI CLAVE DE CIFRADO";
           String extension="json";
            System.out.println("voy a descifrar ");
            if(FileDecryption.desencriptarFile(fileEnc, fileIvEnc,fileDes, keyDesCifrado, extension)){
              
                       System.out.println("Se desencripto archivo");
            }else{
              
                  System.out.println("No se desencripto el archivo");
            }
         
          } catch (Exception e) {
            JsfUtil.errorDialog("desencriptarFile()", e.getLocalizedMessage());
               System.out.println("desencriptarFile()"+ e.getLocalizedMessage());
        }
        return "";
    }
// </editor-fold>
}

Recive el archivo .zip y lo descomprime

Luego desencripta los archivos

Last updated