Example usage for java.io File listFiles

List of usage examples for java.io File listFiles

Introduction

In this page you can find the example usage for java.io File listFiles.

Prototype

public File[] listFiles() 

Source Link

Document

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Usage

From source file:au.org.ala.layers.grid.GridClassBuilder.java

public static void main(String[] args) {

    logger.info("args[0]=diva grid input file (do not include .grd or .gri)\n\n");

    if (args.length > 0) {

        //remove existing
        try {//from w w  w .j  ava 2 s . com
            File f;

            if ((f = new File(args[0] + ".classes.json")).exists()) {
                f.delete();
            }

            if ((f = new File(args[0])).exists() && f.isDirectory()) {
                File[] fs = f.listFiles();
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].isFile()) {
                        fs[i].delete();
                    }
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        //build new
        try {
            buildFromGrid(args[0]);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:mujava.cli.genmutes.java

public static void main(String[] args) throws Exception {
    // System.out.println("test");
    genmutesCom jct = new genmutesCom();
    String[] argv = { "-all", "-debug", "Flower" }; // development use, when release,
    // comment out this line
    JCommander jCommander = new JCommander(jct, args);

    // check session name
    if (jct.getParameters().size() > 1) {
        Util.Error("Has more parameters than needed.");
        return;//  w  w w  . j  a  va  2 s.c o m
    }

    // set session name
    String sessionName = jct.getParameters().get(0);

    muJavaHomePath = Util.loadConfig();
    // check if debug mode
    if (jct.isDebug()) {
        Util.debug = true;
    }

    // get all existing session name
    File folder = new File(muJavaHomePath);
    // check if the config file has defined the correct folder
    if (!folder.isDirectory()) {
        Util.Error("ERROR: cannot locate the folder specified in mujava.config");
        return;
    }
    File[] listOfFiles = folder.listFiles();
    // null checking
    // check the specified folder has files or not
    if (listOfFiles == null) {
        Util.Error("ERROR: no files in the muJava home folder: " + muJavaHomePath);
        return;
    }
    List<String> fileNameList = new ArrayList<>();
    for (File file : listOfFiles) {
        fileNameList.add(file.getName());
    }

    // check if session is already created.
    if (!fileNameList.contains(sessionName)) {
        Util.Error("Session does not exist.");
        return;

    }

    // get all files in the session
    String[] file_list = new String[1];
    // if(jct.getD())
    // {
    File sessionFolder = new File(muJavaHomePath + "/" + sessionName + "/src");
    File[] listOfFilesInSession = sessionFolder.listFiles();
    file_list = new String[listOfFilesInSession.length];
    for (int i = 0; i < listOfFilesInSession.length; i++) {
        file_list[i] = listOfFilesInSession[i].getName();
    }

    // get all mutation operators selected
    HashMap<String, List<String>> ops = new HashMap<String, List<String>>(); // used
    // for
    // add
    // random
    // percentage
    // and
    // maximum

    String[] paras = new String[] { "1", "0" };
    if (jct.getAll()) // all is selected, add all operators
    {

        // if all is selected, all mutation operators are added
        ops.put("AORB", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AORS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ROR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ASRS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ODL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("VDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("CDL", new ArrayList<String>(Arrays.asList(paras)));
        // ops.put("SDL", jct.getAll());

    } else { // if not all, add selected ops to the list
        if (jct.getAORB()) {
            ops.put("AORB", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAORS()) {
            ops.put("AORS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAOIU()) {
            ops.put("AOIU", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAOIS()) {
            ops.put("AOIS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAODU()) {
            ops.put("AODU", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAODS()) {
            ops.put("AODS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getROR()) {
            ops.put("ROR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCOR()) {
            ops.put("COR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCOD()) {
            ops.put("COD", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCOI()) {
            ops.put("COI", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getSOR()) {
            ops.put("SOR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getLOR()) {
            ops.put("LOR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getLOI()) {
            ops.put("LOI", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getLOD()) {
            ops.put("LOD", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getASRS()) {
            ops.put("ASRS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getSDL()) {
            ops.put("SDL", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getVDL()) {
            ops.put("VDL", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getODL()) {
            ops.put("ODL", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCDL()) {
            ops.put("CDL", new ArrayList<String>(Arrays.asList(paras)));
        }
    }

    // add default option "all"
    if (ops.size() == 0) {
        ops.put("AORB", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AORS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ROR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ASRS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ODL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("VDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("CDL", new ArrayList<String>(Arrays.asList(paras)));
    }

    // String[] tradional_ops = ops.toArray(new String[0]);
    // set system
    setJMutationStructureAndSession(sessionName);
    // MutationSystem.setJMutationStructureAndSession(sessionName);
    MutationSystem.recordInheritanceRelation();
    // generate mutants
    generateMutants(file_list, ops);

    //System.exit(0);
}

From source file:edu.wpi.khufnagle.webimagemanager.WebImageManager.java

/**
 * Defines information for the lighthouses, then runs the
 * photograph-collection process.//from w w  w .ja v a  2  s.c  o m
 * @param args Command-line arguments for this program (not used in this
 *        implementation)
 */
// Auto-boxing done "on the fly" to show progress of downloading images
@SuppressWarnings("boxing")
public static void main(final String[] args) {
    final long startTime = System.nanoTime();
    System.out.println("***BEGIN PHOTO TRANSFER PROCESS***");

    // Add data for lighthouses (next 375 lines or so)
    final List<LighthouseInfo> lighthouseData = new ArrayList<LighthouseInfo>();
    /*
     * lighthouseData.add(new LighthouseInfo("Statue of Liberty", 40.689348,
     * -74.044726));
     */// Statue of Liberty = 2080 photos w/out restrictions
    lighthouseData.add(new LighthouseInfo("Portland Head Light", 43.623104, -70.207867));
    lighthouseData.add(new LighthouseInfo("Pemaquid Point Light", 43.836970, -69.505997));
    lighthouseData.add(new LighthouseInfo("Five Mile Point (New Haven Harbor) Light", 41.248958, -72.903766));
    lighthouseData.add(new LighthouseInfo("Cape Neddick (Nubble) Light", 43.165211, -70.591102));
    lighthouseData.add(new LighthouseInfo("Portland Breakwater Light", 43.655516, -70.234813));
    lighthouseData.add(new LighthouseInfo("Beavertail Light", 41.449368, -71.399372));
    lighthouseData.add(new LighthouseInfo("Bass Harbor Head Light", 44.221976, -68.337214));
    lighthouseData.add(new LighthouseInfo("Nobska Point Light", 41.515792, -70.655116));
    lighthouseData.add(new LighthouseInfo("Spring Point Ledge Light", 43.652108, -70.223922));
    lighthouseData.add(new LighthouseInfo("Gay Head Light", 41.348450, -70.834956));
    lighthouseData.add(new LighthouseInfo("Derby Wharf Light", 42.516566, -70.883536));
    lighthouseData.add(new LighthouseInfo("Rockland Breakwater Light", 44.104006, -69.077453));
    lighthouseData.add(new LighthouseInfo("Sandy Neck Light", 41.722647, -70.280927));
    lighthouseData.add(new LighthouseInfo("Marblehead Light", 42.505411, -70.833708));
    lighthouseData.add(new LighthouseInfo("Portsmouth Harbor Light", 43.071061, -70.708634));
    lighthouseData.add(new LighthouseInfo("Highland Light", 42.039122, -70.062025));
    lighthouseData.add(new LighthouseInfo("Cape Elizabeth Light", 43.566058, -70.200042));
    lighthouseData.add(new LighthouseInfo("Marshall Point Light", 43.917406, -69.261222));
    lighthouseData.add(new LighthouseInfo("Chatham Light", 41.671407, -69.949884));
    lighthouseData.add(new LighthouseInfo("Block Island Southeast Light", 41.153412, -71.552117));
    lighthouseData.add(new LighthouseInfo("Edgartown Light", 41.390863, -70.503057));
    lighthouseData.add(new LighthouseInfo("Watch Hill Light", 41.303884, -71.858575));
    lighthouseData.add(new LighthouseInfo("Nauset Light", 41.858305, -69.951631));
    lighthouseData
            .add(new LighthouseInfo("Fayerweather Island (Black Rock Harbor) Light", 41.142380, -73.217409));
    lighthouseData.add(new LighthouseInfo("Owls Head Light", 44.092138, -69.044105));
    lighthouseData.add(new LighthouseInfo("Point Judith Light", 41.361035, -71.481402));
    lighthouseData.add(new LighthouseInfo("Sankaty Head Light", 41.284379, -69.966244));
    lighthouseData.add(new LighthouseInfo("Eastern Point Light", 42.580229, -70.664537));
    lighthouseData.add(new LighthouseInfo("Fort Pickering Light", 42.526473, -70.866465));
    lighthouseData.add(new LighthouseInfo("Wood Island Light", 43.456788, -70.328976));
    lighthouseData.add(new LighthouseInfo("Stonington Harbor Light", 41.328780, -71.905486));
    lighthouseData.add(new LighthouseInfo("West Quoddy Head Light", 44.815073, -66.950742));
    lighthouseData.add(new LighthouseInfo("Fort Point Light", 44.467265, -68.811717));
    lighthouseData.add(new LighthouseInfo("Annisquam Light", 42.661874, -70.681488));
    lighthouseData.add(new LighthouseInfo("Newport Harbor Light", 41.493299, -71.327038));
    lighthouseData.add(new LighthouseInfo("Long Point Light", 42.033117, -70.168651));
    lighthouseData.add(new LighthouseInfo("Castle Hill Light", 41.462116, -71.362919));
    lighthouseData.add(new LighthouseInfo("Brant Point Light", 41.289918, -70.090287));
    lighthouseData.add(new LighthouseInfo("Stratford Point Light", 41.151984, -73.103276));
    lighthouseData.add(new LighthouseInfo("Boston Light", 42.327925, -70.890101));
    lighthouseData.add(new LighthouseInfo("Lynde Point Light", 41.271452, -72.343142));
    lighthouseData.add(new LighthouseInfo("Scituate Light", 42.204748, -70.715814));
    lighthouseData.add(new LighthouseInfo("Prospect Harbor Light", 44.403285, -68.012922));
    lighthouseData.add(new LighthouseInfo("Wood End Light", 42.021223, -70.193502));
    lighthouseData.add(new LighthouseInfo("Rose Island Light", 41.495477, -71.342742));
    lighthouseData.add(new LighthouseInfo("Saybrook Breakwater Light", 41.263158, -72.342813));
    lighthouseData.add(new LighthouseInfo("Great Point Light", 41.390096, -70.048234));
    lighthouseData.add(new LighthouseInfo("Cape Poge Light", 41.418798, -70.451923));
    lighthouseData.add(new LighthouseInfo("Monhegan Light", 43.764779, -69.316204));
    lighthouseData.add(new LighthouseInfo("Hendricks Head Light", 43.822589, -69.689761));
    lighthouseData.add(new LighthouseInfo("Egg Rock Light", 44.354050, -68.138166));
    lighthouseData.add(new LighthouseInfo("New London Ledge Light", 41.305826, -72.077448));
    lighthouseData.add(new LighthouseInfo("Avery Point Lighthouse", 41.315245, -72.063579));
    lighthouseData.add(new LighthouseInfo("Palmers Island Light", 41.626936, -70.909109));
    lighthouseData.add(new LighthouseInfo("Cuckolds Light", 43.779663, -69.649982));
    lighthouseData.add(new LighthouseInfo("Gull Rocks Light", 41.502451, -71.333140));
    lighthouseData.add(new LighthouseInfo("Goat Island Light", 43.357826, -70.425109));
    lighthouseData.add(new LighthouseInfo("East Chop Light", 41.470245, -70.567439));
    lighthouseData.add(new LighthouseInfo("Neds Point Light", 41.650859, -70.795638));
    lighthouseData.add(new LighthouseInfo("Sakonnet Point Light", 41.453090, -71.202382));
    lighthouseData.add(new LighthouseInfo("Narrows (Bug) Light", 42.323137, -70.919158));
    lighthouseData.add(new LighthouseInfo("Plum Island Light", 42.815119, -70.818981));
    lighthouseData.add(new LighthouseInfo("Block Island North Light", 41.227639, -71.575811));
    lighthouseData.add(new LighthouseInfo("Mount Desert Rock Light", 43.968582, -68.128306));
    lighthouseData.add(new LighthouseInfo("Duxbury Pier Light", 41.987375, -70.648498));
    lighthouseData.add(new LighthouseInfo("Long Island Head Light", 42.330197, -70.957712));
    lighthouseData.add(new LighthouseInfo("Prudence Island Light", 41.605881, -71.303535));
    lighthouseData.add(new LighthouseInfo("Plum Beach Light", 41.530248, -71.405202));
    lighthouseData.add(new LighthouseInfo("Doubling Point Light", 43.882503, -69.806792));
    lighthouseData.add(new LighthouseInfo("Dice Head Light", 44.382732, -68.819022));
    lighthouseData.add(new LighthouseInfo("Ram Island Ledge Light", 43.631457, -70.187366));
    lighthouseData.add(new LighthouseInfo("New London Harbor Light", 41.316619, -72.089743));
    lighthouseData.add(new LighthouseInfo("Lime Rock Light", 41.477536, -71.325924));
    lighthouseData.add(new LighthouseInfo("Ten Pound Island Light", 42.601865, -70.665556));
    lighthouseData.add(new LighthouseInfo("Bristol Ferry Light", 41.642842, -71.260319));
    lighthouseData.add(new LighthouseInfo("Musselbed Shoals Light", 41.636261, -71.259958));
    lighthouseData.add(new LighthouseInfo("Conimicut Light", 41.716969, -71.345106));
    lighthouseData.add(new LighthouseInfo("Tongue Point Light", 41.166590, -73.177497));
    lighthouseData.add(new LighthouseInfo("Bass River Light", 41.651746, -70.169473));
    lighthouseData.add(new LighthouseInfo("Hospital Point Light", 42.546413, -70.856164));
    lighthouseData.add(new LighthouseInfo("Newburyport Range Light", 42.811524, -70.864838));
    lighthouseData.add(new LighthouseInfo("Dutch Island Light", 41.496702, -71.404299));
    lighthouseData.add(new LighthouseInfo("Heron Neck Light", 44.025216, -68.861966));
    lighthouseData.add(new LighthouseInfo("Pumpkin Island Light", 44.309166, -68.742876));
    lighthouseData.add(new LighthouseInfo("Whaleback Light", 43.058744, -70.696306));
    lighthouseData.add(new LighthouseInfo("Hyannis Harbor Light", 41.636267, -70.288439));
    lighthouseData.add(new LighthouseInfo("Stage Harbor Light", 41.658692, -69.983689));
    lighthouseData.add(new LighthouseInfo("Lovells Island Range Light", 42.332440, -70.930214));
    lighthouseData.add(new LighthouseInfo("Hog Island Shoal Light", 41.632338, -71.273198));
    lighthouseData.add(new LighthouseInfo("Ram Island Light", 43.803935, -69.599349));
    lighthouseData.add(new LighthouseInfo("Bridgeport Harbor Light", 41.156718, -73.179950));
    lighthouseData.add(new LighthouseInfo("Straitsmouth Island Light", 42.662236, -70.588157));
    lighthouseData.add(new LighthouseInfo("Squirrel Point Light", 43.816520, -69.802402));
    lighthouseData.add(new LighthouseInfo("Mayos Beach Light", 41.930755, -70.032097));
    lighthouseData.add(new LighthouseInfo("Race Point Light", 42.062314, -70.243084));
    lighthouseData.add(new LighthouseInfo("Point Gammon Light", 41.609647, -70.266196));
    lighthouseData.add(new LighthouseInfo("Wings Neck Light", 41.680235, -70.661250));
    lighthouseData.add(new LighthouseInfo("West Chop Light", 41.480806, -70.599796));
    lighthouseData.add(new LighthouseInfo("Bird Island Light", 41.669295, -70.717341));
    lighthouseData.add(new LighthouseInfo("Clarks Point Light", 41.593176, -70.901416));
    lighthouseData.add(new LighthouseInfo("Thacher Island Light", 42.639168, -70.574759));
    lighthouseData.add(new LighthouseInfo("White Island Light", 42.967228, -70.623249));
    lighthouseData.add(new LighthouseInfo("Wickford Harbor Light", 41.572618, -71.436831));
    lighthouseData.add(new LighthouseInfo("Whale Rock Light", 41.444597, -71.423584));
    lighthouseData.add(new LighthouseInfo("Burnt Island Light", 43.825133, -69.640262));
    lighthouseData.add(new LighthouseInfo("Rockland Harbor Southwest Light", 44.082720, -69.096310));
    lighthouseData.add(new LighthouseInfo("Saddleback Ledge Light", 44.014232, -68.726461));
    lighthouseData.add(new LighthouseInfo("Grindle Point Light", 44.281451, -68.942967));
    lighthouseData.add(new LighthouseInfo("Winter Harbor Light", 44.361421, -68.087742));
    lighthouseData.add(new LighthouseInfo("Peck's Ledge Light", 41.077298, -73.369811));
    lighthouseData.add(new LighthouseInfo("Sheffield Island Light", 41.048251, -73.419931));
    lighthouseData.add(new LighthouseInfo("Whitlocks Mill Light", 45.162793, -67.227395));
    lighthouseData.add(new LighthouseInfo("Boon Island Light", 43.121183, -70.475845));
    lighthouseData.add(new LighthouseInfo("Southwest Ledge Light", 41.234443, -72.912092));
    lighthouseData.add(new LighthouseInfo("Broad Sound Channel Inner Range Light", 42.326933, -70.984649));
    lighthouseData.add(new LighthouseInfo("Spectacle Island Light", 42.326898, -70.984772));
    lighthouseData.add(new LighthouseInfo("Deer Island Light", 42.339836, -70.954525));
    lighthouseData.add(new LighthouseInfo("Nayatt Point Light", 41.725120, -71.338926));
    lighthouseData.add(new LighthouseInfo("Doubling Point Range Lights", 43.882860, -69.795652));
    lighthouseData.add(new LighthouseInfo("Burkehaven Light", 43.371669, -72.065869));
    lighthouseData.add(new LighthouseInfo("Loon Island Light", 43.392123, -72.059977));
    lighthouseData.add(new LighthouseInfo("Curtis Island Light", 44.201372, -69.048865));
    lighthouseData.add(new LighthouseInfo("Butler Flats Light", 41.603775, -70.894556));
    lighthouseData.add(new LighthouseInfo("Graves Light", 42.365098, -70.869191));
    lighthouseData.add(new LighthouseInfo("Stamford Harbor Light", 41.013643, -73.542577));
    lighthouseData.add(new LighthouseInfo("Billingsgate Light", 41.871624, -70.068982));
    lighthouseData.add(new LighthouseInfo("Monomoy Point Light", 41.559310, -69.993650));
    lighthouseData.add(new LighthouseInfo("Bishop & Clerks Light", 41.574154, -70.249963));
    lighthouseData.add(new LighthouseInfo("Plymouth Light", 42.003737, -70.600565));
    lighthouseData.add(new LighthouseInfo("Cleveland Ledge Light", 41.630927, -70.694201));
    lighthouseData.add(new LighthouseInfo("Tarpaulin Cove Light", 41.468822, -70.757514));
    lighthouseData.add(new LighthouseInfo("Minots Ledge Light", 42.269678, -70.759136));
    lighthouseData.add(new LighthouseInfo("Dumpling Rock Light", 41.538167, -70.921427));
    lighthouseData.add(new LighthouseInfo("Bakers Island Light", 42.536470, -70.785995));
    lighthouseData.add(new LighthouseInfo("Cuttyhunk Light", 41.414391, -70.949558));
    lighthouseData.add(new LighthouseInfo("Egg Rock Light", 42.433346, -70.897386));
    lighthouseData.add(new LighthouseInfo("Ipswich Range Light", 42.685360, -70.766128));
    lighthouseData.add(new LighthouseInfo("Borden Flats Light", 41.704450, -71.174395));
    lighthouseData.add(new LighthouseInfo("Bullocks Point Light", 41.737740, -71.364179));
    lighthouseData.add(new LighthouseInfo("Pomham Rocks Light", 41.777618, -71.369594));
    lighthouseData.add(new LighthouseInfo("Sabin Point Light", 41.762010, -71.374234));
    lighthouseData.add(new LighthouseInfo("Fuller Rock Light", 41.794055, -71.379720));
    lighthouseData.add(new LighthouseInfo("Gould Island Light", 41.537826, -71.344804));
    lighthouseData.add(new LighthouseInfo("Warwick Light", 41.667111, -71.378413));
    lighthouseData.add(new LighthouseInfo("Sassafras Point Light", 41.802496, -71.390272));
    lighthouseData.add(new LighthouseInfo("Conanicut Light", 41.573484, -71.371767));
    lighthouseData.add(new LighthouseInfo("Poplar Point Light", 41.571053, -71.439189));
    lighthouseData.add(new LighthouseInfo("Halfway Rock Light", 43.655873, -70.037402));
    lighthouseData.add(new LighthouseInfo("Seguin Island Light", 43.707554, -69.758118));
    lighthouseData.add(new LighthouseInfo("Pond Island Light", 43.740031, -69.770273));
    lighthouseData.add(new LighthouseInfo("Perkins Island Light", 43.786764, -69.785256));
    lighthouseData.add(new LighthouseInfo("Latimer Reef Light", 41.304503, -71.933292));
    lighthouseData.add(new LighthouseInfo("Morgan Point Light", 41.316669, -71.989327));
    lighthouseData.add(new LighthouseInfo("Franklin Island Light", 43.892184, -69.374842));
    lighthouseData.add(new LighthouseInfo("Matinicus Rock Light", 43.783605, -68.854898));
    lighthouseData.add(new LighthouseInfo("Tenants Harbor Light", 43.961107, -69.184877));
    lighthouseData.add(new LighthouseInfo("Whitehead Light", 43.978706, -69.124285));
    lighthouseData.add(new LighthouseInfo("Two Bush Island Light", 43.964239, -69.073942));
    lighthouseData.add(new LighthouseInfo("Indian Island Light", 44.165470, -69.061004));
    lighthouseData.add(new LighthouseInfo("Browns Head Light", 44.111774, -68.909482));
    lighthouseData.add(new LighthouseInfo("Goose Rocks Light", 44.135394, -68.830526));
    lighthouseData.add(new LighthouseInfo("Sperry Light", 41.221221, -72.423110));
    lighthouseData.add(new LighthouseInfo("Isle au Haut Light", 44.064733, -68.651339));
    lighthouseData.add(new LighthouseInfo("Deer Island Thorofare Light", 44.134338, -68.703202));
    lighthouseData.add(new LighthouseInfo("Herrick Cove Light", 43.411136, -72.041706));
    lighthouseData.add(new LighthouseInfo("Eagle Island Light", 44.217634, -68.767743));
    lighthouseData.add(new LighthouseInfo("Burnt Coat Harbor Light", 44.134176, -68.447258));
    lighthouseData.add(new LighthouseInfo("Faulkner's Island Light", 41.211612, -72.655088));
    lighthouseData.add(new LighthouseInfo("Blue Hill Bay Light", 44.248746, -68.497880));
    lighthouseData.add(new LighthouseInfo("Great Duck Island Light", 44.142193, -68.245836));
    lighthouseData.add(new LighthouseInfo("Bear Island Light", 44.283485, -68.269858));
    lighthouseData.add(new LighthouseInfo("Baker Island Light", 44.241266, -68.198923));
    lighthouseData.add(new LighthouseInfo("Crabtree Ledge Light", 44.475613, -68.199383));
    lighthouseData.add(new LighthouseInfo("Statford Shoal Light", 41.059557, -73.101394));
    lighthouseData.add(new LighthouseInfo("Petit Manan Light", 44.367574, -67.864129));
    lighthouseData.add(new LighthouseInfo("Penfield Reef Light", 41.117101, -73.222070));
    lighthouseData.add(new LighthouseInfo("Narraguagus Light", 44.462467, -67.837844));
    lighthouseData.add(new LighthouseInfo("Nash Island Light", 44.464305, -67.747299));
    lighthouseData.add(new LighthouseInfo("Moose Peak Light", 44.474244, -67.533471));
    lighthouseData.add(new LighthouseInfo("Green's Ledge Light", 41.041551, -73.443974));
    lighthouseData.add(new LighthouseInfo("Libby Island Light", 44.568236, -67.367339));
    lighthouseData.add(new LighthouseInfo("Great Captain Island Light", 40.982478, -73.623706));
    lighthouseData.add(new LighthouseInfo("Avery Rock Light", 44.654358, -67.344137));
    lighthouseData.add(new LighthouseInfo("Little River Light", 44.650873, -67.192325));
    lighthouseData.add(new LighthouseInfo("Lubec Channel Light", 44.841955, -66.976731));
    lighthouseData.add(new LighthouseInfo("St. Croix River Light", 45.128762, -67.133594));

    /*
     * "Clean out" photo directories before beginning photo transfer process.
     */
    final File photosDir = new File("photos");
    final File[] photoLighthouseDirsToDelete = photosDir.listFiles();
    if (photoLighthouseDirsToDelete != null) {
        for (final File photoLighthouseDir : photoLighthouseDirsToDelete) {
            // Use Apache Commons IO (again) to recursively delete the directory
            // and all of the files within it
            if (photoLighthouseDir.exists() && photoLighthouseDir.isDirectory()) {
                try {
                    FileUtils.deleteDirectory(photoLighthouseDir);
                    System.out.println("Deleted directory \"" + photoLighthouseDir + "\" successfully.");
                } catch (final IOException ioe) {
                    System.err.println(
                            "Could not delete directory: \"" + photoLighthouseDir + "\" successfully!");
                }
            }
        }
    }

    // Keep track of elapsed time
    long estimatedTime = System.nanoTime() - startTime;
    String elapsedTime = WebImageManager.calculateElapsedTime(estimatedTime);

    System.out.println("Estimated elapsed time: " + elapsedTime + ".");

    System.out.println();

    /*
     * Keep track of total number of photographs transferred from Flickr
     * websites to disks across _all_ lighthouses
     */
    int totalNumPhotosTransferred = 0;

    /*
     * Keep track of total number of photographs that _should_ be transferred
     * from Flickr for _all_ lighthouses
     */
    int totalNumPhotos = 0;

    for (final LighthouseInfo lighthousePieceOfData : lighthouseData) {
        System.out.println("Processing photos of " + lighthousePieceOfData.getName() + "...");

        /*
         * URL for accessing Flickr APIs. For a given lighthouse, this URL
         * provides an XML file in response that lists information about every
         * geotagged, Creative Commons-enabled photograph for that lighthouse
         * on Flickr.
         */
        // GET Parameter Explanation:
        // method - Use the "search photos" method for the Flickr APIs
        //
        // api_key - A unique key that I use to get the results
        //
        // text - Find all lighthouses whose title, tags, or description
        // contains the word "lighthouse"
        //
        // license - Find all photos with a Creative Commons license _except_
        // those that do not allow for modification on my part
        //
        // content_type - Find photos only (no videos)
        //
        // has_geo - Implicitly set to true; implies that all photos are
        // geotagged
        //
        // lat - The latitude of the center of the "search circle"
        //
        // lon - The longitude of the center of the "search circle"
        //
        // radius - The radius of the "search circle," in _kilometers_ (NOT
        // miles)
        //
        // extras - Also include a URL to the "raw" photo (small version)
        final String inputURLText = "http://ycpi.api.flickr.com/services/rest/?" + "method=flickr.photos.search"
                + "&api_key=3ea8366b020383eb91f170c6f41748f5" + "&text=lighthouse" + "&license=1,2,4,5,7"
                + "&content_type=1" + "&has_geo" + "&lat=" + lighthousePieceOfData.getLatitude() + "&lon="
                + lighthousePieceOfData.getLongitude() + "&radius=1" + "&extras=url_s";
        // Output file where XML web response will be stored temporarily
        final String outputFileName = "output.xml";

        /*
         * Convert the name of the lighthouse to a "computer friendly" version
         * with all lower-case letters and underscores replacing spaces,
         * apostrophes, and parenthesis
         */
        String lighthouseName = lighthousePieceOfData.getName();
        lighthouseName = lighthouseName.toLowerCase();
        lighthouseName = lighthouseName.replace(' ', '_');
        lighthouseName = lighthouseName.replace('\'', '_');
        lighthouseName = lighthouseName.replace('(', '_');
        lighthouseName = lighthouseName.replace(')', '_');

        // Will contain the textual links to each "raw" photo website
        Set<String> rawPhotoURLs = new HashSet<String>();

        // Make sure file for XML output does not exist at first
        // (don't want to use an old, incorrect version accidentally)
        final File outputXMLFile = new File(outputFileName);
        if (outputXMLFile.exists()) {
            outputXMLFile.delete();
        }
        System.out.println("Cleaned output XML file containing photo URLs on disk successfully.");

        /*
         * Access the list of photographs for a given lighthouse and copy them
         * to the XML file on disk
         */
        final WebDataExtractor extractor = new WebDataExtractor(inputURLText, outputFileName);
        System.out.println("Looking for XML file containing lighthosue photo information...");
        extractor.transferURLToFile();
        System.out.println("Found XML file containing lighthouse photo URLs.");

        /*
         * Object for extracting the "raw" URLs from each piece of photo data
         * in the XML file
         */
        final XMLParser parser = new FlickrXMLOutputParser(outputFileName);

        // Complete the extraction process
        rawPhotoURLs = parser.parseFile("//photo/@url_s");

        final int numPhotos = rawPhotoURLs.size();
        totalNumPhotos += numPhotos;
        int i = 0; // Counter for keeping track of progress

        /*
         * Keep track of photos transferred successfully (which might be less
         * than the total number of photos defined int the XML output from
         * Flickr, especially if connection issues occur
         */
        int numPhotosTransferred = 0;
        for (final String photoURL : rawPhotoURLs) {
            System.out.print("Transferring photos...");
            i++;

            /*
             * Go to a website containing a "raw" JPEG image file and save it
             * accordingly on disk in the photo folder corresponding to the
             * lighthouse name
             */
            final WebDataExtractor rawPhotoExtractor = new WebDataExtractor(photoURL,
                    "photos/" + lighthouseName + "/lighthouse_photo_" + Integer.toString(i) + ".jpg");
            final boolean transferSuccessful = rawPhotoExtractor.transferURLToFile();
            if (transferSuccessful) {
                numPhotosTransferred++;
            }

            // Simple progress tracker
            System.out.printf("%d of %d (%.1f%%) complete.\n", i, numPhotos, i * 1.0 / numPhotos * 100.0);
        }

        // Indicate number of photos successfully transferred to disk
        if (numPhotosTransferred == numPhotos && numPhotos > 0) {
            System.out.println("All photos transferred to disk successfully!");
        } else if (numPhotos == 0) {
            System.out.println("It appears there are no photos available for this lighthouse...");
        } else if (numPhotosTransferred == 1 && numPhotos > 1) {
            System.out.println("1 photo transferred to disk successfully.");
        } else if (numPhotosTransferred == 1 && numPhotos == 1) {
            System.out.println("The photo transferred to disk successfully!");
        } else {
            System.out.println(numPhotosTransferred + " photos transferred to disk successfully.");
        }

        // Keep track of elapsed time
        estimatedTime = System.nanoTime() - startTime;
        elapsedTime = WebImageManager.calculateElapsedTime(estimatedTime);
        System.out.println("Estimated elapsed time: " + elapsedTime + ".");

        // Add extra line in between lighthouses in output stream
        System.out.println();

        /*
         * Keep track of total number of photos transferred so far across
         * _all_lighthouses
         */
        totalNumPhotosTransferred += numPhotosTransferred;

    }

    // Display "grand" total (which is hopefully greater than 0)
    System.out.println("***GRAND TOTAL: " + totalNumPhotosTransferred + " OF " + totalNumPhotos
            + " PHOTOS TRANSFERRED SUCCESSFULLY***");
    estimatedTime = System.nanoTime() - startTime;
    elapsedTime = WebImageManager.calculateElapsedTime(estimatedTime);
    System.out.println("TOTAL ELAPSED TIME: " + elapsedTime.toUpperCase());
}

From source file:net.skyebook.zerocollada.ZeroCollada.java

/**
 * @param args//from  w ww  .  jav a 2s  .co m
 * @throws ParseException 
 * @throws IOException 
 * @throws JDOMException 
 */
public static void main(String[] args) throws ParseException, JDOMException, IOException {
    // Setup Apache Commons CLI
    optionsSetup();

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (args.length == 0 || cmd.hasOption(ZCOpts.help)) {
        showHelp();
    }

    // was there a valid operation specified?
    if (hasValidOption(cmd)) {
        File fileFromCommandLine = new File(args[args.length - 1]);
        if (!fileFromCommandLine.exists()) {
            System.err.println(
                    "The file located at " + fileFromCommandLine.toString() + " does not exist!  Qutting.");
            return;
        } else if (fileFromCommandLine.isFile() && fileFromCommandLine.toString().endsWith(".dae")) {
            // we've been given a single file.  Act on this single file
            doRequestedAction(fileFromCommandLine, cmd);
        } else if (fileFromCommandLine.isDirectory()) {
            // We've been given a directory of files process the ones that are .dae
            for (File file : fileFromCommandLine.listFiles()) {
                if (file.isFile() && file.toString().endsWith(".dae")) {
                    doRequestedAction(file, cmd);
                } else {
                    System.err.println(file.toString() + " does not seem to be a COLLADA file");
                }
            }
        }
    } else {
        // Then why are we here?
        if (cmd.hasOption(ZCOpts.includeY)) {
            System.err.println(
                    "You have used the " + ZCOpts.includeY + " option but have not asked for a transform (t)");
        } else if (cmd.hasOption(ZCOpts.anchorCenter)) {
            System.err.println(
                    "You have used the " + ZCOpts.includeY + " option but have not asked for a transform (t)");
        }
    }

}

From source file:com.clustercontrol.agent.Agent.java

/**
 * ?//from  w  ww. jav a2  s  .c  om
 * 
 * @param args ??
 */
public static void main(String[] args) throws Exception {

    // ?
    if (args.length != 1) {
        System.out.println("Usage : java Agent [Agent.properties File Path]");
        System.exit(1);
    }

    try {
        // System
        m_log.info("starting Hinemos Agent...");
        m_log.info("java.vm.version = " + System.getProperty("java.vm.version"));
        m_log.info("java.vm.vendor = " + System.getProperty("java.vm.vendor"));
        m_log.info("java.home = " + System.getProperty("java.home"));
        m_log.info("os.name = " + System.getProperty("os.name"));
        m_log.info("os.arch = " + System.getProperty("os.arch"));
        m_log.info("os.version = " + System.getProperty("os.version"));
        m_log.info("user.name = " + System.getProperty("user.name"));
        m_log.info("user.dir = " + System.getProperty("user.dir"));
        m_log.info("user.country = " + System.getProperty("user.country"));
        m_log.info("user.language = " + System.getProperty("user.language"));
        m_log.info("file.encoding = " + System.getProperty("file.encoding"));

        // System(SET)
        String limitKey = "jdk.xml.entityExpansionLimit"; // TODO JRE???????????????????
        System.setProperty(limitKey, "0");
        m_log.info(limitKey + " = " + System.getProperty(limitKey));

        // TODO ???agentHome
        // ??????????
        File file = new File(args[0]);
        agentHome = file.getParentFile().getParent() + "/";
        m_log.info("agentHome=" + agentHome);

        // 
        long startDate = HinemosTime.currentTimeMillis();
        m_log.info("start date = " + new Date(startDate) + "(" + startDate + ")");
        agentInfo.setStartupTime(startDate);

        // Agent??
        m_log.info("Agent.properties = " + args[0]);

        // ?
        File scriptDir = new File(agentHome + "script/");
        if (scriptDir.exists()) {
            File[] listFiles = scriptDir.listFiles();
            if (listFiles != null) {
                for (File f : listFiles) {
                    boolean ret = f.delete();
                    if (ret) {
                        m_log.debug("delete script : " + f.getName());
                    } else {
                        m_log.warn("delete script error : " + f.getName());
                    }
                }
            } else {
                m_log.warn("listFiles is null");
            }
        } else {
            //????????
            boolean ret = scriptDir.mkdir();
            if (!ret) {
                m_log.warn("mkdir error " + scriptDir.getPath());
            }
        }

        // queue?
        m_sendQueue = new SendQueue();

        // Agent?
        Agent agent = new Agent(args[0]);

        //-----------------
        //-- 
        //-----------------
        m_log.debug("exec() : create topic ");

        m_receiveTopic = new ReceiveTopic(m_sendQueue);
        m_receiveTopic.setName("ReceiveTopicThread");
        m_log.info("receiveTopic start 1");
        m_receiveTopic.start();
        m_log.info("receiveTopic start 2");

        // ?
        agent.exec();

        m_log.info("Hinemos Agent started");

        // ?
        agent.waitAwakeAgent();
    } catch (Throwable e) {
        m_log.error("Agent.java: Runtime Exception Occurred. " + e.getClass().getName() + ", " + e.getMessage(),
                e);
    }
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.PdfaConvert.java

public static void main(String[] args) throws IOException {
    if (logger == null) {
        System.out.println("About to initialize Log4j");
        logger = LogManager.getLogger();
        System.out.println("Finished initializing Log4j");
    }//from   w  w w  . java2  s  . c  om

    logger.debug("Entering main()");

    // WIP: the following command line code was pulled from FITS
    Options options = new Options();
    Option inputFileOption = new Option(PARAM_I, true, "input file");
    options.addOption(inputFileOption);
    options.addOption(PARAM_V, false, "print version information");
    options.addOption(PARAM_H, false, "help information");
    options.addOption(PARAM_O, true, "output sub-directory");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args, true);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // print version info
    if (cmd.hasOption(PARAM_V)) {
        if (StringUtils.isEmpty(applicationVersion)) {
            applicationVersion = "<not set>";
            System.exit(1);
        }
        System.out.println("Version: " + applicationVersion);
        System.exit(0);
    }

    // print help info
    if (cmd.hasOption(PARAM_H)) {
        displayHelp();
        System.exit(0);
    }

    // input parameter
    if (cmd.hasOption(PARAM_I)) {
        String input = cmd.getOptionValue(PARAM_I);
        boolean hasValue = cmd.hasOption(PARAM_I);
        logger.debug("Has option {} value: [{}]", PARAM_I, hasValue);
        String paramVal = cmd.getOptionValue(PARAM_I);
        logger.debug("value of option: [{}] ****", paramVal);

        File inputFile = new File(input);
        if (!inputFile.exists()) {
            logger.warn("{} does not exist or is not readable.", input);
            System.exit(1);
        }

        String subDir = cmd.getOptionValue(PARAM_O);
        PdfaConvert convert;
        if (!StringUtils.isEmpty(subDir)) {
            convert = new PdfaConvert(subDir);
        } else {
            convert = new PdfaConvert();
        }
        if (inputFile.isDirectory()) {
            if (inputFile.listFiles() == null || inputFile.listFiles().length < 1) {
                logger.warn("Input directory is empty, nothing to process.");
                System.exit(1);
            } else {
                logger.debug("Have directory: [{}] with file count: {}", inputFile.getAbsolutePath(),
                        inputFile.listFiles().length);
                DirectoryStream<Path> dirStream = null;
                dirStream = Files.newDirectoryStream(inputFile.toPath());
                for (Path filePath : dirStream) {
                    logger.debug("Have file name: {}", filePath.toString());
                    // Note: only handling files, not recursively going into sub-directories
                    if (filePath.toFile().isFile()) {
                        // Catch possible exception for each file so can handle other files in directory.
                        try {
                            convert.examine(filePath.toFile());
                        } catch (Exception e) {
                            logger.error("Problem processing file: {} -- Error message: {}",
                                    filePath.getFileName(), e.getMessage());
                        }
                    } else {
                        logger.warn("Not a file so not processing: {}", filePath.toString()); // could be a directory but not recursing
                    }
                }
                dirStream.close();
            }
        } else {
            logger.debug("About to process file: {}", inputFile.getPath());
            try {
                convert.examine(inputFile);
            } catch (Exception e) {
                logger.error("Problem processing file: {} -- Error message: {}", inputFile.getName(),
                        e.getMessage());
                logger.debug("Problem processing file: {} -- Error message: {}", inputFile.getName(),
                        e.getMessage(), e);
            }
        }
    } else {
        System.err.println("Missing required option: " + PARAM_I);
        displayHelp();
        System.exit(-1);
    }

    System.exit(0);
}

From source file:edu.isi.karma.research.modeling.ModelLearner_LOD.java

public static void main(String[] args) throws Exception {

    ServletContextParameterMap contextParameters = ContextParametersRegistry.getInstance().getDefault();
    contextParameters.setParameterValue(ContextParameter.USER_CONFIG_DIRECTORY, "/Users/mohsen/karma/config");

    OntologyManager ontologyManager = new OntologyManager(contextParameters.getId());
    File ff = new File(Params.ONTOLOGY_DIR);
    File[] files = ff.listFiles();
    if (files == null) {
        logger.error("no ontology to import at " + ff.getAbsolutePath());
        return;/*  w ww .  j  av  a 2s  .  c om*/
    }

    for (File f : files) {
        if (f.getName().endsWith(".owl") || f.getName().endsWith(".rdf") || f.getName().endsWith(".n3")
                || f.getName().endsWith(".ttl") || f.getName().endsWith(".xml")) {
            logger.info("Loading ontology file: " + f.getAbsolutePath());
            ontologyManager.doImport(f, "UTF-8");
        }
    }
    ontologyManager.updateCache();

    String outputPath = Params.OUTPUT_DIR;
    String graphPath = Params.GRAPHS_DIR;

    FileUtils.cleanDirectory(new File(graphPath));

    List<SemanticModel> semanticModels = ModelReader.importSemanticModelsFromJsonFiles(Params.MODEL_DIR,
            Params.MODEL_MAIN_FILE_EXT);

    ModelLearner_LOD modelLearner = null;

    boolean onlyGenerateSemanticTypeStatistics = false;
    boolean onlyUseOntology = false;
    boolean useCorrectType = false;
    int numberOfCandidates = 4;
    boolean onlyEvaluateInternalLinks = false;
    int maxPatternSize = 3;

    if (onlyGenerateSemanticTypeStatistics) {
        getStatistics(semanticModels);
        return;
    }

    String filePath = Params.RESULTS_DIR + "temp/";
    String filename = "";

    filename += "lod-results";
    filename += useCorrectType ? "-correct" : "-k=" + numberOfCandidates;
    filename += onlyUseOntology ? "-ontology" : "-p" + maxPatternSize;
    filename += onlyEvaluateInternalLinks ? "-internal" : "-all";
    filename += ".csv";

    PrintWriter resultFile = new PrintWriter(new File(filePath + filename));

    resultFile.println("source \t p \t r \t t \n");

    for (int i = 0; i < semanticModels.size(); i++) {
        //      for (int i = 0; i <= 10; i++) {
        //      int i = 1; {

        int newSourceIndex = i;
        SemanticModel newSource = semanticModels.get(newSourceIndex);

        logger.info("======================================================");
        logger.info(newSource.getName() + "(#attributes:" + newSource.getColumnNodes().size() + ")");
        System.out.println(newSource.getName() + "(#attributes:" + newSource.getColumnNodes().size() + ")");
        logger.info("======================================================");

        SemanticModel correctModel = newSource;
        List<ColumnNode> columnNodes = correctModel.getColumnNodes();

        List<Node> steinerNodes = new LinkedList<Node>(columnNodes);

        String graphName = graphPath + "lod" + Params.GRAPH_FILE_EXT;

        if (onlyUseOntology) {
            modelLearner = new ModelLearner_LOD(new GraphBuilder(ontologyManager, false), steinerNodes);
        } else if (new File(graphName).exists()) {
            // read graph from file
            try {
                logger.info("loading the graph ...");
                DirectedWeightedMultigraph<Node, DefaultLink> graph = GraphUtil.importJson(graphName);
                modelLearner = new ModelLearner_LOD(new GraphBuilderTopK(ontologyManager, graph), steinerNodes);
            } catch (Exception e) {
                e.printStackTrace();
                resultFile.close();
                return;
            }
        } else {
            logger.info("building the graph ...");
            // create and save the graph to file
            //            GraphBuilder_Popularity b = new GraphBuilder_Popularity(ontologyManager, 
            //                  Params.LOD_OBJECT_PROPERIES_FILE, 
            //                  Params.LOD_DATA_PROPERIES_FILE);
            GraphBuilder_LOD_Pattern b = new GraphBuilder_LOD_Pattern(ontologyManager, Params.PATTERNS_DIR,
                    maxPatternSize);
            modelLearner = new ModelLearner_LOD(b.getGraphBuilder(), steinerNodes);
        }

        long start = System.currentTimeMillis();

        List<SortableSemanticModel> hypothesisList = modelLearner.hypothesize(useCorrectType,
                numberOfCandidates);

        long elapsedTimeMillis = System.currentTimeMillis() - start;
        float elapsedTimeSec = elapsedTimeMillis / 1000F;

        List<SortableSemanticModel> topHypotheses = null;
        if (hypothesisList != null) {

            //            for (SortableSemanticModel sss : hypothesisList) {
            //               ModelEvaluation mmm = sss.evaluate(correctModel);
            //               System.out.println(mmm.getPrecision() + ", " + mmm.getRecall());
            //            }
            topHypotheses = hypothesisList.size() > 10 ? hypothesisList.subList(0, 10) : hypothesisList;
        }

        Map<String, SemanticModel> models = new TreeMap<String, SemanticModel>();

        ModelEvaluation me;
        models.put("1-correct model", correctModel);
        if (topHypotheses != null)
            for (int k = 0; k < topHypotheses.size(); k++) {

                SortableSemanticModel m = topHypotheses.get(k);

                me = m.evaluate(correctModel, onlyEvaluateInternalLinks, false);

                String label = "candidate " + k + "\n" +
                //                     (m.getSteinerNodes() == null ? "" : m.getSteinerNodes().getScoreDetailsString()) +
                        "link coherence:"
                        + (m.getLinkCoherence() == null ? "" : m.getLinkCoherence().getCoherenceValue()) + "\n";
                label += (m.getSteinerNodes() == null || m.getSteinerNodes().getCoherence() == null) ? ""
                        : "node coherence:" + m.getSteinerNodes().getCoherence().getCoherenceValue() + "\n";
                label += "confidence:" + m.getConfidenceScore() + "\n";
                label += m.getSteinerNodes() == null ? ""
                        : "mapping score:" + m.getSteinerNodes().getScore() + "\n";
                label += "cost:" + roundDecimals(m.getCost(), 6) + "\n" +
                //                        "-distance:" + me.getDistance() + 
                        "-precision:" + me.getPrecision() + "-recall:" + me.getRecall();

                models.put(label, m);

                if (k == 0) { // first rank model
                    System.out.println("precision: " + me.getPrecision() + ", recall: " + me.getRecall()
                            + ", time: " + elapsedTimeSec);
                    logger.info("precision: " + me.getPrecision() + ", recall: " + me.getRecall() + ", time: "
                            + elapsedTimeSec);
                    String s = newSource.getName() + "\t" + me.getPrecision() + "\t" + me.getRecall() + "\t"
                            + elapsedTimeSec;
                    resultFile.println(s);

                }
            }

        String outName = outputPath + newSource.getName() + Params.GRAPHVIS_OUT_DETAILS_FILE_EXT;

        GraphVizUtil.exportSemanticModelsToGraphviz(models, newSource.getName(), outName,
                GraphVizLabelType.LocalId, GraphVizLabelType.LocalUri, true, true);

    }

    resultFile.close();

}

From source file:DIA_Umpire_Quant.DIA_Umpire_ProtQuant.java

/**
 * @param args the command line arguments
 *//*w ww  .  ja  v a2s.  co  m*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println(
            "DIA-Umpire protein quantitation module (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_PortQuant.jar diaumpire_module.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_orotquant.log");
    } catch (Exception e) {
    }

    Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
    Logger.getRootLogger().info("Parameter file:" + args[0]);

    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    String line = "";
    String WorkFolder = "";
    int NoCPUs = 2;

    String Combined_Prot = "";
    boolean DefaultProtFiltering = true;

    float Freq = 0f;
    int TopNPep = 6;
    int TopNFrag = 6;
    String FilterWeight = "GW";
    float MinWeight = 0.9f;

    TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
    HashMap<String, File> AssignFiles = new HashMap<>();

    boolean ExportSaint = false;
    boolean SAINT_MS1 = false;
    boolean SAINT_MS2 = true;

    HashMap<String, String[]> BaitList = new HashMap<>();
    HashMap<String, String> BaitName = new HashMap<>();
    HashMap<String, String[]> ControlList = new HashMap<>();
    HashMap<String, String> ControlName = new HashMap<>();

    //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==File list begin")) {
                do {
                    line = reader.readLine();
                    line = line.trim();
                    if (line.equals("==File list end")) {
                        continue;
                    } else if (!"".equals(line)) {
                        File newfile = new File(line);
                        if (newfile.exists()) {
                            AssignFiles.put(newfile.getAbsolutePath(), newfile);
                        } else {
                            Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                        }
                    }
                } while (!line.equals("==File list end"));
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            String value = line.split("=")[1].trim();
            switch (type) {
            case "Path": {
                WorkFolder = value;
                break;
            }
            case "path": {
                WorkFolder = value;
                break;
            }
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }
            case "Fasta": {
                tandemPara.FastaPath = value;
                break;
            }
            case "Combined_Prot": {
                Combined_Prot = value;
                break;
            }
            case "DefaultProtFiltering": {
                DefaultProtFiltering = Boolean.parseBoolean(value);
                break;
            }
            case "DecoyPrefix": {
                if (!"".equals(value)) {
                    tandemPara.DecoyPrefix = value;
                }
                break;
            }
            case "ProteinFDR": {
                tandemPara.ProtFDR = Float.parseFloat(value);
                break;
            }
            case "FilterWeight": {
                FilterWeight = value;
                break;
            }
            case "MinWeight": {
                MinWeight = Float.parseFloat(value);
                break;
            }
            case "TopNFrag": {
                TopNFrag = Integer.parseInt(value);
                break;
            }
            case "TopNPep": {
                TopNPep = Integer.parseInt(value);
                break;
            }
            case "Freq": {
                Freq = Float.parseFloat(value);
                break;
            }
            //<editor-fold defaultstate="collapsed" desc="SaintOutput">
            case "ExportSaintInput": {
                ExportSaint = Boolean.parseBoolean(value);
                break;
            }
            case "QuantitationType": {
                switch (value) {
                case "MS1": {
                    SAINT_MS1 = true;
                    SAINT_MS2 = false;
                    break;
                }
                case "MS2": {
                    SAINT_MS1 = false;
                    SAINT_MS2 = true;
                    break;
                }
                case "BOTH": {
                    SAINT_MS1 = true;
                    SAINT_MS2 = true;
                    break;
                }
                }
                break;
            }
            //                    case "BaitInputFile": {
            //                        SaintBaitFile = value;
            //                        break;
            //                    }
            //                    case "PreyInputFile": {
            //                        SaintPreyFile = value;
            //                        break;
            //                    }
            //                    case "InterationInputFile": {
            //                        SaintInteractionFile = value;
            //                        break;
            //                    }
            default: {
                if (type.startsWith("BaitName_")) {
                    BaitName.put(type.substring(9), value);
                }
                if (type.startsWith("BaitFile_")) {
                    BaitList.put(type.substring(9), value.split("\t"));
                }
                if (type.startsWith("ControlName_")) {
                    ControlName.put(type.substring(12), value);
                }
                if (type.startsWith("ControlFile_")) {
                    ControlList.put(type.substring(12), value.split("\t"));
                }
                break;
            }
            //</editor-fold>                    
            }
        }
    }
    //</editor-fold>

    //Initialize PTM manager using compomics library
    PTMManager.GetInstance();

    //Check if the fasta file can be found
    if (!new File(tandemPara.FastaPath).exists()) {
        Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath
                + " cannot be found, the process will be terminated, please check.");
        System.exit(1);
    }

    //Check if the prot.xml file can be found
    if (!new File(Combined_Prot).exists()) {
        Logger.getRootLogger().info("ProtXML file: " + Combined_Prot
                + " cannot be found, the export protein summary table will be empty.");
    }
    LCMSID protID = null;

    //Parse prot.xml and generate protein master list given an FDR 
    if (Combined_Prot != null && !Combined_Prot.equals("")) {
        protID = LCMSID.ReadLCMSIDSerialization(Combined_Prot);
        if (!"".equals(Combined_Prot) && protID == null) {
            protID = new LCMSID(Combined_Prot, tandemPara.DecoyPrefix, tandemPara.FastaPath);
            ProtXMLParser protxmlparser = new ProtXMLParser(protID, Combined_Prot, 0f);
            //Use DIA-Umpire default protein FDR calculation
            if (DefaultProtFiltering) {
                protID.RemoveLowLocalPWProtein(0.8f);
                protID.RemoveLowMaxIniProbProtein(0.9f);
                protID.FilterByProteinDecoyFDRUsingMaxIniProb(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
            }
            //Get protein FDR calculation without other filtering
            else {
                protID.FilterByProteinDecoyFDRUsingLocalPW(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
            }
            protID.LoadSequence();
            protID.WriteLCMSIDSerialization(Combined_Prot);
        }
        Logger.getRootLogger().info("Protein No.:" + protID.ProteinList.size());
    }
    HashMap<String, HashMap<String, FragmentPeak>> IDSummaryFragments = new HashMap<>();

    //Generate DIA file list
    ArrayList<DIAPack> FileList = new ArrayList<>();
    try {
        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
            System.exit(1);
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile()
                    && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile()
                            && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                    | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
        }

        for (File fileEntry : AssignFiles.values()) {
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                Logger.getRootLogger().info(
                        "=================================================================================================");
                Logger.getRootLogger().info("Processing " + mzXMLFile);
                if (!DiaFile.LoadDIASetting()) {
                    Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                    System.exit(1);
                }
                if (!DiaFile.LoadParams()) {
                    Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                    System.exit(1);
                }
                Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "....");

                //If the serialization file for ID file existed
                if (DiaFile.ReadSerializedLCMSID()) {
                    DiaFile.IDsummary.ReduceMemoryUsage();
                    DiaFile.IDsummary.ClearAssignPeakCluster();
                    FileList.add(DiaFile);
                    HashMap<String, FragmentPeak> FragMap = new HashMap<>();
                    IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap);
                }
            }
        }

        //<editor-fold defaultstate="collapsed" desc="Peptide and fragment selection">

        Logger.getRootLogger().info("Peptide and fragment selection across the whole dataset");
        ArrayList<LCMSID> SummaryList = new ArrayList<>();
        for (DIAPack diafile : FileList) {
            if (protID != null) {
                //Generate protein list according to mapping of peptide ions for each DIA file to the master protein list
                diafile.IDsummary.GenerateProteinByRefIDByPepSeq(protID, true);
                diafile.IDsummary.ReMapProPep();
            }
            if ("GW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByGroupWeight();
            } else if ("PepW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByWeight();
            }
            SummaryList.add(diafile.IDsummary);
        }
        FragmentSelection fragselection = new FragmentSelection(SummaryList);
        fragselection.freqPercent = Freq;
        fragselection.GeneratePepFragScoreMap();
        fragselection.GenerateTopFragMap(TopNFrag);
        fragselection.GenerateProtPepScoreMap(MinWeight);
        fragselection.GenerateTopPepMap(TopNPep);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Writing general reports">                 
        ExportTable export = new ExportTable(WorkFolder, SummaryList, IDSummaryFragments, protID,
                fragselection);
        export.Export(TopNPep, TopNFrag, Freq);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="//<editor-fold defaultstate="collapsed" desc="Generate SAINT input files">
        if (ExportSaint && protID != null) {
            HashMap<String, DIAPack> Filemap = new HashMap<>();
            for (DIAPack DIAfile : FileList) {
                Filemap.put(DIAfile.GetBaseName(), DIAfile);
            }

            FileWriter baitfile = new FileWriter(WorkFolder + "SAINT_Bait_" + DateTimeTag.GetTag() + ".txt");
            FileWriter preyfile = new FileWriter(WorkFolder + "SAINT_Prey_" + DateTimeTag.GetTag() + ".txt");
            FileWriter interactionfileMS1 = null;
            FileWriter interactionfileMS2 = null;
            if (SAINT_MS1) {
                interactionfileMS1 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS1_" + DateTimeTag.GetTag() + ".txt");
            }
            if (SAINT_MS2) {
                interactionfileMS2 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS2_" + DateTimeTag.GetTag() + ".txt");
            }
            HashMap<String, String> PreyID = new HashMap<>();

            for (String samplekey : ControlName.keySet()) {
                String name = ControlName.get(samplekey);
                for (String file : ControlList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "C\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            for (String samplekey : BaitName.keySet()) {
                String name = BaitName.get(samplekey);
                for (String file : BaitList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "T\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            baitfile.close();
            if (SAINT_MS1) {
                interactionfileMS1.close();
            }
            if (SAINT_MS2) {
                interactionfileMS2.close();
            }
            for (String AccNo : PreyID.keySet()) {
                preyfile.write(AccNo + "\t" + PreyID.get(AccNo) + "\n");
            }
            preyfile.close();
        }

        //</editor-fold>

        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");

    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:net.iiit.siel.analysis.lang.LanguageIdentifier.java

/**
 * The main method.//from   ww  w. j av a  2  s  . co m
 *
 * @param args the arguments
 */
public static void main(String args[]) {

    String usage = "Usage: LanguageIdentifier " + "[-identifyrows filename maxlines] "
            + "[-identifyfile charset filename] " + "[-identifyfileset charset files] "
            + "[-identifytext text] " + "[-identifyurl url]";
    int command = 0;

    final int IDFILE = 1;
    final int IDTEXT = 2;
    final int IDURL = 3;
    final int IDFILESET = 4;
    final int IDROWS = 5;

    Vector fileset = new Vector();
    String filename = "";
    String charset = "";
    String url = "";
    String text = "";
    int max = 0;

    // TODO niket writing test args here..
    /*      args = new String[2];
          args[0] = "-identifyurl";
          args[1] = "file:/home1/niket/TamilSamplePage.html";
          //args[2] = "/home1/niket/nutch-clia/input.txt";
    */
    // TODO niket end here

    if (args.length == 0) {
        System.err.println(usage);
        System.exit(-1);
    }

    for (int i = 0; i < args.length; i++) { // parse command line
        if (args[i].equals("-identifyfile")) {
            command = IDFILE;
            charset = args[++i];
            filename = args[++i];
        }

        if (args[i].equals("-identifyurl")) {
            command = IDURL;
            filename = args[++i];
        }

        if (args[i].equals("-identifyrows")) {
            command = IDROWS;
            filename = args[++i];
            max = Integer.parseInt(args[++i]);
        }

        if (args[i].equals("-identifytext")) {
            command = IDTEXT;
            for (i++; i < args.length - 1; i++)
                text += args[i] + " ";
        }

        if (args[i].equals("-identifyfileset")) {
            command = IDFILESET;
            charset = args[++i];
            for (i++; i < args.length; i++) {
                File[] files = null;
                File f = new File(args[i]);
                if (f.isDirectory()) {
                    files = f.listFiles();
                } else {
                    files = new File[] { f };
                }
                for (int j = 0; j < files.length; j++) {
                    fileset.add(files[j].getAbsolutePath());
                }
            }
        }

    }

    Configuration conf = NutchConfiguration.create();
    String lang = null;
    LanguageIdentifier idfr = new LanguageIdentifier(conf);
    File f;
    FileInputStream fis;
    try {
        switch (command) {

        case IDTEXT:
            lang = idfr.identify(text);
            System.out.println("Lang :" + lang);
            break;

        case IDFILE:
            f = new File(filename);
            fis = new FileInputStream(f);
            lang = idfr.identify(fis, charset);
            fis.close();
            break;

        case IDURL:
            lang = LangIdentifierUtility.IdentifyLangFromURLDirectly(filename);

            /*
             * our url identifier is confused or couldn't identify lang from
             * URL
             */
            if (lang == null || lang.equalsIgnoreCase("en")) {
                System.out.println("Ambuguity in identifying language from URL");
            } else {
                System.out.println("Lang was identified(using URL) as: " + lang);
            }
            break;

        case IDROWS:
            f = new File(filename);
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
            String line;
            while (max > 0 && (line = br.readLine()) != null) {
                line = line.trim();
                if (line.length() > 2) {
                    max--;
                    lang = idfr.identify(line);
                    System.out.println("R=" + lang + ":" + line);
                }
            }

            br.close();
            System.exit(0);
            break;

        case IDFILESET:
            /*
             * used for benchs for (int j=128; j<=524288; j*=2) { long start
             * = System.currentTimeMillis(); idfr.analyzeLength = j;
             */
            System.out.println("FILESET");
            Iterator i = fileset.iterator();
            while (i.hasNext()) {
                try {
                    filename = (String) i.next();
                    f = new File(filename);
                    fis = new FileInputStream(f);
                    lang = idfr.identify(fis, charset);
                    fis.close();
                } catch (Exception e) {
                    System.out.println(e);
                }
                System.out.println(filename + " was identified as " + lang);
            }
            /*
             * used for benchs System.out.println(j + "/" +
             * (System.currentTimeMillis()-start)); }
             */
            System.exit(0);
            break;
        }
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("lang could not be identified properly");
        e.printStackTrace();
    }
    System.out.println("text was identified as " + lang);

    /*
     * DONOT delete the next few lines, they should be enabled, when a lang.
     * mapping map needs to be generated. TODO  this is for printing
     * the hashMapRangeLangIDTable only
     * 
     * idfr.langMarkerObject.printHashmapTableWithFormatting();
     * 
     * System.out
     * .println("\n\n\n Printing english text contents in this file:\n");
     * System.out.println(idfr.langMarkerObject.getLangCharacters(
     * LanguageIdentifierConstants.LangShortNames.ENGLISH
     * .langShortName()).toString());
     * 
     * System.out
     * .println("\n\n\n Printing telugu text contents in this file:\n");
     * System.out.println(idfr.langMarkerObject.getLangCharacters(
     * LanguageIdentifierConstants.LangShortNames.TELUGU
     * .langShortName()).toString());
     * 
     * System.out
     * .println("\n\n\n Printing unknown text contents in this file:\n");
     * System.out.println(idfr.langMarkerObject.getLangCharacters(
     * LanguageIdentifierConstants.LangShortNames.UNKNOWN_LANG
     * .langShortName()).toString());
     */
}

From source file:org.silverpeas.dbbuilder.DBBuilder.java

/**
 * @param args//ww w .  j av  a 2s  .c  o m
 * @see
 */
public static void main(String[] args) {
    ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext(
            "classpath:/spring-jdbc-datasource.xml");
    try {
        // Ouverture des traces
        Date startDate = new Date();
        System.out.println(
                MessageFormat.format(messages.getString("dbbuilder.start"), DBBuilderAppVersion, startDate));
        console = new Console(DBBuilder.class);
        console.printMessage("*************************************************************");
        console.printMessage(
                MessageFormat.format(messages.getString("dbbuilder.start"), DBBuilderAppVersion, startDate));
        // Lecture des variables d'environnement  partir de dbBuilderSettings
        dbBuilderResources = FileUtil
                .loadResource("/org/silverpeas/dbBuilder/settings/dbBuilderSettings.properties");
        // Lecture des paramtres d'entre
        params = new CommandLineParameters(console, args);

        if (params.isSimulate() && DatabaseType.ORACLE == params.getDbType()) {
            throw new Exception(messages.getString("oracle.simulate.error"));
        }
        console.printMessage(messages.getString("jdbc.connection.configuration"));
        console.printMessage(ConnectionFactory.getConnectionInfo());
        console.printMessage("\tAction        : " + params.getAction());
        console.printMessage("\tVerbose mode  : " + params.isVerbose());
        console.printMessage("\tSimulate mode : " + params.isSimulate());
        if (Action.ACTION_CONNECT == params.getAction()) {
            // un petit message et puis c'est tout
            console.printMessage(messages.getString("connection.success"));
            System.out.println(messages.getString("connection.success"));
        } else {
            // Modules en place sur la BD avant install
            console.printMessage("DB Status before build :");
            List<String> packagesIntoDB = checkDBStatus();
            // initialisation d'un vecteur des instructions SQL  passer en fin d'upgrade
            // pour mettre  niveau les versions de modules en base
            MetaInstructions sqlMetaInstructions = new MetaInstructions();
            File dirXml = new File(params.getDbType().getDBContributionDir());
            DBXmlDocument destXml = loadMasterContribution(dirXml);
            UninstallInformations processesToCacheIntoDB = new UninstallInformations();

            File[] listeFileXml = dirXml.listFiles();
            Arrays.sort(listeFileXml);

            List<DBXmlDocument> listeDBXmlDocument = new ArrayList<DBXmlDocument>(listeFileXml.length);
            int ignoredFiles = 0;
            // Ouverture de tous les fichiers de configurations
            console.printMessage(messages.getString("ignored.contribution"));

            for (File xmlFile : listeFileXml) {
                if (xmlFile.isFile() && "xml".equals(FileUtil.getExtension(xmlFile))
                        && !(FIRST_DBCONTRIBUTION_FILE.equalsIgnoreCase(xmlFile.getName()))
                        && !(MASTER_DBCONTRIBUTION_FILE.equalsIgnoreCase(xmlFile.getName()))) {
                    DBXmlDocument fXml = new DBXmlDocument(dirXml, xmlFile.getName());
                    fXml.load();
                    // vrification des dpendances et prise en compte uniquement si dependences OK
                    if (hasUnresolvedRequirements(listeFileXml, fXml)) {
                        console.printMessage(
                                '\t' + xmlFile.getName() + " (because of unresolved requirements).");
                        ignoredFiles++;
                    } else if (ACTION_ENFORCE_UNINSTALL == params.getAction()) {
                        console.printMessage('\t' + xmlFile.getName() + " (because of "
                                + ACTION_ENFORCE_UNINSTALL + " mode).");
                        ignoredFiles++;
                    } else {
                        listeDBXmlDocument.add(fXml);
                    }
                }
            }
            if (0 == ignoredFiles) {
                console.printMessage("\t(none)");
            }

            // prpare une HashMap des modules prsents en fichiers de contribution
            Map packagesIntoFile = new HashMap();
            int j = 0;
            console.printMessage(messages.getString("merged.contribution"));
            console.printMessage(params.getAction().toString());
            if (ACTION_ENFORCE_UNINSTALL != params.getAction()) {
                console.printMessage('\t' + FIRST_DBCONTRIBUTION_FILE);
                j++;
            }
            for (DBXmlDocument currentDoc : listeDBXmlDocument) {
                console.printMessage('\t' + currentDoc.getName());
                j++;
            }
            if (0 == j) {
                console.printMessage("\t(none)");
            }
            // merge des diffrents fichiers de contribution ligibles :
            console.printMessage("Build decisions are :");
            // d'abord le fichier dbbuilder-contribution ...
            DBXmlDocument fileXml;
            if (ACTION_ENFORCE_UNINSTALL != params.getAction()) {
                try {
                    fileXml = new DBXmlDocument(dirXml, FIRST_DBCONTRIBUTION_FILE);
                    fileXml.load();
                } catch (Exception e) {
                    // contribution de dbbuilder non trouve -> on continue, on est certainement en train
                    // de desinstaller la totale
                    fileXml = null;
                }
                if (null != fileXml) {
                    DBBuilderFileItem dbbuilderItem = new DBBuilderFileItem(fileXml);
                    packagesIntoFile.put(dbbuilderItem.getModule(), null);
                    mergeActionsToDo(dbbuilderItem, destXml, processesToCacheIntoDB, sqlMetaInstructions);
                }
            }

            // ... puis les autres
            for (DBXmlDocument currentDoc : listeDBXmlDocument) {
                DBBuilderFileItem tmpdbbuilderItem = new DBBuilderFileItem(currentDoc);
                packagesIntoFile.put(tmpdbbuilderItem.getModule(), null);
                mergeActionsToDo(tmpdbbuilderItem, destXml, processesToCacheIntoDB, sqlMetaInstructions);
            }

            // ... et enfin les pices BD  dsinstaller
            // ... attention, l'ordonnancement n'tant pas dispo, on les traite dans
            // l'ordre inverse pour faire passer busCore a la fin, de nombreuses contraintes
            // des autres modules referencant les PK de busCore
            List<String> itemsList = new ArrayList<String>();

            boolean foundDBBuilder = false;
            for (String dbPackage : packagesIntoDB) {
                if (!packagesIntoFile.containsKey(dbPackage)) {
                    // Package en base et non en contribution -> candidat  desinstallation
                    if (DBBUILDER_MODULE.equalsIgnoreCase(dbPackage)) {
                        foundDBBuilder = true;
                    } else if (ACTION_ENFORCE_UNINSTALL == params.getAction()) {
                        if (dbPackage.equals(params.getModuleName())) {
                            itemsList.add(0, dbPackage);
                        }
                    } else {
                        itemsList.add(0, dbPackage);
                    }
                }
            }

            if (foundDBBuilder) {
                if (ACTION_ENFORCE_UNINSTALL == params.getAction()) {
                    if (DBBUILDER_MODULE.equals(params.getModuleName())) {
                        itemsList.add(itemsList.size(), DBBUILDER_MODULE);
                    }
                } else {
                    itemsList.add(itemsList.size(), DBBUILDER_MODULE);
                }
            }
            for (String item : itemsList) {
                console.printMessage("**** Treating " + item + " ****");
                DBBuilderDBItem tmpdbbuilderItem = new DBBuilderDBItem(item);
                mergeActionsToDo(tmpdbbuilderItem, destXml, processesToCacheIntoDB, sqlMetaInstructions);
            }
            destXml.setName("res.txt");
            destXml.save();
            console.printMessage("Build parts are :");
            // Traitement des pices slectionnes
            // remarque : durant cette phase, les erreurs sont traites -> on les catche en
            // retour sans les retraiter
            if (ACTION_INSTALL == params.getAction()) {
                processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_INSTALL);
            } else if (ACTION_UNINSTALL == params.getAction()
                    || ACTION_ENFORCE_UNINSTALL == params.getAction()) {
                processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_UNINSTALL);
            } else if (ACTION_OPTIMIZE == params.getAction()) {
                processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_OPTIMIZE);
            } else if (ACTION_ALL == params.getAction()) {
                processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_ALL);
            }
            // Modules en place sur la BD en final
            console.printMessage("Finally DB Status :");
            checkDBStatus();
        }
        Date endDate = new Date();
        console.printMessage(MessageFormat.format(messages.getString("dbbuilder.success"), endDate));
        System.out.println("*******************************************************************");
        System.out.println(MessageFormat.format(messages.getString("dbbuilder.success"), endDate));
    } catch (Exception e) {
        e.printStackTrace();
        console.printError(e.getMessage(), e);
        Date endDate = new Date();
        console.printError(MessageFormat.format(messages.getString("dbbuilder.failure"), endDate));
        System.out.println("*******************************************************************");
        System.out.println(MessageFormat.format(messages.getString("dbbuilder.failure"), endDate));
        System.exit(1);
    } finally {
        springContext.close();
        console.close();
    }
}