Example usage for java.util.logging Logger getLogger

List of usage examples for java.util.logging Logger getLogger

Introduction

In this page you can find the example usage for java.util.logging Logger getLogger.

Prototype




@CallerSensitive
public static Logger getLogger(String name) 

Source Link

Document

Find or create a logger for a named subsystem.

Usage

From source file:com.game.ui.views.MapPanel.java

public static void main(String[] args) throws IOException {
    MapInformation map = new MapInformation();
    try {/*from  ww w . j  a v a2  s . c  o m*/
        map = GameUtils.fetchParticularMapData(Configuration.PATH_FOR_MAP, "Test1");
        Player player = new Player();
        player.setType("Barbarian");
        player.setMovement(1);
        int user = 0;
        LinkedHashMap<Integer, Integer> userLocation = new LinkedHashMap<>();
        TreeMap<Integer, TileInformation> tileInfo = map.getPathMap();
        for (Map.Entry<Integer, TileInformation> entry : tileInfo.entrySet()) {
            if (entry.getValue().isStartTile()) {
                userLocation.put(user, entry.getValue().getLocation());
                entry.getValue().setPlayer(player);
                user++;
            }
        }
        map.setUserLocation(userLocation);
    } catch (Exception ex) {
        Logger.getLogger(MapPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
    new MapPanel(map);
}

From source file:di.uniba.it.tee2.text.TextDirIndex.java

/**
 * language_0 starting_dir_1 output_dir_2 n_thread_3
 *
 * @param args the command line arguments
 *//* www .j a v a2 s.c o m*/
public static void main(String[] args) {
    try {
        CommandLine cmd = cmdParser.parse(options, args);
        if (cmd.hasOption("l") && cmd.hasOption("i") && cmd.hasOption("o")) {
            int nt = Integer.parseInt(cmd.getOptionValue("n", "2"));
            TextDirIndex builder = new TextDirIndex();
            builder.init(cmd.getOptionValue("l"), cmd.getOptionValue("o"), nt);
            builder.build(cmd.getOptionValue("l"), cmd.getOptionValue("i"));
        } else {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Index a directory", options, true);
        }
    } catch (Exception ex) {
        Logger.getLogger(TextDirIndex.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:lambertmrev.LambertMRev.java

/**
 * @param args the command line arguments
 *///from  w  ww.  ja  v  a2  s .c o m
public static void main(String[] args) {
    // Want to test the Lambert class so you can specify the number of revs for which to compute
    //System.out.print("this is the frames tutorial \n");
    try {
        Frame inertialFrame = FramesFactory.getEME2000();
        TimeScale utc = TimeScalesFactory.getTAI();
        AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, utc);
        double mu = 3.986004415e+14;

        double a = 24396159; // semi major axis in meters
        double e = 0.72831215; // eccentricity
        double i = Math.toRadians(7); // inclination
        double omega = Math.toRadians(180); // perigee argument
        double raan = Math.toRadians(261); // right ascension of ascending node
        double lM = 0; // mean anomaly

        Orbit initialOrbit = new KeplerianOrbit(a, e, i, omega, raan, lM, PositionAngle.MEAN, inertialFrame,
                initialDate, mu);
        //KeplerianPropagator kepler = new KeplerianPropagator(initialOrbit);

        // set geocentric positions
        Vector3D r1 = new Vector3D(-6.88999e3, 3.92763e4, 2.67053e3);
        Vector3D r2 = new Vector3D(-3.41458e4, 2.05328e4, 3.44315e3);
        Vector3D r1_site = new Vector3D(4.72599e3, 1.26633e3, 4.07799e3);
        Vector3D r2_site = new Vector3D(4.70819e3, 1.33099e3, 4.07799e3);

        // get the topocentric positions
        Vector3D top1 = Transform.geo2radec(r1.scalarMultiply(1000), r1_site.scalarMultiply(1000));
        Vector3D top2 = Transform.geo2radec(r2.scalarMultiply(1000), r2_site.scalarMultiply(1000));

        // time of flight in seconds
        double tof = 3 * 3600;

        // propagate to 0 and tof
        Lambert test = new Lambert();

        boolean cw = false;
        int multi_revs = 1;
        RealMatrix v1_mat;
        Random randomGenerator = new Random();

        PrintWriter out_a = new PrintWriter("out_java_a.txt");
        PrintWriter out_e = new PrintWriter("out_java_e.txt");
        PrintWriter out_rho1 = new PrintWriter("out_java_rho1.txt");
        PrintWriter out_rho2 = new PrintWriter("out_java_rho2.txt");

        // start the loop
        double A, Ecc, rho1, rho2, tof_hyp;

        long time1 = System.nanoTime();
        for (int ll = 0; ll < 1e6; ll++) {

            rho1 = top1.getZ() / 1000 + 1e-3 * randomGenerator.nextGaussian() * top1.getZ() / 1000;
            rho2 = top2.getZ() / 1000 + 1e-3 * randomGenerator.nextGaussian() * top2.getZ() / 1000;
            //tof_hyp = FastMath.abs(tof + 0.1*3600 * randomGenerator.nextGaussian());
            // from topo to geo
            Vector3D r1_hyp = Transform.radec2geo(top1.getX(), top1.getY(), rho1, r1_site);
            Vector3D r2_hyp = Transform.radec2geo(top2.getX(), top2.getY(), rho2, r2_site);
            //            System.out.println(r1_hyp.scalarMultiply(1000).getNorm());
            //            System.out.println(r2_hyp.scalarMultiply(1000).getNorm());
            //            System.out.println(tof/3600);
            test.lambert_problem(r1_hyp.scalarMultiply(1000), r2_hyp.scalarMultiply(1000), tof, mu, cw,
                    multi_revs);

            v1_mat = test.get_v1();

            Vector3D v1 = new Vector3D(v1_mat.getEntry(0, 0), v1_mat.getEntry(0, 1), v1_mat.getEntry(0, 2));
            //            System.out.println(v1);
            PVCoordinates rv1 = new PVCoordinates(r1_hyp.scalarMultiply(1000), v1);
            Orbit orbit_out = new KeplerianOrbit(rv1, inertialFrame, initialDate, mu);
            A = orbit_out.getA();
            Ecc = orbit_out.getE();

            //            System.out.println(ll + " - " +A);
            out_a.println(A);
            out_e.println(Ecc);
            out_rho1.println(rho1);
            out_rho2.println(rho2);
        }
        long time2 = System.nanoTime();
        long timeTaken = time2 - time1;

        out_a.close();
        out_e.close();
        out_rho1.close();
        out_rho2.close();

        System.out.println("Time taken " + timeTaken / 1000 / 1000 + " milli secs");

        // get the truth
        test.lambert_problem(r1.scalarMultiply(1000), r2.scalarMultiply(1000), tof, mu, cw, multi_revs);
        v1_mat = test.get_v1();
        Vector3D v1 = new Vector3D(v1_mat.getEntry(0, 0), v1_mat.getEntry(0, 1), v1_mat.getEntry(0, 2));
        PVCoordinates rv1 = new PVCoordinates(r1.scalarMultiply(1000), v1);
        Orbit orbit_out = new KeplerianOrbit(rv1, inertialFrame, initialDate, mu);
        //System.out.println(orbit_out.getA());
    } catch (FileNotFoundException ex) {
        Logger.getLogger(LambertMRev.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Cache.Servidor.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    // Se calcula el tamao de las particiones del cache
    // de manera que la relacin sea
    // 25% Esttico y 75% Dinmico,
    // siendo la porcin dinmica particionada en 3 partes.

    Lector l = new Lector(); // Obtener tamao total del cache.
    int tamCache = l.leerTamCache("config.txt");
    //===================================
    int tamCaches = 0;
    if (tamCache % 4 == 0) { // Asegura que el nro sea divisible por 4.
        tamCaches = tamCache / 4;/*from  ww  w  .  j av  a2s.  c o m*/
    } else { // Si no, suma para que lo sea.
        tamCaches = (tamCache - (tamCache) % 4 + 4) / 4;
    } // y divide por 4.

    System.out.println("Tamao total Cache: " + (int) tamCache); // imprimir tamao cache.
    System.out.println("Tamao particiones y parte esttica: " + tamCaches); // imprimir tamao particiones.
    //===================================

    lru_cache1 = new LRUCache(tamCaches); //Instanciar atributos.

    lru_cache2 = new LRUCache(tamCaches);
    lru_cache3 = new LRUCache(tamCaches);
    cestatico = new CacheEstatico(tamCaches);
    cestatico.addEntryToCache("query3", "respuesta cacheEstatico a query 3");
    cestatico.addEntryToCache("query7", "respuesta cacheEstatico a query 7");

    try {
        ServerSocket servidor = new ServerSocket(4500); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            System.out.println("Objeto llego");
            //===================================
            Cache1 hilox1 = new Cache1(); // Instanciar hebras.
            Cache2 hilox2 = new Cache2();
            Cache3 hilox3 = new Cache3();

            // Leer el objeto, es un String.
            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("busqueda");

            //*************************Actualizar CACHE**************************************
            int actualizar = (int) request.get("actualizacion");
            // Si vienen el objeto que llego viene del Index es que va a actualizar el cache
            if (actualizar == 1) {
                int lleno = cestatico.lleno();
                if (lleno == 0) {
                    cestatico.addEntryToCache((String) request.get("busqueda"),
                            (String) request.get("respuesta"));
                } else {
                    // si el cache estatico esta lleno
                    //agrego l cache dinamico

                    if (hash(b) % 3 == 0) {
                        lru_cache1.addEntryToCache((String) request.get("busqueda"),
                                (String) request.get("respuesta"));
                    } else {
                        if (hash(b) % 3 == 1) {
                            lru_cache2.addEntryToCache((String) request.get("busqueda"),
                                    (String) request.get("respuesta"));

                        } else {
                            lru_cache3.addEntryToCache((String) request.get("busqueda"),
                                    (String) request.get("respuesta"));

                        }
                    }

                }
            } //***************************************************************
            else {

                // Para cada request del arreglo se distribuye
                // en Cache 1 2 o 3 segn su hash.
                JSONObject respuesta = new JSONObject();
                if (hash(b) % 3 == 0) {
                    respuesta = hilox1.fn(request); //Y corre la funcin de una hebra.
                } else {
                    if (hash(b) % 3 == 1) {
                        respuesta = hilox2.fn(request);
                    } else {
                        respuesta = hilox3.fn(request);
                    }
                }

                //RESPONDER DESDE EL SERVIDOR
                ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj
                resp.writeObject(respuesta);
                System.out.println("msj enviado desde el servidor");

                //clienteNuevo.close();
                //servidor.close();
            }

        }
    } catch (IOException ex) {
        Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:eu.tango.energymodeller.EnergyModeller.java

/**
 * This runs the energy modeller in standalone mode.
 *
 * @param args no args are expected.//from   w w  w  .  ja  v  a  2 s  .c om
 */
public static void main(String[] args) {
    boolean running = true;
    try {
        if (new File("energy-modeller-logging.properties").exists()) {
            LogManager.getLogManager()
                    .readConfiguration(new FileInputStream(new File("energy-modeller-logging.properties")));
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException | SecurityException ex) {
        Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE,
                "Could not read the energy modeller's log settings file", ex);
    }
    /**
     * Only the instance that is stated in standalone mode should write to
     * the background database and log VM data out to disk. All other
     * instances should read from the database only.
     */
    EnergyModeller modeller = new EnergyModeller(true);
    Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE,
            "The logger for the energy modeller has now started");
    while (running) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE,
                    "The energy modeller was interupted.", ex);
        } catch (Exception ex) {
            Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE, "An unhandled exception occured",
                    ex);
            running = false;
        }
    }
}

From source file:uk.co.moonsit.rmi.GraphClient.java

@SuppressWarnings("SleepWhileInLoop")
public static void main(String args[]) {
    Properties p = new Properties();
    try {/*w w w .  j  av a  2s .com*/
        p.load(new FileReader("graph.properties"));
    } catch (IOException ex) {
        Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    //String[] labels = p.getProperty("labels").split(",");
    GraphClient demo = null;
    int type = 0;
    boolean log = false;
    if (args[0].equals("-l")) {
        log = true;
    }

    switch (type) {
    case 0:
        try {
            System.setProperty("java.security.policy", "file:./client.policy");
            if (System.getSecurityManager() == null) {
                System.setSecurityManager(new RMISecurityManager());
            }
            String name = "GraphServer";
            String host = p.getProperty("host");
            System.out.println(host);
            Registry registry = LocateRegistry.getRegistry(host);
            String[] list = registry.list();
            for (String s : list) {
                System.out.println(s);
            }
            GraphDataInterface gs = null;
            boolean bound = false;
            while (!bound) {
                try {
                    gs = (GraphDataInterface) registry.lookup(name);
                    bound = true;
                } catch (NotBoundException e) {
                    System.err.println("GraphServer exception:" + e.toString());
                    Thread.sleep(500);
                }
            }
            @SuppressWarnings("null")
            String config = gs.getConfig();
            System.out.println(config);
            /*float[] fs = gs.getValues();
             for (float f : fs) {
             System.out.println(f);
             }*/

            demo = new GraphClient(gs, 1000, 700, Float.parseFloat(p.getProperty("frequency")), log);
            demo.init(config);
            demo.run();
        } catch (RemoteException e) {
            System.err.println("GraphClient exception:" + e.toString());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (demo != null) {
                demo.close();
            }
        }
        break;
    case 1:
        try {
            demo = new GraphClient(1000, 700, Float.parseFloat(p.getProperty("frequency")));
            demo.init("A^B|Time|Error|-360|360");

            demo.addData(0, 1, 100);
            demo.addData(0, 2, 200);

            demo.addData(1, 1, 50);
            demo.addData(1, 2, 450);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        break;
    }

}

From source file:de.mendelson.comm.as2.AS2.java

/**Method to start the server on from the command line*/
public static void main(String args[]) {

    // TODO remove
    cleanup();//from  ww w.j av a  2s. com

    String language = null;
    boolean startHTTP = true;
    boolean allowAllClients = false;
    int optind;
    for (optind = 0; optind < args.length; optind++) {
        if (args[optind].toLowerCase().equals("-lang")) {
            language = args[++optind];
        } else if (args[optind].toLowerCase().equals("-nohttpserver")) {
            startHTTP = false;
        } else if (args[optind].toLowerCase().equals("-allowallclients")) {
            allowAllClients = true;
        } else if (args[optind].toLowerCase().equals("-?")) {
            AS2.printUsage();
            System.exit(1);
        } else if (args[optind].toLowerCase().equals("-h")) {
            AS2.printUsage();
            System.exit(1);
        } else if (args[optind].toLowerCase().equals("-help")) {
            AS2.printUsage();
            System.exit(1);
        }
    }
    //load language from preferences
    if (language == null) {
        PreferencesAS2 preferences = new PreferencesAS2();
        language = preferences.get(PreferencesAS2.LANGUAGE);
    }
    if (language != null) {
        if (language.toLowerCase().equals("en")) {
            Locale.setDefault(Locale.ENGLISH);
        } else if (language.toLowerCase().equals("de")) {
            Locale.setDefault(Locale.GERMAN);
        } else if (language.toLowerCase().equals("fr")) {
            Locale.setDefault(Locale.FRENCH);
        } else {
            AS2.printUsage();
            System.out.println();
            System.out.println("Language " + language + " is not supported.");
            System.exit(1);
        }
    }
    Splash splash = new Splash("/de/mendelson/comm/as2/client/Splash.jpg");
    AffineTransform transform = new AffineTransform();
    splash.setTextAntiAliasing(false);
    transform.setToScale(1.0, 1.0);
    splash.addDisplayString(new Font("Verdana", Font.BOLD, 11), 7, 262, AS2ServerVersion.getFullProductName(),
            new Color(0x65, 0xB1, 0x80), transform);
    splash.setVisible(true);
    splash.toFront();
    //start server
    try {
        //register the database drivers for the VM
        Class.forName("org.hsqldb.jdbcDriver");
        //initialize the security provider
        BCCryptoHelper helper = new BCCryptoHelper();
        helper.initialize();
        AS2Server as2Server = new AS2Server(startHTTP, allowAllClients);
        AS2Agent agent = new AS2Agent(as2Server);
    } catch (UpgradeRequiredException e) {
        //an upgrade to HSQLDB 2.x is required, delete the lock file
        Logger.getLogger(AS2Server.SERVER_LOGGER_NAME).warning(e.getMessage());
        JOptionPane.showMessageDialog(null, e.getClass().getName() + ": " + e.getMessage());
        AS2Server.deleteLockFile();
        System.exit(1);
    } catch (Throwable e) {
        if (splash != null) {
            splash.destroy();
        }
        JOptionPane.showMessageDialog(null, e.getMessage());
        System.exit(1);
    }
    //start client
    AS2Gui gui = new AS2Gui(splash, "localhost");
    gui.setVisible(true);
    splash.destroy();
    splash.dispose();
}

From source file:com.diversityarrays.dal.server.DalServer.java

public static void main(String[] args) {

    String host = null;/*from w  w w .  jav a 2s.  c o  m*/
    int port = DalServerUtil.DEFAULT_DAL_SERVER_PORT;

    int inactiveMins = DalServerUtil.DEFAULT_MAX_INACTIVE_MINUTES;

    File docRoot = null;

    String serviceName = null;

    for (int i = 0; i < args.length; ++i) {
        String argi = args[i];
        if (argi.startsWith("-")) {
            if ("--".equals(argi)) {
                break;
            }

            if ("-version".equals(argi)) {
                System.out.println(DAL_SERVER_VERSION);
                System.exit(0);
            }

            if ("-help".equals(argi)) {
                giveHelpThenExit(0);
            }

            if ("-docroot".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }
                docRoot = new File(args[i]);
            } else if ("-sqllog".equals(argi)) {
                SqlUtil.logger = Logger.getLogger(SqlUtil.class.getName());
            } else if ("-expire".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }

                try {
                    inactiveMins = Integer.parseInt(args[i], 10);
                    if (inactiveMins <= 0) {
                        fatal("invalid minutes: " + args[i]);
                    }
                } catch (NumberFormatException e) {
                    fatal("invalid minutes: " + args[i]);
                }
            } else if ("-localhost".equals(argi)) {
                host = "localhost";
            } else if ("-port".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }
                try {
                    port = Integer.parseInt(args[i], 10);
                    if (port < 0 || port > 65535) {
                        fatal("invalid port number: " + args[i]);
                    }
                } catch (NumberFormatException e) {
                    fatal("invalid port number: " + args[i]);
                }
            } else {
                fatal("invalid option: " + argi);
            }
        } else {
            if (serviceName != null) {
                fatal("multiple serviceNames not supported: " + argi);
            }
            serviceName = argi;
        }
    }

    final DalServerPreferences preferences = new DalServerPreferences(
            Preferences.userNodeForPackage(DalServer.class));

    if (docRoot == null) {
        docRoot = preferences.getWebRoot(new File(System.getProperty("user.dir"), "www"));
    }

    DalServer server = null;

    if (serviceName != null && docRoot.isDirectory()) {
        try {
            DalDatabase db = createDalDatabase(serviceName, preferences);
            if (db.isInitialiseRequired()) {
                Closure<String> progress = new Closure<String>() {
                    @Override
                    public void execute(String msg) {
                        System.out.println("Database Initialisation: " + msg);
                    }
                };
                db.initialise(progress);
            }
            server = create(preferences, host, port, docRoot, db);
        } catch (NoServiceException e) {
            throw new RuntimeException(e);
        } catch (DalDbException e) {
            throw new RuntimeException(e);
        }
    }

    Image serverIconImage = null;
    InputStream imageIs = DalServer.class.getResourceAsStream("dalserver-24.png");
    if (imageIs != null) {
        try {
            serverIconImage = ImageIO.read(imageIs);

            if (Util.isMacOS()) {
                try {
                    MacApplication macapp = new MacApplication(null);
                    macapp.setDockIconImage(serverIconImage);
                } catch (MacApplicationException e) {
                    System.err.println(e.getMessage());
                }
            }

        } catch (IOException ignore) {
        }
    }

    if (server != null) {
        server.setMaxInactiveMinutes(inactiveMins);
    } else {
        AskServerParams asker = new AskServerParams(serverIconImage, null, "DAL Server Start", docRoot,
                preferences);
        GuiUtil.centreOnScreen(asker);
        asker.setVisible(true);

        if (asker.cancelled) {
            System.exit(0);
        }

        host = asker.dalServerHostName;
        port = asker.dalServerPort;
        inactiveMins = asker.maxInactiveMinutes;

        server = create(preferences, host, port, asker.wwwRoot, asker.dalDatabase);
        // server.setUseSimpleDatabase(asker.useSimpleDatabase);
    }

    final DalServer f_server = server;
    final File f_wwwRoot = docRoot;
    final Image f_serverIconImage = serverIconImage;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            DalServerFactory factory = new DalServerFactory() {
                @Override
                public DalServer create(String hostName, int port, File wwwRoot, DalDatabase dalDatabase) {
                    return DalServer.create(preferences, hostName, port, wwwRoot, dalDatabase);
                }
            };
            ServerGui gui = new ServerGui(f_serverIconImage, f_server, factory, f_wwwRoot, preferences);
            gui.setVisible(true);
        }
    });

}

From source file:di.uniba.it.tee2.wiki.Wikidump2Index.java

/**
 * language xml_dump output_dir encoding
 *
 * @param args the command line arguments
 *///from   ww  w  . j a  v a 2 s  .c o  m
public static void main(String[] args) {
    try {
        CommandLine cmd = cmdParser.parse(options, args);
        if (cmd.hasOption("l") && cmd.hasOption("d") && cmd.hasOption("o")) {
            encoding = cmd.getOptionValue("e", "UTF-8");
            minTextLegth = Integer.parseInt(cmd.getOptionValue("m", "4000"));
            if (cmd.hasOption("p")) {
                pageLimit = Integer.parseInt(cmd.getOptionValue("p"));
            }
            Wikidump2Index builder = new Wikidump2Index();
            builder.init(cmd.getOptionValue("l"), cmd.getOptionValue("o"));
            builder.build(cmd.getOptionValue("d"), cmd.getOptionValue("l"));
        } else {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Index Wikipedia dump (single thread)", options, true);
        }
    } catch (Exception ex) {
        Logger.getLogger(Wikidump2Index.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:baldrickv.s3streamingtool.S3StreamingTool.java

public static void main(String args[]) throws Exception {
    BasicParser p = new BasicParser();

    Options o = getOptions();//from  w ww  . j  av  a  2 s  .  c  o m

    CommandLine cl = p.parse(o, args);

    if (cl.hasOption('h')) {
        HelpFormatter hf = new HelpFormatter();
        hf.setWidth(80);

        StringBuilder sb = new StringBuilder();

        sb.append("\n");
        sb.append("Upload:\n");
        sb.append("    -u -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Download:\n");
        sb.append("    -d -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Upload encrypted:\n");
        sb.append("    -u -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Download encrypted:\n");
        sb.append("    -d -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Cleanup in-progress multipart uploads\n");
        sb.append("    -c -r creds -b my_bucket\n");
        System.out.println(sb.toString());

        hf.printHelp("See above", o);

        return;
    }

    int n = 0;
    if (cl.hasOption('d'))
        n++;
    if (cl.hasOption('u'))
        n++;
    if (cl.hasOption('c'))
        n++;
    if (cl.hasOption('m'))
        n++;

    if (n != 1) {
        System.err.println("Must specify at exactly one of -d, -u, -c or -m");
        System.exit(-1);
    }

    if (cl.hasOption('m')) {
        //InputStream in = new java.io.BufferedInputStream(System.in,1024*1024*2);
        InputStream in = System.in;
        System.out.println(TreeHashGenerator.calculateTreeHash(in));
        return;
    }

    require(cl, 'b');

    if (cl.hasOption('d') || cl.hasOption('u')) {
        require(cl, 'f');
    }
    if (cl.hasOption('z')) {
        require(cl, 'k');
    }

    AWSCredentials creds = null;

    if (cl.hasOption('r')) {
        creds = Utils.loadAWSCredentails(cl.getOptionValue('r'));
    } else {
        if (cl.hasOption('i') && cl.hasOption('e')) {
            creds = new BasicAWSCredentials(cl.getOptionValue('i'), cl.getOptionValue('e'));
        } else {

            System.out.println("Must specify either credential file (-r) or AWS key ID and secret (-i and -e)");
            System.exit(-1);
        }
    }

    S3StreamConfig config = new S3StreamConfig();
    config.setEncryption(false);
    if (cl.hasOption('z')) {
        config.setEncryption(true);
        config.setSecretKey(Utils.loadSecretKey(cl.getOptionValue("k")));
    }

    if (cl.hasOption("encryption-mode")) {
        config.setEncryptionMode(cl.getOptionValue("encryption-mode"));
    }
    config.setS3Bucket(cl.getOptionValue("bucket"));
    if (cl.hasOption("file")) {
        config.setS3File(cl.getOptionValue("file"));
    }

    if (cl.hasOption("threads")) {
        config.setIOThreads(Integer.parseInt(cl.getOptionValue("threads")));
    }

    if (cl.hasOption("blocksize")) {
        String s = cl.getOptionValue("blocksize");
        s = s.toUpperCase();
        int multi = 1;

        int end = 0;
        while ((end < s.length()) && (s.charAt(end) >= '0') && (s.charAt(end) <= '9')) {
            end++;
        }
        int size = Integer.parseInt(s.substring(0, end));

        if (end < s.length()) {
            String m = s.substring(end);
            if (m.equals("K"))
                multi = 1024;
            else if (m.equals("M"))
                multi = 1048576;
            else if (m.equals("G"))
                multi = 1024 * 1024 * 1024;
            else if (m.equals("KB"))
                multi = 1024;
            else if (m.equals("MB"))
                multi = 1048576;
            else if (m.equals("GB"))
                multi = 1024 * 1024 * 1024;
            else {
                System.out.println("Unknown suffix on block size.  Only K,M and G understood.");
                System.exit(-1);
            }

        }
        size *= multi;
        config.setBlockSize(size);
    }

    Logger.getLogger("").setLevel(Level.FINE);

    S3StreamingDownload.log.setLevel(Level.FINE);
    S3StreamingUpload.log.setLevel(Level.FINE);

    config.setS3Client(new AmazonS3Client(creds));
    config.setGlacierClient(new AmazonGlacierClient(creds));
    config.getGlacierClient().setEndpoint("glacier.us-west-2.amazonaws.com");

    if (cl.hasOption("glacier")) {
        config.setGlacier(true);
        config.setStorageInterface(new StorageGlacier(config.getGlacierClient()));
    } else {
        config.setStorageInterface(new StorageS3(config.getS3Client()));
    }
    if (cl.hasOption("bwlimit")) {
        config.setMaxBytesPerSecond(Double.parseDouble(cl.getOptionValue("bwlimit")));

    }

    if (cl.hasOption('c')) {
        if (config.getGlacier()) {
            GlacierCleanupMultipart.cleanup(config);
        } else {
            S3CleanupMultipart.cleanup(config);
        }
        return;
    }
    if (cl.hasOption('d')) {
        config.setOutputStream(System.out);
        S3StreamingDownload.download(config);
        return;
    }
    if (cl.hasOption('u')) {
        config.setInputStream(System.in);
        S3StreamingUpload.upload(config);
        return;
    }

}