ips1ap101.lib.core.db.util.DBUtils.java Source code

Java tutorial

Introduction

Here is the source code for ips1ap101.lib.core.db.util.DBUtils.java

Source

/*
 * Este programa es software libre; usted puede redistribuirlo y/o modificarlo bajo los trminos
 * de la licencia "GNU General Public License" publicada por la Fundacin "Free Software Foundation".
 * Este programa se distribuye con la esperanza de que pueda ser til, pero SIN NINGUNA GARANTIA;
 * vea la licencia "GNU General Public License" para obtener mas informacin.
 */
package ips1ap101.lib.core.db.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.rowset.spi.SyncResolver;
import ips1ap101.lib.base.bundle.BundleMensajes;
import ips1ap101.lib.base.bundle.BundleWebui;
import ips1ap101.lib.core.app.Bitacora;
import org.apache.commons.lang.StringUtils;

/**
 * @author Jorge Campins
 */
public class DBUtils {

    private static final String BOMK = ""; // left guillemet

    private static final String EOMK = ""; // right guillemet

    private static final String[] INFIJOS = new String[] { "_ck", "_fk", "_pk", "_uk" };

    private static final String SUFIJO = "___";

    private static final String WHERE = " Where: ";

    private static final String ERROR = "ERROR: ";

    /**
     * Busca el nombre del constraint en el mensaje que envia el RDBMS cuando se produce un conflicto
     *
     * @param message Cadena correspondiente al mensaje que envia el RDBMS
     * @param status Entero correspondiente al tipo de conflicto (cualquiera de las constantes ROW_CONFLICT de SyncResolver)
     * @return Si se consigue, el nombre del constraint; de lo contratio retorna null
     */
    public static String getConstraintMessageKey(String message, int status) {
        String trimmed = StringUtils.trimToNull(message);
        if (trimmed != null) {
            trimmed = trimmed.replaceAll("[^a-zA-Z0-9_]", " ");
            trimmed = trimmed.trim().toLowerCase();
            String[] tokens = StringUtils.split(trimmed);
            if (tokens != null && tokens.length > 0) {
                String key, string;
                for (int i = 0; i < tokens.length; i++) {
                    key = tokens[i];
                    if (key.endsWith(SUFIJO) && StringUtils.indexOfAny(key, INFIJOS) > 0) {
                        key = StringUtils.removeEnd(key, SUFIJO);
                        if (key.contains("_fk_")) {
                            key += status == 1 ? ".1" : ".2";
                        }
                        string = BundleMensajes.getString(key);
                        return isKey(string) ? string : "<" + key + ">";
                    }
                }
            }
        }
        return null;
    }

    public static String getProperErrorMessage(String message) {
        String join = getConstraintMessageJoin(message, "");
        String trim = StringUtils.trimToEmpty(StringUtils.substringBefore(message, WHERE));
        return StringUtils.defaultIfBlank(join, trim);
    }

    public static String getConstraintMessageJoin(String message, String identifier) {
        String[] messages = getConstraintMessages(message, identifier);
        if (messages != null && messages.length > 0) {
            return StringUtils.join(messages, "; ");
        }
        return null;
    }

    public static String[] getConstraintMessages(String message, String identifier) {
        String[] keys = getConstraintMessageKeys(message);
        if (keys != null && keys.length > 0) {
            String transaction = BundleWebui.getString("database.action.command");
            String[] messages = new String[keys.length];
            for (int i = 0; i < keys.length; i++) {
                messages[i] = StringUtils.trimToEmpty(Bitacora.getTextoMensaje(keys[i], transaction, identifier));
            }
            return messages;
        }
        return null;
    }

    public static String[] getConstraintMessageKeys(String message) {
        String trimmed = StringUtils
                .trimToEmpty(StringUtils.substringAfter(StringUtils.substringBefore(message, WHERE), ERROR));
        if (StringUtils.isNotBlank(trimmed)) {
            String[] tokens = StringUtils.split(trimmed, ';');
            if (tokens != null && tokens.length > 1) {
                String key = tokens[0].trim();
                if (key.matches("^[0-9]{1,3}$")) {
                    int length = Integer.valueOf(key);
                    if (length == tokens.length - 1) {
                        String string;
                        String[] keys = new String[length];
                        for (int i = 1; i < tokens.length; i++) {
                            key = tokens[i].trim();
                            if (key.endsWith(SUFIJO) && StringUtils.indexOfAny(key, INFIJOS) > 0) {
                                key = StringUtils.removeEnd(key, SUFIJO);
                                string = BundleMensajes.getString(key);
                                keys[i - 1] = isKey(string) ? string : "<" + key + ">";
                            } else {
                                return null;
                            }
                        }
                        return keys;
                    }
                }
            }
            String key, string;
            String stripChars = BOMK + EOMK;
            List<String> list = new ArrayList<>();
            Pattern pattern = Pattern.compile("\\" + BOMK + ".*\\" + EOMK);
            Matcher matcher = pattern.matcher(trimmed);
            while (matcher.find()) {
                key = StringUtils.strip(matcher.group(), stripChars);
                if (key.endsWith(SUFIJO) && StringUtils.indexOfAny(key, INFIJOS) > 0) {
                    key = StringUtils.removeEnd(key, SUFIJO);
                    string = BundleMensajes.getString(key);
                    key = isKey(string) ? string : "<" + key + ">";
                    list.add(key);
                }
            }
            return (list.isEmpty()) ? null : list.toArray(new String[list.size()]);
        }
        return null;
    }

    public static String getTransactionLabel(int status) {
        String value;
        switch (status) {
        case SyncResolver.INSERT_ROW_CONFLICT:
            value = BundleWebui.getString("database.insert.command");
            break;
        case SyncResolver.UPDATE_ROW_CONFLICT:
            value = BundleWebui.getString("database.update.command");
            break;
        case SyncResolver.DELETE_ROW_CONFLICT:
            value = BundleWebui.getString("database.delete.command");
            break;
        default:
            value = BundleWebui.getString("database.commit.command");
            break;
        }
        return value;
    }

    private static boolean isKey(String string) {
        String key = StringUtils.trimToEmpty(string);
        return key.startsWith("<") && key.endsWith(">");
    }

}