Binaries.java [tools/WepsReportData/src/usda/weru/util] Revision: defeb2ba3861ae248dfdcc875844cb78e2452046  Date: Thu Aug 27 13:53:18 MDT 2015
/*
 * $Id$
 * 
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * 2010-2013, Olaf David and others, Colorado State University.
 *
 * CSIP 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, version 2.1.
 *
 * CSIP 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 OMS.  If not, see <http://www.gnu.org/licenses/lgpl.txt>.
 */
package usda.weru.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;

/**
 *
 * @author od
 */
public class Binaries {

    /**
     * Get the architecture
     * @return
     */
    public static String getArch() {
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("bsd")) {
            os = "bsd";
        } else {
            os = os.substring(0, 3);
        }
        return os + "-" + System.getProperty("os.arch").toLowerCase();
    }

   
    static String replaceArch(String s) {
        return s.replace("${arch}", getArch());
    }

    /**
     *
     * @param name
     * @param newName
     * @return
     * @throws IOException
     */
    public static File unpackResourceAbsolute(String name, String newName) throws IOException {
        name = replaceArch(name);
        URL u = Binaries.class.getResource(name);
        if (u == null) {
            throw new IllegalArgumentException("No such resource " + name);
        }

        File outFile = new File(newName);
        URLConnection con = u.openConnection();

        if (outFile.exists() && con.getDate() < outFile.lastModified()) {
            // the local file exists and is newer.
            return outFile;
        }

        if (outFile.exists() && con.getContentLength() == outFile.length()) {
            return outFile;
        }

        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }

        InputStream in = new BufferedInputStream(u.openStream());
        FileUtils.copyInputStreamToFile(in, outFile);
        in.close();

        outFile.setExecutable(true);
        outFile.setLastModified(con.getDate());
        return outFile;
    }


    /**
     * get the FS usage of that directory/file location in percent.
     *
     * @param file
     * @return value 0.0 .. 1.0, 1.0 means 100% full.
     */
    public static double getFSUsage(File file) {
        return 1 - (double) file.getUsableSpace() / file.getTotalSpace();
    }


    /**
     * get the library jars
     *
     * @param dir
     * @return
     */
    public static List<File> getJars(File dir) {
        File[] f = dir.listFiles((FilenameFilter) new WildcardFileFilter("*.jar"));
        if (f == null) {
            return new ArrayList<>();
        }
        return Arrays.asList(f);
    }


    /**
     * Convert the files to a classpath
     *
     * @param f
     * @param jar file list
     * @return
     */
    public static String asClassPath(List<File> f) {
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < f.size(); i++) {
            if (f.get(i).getName().endsWith(".jar")) {
                b.append(f.get(i).toString());
                if (i < f.size() - 1) {
                    b.append(File.pathSeparatorChar);
                }
            }
        }
        return b.toString();
    }


    /**
     * Converts a map to system properties.
     *
     * @param m
     * @return
     */
    public static String[] asSysProps(Map<String, String> m) {
        List<String> b = new ArrayList<>();
        for (String key : m.keySet()) {
            String val = m.get(key);
            b.add("-D" + key + "=" + val);
        }
        return b.toArray(new String[b.size()]);
    }


    /**
     *
     * @param env
     * @return
     */
    public static Map<String, String> parseEnv(String e) {
        String[] env = e.split("\\s+");
        Map<String, String> m = new HashMap<>();
        for (String s : env) {
            String t[] = s.trim().split("\\s*=\\s*");
            if (t.length == 2) {
                m.put(t[0], t[1]);
            }
        }
        return m;
    }


    public static void main(String[] args) throws Exception {
        
        String a = "jdbc:sqlserver://129.82.20.242:1433;databaseName=lmod_ZedX;user=lmod-rw;password=managements";
        String b = a.replaceAll("password=.+[;]?", "password=****;");
        
        System.out.println(b);
                
//        String a = resolve("${csip.arch}  all to ${user.dir} is true. '${}'live in ${csip.dir}");
//        System.out.println(a);
//
////        File dir = new File("/tmp");
////        
////        String b = "odd/bcd/ab.txt";
//        File f = new File("odd/bcd/ab.txt");
//        f.getParentFile().mkdirs();
//
//        FileOutputStream os = new FileOutputStream(f);
//        os.write("olaf".getBytes());
//        os.close();
////        IOUtils.writeStringToFile(f, "hi there");

    }

    /**
     * property substitution in a string.
     *
     * @param str
     * @return
     */
    private static String resolve0(String str, Properties p) {
        int idx = 0;
        while (idx < str.length()) {
            int start = str.indexOf("${", idx);
            int end = str.indexOf("}", idx);
            if (start == -1 || end == -1 || end < start) {
                break;
            }
            String key = str.substring(start + 2, end);
            String val = p.getProperty(key);
            int inc;
            if (val != null) {
                str = str.replace("${" + key + "}", val);
                inc = val.length();
            } else {
                inc = key.length() + 3;
            }
            idx = start + inc;
        }
        return str;
    }

}