Example usage for java.util Vector toArray

List of usage examples for java.util Vector toArray

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public synchronized <T> T[] toArray(T[] a) 

Source Link

Document

Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.

Usage

From source file:MainClass.java

public static void main(String args[]) {
    Vector v1 = new Vector();
    v1.add("A");/*from www .j a va  2 s .c om*/
    v1.add("B");
    v1.add("C");
    String array[] = new String[0];
    array = (String[]) v1.toArray(array);

    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }
}

From source file:Main.java

public static void main(String args[]) {
    Vector<String> v1 = new Vector<String>();
    v1.add("A");//from   w w w .  j a  v  a  2 s  .c  o  m
    v1.add("B");
    v1.add("C");
    String array[] = new String[0];
    array = (String[]) v1.toArray(array);

    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }
}

From source file:Main.java

public static void main(String[] args) {
    Vector<Integer> vec = new Vector<Integer>(4);
    Integer[] anArray = new Integer[4];

    vec.add(4);/*from w  w  w . j a  v a 2 s. c  o m*/
    vec.add(3);
    vec.add(2);
    vec.add(1);

    // fill the array from the vector
    vec.toArray(anArray);

    for (int i = 0; i < anArray.length; i++) {
        System.out.println(anArray[i]);
    }
}

From source file:createSod.java

/**
 * @param args//from w w w.  j  av  a2  s.  c  o  m
 * @throws CMSException 
 */
public static void main(String[] args) throws Exception {

    try {
        CommandLine options = verifyArgs(args);
        String privateKeyLocation = options.getOptionValue("privatekey");
        String keyPassword = options.getOptionValue("keypass");
        String certificate = options.getOptionValue("certificate");
        String sodContent = options.getOptionValue("content");
        String sod = "";
        if (options.hasOption("out")) {
            sod = options.getOptionValue("out");
        }

        // CHARGEMENT DU FICHIER PKCS#12

        KeyStore ks = null;
        char[] password = null;

        Security.addProvider(new BouncyCastleProvider());
        try {
            ks = KeyStore.getInstance("PKCS12");
            // Password pour le fichier personnal_nyal.p12
            password = keyPassword.toCharArray();
            ks.load(new FileInputStream(privateKeyLocation), password);
        } catch (Exception e) {
            System.out.println("Erreur: fichier " + privateKeyLocation
                    + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
            return;
        }

        // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE

        X509Certificate cert = null;
        PrivateKey privatekey = null;
        PublicKey publickey = null;

        try {
            Enumeration en = ks.aliases();
            String ALIAS = "";
            Vector vectaliases = new Vector();

            while (en.hasMoreElements())
                vectaliases.add(en.nextElement());
            String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
            for (int i = 0; i < aliases.length; i++)
                if (ks.isKeyEntry(aliases[i])) {
                    ALIAS = aliases[i];
                    break;
                }
            privatekey = (PrivateKey) ks.getKey(ALIAS, password);
            cert = (X509Certificate) ks.getCertificate(ALIAS);
            publickey = ks.getCertificate(ALIAS).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Chargement du certificat  partir du fichier

        InputStream inStream = new FileInputStream(certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Chargement du fichier qui va tre sign

        File file_to_sign = new File(sodContent);
        byte[] buffer = new byte[(int) file_to_sign.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
        in.readFully(buffer);
        in.close();

        // Chargement des certificats qui seront stocks dans le fichier .p7
        // Ici, seulement le certificat personnal_nyal.cer sera associ.
        // Par contre, la chane des certificats non.

        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // privatekey correspond  notre cl prive rcupre du fichier PKCS#12
        // cert correspond au certificat publique personnal_nyal.cer
        // Le dernier argument est l'algorithme de hachage qui sera utilis

        signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        signGen.addCertificatesAndCRLs(certs);
        CMSProcessable content = new CMSProcessableByteArray(buffer);

        // Generation du fichier CMS/PKCS#7
        // L'argument deux permet de signifier si le document doit tre attach avec la signature
        //     Valeur true:  le fichier est attach (c'est le cas ici)
        //     Valeur false: le fichier est dtach

        CMSSignedData signedData = signGen.generate(content, true, "BC");
        byte[] signeddata = signedData.getEncoded();

        // Ecriture du buffer dans un fichier.   

        if (sod.equals("")) {
            System.out.print(signeddata.toString());
        } else {
            FileOutputStream envfos = new FileOutputStream(sod);
            envfos.write(signeddata);
            envfos.close();
        }

    } catch (OptionException oe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NAME, getOptions());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

}

From source file:it.acubelab.smaph.learn.GenerateModel.java

public static void main(String[] args) throws Exception {
    Locale.setDefault(Locale.US);
    String freebKey = "";

    SmaphConfig.setConfigFile("smaph-config.xml");
    String bingKey = SmaphConfig.getDefaultBingKey();

    WikipediaApiInterface wikiApi = new WikipediaApiInterface("wid.cache", "redirect.cache");
    FreebaseApi freebApi = new FreebaseApi(freebKey, "freeb.cache");
    double[][] paramsToTest = new double[][] {
            /*//w w w  .  jav a 2  s.c o  m
             * {0.035, 0.5 }, {0.035, 1 }, {0.035, 4 }, {0.035, 8 }, {0.035, 10 },
             * {0.035, 16 }, {0.714, .5 }, {0.714, 1 }, {0.714, 4 }, {0.714, 8 },
             * {0.714, 10 }, {0.714, 16 }, {0.9, .5 }, {0.9, 1 }, {0.9, 4 }, {0.9, 8
             * }, {0.9, 10 }, {0.9, 16 },
             * 
             * { 1.0/15.0, 1 }, { 1.0/27.0, 1 },
             */

            /*
             * {0.01, 1}, {0.01, 5}, {0.01, 10}, {0.03, 1}, {0.03, 5}, {0.03, 10},
             * {0.044, 1}, {0.044, 5}, {0.044, 10}, {0.06, 1}, {0.06, 5}, {0.06,
             * 10},
             */
            { 0.03, 5 }, };
    double[][] weightsToTest = new double[][] {

            /*
             * { 3, 4 }
             */
            { 3.8, 3 }, { 3.8, 4 }, { 3.8, 5 }, { 3.8, 6 }, { 3.8, 7 }, { 3.8, 8 }, { 3.8, 9 }, { 3.8, 10 },

    };
    Integer[][] featuresSetsToTest = new Integer[][] {
            //{ 1, 2, 3, 6, 7, 8,   9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 },
            { 1, 2, 3, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 },
            /*
             * { 1, 2, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18},
             */

    }; // < -------------------------------------- MIND THIS
    int wikiSearckTopK = 10; // <---------------------------
    String filePrefix = "_ANW";// <---------------------------

    WikipediaToFreebase wikiToFreebase = new WikipediaToFreebase("mapdb");
    List<ModelConfigurationResult> mcrs = new Vector<>();
    for (double editDistanceThr = 0.7; editDistanceThr <= 0.7; editDistanceThr += 0.7) {
        SmaphAnnotator bingAnnotator = GenerateTrainingAndTest.getDefaultBingAnnotator(wikiApi, wikiToFreebase,
                editDistanceThr, wikiSearckTopK, bingKey);
        WATAnnotator.setCache("wikisense.cache");
        SmaphAnnotator.setCache(SmaphConfig.getDefaultBingCache());

        BinaryExampleGatherer trainEntityFilterGatherer = new BinaryExampleGatherer();
        BinaryExampleGatherer testEntityFilterGatherer = new BinaryExampleGatherer();
        GenerateTrainingAndTest.gatherExamplesTrainingAndDevel(bingAnnotator, trainEntityFilterGatherer,
                testEntityFilterGatherer, wikiApi, wikiToFreebase, freebApi);

        SmaphAnnotator.unSetCache();
        BinaryExampleGatherer trainGatherer = trainEntityFilterGatherer; // //////////////
        // <----------------------
        BinaryExampleGatherer testGatherer = testEntityFilterGatherer; // //////////////
        // <----------------------

        int count = 0;
        for (Integer[] ftrToTestArray : featuresSetsToTest) {
            // double gamma = 1.0 / ftrToTestArray.length; //
            // <--------------------- MIND THIS
            // double C = 1;// < -------------------------------------- MIND
            // THIS
            for (double[] paramsToTestArray : paramsToTest) {
                double gamma = paramsToTestArray[0];
                double C = paramsToTestArray[1];
                for (double[] weightsPosNeg : weightsToTest) {
                    double wPos = weightsPosNeg[0], wNeg = weightsPosNeg[1];
                    Vector<Integer> features = new Vector<>(Arrays.asList(ftrToTestArray));
                    Triple<svm_problem, double[], double[]> ftrsMinsMaxs = TuneModel
                            .getScaledTrainProblem(features, trainGatherer);
                    svm_problem trainProblem = ftrsMinsMaxs.getLeft();

                    String fileBase = getModelFileNameBaseEF(features.toArray(new Integer[0]), wPos, wNeg,
                            editDistanceThr, gamma, C) + filePrefix;
                    /*
                     * String fileBase = getModelFileNameBaseEQF(
                     * features.toArray(new Integer[0]), wPos, wNeg);
                     */// < -------------------------
                    LibSvmUtils.dumpRanges(ftrsMinsMaxs.getMiddle(), ftrsMinsMaxs.getRight(),
                            fileBase + ".range");
                    svm_model model = TuneModel.trainModel(wPos, wNeg, features, trainProblem, gamma, C);
                    svm.svm_save_model(fileBase + ".model", model);

                    MetricsResultSet metrics = TuneModel.ParameterTester.computeMetrics(model,
                            TuneModel.getScaledTestProblems(features, testGatherer, ftrsMinsMaxs.getMiddle(),
                                    ftrsMinsMaxs.getRight()));

                    int tp = metrics.getGlobalTp();
                    int fp = metrics.getGlobalFp();
                    int fn = metrics.getGlobalFn();
                    float microF1 = metrics.getMicroF1();
                    float macroF1 = metrics.getMacroF1();
                    float macroRec = metrics.getMacroRecall();
                    float macroPrec = metrics.getMacroPrecision();
                    int totVects = testGatherer.getExamplesCount();
                    mcrs.add(new ModelConfigurationResult(features, wPos, wNeg, editDistanceThr, tp, fp, fn,
                            totVects - tp - fp - fn, microF1, macroF1, macroRec, macroPrec));

                    System.err.printf("Trained %d/%d models.%n", ++count,
                            weightsToTest.length * featuresSetsToTest.length * paramsToTest.length);
                }
            }
        }
    }
    for (ModelConfigurationResult mcr : mcrs)
        System.out.printf("%.5f%%\t%.5f%%\t%.5f%%%n", mcr.getMacroPrecision() * 100, mcr.getMacroRecall() * 100,
                mcr.getMacroF1() * 100);
    for (double[] weightPosNeg : weightsToTest)
        System.out.printf("%.5f\t%.5f%n", weightPosNeg[0], weightPosNeg[1]);
    for (ModelConfigurationResult mcr : mcrs)
        System.out.println(mcr.getReadable());
    for (double[] paramGammaC : paramsToTest)
        System.out.printf("%.5f\t%.5f%n", paramGammaC[0], paramGammaC[1]);
    WATAnnotator.flush();
}

From source file:org.kchine.r.server.CoreMain.java

public static void main(String[] args) throws Exception {
    PoolUtils.initLog4J();// w  w  w.j  a v  a  2  s  .co  m

    if (System.getProperty("rmi.port.start") != null && !System.getProperty("rmi.port.start").equals("")) {

        int width = 300;
        if (System.getProperty("submit.ssh.rmi.port.width") != null
                && !System.getProperty("submit.ssh.rmi.port.width").equals("")) {
            width = Integer.decode(System.getProperty("submit.ssh.rmi.port.width"));
        }

        int rmi_port_start = Integer.decode(System.getProperty("rmi.port.start"));
        Integer valid_port = null;
        for (int i = 0; i < (width / RServantImpl.PORT_RANGE_WIDTH); ++i) {
            try {
                ServerSocket s = new ServerSocket(rmi_port_start + i * RServantImpl.PORT_RANGE_WIDTH);
                s.close();
                valid_port = rmi_port_start + i * RServantImpl.PORT_RANGE_WIDTH;
                break;
            } catch (Exception e) {
            }
        }
        if (valid_port == null) {
            log.info("all available ports are taken, can't create server");
            System.exit(0);
        }

        System.setProperty("rmi.port.start", "" + valid_port);
        log.info("rmi.port.start:" + System.getProperty("rmi.port.start"));
    }

    Vector<URL> codeUrls = new Vector<URL>();
    if (args.length > 0) {
        for (int i = 0; i < args.length; ++i) {
            codeUrls.add(new URL(args[i]));
        }
    } else {
        /*
        String jar = CoreMain.class.getResource("/org/kchine/r/server/CoreMain.class").toString();
        if (jar.startsWith("jar:")) {
           String jarfile = jar.substring("jar:".length(), jar.length() - "/org/kchine/r/server/CoreMain.class".length() - 1);
           System.out.println("jarfile:" + jarfile);
           try {
              codeUrls.add(new URL(jarfile));
           } catch (Exception e) {
              e.printStackTrace();
           }
        }
        */
    }

    boolean wait = System.getProperty("wait") == null || System.getProperty("wait").equals("")
            || new Boolean(System.getProperty("wait"));

    RServices r = null;

    if (ServerDefaults.isRegistryAccessible()) {
        String name = System.getProperty("name");
        String rbinary = System.getProperty("r.binary");
        r = ServerManager.createR(rbinary, false, wait ? false : true, PoolUtils.getHostIp(),
                LocalHttpServer.getLocalHttpServerPort(), ServerManager.getNamingInfo(),
                ServerDefaults._memoryMin, ServerDefaults._memoryMax, name, false,
                (URL[]) codeUrls.toArray(new URL[0]), System.getProperty("log.file"), "standard",
                new Runnable() {
                    public void run() {
                        System.exit(0);
                    }
                }, null);

    } else {
        System.out.println("Can't Launch R Server, Rmi Registry is not accessible!!");
    }

    /*
     * inet httpServerPort=-1; try { if
     * (System.getProperty("http.port")!=null &&
     * !System.getProperty("http.port").equals("")) {
     * httpServerPort=Integer.decode(System.getProperty("http.port")); } }
     * catch (Exception e) {} if (httpServerPort!=-1) {
     * r.startHttpServer(httpServerPort); }
     */

    if (wait) {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {
            }
        }
    } else {
        System.exit(0);
    }
}

From source file:org.apache.nutch.tools.PruneIndexTool.java

public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        usage();/*from   w  w  w  .  j  ava 2  s  .c o  m*/
        if (LOG.isFatalEnabled()) {
            LOG.fatal("Missing arguments");
        }
        return;
    }
    File idx = new File(args[0]);
    if (!idx.isDirectory()) {
        usage();
        if (LOG.isFatalEnabled()) {
            LOG.fatal("Not a directory: " + idx);
        }
        return;
    }
    Vector<File> paths = new Vector<File>();
    if (IndexReader.indexExists(FSDirectory.open(idx))) {
        paths.add(idx);
    } else {
        // try and see if there are segments inside, with index dirs
        File[] dirs = idx.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory();
            }
        });
        if (dirs == null || dirs.length == 0) {
            usage();
            if (LOG.isFatalEnabled()) {
                LOG.fatal("No indexes in " + idx);
            }
            return;
        }
        for (int i = 0; i < dirs.length; i++) {
            File sidx = new File(dirs[i], "index");
            if (sidx.exists() && sidx.isDirectory() && IndexReader.indexExists(FSDirectory.open(sidx))) {
                paths.add(sidx);
            }
        }
        if (paths.size() == 0) {
            usage();
            if (LOG.isFatalEnabled()) {
                LOG.fatal("No indexes in " + idx + " or its subdirs.");
            }
            return;
        }
    }
    File[] indexes = paths.toArray(new File[0]);
    boolean force = false;
    boolean dryrun = false;
    String qPath = null;
    String outPath = null;
    String fList = null;
    for (int i = 1; i < args.length; i++) {
        if (args[i].equals("-force")) {
            force = true;
        } else if (args[i].equals("-queries")) {
            qPath = args[++i];
        } else if (args[i].equals("-output")) {
            outPath = args[++i];
        } else if (args[i].equals("-showfields")) {
            fList = args[++i];
        } else if (args[i].equals("-dryrun")) {
            dryrun = true;
        } else {
            usage();
            if (LOG.isFatalEnabled()) {
                LOG.fatal("Unrecognized option: " + args[i]);
            }
            return;
        }
    }
    Vector<PruneChecker> cv = new Vector<PruneChecker>();
    if (fList != null) {
        StringTokenizer st = new StringTokenizer(fList, ",");
        Vector<String> tokens = new Vector<String>();
        while (st.hasMoreTokens())
            tokens.add(st.nextToken());
        String[] fields = tokens.toArray(new String[0]);
        PruneChecker pc = new PrintFieldsChecker(System.out, fields);
        cv.add(pc);
    }

    if (outPath != null) {
        StoreUrlsChecker luc = new StoreUrlsChecker(new File(outPath), false);
        cv.add(luc);
    }

    PruneChecker[] checkers = null;
    if (cv.size() > 0) {
        checkers = cv.toArray(new PruneChecker[0]);
    }
    Query[] queries = null;
    InputStream is = null;
    if (qPath != null) {
        is = new FileInputStream(qPath);
    } else {
        Configuration conf = NutchConfiguration.create();
        qPath = conf.get("prune.index.tool.queries");
        is = conf.getConfResourceAsInputStream(qPath);
    }
    if (is == null) {
        if (LOG.isFatalEnabled()) {
            LOG.fatal("Can't load queries from " + qPath);
        }
        return;
    }
    try {
        queries = parseQueries(is);
    } catch (Exception e) {
        if (LOG.isFatalEnabled()) {
            LOG.fatal("Error parsing queries: " + e.getMessage());
        }
        return;
    }
    try {
        PruneIndexTool pit = new PruneIndexTool(indexes, queries, checkers, force, dryrun);
        pit.run();
    } catch (Exception e) {
        if (LOG.isFatalEnabled()) {
            LOG.fatal("Error running PruneIndexTool: " + e.getMessage());
        }
        return;
    }
}

From source file:Cresendo.java

public static void main(String[] args) {
    String cfgFileReceiver = null; // Path to config file for eif receiver agent
    String cfgFileEngine = null; // Path to config file for xml event engine
    Options opts = null; // Command line options
    HelpFormatter hf = null; // Command line help formatter

    // Setup the message record which will contain text written to the log file
    ////from w w  w  .  j a v a  2 s .co  m
    // The message logger object is created when the "-l" is processed
    // as this object need to be associated with a log file
    //
    LogRecord msg = new LogRecord(LogRecord.TYPE_INFO, "Cresendo", "main", "", "", "", "", "");

    // Get the directory separator (defaults to "/")
    //
    dirSep = System.getProperty("file.separator", "/");

    // Initialise the structure containing the event handler objects
    //
    Vector<IEventHandler> eventHandler = new Vector<IEventHandler>(10, 10);

    // Process the command line arguments
    //
    try {
        opts = new Options();
        hf = new HelpFormatter();

        opts.addOption("h", "help", false, "Command line arguments help");
        opts.addOption("i", "instance name", true, "Name of cresendo instance");
        opts.addOption("l", "log dir", true, "Path to log file directory");
        opts.addOption("c", "config dir", true, "Path to configuarion file directory");

        opts.getOption("l").setRequired(true);
        opts.getOption("c").setRequired(true);

        BasicParser parser = new BasicParser();
        CommandLine cl = parser.parse(opts, args);

        // Print out some help and exit
        //
        if (cl.hasOption('h')) {
            hf.printHelp("Options", opts);
            System.exit(0);
        }

        // Set the instance name
        //
        if (cl.hasOption('i')) {
            instanceName = cl.getOptionValue('i'); // Set to something other than "default"
        }

        // Setup the message and trace logging objects for the EventEngine
        //
        if (cl.hasOption('l')) {
            // Setup the the paths to the message, trace and status log files
            //
            logDir = cl.getOptionValue("l");

            logPath = logDir + dirSep + instanceName + "-engine.log";
            tracePath = logDir + dirSep + instanceName + "-engine.trace";
            statusPath = logDir + dirSep + instanceName + "-engine.status";
        } else {
            // NOTE:  This should be picked up by the MissingOptionException catch below
            //        but I couldn't get this to work so I added the following code:
            //
            hf.printHelp("Option 'l' is a required option", opts);
            System.exit(1);
        }

        // Read the receiver and engine config files in the config directory
        //
        if (cl.hasOption('c')) {
            // Setup and check path to eif config file for TECAgent receiver object
            //
            configDir = cl.getOptionValue("c");
            cfgFileReceiver = configDir + dirSep + instanceName + ".conf";
            checkConfigFile(cfgFileReceiver);

            // Setup and check path to xml config file for the EventEngine
            //
            cfgFileEngine = cl.getOptionValue("c") + dirSep + instanceName + ".xml";
            checkConfigFile(cfgFileEngine);

        } else {
            // NOTE:  This should be picked up by the MissingOptionException catch below
            //        but I couldn't get this to work so I added the following code:
            //
            hf.printHelp("Option 'c' is a required option", opts);
            System.exit(1);
        }
    } catch (UnrecognizedOptionException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (MissingOptionException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (MissingArgumentException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(1);
    } catch (Exception e) {
        System.err.println(e.toString());
        System.exit(1);
    }

    // Main program
    //
    try {
        // =====================================================================
        // Setup the message, trace and status logger objects
        //
        try {
            msgHandler = new FileHandler("cresendo", "message handler", logPath);
            msgHandler.openDevice();

            msgLogger = new MessageLogger("cresendo", "message log");
            msgLogger.addHandler(msgHandler);

            trcHandler = new FileHandler("cresendo", "trace handler", tracePath);
            trcHandler.openDevice();

            trcLogger = new TraceLogger("cresendo", "trace log");
            trcLogger.addHandler(trcHandler);

            statLogger = new StatusLogger(statusPath);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // Add the shutdown hook
        //
        Runtime.getRuntime().addShutdownHook(new ShutdownThread(msgLogger, instanceName));

        // ---------------------------------------------------------------------
        // =====================================================================
        // Load and parse the xml event engine configuration file
        //
        //
        msg.setText("Loading xml engine from: '" + cfgFileEngine + "'");

        try {
            XMLConfiguration xmlProcessor = new XMLConfiguration();
            xmlProcessor.setFileName(cfgFileEngine);

            // Validate the xml against a document type declaration
            //
            xmlProcessor.setValidating(true);

            // Don't interpolate the tag contents by splitting them on a delimiter
            // (ie by default a comma)
            //
            xmlProcessor.setDelimiterParsingDisabled(true);

            // This will throw a ConfigurationException if the xml document does not
            // conform to its dtd.  By doing this we hopefully catch any errors left
            // behind after the xml configuration file has been edited.
            //
            xmlProcessor.load();

            // Setup the trace flag
            //
            ConfigurationNode engine = xmlProcessor.getRootNode();
            List rootAttribute = engine.getAttributes();

            for (Iterator it = rootAttribute.iterator(); it.hasNext();) {
                ConfigurationNode attr = (ConfigurationNode) it.next();

                String attrName = attr.getName();
                String attrValue = (String) attr.getValue();

                if (attrValue == null || attrValue == "") {
                    System.err.println("\n  Error: The value of the attribute '" + attrName + "'"
                            + "\n         in the xml file '" + cfgFileEngine + "'" + "\n         is not set");
                    System.exit(1);
                }

                if (attrName.matches("trace")) {
                    if (attrValue.matches("true") || attrValue.matches("on")) {
                        trcLogger.setLogging(true);
                    }
                }

                if (attrName.matches("status")) {
                    if (attrValue.matches("true") || attrValue.matches("on")) {
                        statLogger.setLogging(true);
                    } else {
                        statLogger.setLogging(false);
                    }
                }

                if (attrName.matches("interval")) {
                    if (!attrValue.matches("[0-9]+")) {
                        System.err.println("\n  Error: The value of the interval attribute in: '"
                                + cfgFileEngine + "'" + "\n         should only contain digits from 0 to 9."
                                + "\n         It currently contains: '" + attrValue + "'");
                        System.exit(1);
                    }

                    statLogger.setInterval(Integer.parseInt(attrValue));
                }
            }

            // Now build and instantiate the list of classes that will process events
            // received by the TECAgent receiver in a chain like manner.
            //
            List classes = xmlProcessor.configurationsAt("class");

            for (Iterator it = classes.iterator(); it.hasNext();) {
                HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();

                // sub contains now all data contained in a single <class></class> tag set
                //
                String className = sub.getString("name");

                // Log message
                //
                msg.setText(msg.getText() + "\n  Instantiated event handler class: '" + className + "'");

                // The angle brackets describing the class of object held by the
                // Vector are implemented by Java 1.5 and have 2 effects.
                //
                // 1. The list accepts only elements of that class and nothing else
                // (Of course thanks to Auto-Wrap you can also add double-values)
                //
                // 2. the get(), firstElement() ... Methods don't return a Object, but
                //    they deliver an element of the class.
                //
                Vector<Class> optTypes = new Vector<Class>(10, 10);
                Vector<Object> optValues = new Vector<Object>(10, 10);

                for (int i = 0; i <= sub.getMaxIndex("option"); i++) {
                    Object optValue = null;
                    String optVarName = sub.getString("option(" + i + ")[@varname]");
                    String optJavaType = sub.getString("option(" + i + ")[@javatype]");

                    // Use the specified java type in order to make the method call
                    // to the heirarchical sub object [painful :-((]
                    //
                    if (optJavaType.matches("byte")) {
                        optTypes.addElement(byte.class);
                        optValue = sub.getByte("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("short")) {
                        optTypes.addElement(byte.class);
                        optValue = sub.getShort("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("int")) {
                        optTypes.addElement(int.class);
                        optValue = sub.getInt("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("long")) {
                        optTypes.addElement(long.class);
                        optValue = sub.getLong("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("float")) {
                        optTypes.addElement(float.class);
                        optValue = sub.getFloat("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0.0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("double")) {
                        optTypes.addElement(double.class);
                        optValue = sub.getDouble("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0.0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("boolean")) {
                        optTypes.addElement(boolean.class);
                        optValue = sub.getBoolean("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = false; // Set to something nullish
                        }
                    } else if (optJavaType.matches("String")) {
                        optTypes.addElement(String.class);
                        optValue = sub.getString("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = ""; // Set it to something nullish
                        }
                    } else {
                        System.err.println(
                                "Error: Unsupported java type found in xml config: '" + optJavaType + "'");
                        System.exit(1);
                    }

                    // Add option value element
                    //
                    //              System.out.println("Option value is: '" + optValue.toString() + "'\n");
                    //
                    optValues.addElement(optValue);

                    // Append to message text
                    //
                    String msgTemp = msg.getText();
                    msgTemp += "\n      option name: '" + optVarName + "'";
                    msgTemp += "\n      option type: '" + optJavaType + "'";
                    msgTemp += "\n     option value: '" + optValues.lastElement().toString() + "'";
                    msg.setText(msgTemp);
                }

                try {
                    // Instantiate the class with the java reflection api
                    //
                    Class klass = Class.forName(className);

                    // Setup an array of paramater types in order to retrieve the matching constructor
                    //
                    Class[] types = optTypes.toArray(new Class[optTypes.size()]);

                    // Get the constructor for the class which matches the parameter types
                    //
                    Constructor konstruct = klass.getConstructor(types);

                    // Create an instance of the event handler
                    //
                    IEventHandler eventProcessor = (IEventHandler) konstruct.newInstance(optValues.toArray());

                    // Add the instance to the list of event handlers
                    //
                    eventHandler.addElement(eventProcessor);

                } catch (InvocationTargetException e) {
                    System.err.println("Error: " + e.toString());
                    System.exit(1);
                } catch (ClassNotFoundException e) {
                    System.err.println("Error: class name not found: '" + className + "' \n" + e.toString());
                    System.exit(1);
                } catch (Exception e) {
                    System.err.println(
                            "Error: failed to instantiate class: '" + className + "' \n" + e.toString());
                    System.exit(1);
                }
            }
        } catch (ConfigurationException cex) // Something went wrong loading the xml file
        {
            System.err.println("\n" + "Error loading XML file: " + cfgFileEngine + "\n" + cex.toString());
            System.exit(1);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // ---------------------------------------------------------------------
        // =====================================================================
        // Setup the TECAgent receiver 
        // 
        Reader cfgIn = null;

        try {
            cfgIn = new FileReader(cfgFileReceiver);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // Start the TECAgent receiver and register the event engine handler
        //
        TECAgent receiver = new TECAgent(cfgIn, TECAgent.RECEIVER_MODE, false);

        EventEngine ee = new EventEngine(eventHandler, msgLogger, trcLogger);

        receiver.registerListener(ee);

        // Construct message and send it to the message log
        //
        String text = "\n  Cresendo instance '" + instanceName + "' listening for events on port '"
                + receiver.getConfigVal("ServerPort") + "'";

        msg.setText(msg.getText() + text);
        msgLogger.log(msg); // Send message to log

        // ---------------------------------------------------------------------
        // =====================================================================
        // Initiate status logging
        //
        if (statLogger.isLogging()) {
            int seconds = statLogger.getInterval();

            while (true) {
                try {
                    statLogger.log();
                } catch (Exception ex) {
                    System.err.println("\n  An error occurred while writing to '" + statusPath + "'" + "\n  '"
                            + ex.toString() + "'");
                }

                Thread.sleep(seconds * 1000); // Convert sleep time to milliseconds
            }
        }

        // ---------------------------------------------------------------------
    } catch (Exception e) {
        System.err.println(e.toString());
        System.exit(1);
    }
}

From source file:Main.java

public static String[] getPuzzleFiles(Context context) {
    String[] files = context.fileList();
    Vector<String> puzzleFiles = new Vector<String>();
    for (String file : files)
        if (file.endsWith(".pfy"))
            puzzleFiles.add(file);/*from   www.j  ava 2 s . co m*/
    String[] ret = new String[0];
    return puzzleFiles.toArray(ret);
}

From source file:Main.java

public static synchronized Node[] getChildNodes(Node node) {
    if (node == null) {
        return null;
    }//from   w  ww  . jav  a2s.c  o m
    Vector childs = new Vector();
    for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling()) {
        childs.add((Element) n);
    }
    Node[] childNodes = new Element[childs.size()];
    childs.toArray(childNodes);
    return childNodes;
}