com.thejustdo.util.Utils.java Source code

Java tutorial

Introduction

Here is the source code for com.thejustdo.util.Utils.java

Source

/*
 * Utils.java
 * Copyright (c) Oct 28, 2012, Software Colombia All rights reserved
 * 
 * This software is the confidential and propietary information of The Just DO!.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with 
 * The Just DO!.
 */
package com.thejustdo.util;

import com.thejustdo.model.Role;
import com.thejustdo.resources.Constants;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.EnumMap;
import java.util.Map;
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 javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringEscapeUtils;

/**
 * Groups a set of useful methods for the application.
 *
 * @author Edison F Mendez C [efmcuiti]
 */
public class Utils {

    /**
     * Separator for the CSV file.
     */
    public static final String CSV_SPLITTER = ",";
    /**
     * Affirmative word for the CSV file.
     */
    public static final String YES = "Si";
    /**
     * Negative word for the CSV file.
     */
    public static final String NO = "No";
    /**
     * Name of the attached CSV file.
     */
    public static final String CSV_FILENAME = "reporteSemanal.csv";
    /**
     * Allows us to print messages on the console.
     */
    private static final Logger log = Logger.getLogger(Utils.class.getName());
    /**
     * Defines all the key-destination values for redirections.
     */
    private static final Map<UtilRole, String> redirections;

    static {
        redirections = new EnumMap<UtilRole, String>(UtilRole.class);
        // adding statically all the redirections.
        redirections.put(UtilRole.ADMIN, "/control/ManageUsers");
        redirections.put(UtilRole.CANCELATION, "/WEB-INF/jsp/admin/actions/cancelacion.jsp");
        redirections.put(UtilRole.REGULAR, "/WEB-INF/jsp/home.jsp");
        redirections.put(UtilRole.REPORTING, "/WEB-INF/jsp/admin/actions/reporter_home.jsp");
    }

    /**
     * Reads the content of a file and returns it in a big string object.
     *
     * @param filename Name and location to the plain file.
     * @return All the lines inside the file.
     */
    public static String getPlainTextFile(String filename) {
        log.log(Level.INFO, "Loading contents of file: {0}.", filename);
        try {
            StringBuilder answer = new StringBuilder();
            FileReader fr = new FileReader(filename);
            BufferedReader reader = new BufferedReader(fr);

            // while there are more lines.
            String line;
            while (reader.ready()) {
                line = reader.readLine();
                answer.append(line).append("\n");
            }

            // closing resources.
            reader.close();

            return answer.toString();
        } catch (IOException ex) {
            log.log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * Reads the content of a file and returns it in a big string object.
     *
     * @param filename Name and location to the plain file.
     * @return All the lines inside the file.
     */
    public static String getPlainTextFileFromContext(String filename) {
        log.log(Level.INFO, "Loading contents of file: {0}.", filename);
        try {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            InputStream is = cl.getResourceAsStream(filename);
            StringBuilder answer = new StringBuilder();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);

            // while there are more lines.
            String line;
            while (reader.ready()) {
                line = reader.readLine();
                answer.append(line).append("\n");
            }

            // closing resources.
            reader.close();

            return answer.toString();
        } catch (IOException ex) {
            log.log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * Reads the content of a file and returns it in a big string object.
     *
     * @param location Name and location to the plain file.
     * @param ctx Context to use.
     * @return
     */
    public static String getPlainTextFileFromContext(String location, ServletContext ctx) {
        log.log(Level.INFO, "Loading contents of file: {0} and context: {1}.",
                new Object[] { location, ctx.getContextPath() });
        try {
            InputStream is = ctx.getResourceAsStream(location);
            StringBuilder answer = new StringBuilder();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);

            // while there are more lines.
            String line;
            while (reader.ready()) {
                line = reader.readLine();
                answer.append(line).append("\n");
            }

            // closing resources.
            reader.close();

            return answer.toString();
        } catch (IOException ex) {
            log.log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * Given some data it creates a new file inside the servlet context.
     *
     * @param location Where to create the file.
     * @param ctx Gives us the real paths to be used.
     * @param content What to write.
     * @param filename What name will have the new file.
     * @return The created file.
     * @throws IOException If any errors.
     */
    public static File createNewFileInsideContext(String location, ServletContext ctx, String content,
            String filename) throws IOException {
        String real = ctx.getContextPath();
        String path = real + location + filename;
        log.info(String.format("File to save: %s", path));
        File f = new File(path);

        // 1. Creating the writers.
        FileWriter fw = new FileWriter(f);
        BufferedWriter writer = new BufferedWriter(fw);

        // 2. Writing contents.
        writer.write(content);

        // 3. Closing stream.
        writer.flush();
        writer.close();
        fw.close();

        return f;
    }

    /**
     * Formats a string to avoid any injection exploit by escaping the special
     * characters.
     *
     * @param s String to be modified.
     * @return Modified string.
     */
    public static String escapeString(String s) {
        String answer;
        answer = StringEscapeUtils.escapeCsv(s);
        answer = StringEscapeUtils.escapeEcmaScript(answer);
        answer = StringEscapeUtils.escapeHtml3(answer);
        answer = StringEscapeUtils.escapeHtml4(answer);
        answer = StringEscapeUtils.escapeJava(answer);
        answer = StringEscapeUtils.escapeXml(answer);
        return answer;
    }

    /**
     * Given a persistent Role, this method gives where the fuck must be
     * redirected.
     *
     * @param r Role to process.
     * @return The URL where to redirect.
     */
    public static String getRedirectByRole(Role r) {
        if ((r == null) || (r.getName() == null) || ("".equals(r.getName().trim()))) {
            return null;
        }

        UtilRole ur = UtilRole.valueOf(r.getName().toUpperCase());
        return redirections.get(ur);
    }

    /**
     * Builds a random code for a new Dream Box.
     *
     * @param prefix What must be putted before the real code.
     * @param length How long must be the new number
     * @return The built code.
     */
    public static String buildRandomCode(String prefix, int length) {
        // 1. Gatter the prefix size.
        int prefixL = prefix.length();
        int n = length - prefixL;
        // 2. Build the n digit code.
        String code = "";
        Random random = new Random();
        do {
            code += random.nextInt(10);
        } while (code.length() < n);
        return prefix + code;
    }

    /**
     * Removes all the files inside a directory (or creates it).
     *
     * @param d Directory target.
     */
    public static void cleanDirectory(File d) throws IOException {
        // 1. If inexistent, then creates it.
        if (!d.exists()) {
            log.info(String.format("Created Directory: %s", d.getName()));
            d.mkdirs();
            return;
        }

        // 2. If a file, deletes it and re-build.
        if (d.isFile()) {
            d.delete();
            log.info(String.format("Created Directory (after deleting file): %s", d.getName()));
            d.mkdirs();
        }

        // 3. Otherwise we clean it.
        delete(d);
        d.mkdirs();
        log.info(String.format("Created Directory (after cleaning): %s", d.getName()));
    }

    /**
     * Recursively deletes files on directory. Taken from:
     * <strong>http://www.mkyong.com/java/how-to-delete-directory-in-java/</strong>
     *
     * @param file What to clean.
     * @throws IOException If couldn't delete.
     */
    public static void delete(File file) throws IOException {

        if (file.isDirectory()) {

            //directory is empty, then delete it
            if (file.list().length == 0) {

                file.delete();
                log.log(Level.INFO, "Directory is deleted : {0}", file.getAbsolutePath());

            } else {

                //list all the directory contents
                String files[] = file.list();

                for (String temp : files) {
                    //construct the file structure
                    File fileDelete = new File(file, temp);

                    //recursive delete
                    delete(fileDelete);
                }

                //check the directory again, if empty then delete it
                if (file.list().length == 0) {
                    file.delete();
                    log.log(Level.INFO, "Directory is deleted : {0}", file.getAbsolutePath());
                }
            }

        } else {
            //if file, then delete it
            file.delete();
            log.log(Level.INFO, "File is deleted : {0}", file.getAbsolutePath());
        }
    }

    /**
     * Creates a ZIP file containing all the files inside a directory.
     * @param location Directory to read.
     * @param pathname Name and path where to store the file.
     * @throws FileNotFoundException If can't find the initial directory.
     * @throws IOException If can't read/write.
     */
    public static void zipDirectory(File location, File pathname) throws FileNotFoundException, IOException {

        BufferedInputStream origin;
        FileOutputStream dest = new FileOutputStream(pathname);
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
        byte data[] = new byte[2048];

        // 1. Get a list of files from current directory
        String files[] = location.list();
        File f;

        // 2. Adding each file to the zip-set.
        for (String s : files) {
            log.info(String.format("Adding: %s", s));
            f = new File(location, s);
            FileInputStream fi = new FileInputStream(f);
            origin = new BufferedInputStream(fi, 2048);
            ZipEntry entry = new ZipEntry(location.getName() + File.separator + s);
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, 2048)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }
        out.close();
    }

    /**
     * Given a temporal directory and getting help from the Constants class, 
     * we may copy if necessary all the info required for the correct generation 
     * of PDF files.
     * @param tmp Where is the temporal directory of the server.
     * @return The directory in which the temporal files can be saved.
     */
    public static File preparePDFDirs(File tmp, ServletContext sc) throws IOException {
        // 0. Creating the pdf directory if needed.
        File pdf = new File(tmp, Constants.TMP_PDF);

        if (pdf.exists()) {
            log.info(String.format("Found temporal directory for pdfs %s", pdf.getAbsolutePath()));
            return pdf;
        }

        // 1. Creating the structure.
        pdf.mkdirs();

        File tmpImg = new File(pdf, "images");
        tmpImg.mkdirs();

        // 2. Copying content.
        InputStream is;
        FileOutputStream os;
        File goal;
        int read;
        byte bytes[] = new byte[1024];
        for (String s : Constants.PDF_IMGS) {
            log.info(String.format("Copying file %s%s", Constants.PDF_IMAGE_PATH, s));
            is = sc.getResourceAsStream(Constants.PDF_IMAGE_PATH + s);
            goal = new File(tmpImg, s);
            os = new FileOutputStream(goal);

            // Writing file.
            while ((read = is.read(bytes)) != -1) {
                os.write(bytes, 0, read);
            }

            // Done writing.
            os.flush();
            os.close();
            is.close();
        }

        // File origin = new File(sc.getRealPath(Constants.PDF_IMAGE_PATH));
        // FileUtils.copyDirectoryToDirectory(origin, pdf);
        log.info(String.format("Created pdf data at: %s", pdf.getAbsolutePath()));

        return pdf;
    }

    /**
     * Creates a new temporal file with the content given in the string.
     * @param content What to write son of a bitch.
     */
    public static void createTMPFile(String content, File goal) throws IOException {
        // 1. Creating the writers.
        FileOutputStream fos = new FileOutputStream(goal);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "ISO-8859-1"));

        // 2. Writing contents.
        writer.write(content);

        // 3. Closing stream.
        writer.flush();
        writer.close();
        fos.close();
    }
}