Example usage for java.util List toArray

List of usage examples for java.util List toArray

Introduction

In this page you can find the example usage for java.util List toArray.

Prototype

<T> T[] toArray(T[] a);

Source Link

Document

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Usage

From source file:AllFieldsSnippet.java

public static void main(String[] args) {
    Object obj = new Object();
    //start extract AllFieldsSnippet

    Class cls = obj.getClass();/*from   w  ww  .  j  av a  2  s  .  c  o  m*/
    List accum = new LinkedList();
    while (cls != null) {
        Field[] f = cls.getDeclaredFields();
        for (int i = 0; i < f.length; i++) {
            accum.add(f[i]);
        }
        cls = cls.getSuperclass();
    }
    Field[] allFields = (Field[]) accum.toArray(new Field[accum.size()]);
    //stop extract AllFieldsSnippet
}

From source file:com.yahoo.labs.samoa.topology.impl.StormTopologySubmitter.java

public static void main(String[] args) throws IOException {
    Properties props = StormSamoaUtils.getProperties();

    String uploadedJarLocation = props.getProperty(StormJarSubmitter.UPLOADED_JAR_LOCATION_KEY);
    if (uploadedJarLocation == null) {
        logger.error("Invalid properties file. It must have key {}",
                StormJarSubmitter.UPLOADED_JAR_LOCATION_KEY);
        return;/*  w  w  w. j a v  a2 s .  c om*/
    }

    List<String> tmpArgs = new ArrayList<String>(Arrays.asList(args));
    int numWorkers = StormSamoaUtils.numWorkers(tmpArgs);

    args = tmpArgs.toArray(new String[0]);
    StormTopology stormTopo = StormSamoaUtils.argsToTopology(args);

    Config conf = new Config();
    conf.putAll(Utils.readStormConfig());
    conf.putAll(Utils.readCommandLineOpts());
    conf.setDebug(false);
    conf.setNumWorkers(numWorkers);

    String profilerOption = props.getProperty(StormTopologySubmitter.YJP_OPTIONS_KEY);
    if (profilerOption != null) {
        String topoWorkerChildOpts = (String) conf.get(Config.TOPOLOGY_WORKER_CHILDOPTS);
        StringBuilder optionBuilder = new StringBuilder();
        if (topoWorkerChildOpts != null) {
            optionBuilder.append(topoWorkerChildOpts);
            optionBuilder.append(' ');
        }
        optionBuilder.append(profilerOption);
        conf.put(Config.TOPOLOGY_WORKER_CHILDOPTS, optionBuilder.toString());
    }

    Map<String, Object> myConfigMap = new HashMap<String, Object>(conf);
    StringWriter out = new StringWriter();

    try {
        JSONValue.writeJSONString(myConfigMap, out);
    } catch (IOException e) {
        System.out.println("Error in writing JSONString");
        e.printStackTrace();
        return;
    }

    Config config = new Config();
    config.putAll(Utils.readStormConfig());

    String nimbusHost = (String) config.get(Config.NIMBUS_HOST);

    NimbusClient nc = new NimbusClient(nimbusHost);
    String topologyName = stormTopo.getTopologyName();
    try {
        System.out.println("Submitting topology with name: " + topologyName);
        nc.getClient().submitTopology(topologyName, uploadedJarLocation, out.toString(),
                stormTopo.getStormBuilder().createTopology());
        System.out.println(topologyName + " is successfully submitted");

    } catch (AlreadyAliveException aae) {
        System.out.println("Fail to submit " + topologyName + "\nError message: " + aae.get_msg());
    } catch (InvalidTopologyException ite) {
        System.out.println("Invalid topology for " + topologyName);
        ite.printStackTrace();
    } catch (TException te) {
        System.out.println("Texception for " + topologyName);
        te.printStackTrace();
    }
}

From source file:gov.nih.nci.cacis.mirth.XSLForMirthFormatter.java

/**
 * @param args - main method args//from  w w w. j  a va 2s.c o  m
 * @throws IOException - error thrown, if any
 * @throws URISyntaxException - error thrown, if any
 */
public static void main(String[] args) throws IOException, URISyntaxException {
    if (args.length < 2) {
        LOG.error("Usage: XSLForMirthFormatter <formatted-file-output-dir> <xsl-file-1> <xsl-file-2> ...");
        System.exit(1);
    }
    final List<String> lst = new ArrayList<String>(Arrays.asList(args));
    lst.remove(0);
    final XSLForMirthFormatter frmtr = new XSLForMirthFormatter();
    frmtr.formatXSL(args[0], (String[]) lst.toArray(new String[lst.size()]));
}

From source file:cu.uci.gws.sdlcrawler.PdfCrawlController.java

public static void main(String[] args) throws Exception {
    Properties cm = PdfCrawlerConfigManager.getInstance().loadConfigFile();
    long startTime = System.currentTimeMillis();
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    System.out.println(dateFormat.format(date));
    int numberOfCrawlers = Integer.parseInt(cm.getProperty("sdlcrawler.NumberOfCrawlers"));
    String pdfFolder = cm.getProperty("sdlcrawler.CrawlPdfFolder");

    CrawlConfig config = new CrawlConfig();

    config.setCrawlStorageFolder(cm.getProperty("sdlcrawler.CrawlStorageFolder"));
    config.setProxyHost(cm.getProperty("sdlcrawler.ProxyHost"));
    if (!"".equals(cm.getProperty("sdlcrawler.ProxyPort"))) {
        config.setProxyPort(Integer.parseInt(cm.getProperty("sdlcrawler.ProxyPort")));
    }/*from  w w w .  ja  va2  s  .  c  om*/
    config.setProxyUsername(cm.getProperty("sdlcrawler.ProxyUser"));
    config.setProxyPassword(cm.getProperty("sdlcrawler.ProxyPass"));
    config.setMaxDownloadSize(Integer.parseInt(cm.getProperty("sdlcrawler.MaxDownloadSize")));
    config.setIncludeBinaryContentInCrawling(
            Boolean.parseBoolean(cm.getProperty("sdlcrawler.IncludeBinaryContent")));
    config.setFollowRedirects(Boolean.parseBoolean(cm.getProperty("sdlcrawler.Redirects")));
    config.setUserAgentString(cm.getProperty("sdlcrawler.UserAgent"));
    config.setMaxDepthOfCrawling(Integer.parseInt(cm.getProperty("sdlcrawler.MaxDepthCrawl")));
    config.setMaxConnectionsPerHost(Integer.parseInt(cm.getProperty("sdlcrawler.MaxConnectionsPerHost")));
    config.setSocketTimeout(Integer.parseInt(cm.getProperty("sdlcrawler.SocketTimeout")));
    config.setMaxOutgoingLinksToFollow(Integer.parseInt(cm.getProperty("sdlcrawler.MaxOutgoingLinks")));
    config.setResumableCrawling(Boolean.parseBoolean(cm.getProperty("sdlcrawler.ResumableCrawling")));
    config.setIncludeHttpsPages(Boolean.parseBoolean(cm.getProperty("sdlcrawler.IncludeHttpsPages")));
    config.setMaxTotalConnections(Integer.parseInt(cm.getProperty("sdlcrawler.MaxTotalConnections")));
    config.setMaxPagesToFetch(Integer.parseInt(cm.getProperty("sdlcrawler.MaxPagesToFetch")));
    config.setPolitenessDelay(Integer.parseInt(cm.getProperty("sdlcrawler.PolitenessDelay")));
    config.setConnectionTimeout(Integer.parseInt(cm.getProperty("sdlcrawler.ConnectionTimeout")));

    System.out.println(config.toString());
    Collection<BasicHeader> defaultHeaders = new HashSet<>();
    defaultHeaders
            .add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
    defaultHeaders.add(new BasicHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3"));
    defaultHeaders.add(new BasicHeader("Accept-Language", "en-US,en,es-ES,es;q=0.8"));
    defaultHeaders.add(new BasicHeader("Connection", "keep-alive"));
    config.setDefaultHeaders(defaultHeaders);

    List<String> list = Files.readAllLines(Paths.get("config/" + cm.getProperty("sdlcrawler.SeedFile")),
            StandardCharsets.UTF_8);
    String[] crawlDomains = list.toArray(new String[list.size()]);

    PageFetcher pageFetcher = new PageFetcher(config);
    RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
    RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
    CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
    for (String domain : crawlDomains) {
        controller.addSeed(domain);
    }

    PdfCrawler.configure(crawlDomains, pdfFolder);
    controller.start(PdfCrawler.class, numberOfCrawlers);
    DateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date1 = new Date();
    System.out.println(dateFormat1.format(date1));
    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    System.out.println("Total time:" + totalTime);
}

From source file:com.mirth.connect.cli.launcher.CommandLineLauncher.java

public static void main(String[] args) {
    System.setProperty("log4j.configuration", "log4j-cli.properties");
    logger = Logger.getLogger(CommandLineLauncher.class);

    try {/*  w w w.  j  a  v  a 2 s .c  om*/
        ManifestFile mirthCliJar = new ManifestFile("cli-lib/mirth-cli.jar");
        ManifestFile mirthClientCoreJar = new ManifestFile("cli-lib/mirth-client-core.jar");
        ManifestDirectory cliLibDir = new ManifestDirectory("cli-lib");
        cliLibDir.setExcludes(new String[] { "mirth-client-core.jar" });

        ManifestEntry[] manifest = new ManifestEntry[] { mirthCliJar, mirthClientCoreJar, cliLibDir };

        List<URL> classpathUrls = new ArrayList<URL>();
        addManifestToClasspath(manifest, classpathUrls);
        addSharedLibsToClasspath(classpathUrls);
        URLClassLoader classLoader = new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]));
        Class<?> cliClass = classLoader.loadClass("com.mirth.connect.cli.CommandLineInterface");
        Constructor<?>[] constructors = cliClass.getDeclaredConstructors();

        for (int i = 0; i < constructors.length; i++) {
            Class<?> parameters[] = constructors[i].getParameterTypes();

            if (parameters.length == 1) {
                constructors[i].newInstance(new Object[] { args });
                i = constructors.length;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ffx.xray.TimerTest.java

public static void main(String args[]) {
    // Parameters collection from original Timer script
    String pdbname = System.getProperty("pdbFile", "1N7S.pdb");
    String mtzname = System.getProperty("mtzFile", null);
    String cifname = System.getProperty("cifFile", null);
    final boolean ciOnly = false;
    final String info = "SNARE complex";
    final double r = 19.412671496011;
    final double rfree = 21.555930987573;
    final double sigmaA = 0.9336853524690557;
    final double sigmaW = 0.13192537249786418;

    boolean ci = System.getProperty("ffx.ci", "false").equalsIgnoreCase("true");
    if (!ci && ciOnly) {
        crystalStats = null;/*from  w w  w .ja  v a2s. c o  m*/
        return;
    }

    int index = pdbname.lastIndexOf(".");
    String name = pdbname.substring(0, index);

    // load the structure
    MolecularAssembly molecularAssembly;
    File structure, mtzFile, cifFile;
    structure = new File(pdbname);
    PotentialsFileOpener opener = new PotentialsFileOpener(structure);
    opener.run();
    molecularAssembly = opener.getAssembly();
    mtzFile = new File(mtzname);
    cifFile = new File(cifname);

    // load any properties associated with it
    CompositeConfiguration properties = Keyword.loadProperties(structure);

    // read in Fo/sigFo/FreeR
    MTZFilter mtzFilter = new MTZFilter();
    CIFFilter cifFilter = new CIFFilter();
    Crystal crystal = Crystal.checkProperties(properties);
    Resolution resolution = Resolution.checkProperties(properties);
    if (crystal == null || resolution == null) {
        if (mtzname != null) {
            reflectionList = mtzFilter.getReflectionList(mtzFile);
        } else {
            reflectionList = cifFilter.getReflectionList(cifFile);
        }
    } else {
        reflectionList = new ReflectionList(crystal, resolution);
    }

    refinementData = new DiffractionRefinementData(properties, reflectionList);
    if (mtzname != null) {
        //            assertTrue(info + " mtz file should be read in without errors",
        //                    mtzFilter.readFile(mtzFile, reflectionList, refinementData,
        //                            properties));
    } else {
        //            assertTrue(info + " cif file should be read in without errors",
        //                    cifFilter.readFile(cifFile, reflectionList, refinementData,
        //                            properties));
    }

    ForceFieldFilter forceFieldFilter = new ForceFieldFilter(properties);
    ForceField forceField = forceFieldFilter.parse();

    // associate molecular assembly with the structure, set up forcefield
    molecularAssembly.setForceField(forceField);
    PDBFilter pdbFile = new PDBFilter(structure, molecularAssembly, forceField, properties);
    pdbFile.readFile();
    pdbFile.applyAtomProperties();
    molecularAssembly.finalize(true, forceField);
    ForceFieldEnergy energy = new ForceFieldEnergy(molecularAssembly, pdbFile.getCoordRestraints());

    List<Atom> atomList = molecularAssembly.getAtomList();
    Atom atomArray[] = atomList.toArray(new Atom[atomList.size()]);

    // set up FFT and run it
    parallelTeam = new ParallelTeam();
    CrystalReciprocalSpace crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam,
            parallelTeam, false);
    crs.computeDensity(refinementData.fc);
    refinementData.setCrystalReciprocalSpace_fc(crs);
    crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam, parallelTeam, true);
    crs.computeDensity(refinementData.fs);
    refinementData.setCrystalReciprocalSpace_fs(crs);

    ScaleBulkMinimize scaleBulkMinimize = new ScaleBulkMinimize(reflectionList, refinementData, crs,
            parallelTeam);
    scaleBulkMinimize.minimize(6, 1.0e-4);

    SigmaAMinimize sigmaAMinimize = new SigmaAMinimize(reflectionList, refinementData, parallelTeam);
    sigmaAMinimize.minimize(7, 2.0e-2);

    SplineMinimize splineMinimize = new SplineMinimize(reflectionList, refinementData, refinementData.spline,
            SplineEnergy.Type.FOFC);
    splineMinimize.minimize(7, 1e-5);

    crystalStats = new CrystalStats(reflectionList, refinementData);

    scaleBulkMinimize = new ScaleBulkMinimize(reflectionList, refinementData, refinementData.crs_fs,
            parallelTeam);
    ScaleBulkEnergy scaleBulkEnergy = scaleBulkMinimize.getScaleBulkEnergy();
    int n = scaleBulkMinimize.getNumberOfVariables();
    double x[] = new double[n];
    double g[] = new double[n];
    scaleBulkMinimize.getCoordinates(x);
    scaleBulkEnergy.energyAndGradient(x, g);

    double delta = 1.0e-4;
    double tolerance = 1.0e-4;

    logger.info(String.format("SCATTER TEST"));
    for (int i = 0; i < 30; i++) {
        long time = -System.nanoTime();
        scaleBulkEnergy.energyAndGradient(x, g);
        time += System.nanoTime();
        logger.info(String.format(" Time %12.8f", time * 1.0e-9));
    }
}

From source file:Main.java

public static void main(String[] args) {
    Main testJFrame = new Main();

    List<String> columns = new ArrayList<String>();
    List<String[]> values = new ArrayList<String[]>();

    columns.add("col1");
    columns.add("col2");
    columns.add("col3");

    for (int i = 0; i < 100; i++) {
        values.add(new String[] { "val" + i + " col1", "val" + i + " col2", "val" + i + " col3" });
    }// w  w w  .j  a  va 2  s . com

    TableModel tableModel = new DefaultTableModel(values.toArray(new Object[][] {}), columns.toArray());
    JTable table = new JTable(tableModel);
    testJFrame.setLayout(new BorderLayout());
    testJFrame.add(new JScrollPane(table), BorderLayout.CENTER);

    testJFrame.add(table.getTableHeader(), BorderLayout.NORTH);

    testJFrame.setVisible(true);
    testJFrame.setSize(200, 200);
}

From source file:com.spotify.helios.Utils.java

public static ByteArrayOutputStream main(final List<String> args) throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ByteArrayOutputStream err = new ByteArrayOutputStream();
    final CliMain main = new CliMain(new PrintStream(out), new PrintStream(err),
            args.toArray(new String[args.size()]));
    main.run();/*www .  jav a2  s .c  o m*/
    return out;
}

From source file:de.andrena.tools.macker.plugin.CommandLineFile.java

public static void main(String[] args) throws Exception {
    if (args.length == 0 || args.length > 2) {
        System.err.println("Usage: CommandLineFile <main class> [command line arguments file]");
        System.exit(1);/*from  ww  w. ja v  a2  s .  c o m*/
    }

    String className = args[0];
    Class<?> clazz = Class.forName(className);
    Method main = clazz.getMethod("main", new Class[] { String[].class });

    List<String> lines = new ArrayList<String>();
    if (args.length == 2) {
        Reader in = new InputStreamReader(new FileInputStream(args[1]), "UTF-8");
        try {
            lines = IOUtils.readLines(in);
        } finally {
            in.close();
        }
    }

    try {
        main.invoke(null, new Object[] { lines.toArray(new String[lines.size()]) });
    } catch (InvocationTargetException ex) {
        Throwable cause = ex.getTargetException();
        if (cause instanceof Error) {
            throw (Error) cause;
        }
        throw (Exception) cause;
    }
}

From source file:com.sliit.neuralnetwork.RecurrentNN.java

public static void main(String[] args) {

    RecurrentNN neural_network = new RecurrentNN();
    System.out.println("start=======================");
    try {//  ww w.  java2  s .  c  o  m
        neural_network.inputs = 10;
        neural_network.numHiddenNodes = 5;
        neural_network.HIDDEN_LAYER_COUNT = 2;
        neural_network.outputNum = 2;
        neural_network.buildModel();
        String output = neural_network.trainModel("nn", "D:/Data/originalnormkddaddeddata.csv", 2, 10);
        System.out.println("output " + output);

        System.out.println("Testing........................");
        Charset charset = Charset.forName("ISO-8859-1");
        Path wiki_path = Paths.get("D:/SLIIT/deadlocks/data/", "normtrainadded.csv");

        List<String> lines = Files.readAllLines(wiki_path, charset);
        String[] testDataArr = lines.toArray(new String[lines.size()]);

        Map<Integer, String> map = new HashMap<Integer, String>();

        String testOutput = neural_network.testModel("nn", testDataArr, map, 10, 2, "D:/Data/Test", "");
        System.out.println("Test output " + testOutput);
    } catch (Exception e) {
        e.printStackTrace();
    }
}