Helper.java 2.09 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 10
import java.util.Date;

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

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

16 17 18 19 20 21 22 23
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 {
24
                if(fecha == null || fecha.trim().equals("")) return null;
25 26 27 28 29 30 31 32
                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;
        }
    }
33 34

    public static final long getMonthsDifference(Date date1, Date date2) {
35
        if(date2==null) date2 = new Date();
36 37 38 39 40
        YearMonth m1 = YearMonth.from(date1.toInstant().atZone(ZoneOffset.UTC));
        YearMonth m2 = YearMonth.from(date2.toInstant().atZone(ZoneOffset.UTC));
    
        return m1.until(m2, ChronoUnit.MONTHS) + 1;
    }
Joel Florentin committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

    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;
        }
    }

66
}