lunes, 4 de octubre de 2021

Java: Cambiar formato de importe String a coma para decimales y puntos para miles

 private static final String PATTERN = "#,##0.00";

/**
     * Formatea un importe a String en formato numerico
     * @param valor   Valor a formatear
     * @param entrada Indica true para entrada (hacia tx) o false para salida (hacia
     *                front)
     * @return
     */
    public static String formatImporte(final String valor, final boolean entrada) {
        DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(Locale.GERMAN);
        decimalFormat.applyPattern(PATTERN);

        if (valor != null && !"".equals(valor.trim())) {
            double conValor = 0;
            try {
                conValor = Double.parseDouble(valor);
            } catch (NumberFormatException e) {
                String valorReplace = valor.replace(".", "").replace(",", ".");
                conValor = Double.parseDouble(valorReplace);
            }

            if (entrada) {
                return Double.toString(conValor);
            } else {
                return decimalFormat.format(conValor);
            }
        }

        return valor;
    }

Java: Sumar, redondear BigDecimal, y convertir a String

map.put("balance", refinancingLoanItem.getBalances().getTotalUnpaidAmount().getAmount().add(refinancingLoanItem.getBalances().getOutstandingCapital().getAmount()).setScale(2, BigDecimal.ROUND_CEILING).toPlainString());

domingo, 23 de mayo de 2021

Java: Gettear y setear campos a objetos genéricos mediante Reflection

import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

 

/**
     * Método de reflexión que busca por nombre de atributo en un objeto ese atributo
     * y devuelve su valor
     *
     * @param nombreAtributo
     * @param objetoDondeBuscar
     * @return
     */
    public static String buscaParametroPorNombre(final String nombreAtributo, final Object objetoDondeBuscar) {
        Class<?> c = objetoDondeBuscar.getClass();
        Field f = null;
        String result = null;
        do {
            try {
                f = c.getDeclaredField(nombreAtributo);
            } catch (NoSuchFieldException e) {
                log.debug("No se encuentra el campo: " + nombreAtributo);
            }

            if (f != null) {
                try {
                    f.setAccessible(true);
                    result = f.get(objetoDondeBuscar) != null ? String.valueOf(f.get(objetoDondeBuscar)) : null;
                } catch (IllegalAccessException e) {
                    log.debug("No se encuentra el campo: " + nombreAtributo, e);
                }
            }
            c = c.getSuperclass();
        } while ((c != null) && (c != Object.class));

        return result;
    }

    /**
     * Método de reflexión que setea el valor de un atributo en un objeto
     *
     * @param nombreAtributo
     * @param objetoDondeBuscar
     * @param valorAtributo
     * @return
     */
    public static String setParametroPorNombre(final String nombreAtributo, final Object objetoDondeBuscar,
                                               final String valorAtributo) {
        Class<?> c = objetoDondeBuscar.getClass();
        Field f = null;

        try {
            f = c.getDeclaredField(nombreAtributo);
        } catch (NoSuchFieldException e) {
            log.debug("No se encuentra el campo: " + nombreAtributo);
        }
        if (f != null) {
            try {
                f.setAccessible(true);
                f.set(objetoDondeBuscar, valorAtributo);
            } catch (IllegalAccessException e) {
                log.debug("Error al setear el atributo: " + nombreAtributo + "con valor: " + valorAtributo, e);
            }
        }
        return "OK";
    }

martes, 18 de mayo de 2021

Ordenar una lista de objetos en Java

lstPersonasCuentaDo.sort(Comparator.comparing(Persona::getNombreCompleto, Comparator.nullsLast(Comparator.naturalOrder())));

jueves, 18 de marzo de 2021

Identificarse en GitHub con token de acceso en lugar de contraseña (Eclipse y STS)

If you're using Two Factor Authentication on GitHub, the "not authorized" error can be returned even if you are using the correct username and password. This can be resolved by generating a personal access token.

After generating the secure access token, we'll use this instead of a password. Make sure not to leave the page before you're done, because once you leave the page, you'll never see it again (thankfully it can be regenerated, but anything using the previously generated token will cease to authenticate).

This assumes that you've successfully installed EGit and that you've successfully cloned a repository.

  1. Go to your GitHub.com settings, and in the left hand pane click Personal access tokens.
  2. Click Generate new token. Select the scopes that you'd like this token to be able to use, and generate it.
  3. Copy the token. It should look something like this: 9731f5cf519e9abb53e6ba9f5134075438944888 (don't worry, this is invalid).
  4. Back in Eclipse (Juno, since that's OP's version), click Window > Show View > Other.... Under Git, select Git Repositories.
  5. A new pane appears, from which you can open (repository name) > Remotes > origin.
  6. Right click on a node and choose Change Credentials.... Enter your username for User, and your secure access token for the Password.