org.compiere.mfg_scm.pluginManager.Mfg_scmUtils.java Source code

Java tutorial

Introduction

Here is the source code for org.compiere.mfg_scm.pluginManager.Mfg_scmUtils.java

Source

/*  =====================================================================
*  Mfg_scmUtils -
    
-------------------------------------------------------------------------
Copyright (c) 1991-2013 Andre Charles Legendre <andre.legendre@kalimasystems.org>
Copyright other contributors as noted in the AUTHORS file.
    
This file is part of JSPluginManager, the Javascript pluginManager for java
    
This is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
    
This software is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
    
You should have received a copy of the GNU Lesser General Public
License along with this program. If not, see
<http://www.gnu.org/licenses/>.
*  ===================================================================== */

package org.compiere.mfg_scm.pluginManager;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.DirectoryScanner;

/**
 * Utilities for reading mfg_scm mfg_scmPlugin descriptors, profile descriptors
 * and workspace descriptors.
 * 
 * @author <a href="mailto:andre.legendre@kalimasystems.org">Andre Charles Legendre
 *         </a>
 * @version 0.1a (09/06/2004)
 * 
 */

public class Mfg_scmUtils {
    /** The Log to which logging calls will be made. */
    static final String BROWSER = "org.compiere.mfg_scm.common";

    /**
     * Get a set of files from a specifed directory with a set of includes.
     * 
     * @param directory
     *            Directory to scan.
     * @param includes
     *            Comma separated list of includes.
     * @return files
     */
    public static String[] getFiles(File directory, String includes) {
        return getFiles(directory, includes, null);
    }

    /**
     * Get a set of files from a specifed directory with a set of includes.
     * 
     * @param directory
     *            Directory to scan.
     * @param includes
     *            Comma separated list of includes.
     * @param excludes
     *            Comma separated list of excludes.
     * @return files
     */
    public static String[] getFiles(File directory, String includes, String excludes) {
        String[] includePatterns = null;
        if (includes != null) {
            includePatterns = StringUtils.split(includes, ",");
        }

        String[] excludePatterns = null;
        if (excludes != null) {
            excludePatterns = StringUtils.split(excludes, ",");
        }

        DirectoryScanner directoryScanner = new DirectoryScanner();
        directoryScanner.setBasedir(directory);
        directoryScanner.setIncludes(includePatterns);
        directoryScanner.setExcludes(excludePatterns);
        directoryScanner.scan();
        String[] files = directoryScanner.getIncludedFiles();

        for (int i = 0; i < files.length; i++) {
            files[i] = new File(directory, files[i]).getAbsolutePath();
        }

        return files;
    }

    /**
     * Take a dominant and recessive Map and merge the key:value pairs where the
     * recessive Map may add key:value pairs to the dominant Map but may not
     * override any existing key:value pairs.
     * 
     * If we have two Maps, a dominant and recessive, and their respective keys
     * are as follows:
     * 
     * dominantMapKeys = { a, b, c, d, e, f } recessiveMapKeys = { a, b, c, x, y, z }
     * 
     * Then the result should be the following:
     * 
     * resultantKeys = { a, b, c, d, e, f, x, y, z }
     * 
     * @param dominantMap
     *            Dominant Map.
     * @param recessiveMap
     *            Recessive Map.
     * @return The result map with combined dominant and recessive values.
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map mergeMaps(Map dominantMap, Map recessiveMap) {
        Map result = new HashMap();

        if (dominantMap == null && recessiveMap == null) {
            return null;
        }

        if (dominantMap != null && recessiveMap == null) {
            return dominantMap;
        }

        if (dominantMap == null) {
            return recessiveMap;
        }

        // Grab the keys from the dominant and recessive maps.
        Set dominantMapKeys = dominantMap.keySet();
        Set recessiveMapKeys = recessiveMap.keySet();

        // Create the set of keys that will be contributed by the
        // recessive Map by subtracting the intersection of keys
        // from the recessive Map's keys.
        Collection contributingRecessiveKeys = CollectionUtils.subtract(recessiveMapKeys,
                CollectionUtils.intersection(dominantMapKeys, recessiveMapKeys));

        result.putAll(dominantMap);

        // Now take the keys we just found and extract the values from
        // the recessiveMap and put the key:value pairs into the dominantMap.
        for (Iterator i = contributingRecessiveKeys.iterator(); i.hasNext();) {
            Object key = i.next();
            result.put(key, recessiveMap.get(key));
        }

        return result;
    }

    /**
     * Take a series of <code>Map</code> s and merge them where the ordering of
     * the array from 0..n is the dominant order.
     * 
     * @param maps
     *            An array of Maps to merge.
     * @return Map The result Map produced after the merging process.
     */
    @SuppressWarnings("rawtypes")
    public static Map mergeMaps(Map[] maps) {
        Map result;

        if (maps.length == 0) {
            result = null;
        } else if (maps.length == 1) {
            result = maps[0];
        } else {
            result = mergeMaps(maps[0], maps[1]);

            for (int i = 2; i < maps.length; i++) {
                result = mergeMaps(result, maps[i]);
            }
        }

        return result;
    }

    /**
     * Load properties from a <code>File</code>.
     * 
     * @param file
     *            Propertie file to load.
     * @return The loaded Properties.
     * @throws IOException
     */
    public static Properties loadProperties(File file) throws IOException {
        if (file.exists()) {
            return loadProperties(new FileInputStream(file));
        }
        return null;
    }

    /**
     * Load properties from an <code>InputStream</code>.
     * 
     * @param is
     *            InputStream from which load properties.
     * @return The loaded Properties.
     * @throws IOException
     */
    public static Properties loadProperties(InputStream is) throws IOException {
        Properties properties = new Properties();
        try {
            properties.load(is);
            for (Iterator<Object> i = properties.keySet().iterator(); i.hasNext();) {
                String property = (String) i.next();
                properties.setProperty(property, properties.getProperty(property).trim());
            }
        } catch (IOException e) {
            // ignore
            throw e;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (final IOException e) {
                throw e;
            }
        }
        return properties;
    }

    /** Resource bundle with user messages. */
    private static ResourceBundle messages;

    /**
     * Load Mfg_scm user messages from a resource bundle given the user's
     * locale.
     * 
     */
    private static void loadMessages() {
        try {
            // Look for the the user's locale.
            messages = ResourceBundle.getBundle("org/compiere/mfg_scm/messages/messages");
        } catch (MissingResourceException e) {
            // fall back to English.
            messages = ResourceBundle.getBundle("org/compiere/mfg_scm/messages/messages", Locale.ENGLISH);
        }
    }

    /**
     * Retrieve a user message.
     * 
     * @param messageId
     *            Id of message type to use.
     * @return Message for the user's locale.
     */
    public static String getMessage(String messageId) {
        return getMessage(messageId, null);
    }

    /**
     * Retrieve a user message.
     * 
     * @param messageId
     *            Id of message type to use.
     * @param variable
     *            Value to substitute for ${1} in the given message.
     * @return Message for the user's locale.
     */
    public static String getMessage(String messageId, Object variable) {
        if (messages == null) {
            loadMessages();
        }

        if (variable == null) {
            return messages.getString(messageId);
        }
        return StringUtils.replace(messages.getString(messageId), "${1}", variable.toString());
    }

    /**
     * Get a list of elts from a string.
     * 
     * @param tokenString
     *            the string
     * @return the List
     */
    public static List<String> getListFromString(String tokenString) {
        List<String> tokenList = new ArrayList<String>();
        if (tokenString != null) {
            StringTokenizer tok = new StringTokenizer(tokenString, ",??\t\n\r\f");
            while (tok.hasMoreTokens()) {
                tokenList.add(tok.nextToken());
            }
        }
        return tokenList;
    }

    /**
     * Set a list of elts to a string.
     * 
     * @param tokenList the token list
     * @return tokenString the corresponding string
     */
    public static String setListToString(List<String> tokenList) {
        String tokenString = null;
        for (Iterator<String> i = tokenList.iterator(); i.hasNext();) {
            if (tokenString == null)
                tokenString = (String) i.next();
            else
                tokenString = tokenString.concat("   " + (String) i.next());
        }
        return tokenString;
    }

    /**
     * Tries to convert the specified base path and file name into a file
     * object. The parameter strings can be relative files, absolute files and
     * file URLs.
     * 
     * @param basePath
     *            the base path
     * @param fileName
     *            the file name
     * @return the file object (<b>null</b> if no file can be obtained)
     */
    public static File getFile(String basePath, String fileName) {
        File file = null;
        File absolute = null;
        String fileUrlProtocol = "file";
        URL url;

        /* Look if it is an URL */
        try {
            url = new URL(new URL(basePath), fileName);
        } catch (MalformedURLException ex) {
            try {
                url = new URL(fileName);
            } catch (MalformedURLException ex1) {
                url = null;
            }
        }

        /* If it is an URL */
        if (url != null) {
            if (fileUrlProtocol.equals(url.getProtocol()))
                return new File(url.getPath());
            return null;
        }

        /* If it is not an URL */
        if (fileName != null)
            absolute = new File(fileName);

        if (StringUtils.isEmpty(basePath) || (absolute != null && absolute.isAbsolute())) {
            file = new File(fileName);
        } else {
            StringBuffer fName = new StringBuffer();
            fName.append(basePath);

            if (!basePath.endsWith(File.separator))
                fName.append(File.separator);

            if (fileName.startsWith("." + File.separator)) {
                fName.append(fileName.substring(2));
            } else {
                fName.append(fileName);
            }
            // System.out.println("GetFile : " + fName);
            file = new File(fName.toString());
        }
        return file;
    }

    public static boolean callAuthTool() throws IOException {

        String repositoryFileName = "/pMaster/outils/.mages/config.txt";
        File bufFile = new File(repositoryFileName);
        if (bufFile.exists()) {
            BufferedReader inBuf = new BufferedReader(new InputStreamReader(new FileInputStream(bufFile)));
            String line;
            if ((line = inBuf.readLine()) != null) {
                String result = null;
                String[] columns = line.split("\t");
                if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
                    result = callAuthToolWindows(columns[0]);
                } else {
                    result = callAuthToolDefault(columns[0]);
                }
                if (result != null && result.equals(columns[1]))
                    return (true);
            }
            inBuf.close();
        }
        // FIXME A changer pour false. Force a true temporairement
        return (true);
    }

    private static String callAuthToolWindows(String device) {
        try {
            String[] cmdArray = null;

            cmdArray = new String[] { "ifconfig", device };

            Process process = Runtime.getRuntime().exec(cmdArray);
            OutputStream stdOut = new ByteArrayOutputStream();
            OutputStream stderr = new ByteArrayOutputStream();
            new StreamUtil(process.getInputStream(), stdOut).start();
            new StreamUtil(process.getErrorStream(), stderr).start();
            int result = 0;
            try {
                result = process.waitFor();
            } catch (InterruptedException ie) {
                System.out.println("authCommand  interrupted");
            }
            if (result != 0)
                System.out.println("authCommand  failed");
            return stdOut.toString();
        } catch (FileNotFoundException filenotfoundexception) {
            System.out.println("authCommand failed ");
            filenotfoundexception.printStackTrace();
        } catch (IOException ioexception) {
            System.out.println("authCommand failed ");
            ioexception.printStackTrace();
        }
        return null;
    }

    private static String callAuthToolDefault(String device) {

        try {
            String[] cmdArray = null;

            cmdArray = new String[] { "ifconfig", device };

            Process process = Runtime.getRuntime().exec(cmdArray);
            OutputStream stdOut = new ByteArrayOutputStream();
            OutputStream stderr = new ByteArrayOutputStream();
            new StreamUtil(process.getInputStream(), stdOut).start();
            new StreamUtil(process.getErrorStream(), stderr).start();
            int result = 0;
            try {
                result = process.waitFor();
            } catch (InterruptedException ie) {
                System.out.println("authCommand  interrupted");
            }
            if (result != 0)
                System.out.println("authCommand  failed");
            StringTokenizer st = new StringTokenizer(stdOut.toString(), " \t\n\r\f,");

            boolean next = false;
            String g = null;
            while (st.hasMoreTokens()) {
                g = st.nextToken();
                if (next) {
                    break;
                }
                if (g.equals("HWaddr"))
                    next = true;
            }
            return g;
        } catch (FileNotFoundException filenotfoundexception) {
            System.out.println("authCommand failed ");
            filenotfoundexception.printStackTrace();
        } catch (IOException ioexception) {
            System.out.println("authCommand failed ");
            ioexception.printStackTrace();
        }
        return null;
    }

    public static boolean parseBoolean(String value) {

        if (value != null && !value.equals("")
                && (value.equals("true") || value.equals("True") || value.equals("on") || value.equals("On")))
            return true;
        return false;
    }
}