Example usage for java.lang Class newInstance

List of usage examples for java.lang Class newInstance

Introduction

In this page you can find the example usage for java.lang Class newInstance.

Prototype

@CallerSensitive
@Deprecated(since = "9")
public T newInstance() throws InstantiationException, IllegalAccessException 

Source Link

Document

Creates a new instance of the class represented by this Class object.

Usage

From source file:org.apache.flink.benchmark.Runner.java

public static void main(String[] args) throws Exception {
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    env.getConfig().enableObjectReuse();
    env.getConfig().disableSysoutLogging();

    ParameterTool parameters = ParameterTool.fromArgs(args);

    if (!(parameters.has("p") && parameters.has("types") && parameters.has("algorithms"))) {
        printUsage();/*from w w w  .  j  a v a2s.co m*/
        System.exit(-1);
    }

    int parallelism = parameters.getInt("p");
    env.setParallelism(parallelism);

    Set<IdType> types = new HashSet<>();

    if (parameters.get("types").equals("all")) {
        types.add(IdType.INT);
        types.add(IdType.LONG);
        types.add(IdType.STRING);
    } else {
        for (String type : parameters.get("types").split(",")) {
            if (type.toLowerCase().equals("int")) {
                types.add(IdType.INT);
            } else if (type.toLowerCase().equals("long")) {
                types.add(IdType.LONG);
            } else if (type.toLowerCase().equals("string")) {
                types.add(IdType.STRING);
            } else {
                printUsage();
                throw new RuntimeException("Unknown type: " + type);
            }
        }
    }

    Queue<RunnerWithScore> queue = new PriorityQueue<>();

    if (parameters.get("algorithms").equals("all")) {
        for (Map.Entry<String, Class> entry : AVAILABLE_ALGORITHMS.entrySet()) {
            for (IdType type : types) {
                AlgorithmRunner runner = (AlgorithmRunner) entry.getValue().newInstance();
                runner.initialize(type, SAMPLES, parallelism);
                runner.warmup(env);
                queue.add(new RunnerWithScore(runner, 1.0));
            }
        }
    } else {
        for (String algorithm : parameters.get("algorithms").split(",")) {
            double ratio = 1.0;
            if (algorithm.contains("=")) {
                String[] split = algorithm.split("=");
                algorithm = split[0];
                ratio = Double.parseDouble(split[1]);
            }

            if (AVAILABLE_ALGORITHMS.containsKey(algorithm.toLowerCase())) {
                Class clazz = AVAILABLE_ALGORITHMS.get(algorithm.toLowerCase());

                for (IdType type : types) {
                    AlgorithmRunner runner = (AlgorithmRunner) clazz.newInstance();
                    runner.initialize(type, SAMPLES, parallelism);
                    runner.warmup(env);
                    queue.add(new RunnerWithScore(runner, ratio));
                }
            } else {
                printUsage();
                throw new RuntimeException("Unknown algorithm: " + algorithm);
            }
        }
    }

    JsonFactory factory = new JsonFactory();

    while (queue.size() > 0) {
        RunnerWithScore current = queue.poll();
        AlgorithmRunner runner = current.getRunner();

        StringWriter writer = new StringWriter();
        JsonGenerator gen = factory.createGenerator(writer);
        gen.writeStartObject();
        gen.writeStringField("algorithm", runner.getClass().getSimpleName());

        boolean running = true;

        while (running) {
            try {
                runner.run(env, gen);
                running = false;
            } catch (ProgramInvocationException e) {
                // only suppress job cancellations
                if (!(e.getCause() instanceof JobCancellationException)) {
                    throw e;
                }
            }
        }

        JobExecutionResult result = env.getLastJobExecutionResult();

        long runtime_ms = result.getNetRuntime();
        gen.writeNumberField("runtime_ms", runtime_ms);
        current.credit(runtime_ms);

        if (!runner.finished()) {
            queue.add(current);
        }

        gen.writeObjectFieldStart("accumulators");
        for (Map.Entry<String, Object> accumulatorResult : result.getAllAccumulatorResults().entrySet()) {
            gen.writeStringField(accumulatorResult.getKey(), accumulatorResult.getValue().toString());
        }
        gen.writeEndObject();

        gen.writeEndObject();
        gen.close();
        System.out.println(writer.toString());
    }
}

From source file:PlotDriver.java

/** Construct a Plotter driver, and try it out. */
public static void main(String[] argv) {
    Plotter r;/* w ww  . ja  va2 s .  c  o  m*/
    //      if (argv.length != 1) {
    //      System.err.println("Usage: PlotDriver driverclass");
    //   return;
    //      }
    try {
        Class c = Class.forName("PlotterAWT");
        Object o = c.newInstance();
        if (!(o instanceof Plotter))
            throw new ClassNotFoundException("Not instanceof Plotter");
        r = (Plotter) o;
    } catch (ClassNotFoundException e) {
        System.err.println("Sorry, " + argv[0] + " not a plotter class");
        return;
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
    r.penDown();
    r.penColor(1);
    r.moveTo(200, 200);
    r.penColor(2);
    r.drawBox(123, 200);
    r.rmoveTo(10, 20);
    r.penColor(3);
    r.drawBox(123, 200);
    r.penUp();
    r.moveTo(300, 100);
    r.penDown();
    r.setFont("Helvetica", 14);
    r.drawString("Hello World");
    r.penColor(4);
    r.drawBox(10, 10);
}

From source file:net.semanticmetadata.lire.solr.ParallelSolrIndexer.java

public static void main(String[] args) throws IOException {
    BitSampling.readHashFunctions();/*from ww w .ja v  a2  s . c o m*/
    ParallelSolrIndexer e = new ParallelSolrIndexer();

    // parse programs args ...
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.startsWith("-i")) {
            // infile ...
            if ((i + 1) < args.length)
                e.setFileList(new File(args[i + 1]));
            else {
                System.err.println("Could not set out file.");
                printHelp();
            }
        } else if (arg.startsWith("-o")) {
            // out file, if it's not set a single file for each input image is created.
            if ((i + 1) < args.length)
                e.setOutFile(new File(args[i + 1]));
            else
                printHelp();
        } else if (arg.startsWith("-m")) {
            // out file
            if ((i + 1) < args.length) {
                try {
                    int s = Integer.parseInt(args[i + 1]);
                    if (s > 10)
                        e.setMaxSideLength(s);
                } catch (NumberFormatException e1) {
                    e1.printStackTrace();
                    printHelp();
                }
            } else
                printHelp();
        } else if (arg.startsWith("-r")) {
            // image data processor class.
            if ((i + 1) < args.length) {
                try {
                    Class<?> imageDataProcessorClass = Class.forName(args[i + 1]);
                    if (imageDataProcessorClass.newInstance() instanceof ImageDataProcessor)
                        e.setImageDataProcessor(imageDataProcessorClass);
                } catch (Exception e1) {
                    System.err.println("Did not find imageProcessor class: " + e1.getMessage());
                    printHelp();
                    System.exit(0);
                }
            } else
                printHelp();
        } else if (arg.startsWith("-f") || arg.startsWith("--force")) {
            e.setForce(true);
        } else if (arg.startsWith("-y") || arg.startsWith("--features")) {
            if ((i + 1) < args.length) {
                // parse and check the features.
                String[] ft = args[i + 1].split(",");
                for (int j = 0; j < ft.length; j++) {
                    String s = ft[j].trim();
                    if (FeatureRegistry.getClassForCode(s) != null) {
                        e.addFeature(FeatureRegistry.getClassForCode(s));
                    }
                }
            }
        } else if (arg.startsWith("-p")) {
            e.setPreprocessing(true);
        } else if (arg.startsWith("-h")) {
            // help
            printHelp();
            System.exit(0);
        } else if (arg.startsWith("-n")) {
            if ((i + 1) < args.length)
                try {
                    ParallelSolrIndexer.numberOfThreads = Integer.parseInt(args[i + 1]);
                } catch (Exception e1) {
                    System.err.println("Could not set number of threads to \"" + args[i + 1] + "\".");
                    e1.printStackTrace();
                }
            else
                printHelp();
        }
    }
    // check if there is an infile, an outfile and some features to extract.
    if (!e.isConfigured()) {
        printHelp();
    } else {
        e.run();
    }
}

From source file:Server.java

/**
 * A main() method for running the server as a standalone program. The
 * command-line arguments to the program should be pairs of servicenames and
 * port numbers. For each pair, the program will dynamically load the named
 * Service class, instantiate it, and tell the server to provide that
 * Service on the specified port. The special -control argument should be
 * followed by a password and port, and will start special server control
 * service running on the specified port, protected by the specified
 * password./*ww  w .j  a va2 s.c om*/
 */
public static void main(String[] args) {
    try {
        if (args.length < 2) // Check number of arguments
            throw new IllegalArgumentException("Must specify a service");

        // Create a Server object that uses standard out as its log and
        // has a limit of ten concurrent connections at once.
        Server s = new Server(System.out, 10);

        // Parse the argument list
        int i = 0;
        while (i < args.length) {
            if (args[i].equals("-control")) { // Handle the -control arg
                i++;
                String password = args[i++];
                int port = Integer.parseInt(args[i++]);
                // add control service
                s.addService(new Control(s, password), port);
            } else {
                // Otherwise start a named service on the specified port.
                // Dynamically load and instantiate a Service class
                String serviceName = args[i++];
                Class serviceClass = Class.forName(serviceName);
                Service service = (Service) serviceClass.newInstance();
                int port = Integer.parseInt(args[i++]);
                s.addService(service, port);
            }
        }
    } catch (Exception e) { // Display a message if anything goes wrong
        System.err.println("Server: " + e);
        System.err.println(
                "Usage: java Server " + "[-control <password> <port>] " + "[<servicename> <port> ... ]");
        System.exit(1);
    }
}

From source file:core.PlanC.java

/**
 * inicio de aplicacion//from  ww w.ja  v a 2 s . co m
 * 
 * @param arg - argumentos de entrada
 */
public static void main(String[] args) {

    // user.name

    /*
     * Properties prp = System.getProperties(); System.out.println(getWmicValue("bios", "SerialNumber"));
     * System.out.println(getWmicValue("cpu", "SystemName"));
     */

    try {
        // log
        // -Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
        // System.setProperty("java.util.logging.SimpleFormatter.format",
        // "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n");
        System.setProperty("java.util.logging.SimpleFormatter.format",
                "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %5$s%6$s%n");

        FileHandler fh = new FileHandler(LOG_FILE);
        fh.setFormatter(new SimpleFormatter());
        fh.setLevel(Level.INFO);
        ConsoleHandler ch = new ConsoleHandler();
        ch.setFormatter(new SimpleFormatter());
        ch.setLevel(Level.INFO);
        logger = Logger.getLogger("");
        Handler[] hs = logger.getHandlers();
        for (int x = 0; x < hs.length; x++) {
            logger.removeHandler(hs[x]);
        }
        logger.addHandler(fh);
        logger.addHandler(ch);
        // point apache log to this log
        System.setProperty("org.apache.commons.logging.Log", Jdk14Logger.class.getName());

        TPreferences.init();
        TStringUtils.init();

        Font fo = Font.createFont(Font.TRUETYPE_FONT, TResourceUtils.getFile("Dosis-Light.ttf"));
        GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fo);
        fo = Font.createFont(Font.TRUETYPE_FONT, TResourceUtils.getFile("Dosis-Medium.ttf"));
        GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fo);
        fo = Font.createFont(Font.TRUETYPE_FONT, TResourceUtils.getFile("AERO_ITALIC.ttf"));
        GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fo);

        SwingTimerTimingSource ts = new SwingTimerTimingSource();
        AnimatorBuilder.setDefaultTimingSource(ts);
        ts.init();

        // parse app argument parameters and append to tpreferences to futher uses
        for (String arg : args) {
            String[] kv = arg.split("=");
            TPreferences.setProperty(kv[0], kv[1]);
        }
        RUNNING_MODE = TPreferences.getProperty("runningMode", RM_NORMAL);

        newMsg = Applet.newAudioClip(TResourceUtils.getURL("newMsg.wav"));

    } catch (Exception e) {
        SystemLog.logException1(e, true);
    }

    // pass icon from metal to web look and feel
    Icon i1 = UIManager.getIcon("OptionPane.errorIcon");
    Icon i2 = UIManager.getIcon("OptionPane.informationIcon");
    Icon i3 = UIManager.getIcon("OptionPane.questionIcon");
    Icon i4 = UIManager.getIcon("OptionPane.warningIcon");
    // Object fcui = UIManager.get("FileChooserUI");
    // JFileChooser fc = new JFileChooser();

    WebLookAndFeel.install();
    // WebLookAndFeel.setDecorateFrames(true);
    // WebLookAndFeel.setDecorateDialogs(true);

    UIManager.put("OptionPane.errorIcon", i1);
    UIManager.put("OptionPane.informationIcon", i2);
    UIManager.put("OptionPane.questionIcon", i3);
    UIManager.put("OptionPane.warningIcon", i4);
    // UIManager.put("TFileChooserUI", fcui);

    // warm up the IDW.
    // in my computer, some weird error ocurr if i don't execute this preload.
    new RootWindow(null);

    frame = new TWebFrame();
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            Exit.shutdown();
        }
    });

    if (RUNNING_MODE.equals(RM_NORMAL)) {
        initEnviorement();
    }
    if (RUNNING_MODE.equals(RM_CONSOLE)) {
        initConsoleEnviorement();
    }

    if (RUNNING_MODE.equals(ONE_TASK)) {
        String cln = TPreferences.getProperty("taskName", "*TaskNotFound");
        PlanC.logger.log(Level.INFO, "OneTask parameter found in .properties. file Task name = " + cln);
        try {
            Class cls = Class.forName(cln);
            Object dobj = cls.newInstance();
            // new class must be extends form AbstractExternalTask
            TTaskManager.executeTask((Runnable) dobj);
            return;
        } catch (Exception e) {
            PlanC.logger.log(Level.SEVERE, e.getMessage(), e);
            Exit.shutdown();
        }
    }
}

From source file:org.usergrid.benchmark.boostrap.Command.java

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

    if ((args == null) || (args.length < 1)) {
        System.out.println("No command specified");
        return;
    }

    String command = args[0];

    Class<?> clazz = null;

    try {
        clazz = Class.forName(command);
    } catch (ClassNotFoundException e) {
    }

    if (clazz == null) {
        try {
            clazz = Class.forName("org.usergrid.benchmark.commands." + command);
        } catch (ClassNotFoundException e) {
        }
    }

    if (clazz == null) {
        try {
            clazz = Class.forName("org.usergrid.benchmark.commands." + StringUtils.capitalize(command));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    if (clazz == null) {
        System.out.println("Unable to find command");
        return;
    }

    args = Arrays.copyOfRange(args, 1, args.length);

    try {
        if (ToolBase.class.isAssignableFrom(clazz)) {
            ToolBase tool = (ToolBase) clazz.newInstance();
            tool.startTool(args);
        } else {
            MethodUtils.invokeStaticMethod(clazz, "main", (Object) args);
        }
    } catch (NoSuchMethodException e) {
        System.out.println("Unable to invoke command");
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        System.out.println("Unable to invoke command");
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        System.out.println("Error while invoking command");
        e.printStackTrace();
    } catch (InstantiationException e) {
        System.out.println("Error while instantiating tool object");
        e.printStackTrace();
    }
}

From source file:gobblin.restli.throttling.LocalStressTest.java

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

    CommandLine cli = StressTestUtils.parseCommandLine(OPTIONS, args);

    int stressorThreads = Integer.parseInt(
            cli.getOptionValue(STRESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_STRESSOR_THREADS)));
    int processorThreads = Integer.parseInt(
            cli.getOptionValue(PROCESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_PROCESSOR_THREADS)));
    int artificialLatency = Integer.parseInt(
            cli.getOptionValue(ARTIFICIAL_LATENCY.getOpt(), Integer.toString(DEFAULT_ARTIFICIAL_LATENCY)));
    long targetQps = Integer.parseInt(cli.getOptionValue(QPS.getOpt(), Integer.toString(DEFAULT_TARGET_QPS)));

    Configuration configuration = new Configuration();
    StressTestUtils.populateConfigFromCli(configuration, cli);

    String resourceLimited = LocalStressTest.class.getSimpleName();

    Map<String, String> configMap = Maps.newHashMap();

    ThrottlingPolicyFactory factory = new ThrottlingPolicyFactory();
    SharedLimiterKey res1key = new SharedLimiterKey(resourceLimited);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null,
            ThrottlingPolicyFactory.POLICY_KEY), QPSPolicy.FACTORY_ALIAS);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, QPSPolicy.QPS),
            Long.toString(targetQps));

    ThrottlingGuiceServletConfig guiceServletConfig = new ThrottlingGuiceServletConfig();
    guiceServletConfig.initialize(ConfigFactory.parseMap(configMap));
    LimiterServerResource limiterServer = guiceServletConfig.getInjector()
            .getInstance(LimiterServerResource.class);

    RateComputingLimiterContainer limiterContainer = new RateComputingLimiterContainer();

    Class<? extends Stressor> stressorClass = configuration.getClass(StressTestUtils.STRESSOR_CLASS,
            StressTestUtils.DEFAULT_STRESSOR_CLASS, Stressor.class);

    ExecutorService executorService = Executors.newFixedThreadPool(stressorThreads);

    SharedResourcesBroker broker = guiceServletConfig.getInjector().getInstance(
            Key.get(SharedResourcesBroker.class, Names.named(LimiterServerResource.BROKER_INJECT_NAME)));
    ThrottlingPolicy policy = (ThrottlingPolicy) broker.getSharedResource(new ThrottlingPolicyFactory(),
            new SharedLimiterKey(resourceLimited));
    ScheduledExecutorService reportingThread = Executors.newSingleThreadScheduledExecutor();
    reportingThread.scheduleAtFixedRate(new Reporter(limiterContainer, policy), 0, 15, TimeUnit.SECONDS);

    Queue<Future<?>> futures = new LinkedList<>();
    MockRequester requester = new MockRequester(limiterServer, artificialLatency, processorThreads);

    requester.start();/*from   w w w .  j  a  v a  2 s. c  om*/
    for (int i = 0; i < stressorThreads; i++) {
        RestliServiceBasedLimiter restliLimiter = RestliServiceBasedLimiter.builder()
                .resourceLimited(resourceLimited).requestSender(requester).serviceIdentifier("stressor" + i)
                .build();

        Stressor stressor = stressorClass.newInstance();
        stressor.configure(configuration);
        futures.add(executorService
                .submit(new StressorRunner(limiterContainer.decorateLimiter(restliLimiter), stressor)));
    }
    int stressorFailures = 0;
    for (Future<?> future : futures) {
        try {
            future.get();
        } catch (ExecutionException ee) {
            stressorFailures++;
        }
    }
    requester.stop();

    executorService.shutdownNow();

    if (stressorFailures > 0) {
        log.error("There were " + stressorFailures + " failed stressor threads.");
    }
    System.exit(stressorFailures);
}

From source file:net.mmberg.nadia.processor.NadiaProcessor.java

/**
 * @param args//from  w ww.j  a va  2s. c  o m
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {

    Class<? extends UserInterface> ui_class = ConsoleInterface.class; //default UI
    String dialog_file = default_dialog; //default dialogue

    //process command line args
    Options cli_options = new Options();
    cli_options.addOption("h", "help", false, "print this message");
    cli_options.addOption(OptionBuilder.withLongOpt("interface").withDescription("select user interface")
            .hasArg(true).withArgName("console, rest").create("i"));
    cli_options.addOption("f", "file", true, "specify dialogue path and file, e.g. -f /res/dialogue1.xml");
    cli_options.addOption("r", "resource", true, "load dialogue (by name) from resources, e.g. -r dialogue1");
    cli_options.addOption("s", "store", true, "load dialogue (by name) from internal store, e.g. -s dialogue1");

    CommandLineParser parser = new org.apache.commons.cli.BasicParser();
    try {
        CommandLine cmd = parser.parse(cli_options, args);

        //Help
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("nadia", cli_options, true);
            return;
        }

        //UI
        if (cmd.hasOption("i")) {
            String interf = cmd.getOptionValue("i");
            if (interf.equals("console"))
                ui_class = ConsoleInterface.class;
            else if (interf.equals("rest"))
                ui_class = RESTInterface.class;
        }

        //load dialogue from path file
        if (cmd.hasOption("f")) {
            dialog_file = "file:///" + cmd.getOptionValue("f");
        }
        //load dialogue from resources
        if (cmd.hasOption("r")) {
            dialog_file = config.getProperty(NadiaProcessorConfig.DIALOGUEDIR) + "/" + cmd.getOptionValue("r")
                    + ".xml";
        }
        //load dialogue from internal store
        if (cmd.hasOption("s")) {
            Dialog store_dialog = DialogStore.getInstance().getDialogFromStore((cmd.getOptionValue("s")));
            store_dialog.save();
            dialog_file = config.getProperty(NadiaProcessorConfig.DIALOGUEDIR) + "/" + cmd.getOptionValue("s")
                    + ".xml";
        }

    } catch (ParseException e1) {
        logger.severe("NADIA: loading by main-method failed. " + e1.getMessage());
        e1.printStackTrace();
    }

    //start Nadia with selected UI
    default_dialog = dialog_file;
    NadiaProcessor nadia = new NadiaProcessor();
    try {
        ui = ui_class.newInstance();
        ui.register(nadia);
        ui.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static <T> T newInstanceSafely(Class<T> clz) {
    try {/*from  w ww  . j a v  a2s  .c o  m*/
        return clz.newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static <C extends Set<T>, T> Set<T> toSet(T[] array, Class<C> clazz) {
    try {//from w w w  .  jav  a  2s  .c  om
        Set<T> set = clazz.newInstance();
        for (T o : array) {
            set.add(o);
        }
        return set;
    } catch (Exception e) {
        return null;
    }
}