Helper.java 2.31 KB
Newer Older
1 2
package com.roshka.utils;

Joel Florentin committed
3
import java.io.IOException;
4 5
import java.text.ParseException;
import java.text.SimpleDateFormat;
6 7 8
import java.time.YearMonth;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
9
import java.util.Date;
10
import java.util.concurrent.TimeUnit;
11

Joel Florentin committed
12 13 14 15 16
import com.roshka.modelo.DBFile;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

17 18 19 20 21 22 23 24
public class Helper {
    /**
     * Se espera fecha en el formato yyyy-MM-dd
     * @param fecha
     * @return retorna fecha correcta o nulo si no es posible convertir
     */
    public static Date convertirFecha(String fecha) {
        try {
25
                if(fecha == null || fecha.trim().equals("")) return null;
26 27 28 29 30 31 32 33
                return new SimpleDateFormat("yyyy-MM-dd").parse(fecha);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            System.err.println("Error al parsear");
            e.printStackTrace();
            return null;
        }
    }
34

35 36 37 38 39 40
    /**
     * Diferencia en meses entre 2 fechas.
     * @param date1 La fecha inicial. No puede ser nulo
     * @param date2 La fecha final. Si es nulo, se asume a la fecha de hoy
     * @return
     */
41
    public static final long getMonthsDifference(Date date1, Date date2) {
42
        if(date2==null) date2 = new Date();
43 44
        long diffInMillies = Math.abs(date2.getTime() - date1.getTime());
        long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
45
    
46
        return Math.round(diff/30.d) ;
47
    }
Joel Florentin committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

    public static DBFile createFile(MultipartFile file) {
        // Normalize file name
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        try {
            // Check if the file's name contains invalid characters
            if(fileName.contains("..")) {
                throw new Exception("Sorry! Filename contains invalid path sequence " + fileName);
            }
            if(file.getSize()==0)  throw new Exception("Sorry! File cant be void");;

            DBFile dbFile = new DBFile(fileName, file.getContentType(), file.getBytes());

            return dbFile;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        catch(Exception ex){
            ex.printStackTrace();
            return null;
        }
    }

73
}