jp.terasoluna.fw.batch.util.BatchUtil.java Source code

Java tutorial

Introduction

Here is the source code for jp.terasoluna.fw.batch.util.BatchUtil.java

Source

/*
 * Copyright (c) 2011 NTT DATA Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package jp.terasoluna.fw.batch.util;

import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;

import jp.terasoluna.fw.batch.constants.LogId;
import jp.terasoluna.fw.batch.exception.IllegalClassTypeException;
import jp.terasoluna.fw.logger.TLogger;
import jp.terasoluna.fw.util.PropertyUtil;

import org.apache.commons.logging.Log;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * ??<br>
 * <br>
 * ???????
 */
public class BatchUtil {
    /** . */
    private static final TLogger LOGGER = TLogger.getLogger(BatchUtil.class);

    /**
     * 
     */
    protected BatchUtil() {
    }

    /**
     * ??
     * @param args ??
     * @return ????
     */
    public static String cat(Object... args) {

        StringBuilder str = new StringBuilder();

        if (args == null) {
            return null;
        }

        for (Object o : args) {
            if (o != null) {
                str.append(o);
            }
        }

        return str.toString();
    }

    /**
     * ???
     * @param jobCd 
     * @return String 
     */
    public static String getInfoLogStartMsg(String jobCd) {

        return BatchUtil.cat("[", jobCd, "] ", "?");
    }

    /**
     * ???
     * @param jobCd 
     * @return String 
     */
    public static String getInfoLogEndMsg(String jobCd) {

        return BatchUtil.cat("[", jobCd, "] ", "?");
    }

    /**
     * ?TransactionDefinition??
     * @return 
     */
    public static TransactionDefinition getTransactionDefinition() {
        return new DefaultTransactionDefinition();
    }

    /**
     * ?TransactionDefinition??
     * @param propagationBehavior ??(@see TransactionDefinition) TransactionDefinition.PROPAGATION_REQUIRED
     * @param isolationLevel (@see TransactionDefinition) TransactionDefinition.ISOLATION_DEFAULT
     * @param timeout () TransactionDefinition.TIMEOUT_DEFAULT (??)
     * @param readOnly  false
     * @return 
     */
    public static TransactionDefinition getTransactionDefinition(int propagationBehavior, int isolationLevel,
            int timeout, boolean readOnly) {
        DefaultTransactionDefinition td = new DefaultTransactionDefinition();
        td.setPropagationBehavior(propagationBehavior);
        td.setIsolationLevel(isolationLevel);
        td.setTimeout(timeout);
        td.setReadOnly(readOnly);
        return td;
    }

    /**
     * ??
     * @param tran PlatformTransactionManager
     * @return TransactionStatus
     */
    public static TransactionStatus startTransaction(PlatformTransactionManager tran) {
        return startTransaction(tran, getTransactionDefinition(), null);
    }

    /**
     * ??
     * @param tran PlatformTransactionManager
     * @param log Log
     * @return TransactionStatus
     */
    public static TransactionStatus startTransaction(PlatformTransactionManager tran, Log log) {
        return startTransaction(tran, getTransactionDefinition(), log);
    }

    /**
     * ??
     * @param tran PlatformTransactionManager
     * @param propagationBehavior ??(@see TransactionDefinition) TransactionDefinition.PROPAGATION_REQUIRED
     * @param isolationLevel (@see TransactionDefinition) TransactionDefinition.ISOLATION_DEFAULT
     * @param timeout () TransactionDefinition.TIMEOUT_DEFAULT (??)
     * @param readOnly  false
     * @return TransactionStatus
     */
    public static TransactionStatus startTransaction(PlatformTransactionManager tran, int propagationBehavior,
            int isolationLevel, int timeout, boolean readOnly) {
        return startTransaction(tran,
                getTransactionDefinition(propagationBehavior, isolationLevel, timeout, readOnly), null);
    }

    /**
     * ??
     * @param tran PlatformTransactionManager
     * @param propagationBehavior ??(@see TransactionDefinition) TransactionDefinition.PROPAGATION_REQUIRED
     * @param isolationLevel (@see TransactionDefinition) TransactionDefinition.ISOLATION_DEFAULT
     * @param timeout () TransactionDefinition.TIMEOUT_DEFAULT (??)
     * @param readOnly  false
     * @param log Log
     * @return TransactionStatus
     */
    public static TransactionStatus startTransaction(PlatformTransactionManager tran, int propagationBehavior,
            int isolationLevel, int timeout, boolean readOnly, Log log) {
        return startTransaction(tran,
                getTransactionDefinition(propagationBehavior, isolationLevel, timeout, readOnly), log);
    }

    /**
     * ??
     * @param tran PlatformTransactionManager
     * @param def TransactionDefinition
     * @return TransactionStatus
     */
    public static TransactionStatus startTransaction(PlatformTransactionManager tran, TransactionDefinition def) {
        return startTransaction(tran, def, null);
    }

    /**
     * ??
     * @param tran PlatformTransactionManager
     * @param def TransactionDefinition
     * @param log Log
     * @return TransactionStatus
     */
    public static TransactionStatus startTransaction(PlatformTransactionManager tran, TransactionDefinition def,
            Log log) {
        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025033, tran);
            if (def != null) {
                logDebug(log, LogId.DAL025034, def.getPropagationBehavior(), def.getIsolationLevel(),
                        def.getTimeout(), def.isReadOnly(), def.getName());
            }
        }

        TransactionStatus stat = null;
        if (tran != null) {
            stat = tran.getTransaction(def);
        }

        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025035, stat);
        }
        return stat;
    }

    /**
     * ??
     * @param tranDef TransactionDefinition
     * @param tranMap PlatformTransactionManager
     * @return TransactionStatus
     */
    public static Map<String, TransactionStatus> startTransactions(TransactionDefinition tranDef,
            Map<?, ?> tranMap) {
        return startTransactions(tranDef, tranMap, null);
    }

    /**
     * ??
     * @param tranDef TransactionDefinition
     * @param tranMap PlatformTransactionManager
     * @param log Log
     * @return TransactionStatus
     */
    public static Map<String, TransactionStatus> startTransactions(TransactionDefinition tranDef, Map<?, ?> tranMap,
            Log log) {
        Map<String, TransactionStatus> statMap = new LinkedHashMap<String, TransactionStatus>();

        if (!tranMap.isEmpty()) {
            for (Map.Entry<?, ?> ent : tranMap.entrySet()) {
                String key = null;
                PlatformTransactionManager ptm = null;

                // ??
                if (ent.getKey() instanceof String) {
                    key = (String) ent.getKey();
                }
                // ???
                if (ent.getValue() instanceof PlatformTransactionManager) {
                    ptm = (PlatformTransactionManager) ent.getValue();
                }

                if (ptm != null) {

                    if (log != null && log.isDebugEnabled()) {
                        logDebug(log, LogId.DAL025033, key);
                        if (tranDef != null) {
                            logDebug(log, LogId.DAL025034, tranDef.getPropagationBehavior(),
                                    tranDef.getIsolationLevel(), tranDef.getTimeout(), tranDef.isReadOnly(),
                                    tranDef.getName());
                        }
                    }

                    // 
                    TransactionStatus trnStat = null;
                    try {
                        trnStat = ptm.getTransaction(tranDef);
                    } catch (TransactionException e) {
                        if (log != null && log.isErrorEnabled()) {
                            logError(log, LogId.EAL025048, e, key);
                        }
                        endTransactions(tranMap, statMap, log);
                        throw e;
                    }

                    // ?
                    if (statMap != null) {
                        statMap.put(key, trnStat);
                    }

                    if (log != null && log.isDebugEnabled()) {
                        logDebug(log, LogId.DAL025035, key, trnStat);
                    }
                }
            }
        }

        return statMap;
    }

    /**
     * ?? ???
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     */
    public static void commitTransaction(PlatformTransactionManager tran, TransactionStatus stat) {
        commitTransaction(tran, stat, null);
    }

    /**
     * ?? ???
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     * @param log Log
     */
    public static void commitTransaction(PlatformTransactionManager tran, TransactionStatus stat, Log log) {
        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025037, stat);
        }

        if (tran != null && stat != null) {
            tran.commit(stat);
        }
        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025038, stat);
        }
    }

    /**
     * ??
     * @param tranMap 
     * @param statMap 
     */
    public static void commitTransactions(Map<?, ?> tranMap, Map<String, TransactionStatus> statMap) {
        commitTransactions(tranMap, statMap, null);
    }

    /**
     * ??
     * @param tranMap 
     * @param statMap 
     * @param log 
     */
    public static void commitTransactions(Map<?, ?> tranMap, Map<String, TransactionStatus> statMap, Log log) {

        Set<Entry<String, TransactionStatus>> statSet = statMap.entrySet();

        if (statSet.isEmpty()) {
            return;
        }

        Stack<Entry<String, TransactionStatus>> stack = new Stack<Entry<String, TransactionStatus>>();
        for (Entry<String, TransactionStatus> stat : statSet) {
            stack.push(stat);
        }

        while (!stack.isEmpty()) {
            // ???
            Entry<String, TransactionStatus> statEntry = stack.pop();
            String key = statEntry.getKey();
            TransactionStatus trnStat = statEntry.getValue();
            if (trnStat == null) {
                continue;
            }

            // ???
            Object ptmObj = tranMap.get(key);
            if (ptmObj == null || !(ptmObj instanceof PlatformTransactionManager)) {
                continue;
            }
            PlatformTransactionManager ptm = (PlatformTransactionManager) ptmObj;

            if (log != null && log.isDebugEnabled()) {
                logDebug(log, LogId.DAL025038, trnStat);
            }
            // 
            ptm.commit(trnStat);
        }
    }

    /**
     * ???
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     */
    public static void endTransaction(PlatformTransactionManager tran, TransactionStatus stat) {
        endTransaction(tran, stat, null);
    }

    /**
     * ???
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     * @param log Log
     */
    public static void endTransaction(PlatformTransactionManager tran, TransactionStatus stat, Log log) {
        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025040, stat);
        }

        if (tran != null && stat != null && !stat.isCompleted()) {
            tran.rollback(stat);
        }

        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025041, stat);
        }
    }

    /**
     * ???
     * @param tranMap PlatformTransactionManager
     * @param statMap TransactionStatus
     * @return ???PlatformTransactionManager?????????true??
     */
    public static boolean endTransactions(Map<?, ?> tranMap, Map<String, TransactionStatus> statMap) {
        return endTransactions(tranMap, statMap, null);
    }

    /**
     * ???
     * @param tranMap PlatformTransactionManager
     * @param statMap TransactionStatus
     * @param log Log
     * @return ???PlatformTransactionManager?????????true??
     */
    public static boolean endTransactions(Map<?, ?> tranMap, Map<String, TransactionStatus> statMap, Log log) {
        boolean isNormal = true;

        Set<Entry<String, TransactionStatus>> statSet = statMap.entrySet();

        if (statSet == null || statSet.isEmpty()) {
            return isNormal;
        }

        Stack<Entry<String, TransactionStatus>> stack = new Stack<Entry<String, TransactionStatus>>();
        for (Entry<String, TransactionStatus> stat : statSet) {
            stack.push(stat);
        }

        while (!stack.isEmpty()) {
            // ???
            Entry<String, TransactionStatus> statEntry = stack.pop();
            String key = statEntry.getKey();
            TransactionStatus trnStat = statEntry.getValue();

            if (trnStat == null) {
                continue;
            }

            // ???
            Object ptmObj = tranMap.get(key);
            if (ptmObj == null || !(ptmObj instanceof PlatformTransactionManager)) {
                continue;
            }
            PlatformTransactionManager ptm = (PlatformTransactionManager) ptmObj;

            // ??????
            if (trnStat.isCompleted()) {
                continue;
            }

            if (log != null && log.isDebugEnabled()) {
                logDebug(log, LogId.DAL025041, trnStat);
            }

            // ?
            try {
                ptm.rollback(trnStat);
            } catch (TransactionException e) {
                if (log != null && log.isErrorEnabled()) {
                    logError(log, LogId.EAL025045, e, key);
                }
                isNormal = false;
                // ????????
            }

            if (log != null && log.isDebugEnabled()) {
                logDebug(log, LogId.DAL025041, trnStat);
            }
        }
        return isNormal;
    }

    /**
     * ??
     * @param stat TransactionStatus
     * @return Object ?
     */
    public static Object setSavepoint(TransactionStatus stat) {
        return setSavepoint(stat, null);
    }

    /**
     * ??
     * @param stat TransactionStatus
     * @param log Log
     * @return Object ?
     */
    public static Object setSavepoint(TransactionStatus stat, Log log) {
        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025046, stat);
        }

        Object savepoint = stat.createSavepoint();

        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025047, stat);
        }

        return savepoint;
    }

    /**
     * ??
     * @param stat TransactionStatus
     * @param savepoint ?
     */
    public static void releaseSavepoint(TransactionStatus stat, Object savepoint) {
        releaseSavepoint(stat, savepoint, null);
    }

    /**
     * ??
     * @param stat TransactionStatus
     * @param savepoint ?
     * @param log Log
     */
    public static void releaseSavepoint(TransactionStatus stat, Object savepoint, Log log) {
        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025048, stat);
        }

        stat.releaseSavepoint(savepoint);

        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025049, stat);
        }
    }

    /**
     * ??????
     * @param stat TransactionStatus
     * @param savepoint ?
     */
    public static void rollbackSavepoint(TransactionStatus stat, Object savepoint) {
        rollbackSavepoint(stat, savepoint, null);
    }

    /**
     * ??????
     * @param stat TransactionStatus
     * @param savepoint ?
     * @param log Log
     */
    public static void rollbackSavepoint(TransactionStatus stat, Object savepoint, Log log) {
        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025050, stat);
        }

        stat.rollbackToSavepoint(savepoint);

        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025051, stat);
        }
    }

    /**
     * ????
     * @param tran ?
     * @param stat TransactionStatus
     */
    public static void rollbackTransaction(PlatformTransactionManager tran, TransactionStatus stat) {
        rollbackTransaction(tran, stat, null);
    }

    /**
     * ????
     * @param tran ?
     * @param stat TransactionStatus
     * @param log Log
     */
    public static void rollbackTransaction(PlatformTransactionManager tran, TransactionStatus stat, Log log) {
        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025052, stat);
        }
        if (tran != null && stat != null && !stat.isCompleted()) {
            tran.rollback(stat);
        }
        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025053, stat);
        }

    }

    /**
     * ??????
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     * @return 
     */
    public static TransactionStatus commitRestartTransaction(PlatformTransactionManager tran,
            TransactionStatus stat) {
        commitTransaction(tran, stat, null);
        endTransaction(tran, stat, null);
        return startTransaction(tran);
    }

    /**
     * ??????
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     * @param log Log
     */
    public static TransactionStatus commitRestartTransaction(PlatformTransactionManager tran,
            TransactionStatus stat, Log log) {
        commitTransaction(tran, stat, log);
        endTransaction(tran, stat, log);
        return startTransaction(tran, log);
    }

    /**
     * ??????
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     * @param def TransactionDefinition
     */
    public static TransactionStatus commitRestartTransaction(PlatformTransactionManager tran,
            TransactionStatus stat, TransactionDefinition def) {
        commitTransaction(tran, stat, null);
        endTransaction(tran, stat, null);
        return startTransaction(tran, def);
    }

    /**
     * ??????
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     * @param def TransactionDefinition
     * @param log Log
     */
    public static TransactionStatus commitRestartTransaction(PlatformTransactionManager tran,
            TransactionStatus stat, TransactionDefinition def, Log log) {
        commitTransaction(tran, stat, log);
        endTransaction(tran, stat, log);
        return startTransaction(tran, def, log);
    }

    /**
     * ???????
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     */
    public static TransactionStatus rollbackRestartTransaction(PlatformTransactionManager tran,
            TransactionStatus stat) {
        rollbackTransaction(tran, stat, null);
        endTransaction(tran, stat, null);
        return startTransaction(tran);
    }

    /**
     * ???????
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     * @param log Log
     */
    public static TransactionStatus rollbackRestartTransaction(PlatformTransactionManager tran,
            TransactionStatus stat, Log log) {
        rollbackTransaction(tran, stat, log);
        endTransaction(tran, stat, log);
        return startTransaction(tran, log);
    }

    /**
     * ???????
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     * @param def TransactionDefinition
     */
    public static TransactionStatus rollbackRestartTransaction(PlatformTransactionManager tran,
            TransactionStatus stat, TransactionDefinition def) {
        rollbackTransaction(tran, stat, null);
        endTransaction(tran, stat, null);
        return startTransaction(tran, def);
    }

    /**
     * ???????
     * @param tran PlatformTransactionManager
     * @param stat TransactionStatus
     * @param def TransactionDefinition
     * @param log Log
     */
    public static TransactionStatus rollbackRestartTransaction(PlatformTransactionManager tran,
            TransactionStatus stat, TransactionDefinition def, Log log) {
        rollbackTransaction(tran, stat, log);
        endTransaction(tran, stat, log);
        return startTransaction(tran, def, log);
    }

    /**
     * List???? List???????????????
     * @param <E> ??
     * @param list 
     * @param clazz ?????Class?
     * @return List??????
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static <E> E[] changeListToArray(List<E> list, Class clazz) {

        if (clazz == null) {
            throw new IllegalClassTypeException();
        }

        // SQL???
        List<E> castedList = list;

        // ???
        E[] retArray = (E[]) Array.newInstance(clazz, castedList.size());
        try {
            castedList.toArray(retArray);
        } catch (ArrayStoreException e) {
            throw new IllegalClassTypeException(e);
        }

        return retArray;
    }

    /**
     * .properties???? ?????????? ?????
     * @param propertyName .properties????.properties????
     * @param grpKey 
     * @return propertyName??grpKeyPrefix
     */
    public static List<String> getProperties(String propertyName, String grpKey) {

        Properties properties = PropertyUtil.loadProperties(propertyName);
        Enumeration<String> propNames = PropertyUtil.getPropertyNames(properties, grpKey);

        List<String> propNamesList = Collections.list(propNames);
        Collections.sort(propNamesList);

        List<String> resultList = new ArrayList<String>();

        for (String key : propNamesList) {
            resultList.add(PropertyUtil.getProperty(key));
        }

        return resultList;
    }

    /**
     * Java ?????? ??????
     * @return Java ?
     */
    public static String getMemoryInfo() {
        DecimalFormat f1 = new DecimalFormat("#,###KB");
        DecimalFormat f2 = new DecimalFormat("##.#");

        Runtime rt = Runtime.getRuntime();
        long free = rt.freeMemory() / 1024;
        long total = rt.totalMemory() / 1024;
        long max = rt.maxMemory() / 1024;
        long used = total - free;
        double ratio = used * 100 / (double) total;

        StringBuilder sb = new StringBuilder();

        sb.append("Java memory info : ");
        sb.append("used=");
        sb.append(f1.format(used));
        sb.append(" (");
        sb.append(f2.format(ratio));
        sb.append("%), ");
        sb.append("total=");
        sb.append(f1.format(total));
        sb.append(", ");
        sb.append("max=");
        sb.append(f1.format(max));

        return sb.toString();
    }

    /**
     * ??
     * TLogger / commons.logging ??????
     * @param log 
     * @param logId ?ID
     * @param args ?
     */
    private static void logDebug(Log log, String logId, Object... args) {
        if (log instanceof TLogger) {
            TLogger logger = (TLogger) log;
            logger.debug(logId, args);
        } else {
            String msg = LOGGER.getLogMessage(logId, args);
            log.debug(msg);
        }
    }

    /**
     * ??
     * TLogger / commons.logging ??????
     * @param log 
     * @param logId ?ID
     * @param args ?
     */
    private static void logError(Log log, String logId, Object... args) {
        if (log instanceof TLogger) {
            TLogger logger = (TLogger) log;
            logger.error(logId, args);
        } else {
            String msg = LOGGER.getLogMessage(logId, args);
            log.error(msg);
        }
    }
}