com.juancarlosroot.threads.SimulatedUser.java Source code

Java tutorial

Introduction

Here is the source code for com.juancarlosroot.threads.SimulatedUser.java

Source

/*
 * 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.juancarlosroot.threads;

import com.juancarlosroot.control.JGet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import webservice.IOException_Exception;
import webservice.InterruptedException_Exception;
import webservice.NoSuchAlgorithmException_Exception;
import webservice.WriterException_Exception;

/**
 *
 * @author juancarlosroot
 */
public class SimulatedUser implements Runnable {

    public int idSimulatedUser;
    int nFilesSend;
    int nFilesDownload;
    int nFilesVerified;
    int nDownloadErrors;
    int nVerifyErrors;
    int nNotFileFound;

    int sleepTime;
    boolean alive;
    boolean sleep;
    String userFolderPath;

    public SimulatedUser(int idSimulatedUser, int sleepTime) {
        this.idSimulatedUser = idSimulatedUser;
        this.sleepTime = sleepTime * 1000;
        this.alive = true;
        this.sleep = false;
        this.nFilesSend = 0;
        this.nFilesDownload = 0;
        this.nFilesVerified = 0;
        this.nDownloadErrors = 0;
        this.nVerifyErrors = 0;
        this.nNotFileFound = 0;
    }

    @Override
    public synchronized void run() {

        this.userFolderPath = createFolder("User" + Integer.toString(this.idSimulatedUser));
        String fileURL = "";
        while (alive) {
            try {
                this.sleep = true;
                Thread.sleep(sleepTime);
                this.sleep = false;

                int randNumber = randomNumber(1, 59);

                fileURL = firmarImagen(randNumber);

                this.sleep = true;
                Thread.sleep(4000);
                this.sleep = false;

                fileDownload(fileURL);

                this.sleep = true;
                Thread.sleep(4000);
                this.sleep = false;

                consultarFirma(randNumber);

            } catch (InterruptedException ex) {
                Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        deleteFilesInsideFolder("User" + Integer.toString(this.idSimulatedUser));
        deleteFolder("User" + Integer.toString(this.idSimulatedUser));

    }

    private void fileDownload(String urlDownload) {

        String result = JGet.saveImage(urlDownload, userFolderPath);
        if (result != null) {
            nFilesDownload++;
            System.out.println("User : " + idSimulatedUser + " DESCARGADO");
            System.out.println(userFolderPath + "/" + result);
        } else {
            nDownloadErrors++;
        }

    }

    private void consultarFirma(int fileNameId) {
        try {
            FileOutputStream fos = new FileOutputStream(
                    userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.zip");
            ZipOutputStream zos = new ZipOutputStream(fos);

            String file1Name = userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.png";
            File image = new File(file1Name);

            ZipEntry zipEntry = new ZipEntry(image.getName());
            zos.putNextEntry(zipEntry);
            FileInputStream fileInputStream = new FileInputStream(image);

            byte[] buf = new byte[2048];
            int bytesRead;

            while ((bytesRead = fileInputStream.read(buf)) > 0) {
                zos.write(buf, 0, bytesRead);
            }
            zos.closeEntry();
            zos.close();
            fos.close();

            Path path = Paths.get(userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.zip");

            byte[] data = Files.readAllBytes(path);
            byte[] byteArray = Base64.encodeBase64(data);
            String b64 = new String(byteArray);

            System.out.println(consultaFirma(b64, Integer.toString(fileNameId) + "Firmada"));

            nFilesVerified++;
            System.out.println("User : " + idSimulatedUser + " FIRMA VERIFICADA");
        } catch (IOException ex) {
            Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
            nNotFileFound++;
        } catch (IOException_Exception ex) {
            Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
            nVerifyErrors++;
        }
    }

    private String firmarImagen(int fileName) throws IOException {

        String result = "";
        try {
            Path currentRelativePath = Paths.get("");
            String s = currentRelativePath.toAbsolutePath().toString();
            String theFolder = s + "/" + "archivos";

            FileOutputStream fos = new FileOutputStream(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
            ZipOutputStream zos = new ZipOutputStream(fos);

            String file1Name = theFolder + "/" + Integer.toString(fileName) + ".jpg";
            File image = new File(file1Name);

            ZipEntry zipEntry = new ZipEntry(image.getName());
            zos.putNextEntry(zipEntry);
            FileInputStream fileInputStream = new FileInputStream(image);

            byte[] buf = new byte[2048];
            int bytesRead;

            while ((bytesRead = fileInputStream.read(buf)) > 0) {
                zos.write(buf, 0, bytesRead);
            }
            zos.closeEntry();
            zos.close();
            fos.close();

            Path path = Paths.get(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
            byte[] data = Files.readAllBytes(path);
            byte[] byteArray = Base64.encodeBase64(data);
            String b64 = new String(byteArray);

            result = firma(b64, Integer.toString(fileName), "pruebita");
            System.out.println("User : " + idSimulatedUser + " ENVIADO");
            nFilesSend++;

        } catch (FileNotFoundException ex) {
            Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (WriterException_Exception ex) {
            Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException_Exception ex) {
            Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException_Exception ex) {
            Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException_Exception ex) {
            Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "http://" + result;
    }

    private String createFolder(String folderName) {
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();

        File theFolder = new File(s + "/" + folderName);

        if (!theFolder.mkdir()) {
            System.out.println("Ya existe la carpeta : " + s + "/" + folderName);
            deleteFilesInsideFolder(folderName);
        } else {
            System.out.println("Creacin exitosa : " + s + "/" + folderName);
        }
        return s + "/" + folderName;
    }

    private void deleteFilesInsideFolder(String folderName) {
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();
        File theFolder = new File(s + "/" + folderName);

        try {
            FileUtils.cleanDirectory(theFolder);
            System.out.println("Se han borrado los archivos de : " + folderName);
        } catch (IOException ex) {
            Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Error al borrar los archivos de : " + folderName);
        }
    }

    private void deleteFolder(String folderName) {
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();

        Path folderPath = Paths.get(s + "/" + folderName);

        try {
            Files.delete(folderPath);
            System.out.println("Carpeta eliminada : " + s + "/" + folderName);
        } catch (IOException ex) {
            Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Error al eliminar carpeta : " + s + "/" + folderName);
        }
    }

    public void setAlive(boolean alive) {
        this.alive = alive;
    }

    public boolean isSleep() {
        return sleep;
    }

    private int randomNumber(int min, int max) {
        Random r = new Random();
        int R = r.nextInt(max - min) + min;
        return R;
    }

    public int getnFilesVerified() {
        return nFilesVerified;
    }

    public int getnFilesSend() {
        return nFilesSend;
    }

    public int getnFilesDownload() {
        return nFilesDownload;
    }

    public int getSleepTime() {
        return sleepTime;
    }

    public boolean isAlive() {
        return alive;
    }

    public static void addToZipFile(String fileName, ZipOutputStream zos)
            throws FileNotFoundException, IOException {
        File file = new File(fileName);
        FileInputStream fis = new FileInputStream(file);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zos.putNextEntry(zipEntry);

        byte[] bytes = new byte[2048];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zos.write(bytes, 0, length);
        }

        zos.closeEntry();
        fis.close();
    }

    public int getnDownloadErrors() {
        return nDownloadErrors;
    }

    public int getnVerifyErrors() {
        return nVerifyErrors;
    }

    public int getnNotFileFound() {
        return nNotFileFound;
    }

    private static String consultaFirma(java.lang.String arg0, java.lang.String arg1) throws IOException_Exception {
        webservice.ServicioService service = new webservice.ServicioService();
        webservice.ImplementServicio port = service.getServicioPort();
        return port.consultaFirma(arg0, arg1);
    }

    private static String firma(java.lang.String arg0, java.lang.String arg1, java.lang.String arg2)
            throws IOException_Exception, InterruptedException_Exception, WriterException_Exception,
            NoSuchAlgorithmException_Exception {
        webservice.ServicioService service = new webservice.ServicioService();
        webservice.ImplementServicio port = service.getServicioPort();
        return port.firma(arg0, arg1, arg2);
    }

}