Untitled

 avatar
unknown
plain_text
2 years ago
11 kB
6
Indexable
@Slf4j
public class DateUtils {

    private static final String TAG = DateUtils.class.getSimpleName();

    public static Date toFirstDayOfMonth(YearMonth yearMonth) {
        return Date.from(yearMonth.atDay(1)
                .atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    public static YearMonth toYearMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        // cal.get(Calendar.MONTH) return 0 for January.
        return YearMonth.of(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1);
    }

    public static Date parse(String dateString) {
        LocalDate localDate = LocalDate.parse(dateString);
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    public static boolean isLastDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return calendar.get(Calendar.DATE) == calendar.getActualMaximum(Calendar.DATE);
    }

    public static String format(Date date, SimpleDateFormat dateFormat) {
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        }

        return dateFormat.format(date);
    }

    public static Date addDate(Date date, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, amount);
        return cal.getTime();
    }

    public static Date addMonth(Date date, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, amount);
        return cal.getTime();
    }


    public static String toCron(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        // Don't set the 'Day of Week' field
        String cronFormat = "%s %s %s %s %s ? %s";
        return String.format(cronFormat,
                String.valueOf(calendar.get(Calendar.SECOND)),
                String.valueOf(calendar.get(Calendar.MINUTE)),
                String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)),
                String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)),
                String.valueOf(calendar.get(Calendar.MONTH) + 1),
                String.valueOf(calendar.get(Calendar.YEAR)));
    }
}
///////////////////////////////////
public class ExcelUtils {

    public static void export(
            String fileName, XSSFWorkbook workbook, HttpServletResponse response) {

        try {
            response.setHeader(
                    "Content-Disposition",
                    String.format("attachment; filename = \"%s\" ", fileName));
            response.setContentType(
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            workbook.write(response.getOutputStream());
            workbook.close();
            response.flushBuffer();
        } catch (IOException exception) {
            throw new PortalException(exception.getMessage());
        }
    }

    public static CellStyle createHeadCellStyle(XSSFWorkbook workbook) {
        CellStyle headStyle = workbook.createCellStyle();
        headStyle.setAlignment(HorizontalAlignment.CENTER);
        headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headStyle.setWrapText(true);

        XSSFFont headFont = workbook.createFont();
        headFont.setFontName("Arial");
        headFont.setColor(IndexedColors.BLACK.getIndex());
        headFont.setBold(true);
        headStyle.setFont(headFont);

        return headStyle;
    }

    public static CellStyle createTextCellStyle(XSSFWorkbook workbook) {
        CellStyle textStyle = workbook.createCellStyle();
        textStyle.setAlignment(HorizontalAlignment.LEFT);
        textStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        textStyle.setWrapText(true);

        return textStyle;
    }

    public static CellStyle createNumberCellStyle(XSSFWorkbook workbook) {
        CellStyle numberStyle = workbook.createCellStyle();
        numberStyle.setAlignment(HorizontalAlignment.RIGHT);
        numberStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        numberStyle.setDataFormat(workbook.createDataFormat().getFormat("#,##0"));
        numberStyle.setWrapText(true);

        return numberStyle;
    }

    public static CellStyle createFloatCellStyle(XSSFWorkbook workbook) {
        CellStyle floatStyle = workbook.createCellStyle();
        floatStyle.setAlignment(HorizontalAlignment.RIGHT);
        floatStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        floatStyle.setDataFormat(workbook.createDataFormat().getFormat("0.00"));
        floatStyle.setWrapText(true);

        return floatStyle;
    }

    public static CellStyle createDoubleCellStyle(XSSFWorkbook workbook) {
        CellStyle floatStyle = workbook.createCellStyle();
        floatStyle.setAlignment(HorizontalAlignment.RIGHT);
        floatStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        floatStyle.setDataFormat(workbook.createDataFormat().getFormat("0.00000"));
        floatStyle.setWrapText(true);

        return floatStyle;
    }
}
///////////////////////////////////////
public class LogUtils {

    private static final int LOG_LIST_ITEM_COUNT = 10;

    public static String log(Collection<?> list) {
        return log(list, LOG_LIST_ITEM_COUNT);
    }

    public static String log(Collection<?> list, int count) {
        return (list == null || list.size() <= count ? "" + list : "size : " + list.size());
    }

    public static String log(Map<?, ?> list) {
        return log(list, LOG_LIST_ITEM_COUNT);
    }

    public static String log(Map<?, ?> list, int count) {
        return (list == null || list.size() <= count ? "" + list : "size : " + list.size());
    }
}
////////////////////////////////
public class PageUtils {

    public static <T> Page<T> convertToPage(@NonNull List<T> content, @NonNull Pageable pageable) {
        return convertToPage(content, pageable, content.size());
    }

    public static <T> Page<T> convertToPage(
            @NonNull List<T> content, @NonNull Pageable pageable, long total) {
        int from = Long.valueOf(pageable.getOffset()).intValue();
        if (from > content.size()) {
            return new PageImpl<>(Collections.emptyList(), pageable, total);
        }

        int to = Long.valueOf(from + pageable.getPageSize()).intValue();
        if (to > content.size()) to = content.size();

        return new PageImpl<>(
                content.subList(from, to), pageable, total);
    }
}
////////////////////////////////
public class SwaggerUtils {

    public static boolean requestedFromSwagger(HttpServletRequest request) {
        return isSwaggerUri(request.getRequestURI())
                || isSwaggerUri(request.getHeader("referer"));
    }

    private static boolean isSwaggerUri(String uri) {
        if (!TextUtils.isEmpty(uri)) {
            try {
                String path = new URI(uri).getPath();
                return (path != null && path.startsWith("/swagger-ui"))
                        || TextUtils.equals(path, "/dist/redoc/index.html");
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
////////////////////////////
public class TextUtils {

    /**
     * Check string is empty or not
     *
     * @param input string
     * @return false or true
     */
    public static boolean isEmpty(String input) {
        return input == null || input.isEmpty();
    }

    /**
     * Try to parse string into numeric type.
     * If successful, pass the number value to the callback method.
     *
     * @param input    string
     * @param callback callback method to take the result value
     * @return false or true
     */
    public static boolean tryParseNumber(String input,
                                         Consumer<Number> callback) {
        try {
            Double value = Double.parseDouble(input);
            callback.accept(value);
            return true;
        } catch (NumberFormatException ex) {
            return false;
        }
    }

    /**
     * Check if input string is integer type.
     *
     * @param input string
     * @return false or true
     */
    public static boolean isInteger(String input) {
        try {
            Integer.parseInt(input);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * Returns true if a and b are equal, including if they are both null.
     *
     * @param a first CharSequence to check
     * @param b second CharSequence to check
     * @return true if a and b are equal
     */
    public static boolean equals(CharSequence a, CharSequence b) {
        if (a == b) {
            return true;
        }
        int length;
        if (a != null && b != null && (length = a.length()) == b.length()) {
            if (a instanceof String && b instanceof String) {
                return a.equals(b);
            } else {
                for (int i = 0; i < length; i++) {
                    if (a.charAt(i) != b.charAt(i)) {
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }

    /**
     * Returns true if a and b are equal string ignoring case-sensitive
     * and including if they are both null.
     *
     * @param a first String to check
     * @param b second String to check
     * @return true if a and b are equal
     */
    public static boolean equalsIgnoreCase(String a, String b) {
        return equals(a, b)
                || a != null && b != null && a.equalsIgnoreCase(b);
    }

    /**
     * Convert given json object to csv string
     *
     * @param json json object to convert
     * @return converted csv string
     */
    public static String convertJsonToCsv(JsonNode json) throws JsonProcessingException {
        CsvSchema.Builder csvSchemaBuilder = CsvSchema.builder();
        JsonNode firstObject = json.elements().next();
        firstObject
                .fieldNames()
                .forEachRemaining(fieldName -> csvSchemaBuilder.addColumn(fieldName));
        CsvSchema csvSchema = csvSchemaBuilder.build().withHeader();
        CsvMapper csvMapper = new CsvMapper();
        String csvStr = csvMapper.writerFor(JsonNode.class)
                .with(csvSchema)
                .writeValueAsString(json);
        return csvStr;
    }
}
Editor is loading...
Leave a Comment