Example usage for java.lang String length

List of usage examples for java.lang String length

Introduction

In this page you can find the example usage for java.lang String length.

Prototype

public int length() 

Source Link

Document

Returns the length of this string.

Usage

From source file:edu.nyu.tandon.tool.RawHits.java

@SuppressWarnings("unchecked")
public static void main(final String[] arg) throws Exception {

    SimpleJSAP jsap = new SimpleJSAP(RawHits.class.getName(),
            "Loads indices relative to a collection, possibly loads the collection, and answers to queries.",
            new Parameter[] {
                    new FlaggedOption("collection", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'c',
                            "collection", "The collection of documents indexed by the given indices."),
                    new FlaggedOption("objectCollection",
                            new ObjectParser(DocumentCollection.class, MG4JClassParser.PACKAGE),
                            JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o', "object-collection",
                            "An object specification describing a document collection."),
                    new FlaggedOption("titleList", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 't',
                            "title-list",
                            "A serialized big list of titles (will override collection titles if specified)."),
                    new FlaggedOption("titleFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'T',
                            "title-file",
                            "A file of newline-separated, UTF-8 titles (will override collection titles if specified)."),
                    new FlaggedOption("input", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'I', "input",
                            "A file containing the input."),
                    new Switch("noSizes", 'n', "no-sizes",
                            "Disable loading document sizes (they are necessary for BM25 scoring)."),
                    new Switch("http", 'h', "http", "Starts an HTTP query server."),
                    new Switch("verbose", 'v', "verbose", "Print full exception stack traces."),
                    new FlaggedOption("itemClass", MG4JClassParser.getParser(), JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'i', "item-class",
                            "The class that will handle item display in the HTTP server."),
                    new FlaggedOption("itemMimeType", JSAP.STRING_PARSER, "text/html", JSAP.NOT_REQUIRED, 'm',
                            "item-mime-type",
                            "A MIME type suggested to the class handling item display in the HTTP server."),
                    new FlaggedOption("port", JSAP.INTEGER_PARSER, "4242", JSAP.NOT_REQUIRED, 'p', "port",
                            "The port on localhost where the server will appear."),
                    new UnflaggedOption("basenameWeight", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.GREEDY,
                            "The indices that the servlet will use. Indices are specified using their basename, optionally followed by a colon and a double representing the weight used to score results from that index. Indices without a specified weight are weighted 1."),

                    new Switch("noMplex", 'P', "noMplex", "Starts with multiplex disabled."),
                    new FlaggedOption("results", JSAP.INTEGER_PARSER, "1000", JSAP.NOT_REQUIRED, 'r', "results",
                            "The # of results to display"),
                    new FlaggedOption("mode", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'M',
                            "time", "The results display mode"),
                    new FlaggedOption("divert", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'd',
                            "divert", "output file"),
                    new FlaggedOption("dumpsize", JSAP.INTEGER_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'D',
                            "dumpsize", "number of queries before dumping")

            });//from  w  w  w . j  av a2s.c  om

    final JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        return;

    final DocumentCollection documentCollection = (DocumentCollection) (jsapResult.userSpecified("collection")
            ? AbstractDocumentSequence.load(jsapResult.getString("collection"))
            : jsapResult.userSpecified("objectCollection") ? jsapResult.getObject("objectCollection") : null);
    final BigList<? extends CharSequence> titleList = (BigList<? extends CharSequence>) (jsapResult
            .userSpecified("titleList")
                    ? BinIO.loadObject(jsapResult.getString("titleList"))
                    : jsapResult.userSpecified("titleFile")
                            ? new FileLinesBigList(jsapResult.getString("titleFile"), "UTF-8")
                            : null);
    final String[] basenameWeight = jsapResult.getStringArray("basenameWeight");
    final Object2ReferenceLinkedOpenHashMap<String, Index> indexMap = new Object2ReferenceLinkedOpenHashMap<String, Index>(
            Hash.DEFAULT_INITIAL_SIZE, .5f);
    final Reference2DoubleOpenHashMap<Index> index2Weight = new Reference2DoubleOpenHashMap<Index>();
    final boolean verbose = jsapResult.getBoolean("verbose");
    final boolean loadSizes = !jsapResult.getBoolean("noSizes");
    RawHits.loadIndicesFromSpec(basenameWeight, loadSizes, documentCollection, indexMap, index2Weight);

    final long numberOfDocuments = indexMap.values().iterator().next().numberOfDocuments;
    if (titleList != null && titleList.size64() != numberOfDocuments)
        throw new IllegalArgumentException("The number of titles (" + titleList.size64()
                + " and the number of documents (" + numberOfDocuments + ") do not match");

    final Object2ObjectOpenHashMap<String, TermProcessor> termProcessors = new Object2ObjectOpenHashMap<String, TermProcessor>(
            indexMap.size());
    for (String alias : indexMap.keySet())
        termProcessors.put(alias, indexMap.get(alias).termProcessor);

    final SimpleParser simpleParser = new SimpleParser(indexMap.keySet(), indexMap.firstKey(), termProcessors);

    final Reference2ReferenceMap<Index, Object> index2Parser = new Reference2ReferenceOpenHashMap<Index, Object>();
    /*
    // Fetch parsers for payload-based fields.
    for( Index index: indexMap.values() ) if ( index.hasPayloads ) {
     if ( index.payload.getClass() == DatePayload.class ) index2Parser.put( index, DateFormat.getDateInstance( DateFormat.SHORT, Locale.UK ) );
    }
    */

    final HitsQueryEngine queryEngine = new HitsQueryEngine(simpleParser, new DocumentIteratorBuilderVisitor(
            indexMap, index2Parser, indexMap.get(indexMap.firstKey()), MAX_STEMMING), indexMap);
    queryEngine.setWeights(index2Weight);
    queryEngine.score(new Scorer[] { new BM25Scorer(), new VignaScorer() }, new double[] { 1, 1 });

    queryEngine.multiplex = !jsapResult.userSpecified("moPlex") || jsapResult.getBoolean("noMplex");
    queryEngine.intervalSelector = null;
    queryEngine.equalize(1000);

    RawHits query = new RawHits(queryEngine);

    // start docHits with at least 10K results
    query.interpretCommand("$score BM25Scorer");
    //        query.interpretCommand("$mode time");

    if (jsapResult.userSpecified("divert"))
        query.interpretCommand("$divert " + jsapResult.getObject("divert"));

    query.displayMode = OutputType.DOCHHITS;
    query.maxOutput = jsapResult.getInt("results", 1000);

    String q;
    int n = 0;

    String lastQ = "";

    try {
        final BufferedReader br = new BufferedReader(
                new InputStreamReader(new FileInputStream(jsapResult.getString("input"))));

        final ObjectArrayList<DocumentScoreInfo<ObjectArrayList<Byte>>> results = new ObjectArrayList<DocumentScoreInfo<ObjectArrayList<Byte>>>();

        for (;;) {
            q = br.readLine();
            if (q == null) {
                System.err.println();
                break; // CTRL-D
            }
            if (q.length() == 0)
                continue;
            if (q.charAt(0) == '$') {
                if (!query.interpretCommand(q))
                    break;
                continue;
            }

            queryCount++;
            long time = -System.nanoTime();
            if (q.compareTo(lastQ) != 0) {
                try {
                    n = queryEngine.process(q, 0, query.maxOutput, results);
                } catch (QueryParserException e) {
                    if (verbose)
                        e.getCause().printStackTrace(System.err);
                    else
                        System.err.println(e.getCause());
                    continue;
                } catch (Exception e) {
                    if (verbose)
                        e.printStackTrace(System.err);
                    else
                        System.err.println(e);
                    continue;
                }
                lastQ = q;
            }
            time += System.nanoTime();
            query.output(results, documentCollection, titleList, TextMarker.TEXT_BOLDFACE);
        }
    } finally {
    }
}

From source file:de.gbv.ole.Marc21ToOleBulk.java

/**
 * Convertiert eine MARC21-Datei in eine MarcXML-Bulk-Import-SQL-Datei.
 * @param args      Pfad mit auf .mrc endendem Dateinamen der MARC21-Datei.
 * @throws IOException      Fehler beim Dateilesen oder -schreiben
 */// w  w w  .  jav  a2  s  .co  m
public static void main(final String[] args) throws IOException {
    if (args.length < 1 || args.length > 2) {
        usageExit();
    }

    boolean ppn5 = false;
    if (args.length == 2) {
        if ("-5".equals(args[0])) {
            ppn5 = true;
        } else {
            usageExit();
        }
    }
    String infile = args[args.length - 1];

    if (!infile.endsWith(MRCSUFFIX)) {
        System.err.println("Filename ending in .mrc expected, " + "but found filename: " + infile);
        usageExit();
    }

    InputStream in = new FileInputStream(infile);
    MarcStreamReader reader = new MarcStreamReader(in);

    String filename = infile.substring(0, infile.length() - MRCSUFFIX.length());
    Writer bib = utf8Writer(filename + "-bib.sql");
    Writer holdings = utf8Writer(filename + "-holdings.sql");
    Writer item = utf8Writer(filename + "-item.sql");

    while (reader.hasNext()) {
        MarcWriter writer = new Marc21ToOleBulk(bib, holdings, item, ppn5);
        writer.write(reader.next());
        writer.close();
    }

    in.close();
    item.close();
    holdings.close();
    bib.close();
}

From source file:com.liferay.nativity.test.TestDriver.java

public static void main(String[] args) {
    _intitializeLogging();/*from  ww w  . j a  v a 2s .  c  o m*/

    List<String> items = new ArrayList<String>();

    items.add("ONE");

    NativityMessage message = new NativityMessage("BLAH", items);

    try {
        _logger.debug(_objectMapper.writeValueAsString(message));
    } catch (JsonProcessingException jpe) {
        _logger.error(jpe.getMessage(), jpe);
    }

    _logger.debug("main");

    NativityControl nativityControl = NativityControlUtil.getNativityControl();

    FileIconControl fileIconControl = FileIconControlUtil.getFileIconControl(nativityControl,
            new TestFileIconControlCallback());

    ContextMenuControlUtil.getContextMenuControl(nativityControl, new TestContextMenuControlCallback());

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

    nativityControl.connect();

    String read = "";
    boolean stop = false;

    try {
        while (!stop) {
            _list = !_list;

            _logger.debug("Loop start...");

            _logger.debug("_enableFileIcons");
            _enableFileIcons(fileIconControl);

            _logger.debug("_registerFileIcon");
            _registerFileIcon(fileIconControl);

            _logger.debug("_setFilterPath");
            _setFilterPath(nativityControl);

            _logger.debug("_setSystemFolder");
            _setSystemFolder(nativityControl);

            _logger.debug("_updateFileIcon");
            _updateFileIcon(fileIconControl);

            _logger.debug("_clearFileIcon");
            _clearFileIcon(fileIconControl);

            _logger.debug("Ready?");

            if (bufferedReader.ready()) {
                _logger.debug("Reading...");

                read = bufferedReader.readLine();

                _logger.debug("Read {}", read);

                if (read.length() > 0) {
                    stop = true;
                }

                _logger.debug("Stopping {}", stop);
            }
        }
    } catch (IOException e) {
        _logger.error(e.getMessage(), e);
    }

    _logger.debug("Done");
}

From source file:org.kuali.student.git.importer.ConvertBuildTagBranchesToGitTags.java

/**
 * @param args//from  w w  w  .j  av a2s.co m
 */
public static void main(String[] args) {

    if (args.length < 3 || args.length > 6) {
        System.err.println("USAGE: <git repository> <bare> <ref mode> [<ref prefix> <username> <password>]");
        System.err.println("\t<bare> : 0 (false) or 1 (true)");
        System.err.println("\t<ref mode> : local or name of remote");
        System.err.println("\t<ref prefix> : refs/heads (default) or say refs/remotes/origin (test clone)");
        System.exit(-1);
    }

    boolean bare = false;

    if (args[1].trim().equals("1")) {
        bare = true;
    }

    String remoteName = args[2].trim();

    String refPrefix = Constants.R_HEADS;

    if (args.length == 4)
        refPrefix = args[3].trim();

    String userName = null;
    String password = null;

    if (args.length == 5)
        userName = args[4].trim();

    if (args.length == 6)
        password = args[5].trim();

    try {

        Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[0]).getAbsoluteFile(), false,
                bare);

        Git git = new Git(repo);

        ObjectInserter objectInserter = repo.newObjectInserter();

        Collection<Ref> repositoryHeads = repo.getRefDatabase().getRefs(refPrefix).values();

        RevWalk rw = new RevWalk(repo);

        Map<String, ObjectId> tagNameToTagId = new HashMap<>();

        Map<String, Ref> tagNameToRef = new HashMap<>();

        for (Ref ref : repositoryHeads) {

            String branchName = ref.getName().substring(refPrefix.length() + 1);

            if (branchName.contains("tag") && branchName.contains("builds")) {

                String branchParts[] = branchName.split("_");

                int buildsIndex = ArrayUtils.indexOf(branchParts, "builds");

                String moduleName = StringUtils.join(branchParts, "_", buildsIndex + 1, branchParts.length);

                RevCommit commit = rw.parseCommit(ref.getObjectId());

                ObjectId tag = GitRefUtils.insertTag(moduleName, commit, objectInserter);

                tagNameToTagId.put(moduleName, tag);

                tagNameToRef.put(moduleName, ref);

            }

        }

        BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate();

        List<RefSpec> branchesToDelete = new ArrayList<>();

        for (Entry<String, ObjectId> entry : tagNameToTagId.entrySet()) {

            String tagName = entry.getKey();

            // create the reference to the tag object
            batch.addCommand(
                    new ReceiveCommand(null, entry.getValue(), Constants.R_TAGS + tagName, Type.CREATE));

            // delete the original branch object

            Ref branch = tagNameToRef.get(entry.getKey());

            if (remoteName.equals("local")) {

                batch.addCommand(new ReceiveCommand(branch.getObjectId(), null, branch.getName(), Type.DELETE));

            } else {
                String adjustedBranchName = branch.getName().substring(refPrefix.length() + 1);

                branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + adjustedBranchName));
            }

        }

        // create the tags
        batch.execute(rw, new TextProgressMonitor());

        if (!remoteName.equals("local")) {
            // push the tag to the remote right now
            PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags()
                    .setProgressMonitor(new TextProgressMonitor());

            if (userName != null)
                pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password));

            Iterable<PushResult> results = pushCommand.call();

            for (PushResult pushResult : results) {

                if (!pushResult.equals(Result.NEW)) {
                    log.warn("failed to push tag " + pushResult.getMessages());
                }
            }

            // delete the branches from the remote
            results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete)
                    .setProgressMonitor(new TextProgressMonitor()).call();

            log.info("");

        }

        //         Result result = GitRefUtils.createTagReference(repo, moduleName, tag);
        //         
        //         if (!result.equals(Result.NEW)) {
        //            log.warn("failed to create tag {} for branch {}", moduleName, branchName);
        //            continue;
        //         }
        //         
        //         if (deleteMode) {
        //         result = GitRefUtils.deleteRef(repo, ref);
        //   
        //         if (!result.equals(Result.NEW)) {
        //            log.warn("failed to delete branch {}", branchName);
        //            continue;
        //         }

        objectInserter.release();

        rw.release();

    } catch (Exception e) {

        log.error("unexpected Exception ", e);
    }
}

From source file:se.technipelago.weather.chart.Generator.java

public static void main(String[] args) {

    Generator generator = new Generator();

    if (args.length > 0) {
        String outputDir = args[0];
        if (outputDir.endsWith("/")) {
            outputDir = outputDir.substring(0, outputDir.length() - 1);
        }//from w  w  w  .j av  a2  s  . co  m
        generator.setOutputDirectory(outputDir);
    }

    // Generate charts.
    generator.init();
    Map<String, Object> data = generator.getWeatherData();
    generator.generateCurrentCharts(data);
    generator.generateHistoryCharts(-30, 31);
    int year = Calendar.getInstance().get(Calendar.YEAR);
    generator.generateMonthlyCharts(year);
    generator.generateYearlyCharts(year);
}

From source file:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {//from   w ww . j ava  2 s. co  m
        String lang = Locale.getDefault().getLanguage();
        GnuParser cmdparser = new GnuParser();
        Options cmdopts = new Options();
        for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) {
            // hack for printOptions
            java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld);
            fieldopt.setAccessible(true);
            fieldopt.set(cmdopts, new LinkedHashMap<>());
        }
        cmdopts.addOption("h", "help", false, "Help");
        cmdopts.addOption("t", "test", false, "Show only report");
        cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg()
                .withDescription("Path to ADB from Android SDK").create("a"));
        cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg()
                .withDescription("Select device (\"adb devices\")").create("d"));
        cmdopts.addOption(null, "restore", false,
                "If packages have not yet removed and are disabled, " + "you can activate them again");
        cmdopts.addOption(null, "google", false, "Delete packages are in the Google section");
        cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex"
                + System.lineSeparator() + "(It is required to repeat command execution)");
        cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]");
        //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)");
        cmdopts.addOption(null, "scanlibs", false,
                "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib");

        cmdopts.addOptionGroup(new OptionGroup() {
            {
                addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired()
                        .withDescription("Create file with list packages").create());
                addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create());
            }
        });
        cmdopts.getOption("lang").setDescription(
                "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market");
        CommandLine cmd = cmdparser.parse(cmdopts, args);

        if (args.length == 0 || cmd.hasOption("help")) {
            PrintWriter console = new PrintWriter(System.out);
            HelpFormatter cmdhelp = new HelpFormatter();
            cmdhelp.setOptionComparator(new Comparator<Option>() {
                @Override
                public int compare(Option o1, Option o2) {
                    return 0;
                }
            });
            console.println("WARNING: Before use make a backup with ClockworkMod Recovery!");
            console.println();
            console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]");
            cmdhelp.printOptions(console, 80, cmdopts, 3, 2);
            console.flush();
            return;
        }

        String adb = cmd.getOptionValue("adb", "adb");
        try {
            run(adb, "start-server");
        } catch (IOException e) {
            System.out.println("Error: Not found ADB! Use -a or --adb");
            return;
        }

        final boolean NotTest = !cmd.hasOption("test");

        String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev"));
        if (!deverror.isEmpty()) {
            System.out.println(deverror);
            return;
        }

        System.out.println("Getting list packages:");
        LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>();
        for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) {
            // "pm list packages" give list sorted by packages ;)
            String pckg = ln.substring("package:".length());
            String pckgname = ln.substring(ln.lastIndexOf('=') + 1);
            pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1);
            if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) {
                apklist.put(pckg, pckgname);
            }
        }
        for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) {
            String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk");
            if (!apklist.containsKey(path)) {
                apklist.put(path, "");
            }
        }
        apklist.remove("/system/app/mcRegistry");
        for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        String genfile = cmd.getOptionValue("genfile");
        if (genfile != null) {
            Path genpath = Paths.get(genfile);
            try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8,
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                            StandardOpenOption.WRITE })) {
                if (cmd.getOptionValue("lang") != null) {
                    lang = cmd.getOptionValue("lang");
                }

                LinkedHashSet<String> listsystem = new LinkedHashSet<String>() {
                    {
                        add("com.android");
                        add("com.google.android");
                        //add("com.sec.android.app");
                        add("com.monotype.android");
                        add("eu.chainfire.supersu");
                    }
                };

                // \r\n for Windows Notepad
                gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                gen.write("<!-- & raplace with &amp; or use <![CDATA[ ]]> -->\r\n");
                gen.write("<AndroidUninstallStock>\r\n\r\n");
                gen.write("<Normal>\r\n");
                System.out.println();
                System.out.println("\tNormal:");
                writeInfo(gen, apklist, lang, listsystem, true);
                gen.write("\t<apk name=\"Exclude Google and etc\">\r\n");
                for (String exc : listsystem) {
                    gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n");
                }
                gen.write("\t</apk>\r\n");
                gen.write("</Normal>\r\n\r\n");
                gen.write("<Google>\r\n");
                System.out.println();
                System.out.println("\tGoogle:");
                writeInfo(gen, apklist, lang, listsystem, false);
                gen.write("</Google>\r\n\r\n");
                gen.write("</AndroidUninstallStock>\r\n");
                System.out.println("File " + genpath.toAbsolutePath() + " created.");
            }
            return;
        }

        String[] FileName = cmd.getArgs();
        if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) {
            System.out.println("Error: File " + FileName[0] + " not found!");
            return;
        }

        DocumentBuilderFactory xmlfactory = getXmlDocFactory();

        // DocumentBuilder.setErrorHandler() for print errors
        Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0]));

        LinkedList<AusInfo> Normal = new LinkedList<AusInfo>();
        LinkedList<AusInfo> Google = new LinkedList<AusInfo>();

        NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes();
        for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) {
            Node ndnow = ndaus.item(ndausx);
            NodeList nd = ndnow.getChildNodes();
            String ndname = ndnow.getNodeName();
            for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) {
                if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) {
                    continue;
                }
                if (ndname.equalsIgnoreCase("Normal")) {
                    Normal.add(getApkInfo(nd.item(ndx)));
                } else if (ndname.equalsIgnoreCase("Google")) {
                    Google.add(getApkInfo(nd.item(ndx)));
                }
            }
        }

        // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages.
        //       Now requires a restart.
        System.out.println();
        System.out.println("Include and Exclude packages (Normal):");
        LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false);
        System.out.println();
        System.out.println("Global Exclude packages (Normal):");
        apkNormal = getApkFromPattern(apkNormal, Normal, true);
        System.out.println();
        System.out.println("Final list packages (Normal):");
        for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>();
        if (cmd.hasOption("google")) {
            System.out.println();
            System.out.println("Include and Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apklist, Google, false);
            System.out.println();
            System.out.println("Global Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apkGoogle, Google, true);
            System.out.println();
            System.out.println("Final list packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) {
                System.out.println(info.getValue() + " = " + info.getKey());
            }
        }

        if (NotTest) {
            if (!hasRoot(adb)) {
                System.out.println("No Root");
                System.out.println();
                System.out.println("FINISH :)");
                return;
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println();
            System.out.println("Enable (Restore) packages (Normal):");
            damage(adb, "pm enable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Enable (Restore) packages (Google):");
                damage(adb, "pm enable ", NotTest, apkGoogle, 2);
            }
            System.out.println();
            System.out.println("FINISH :)");
            return;
        } else {
            System.out.println();
            System.out.println("Disable packages (Normal):");
            damage(adb, "pm disable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Disable packages (Google):");
                damage(adb, "pm disable ", NotTest, apkGoogle, 2);
            }
        }

        if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) {
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }

        // Reboot now not needed
        /*if (NotTest) {
        reboot(adb, "-s", lastdevice, "reboot");
        if (!hasRoot(adb)) {
            System.out.println("No Root");
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }
        }*/

        if (cmd.hasOption("unlib")) {
            // "find" not found
            System.out.println();
            System.out.println("Getting list libraries:");
            LinkedList<String> liblist = new LinkedList<String>();
            liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/"));
            String dircur = "/system/lib/";
            for (int x = 0; x < liblist.size(); x++) {
                if (liblist.get(x).startsWith("scan:")) {
                    dircur = liblist.get(x).substring("scan:".length());
                    liblist.remove(x);
                    x--;
                } else if (liblist.get(x).startsWith("d")) {
                    String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/";
                    liblist.remove(x);
                    x--;
                    liblist.add("scan:/system/lib/" + dir);
                    liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir));
                    continue;
                }
                liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4));
                System.out.println(liblist.get(x));
            }

            final boolean scanlibs = cmd.hasOption("scanlibs");
            LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal,
                    "Normal", scanlibs);
            libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal");
            System.out.println();
            System.out.println("Final list libraries (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                System.out.println(info.getKey() + " = " + info.getValue());
            }

            LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>();
            if (cmd.hasOption("google")) {
                libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs);
                libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google");
                System.out.println();
                System.out.println("Final list libraries (Google):");
                for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                    System.out.println(info.getKey() + " = " + info.getValue());
                }
            }

            LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist);
            for (String key : apkNormal.keySet()) {
                apkExclude.remove(key);
            }
            for (String key : apkGoogle.keySet()) {
                apkExclude.remove(key);
            }

            System.out.println();
            System.out.println("Include libraries from Exclude packages:");
            LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude);
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libNormal.remove(info.getKey());
                }
            }
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libGoogle.remove(info.getKey());
                }
            }

            System.out.println();
            System.out.println("Delete libraries (Normal):");
            damage(adb, "rm ", NotTest, libNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete libraries (Google):");
                damage(adb, "rm ", NotTest, libGoogle, 1);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Cleaning data packages (Normal):");
            damage(adb, "pm clear ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Cleaning data packages (Google):");
                damage(adb, "pm clear ", NotTest, apkGoogle, 2);
            }

            System.out.println();
            System.out.println("Uninstall packages (Normal):");
            damage(adb, "pm uninstall ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Uninstall packages (Google):");
                damage(adb, "pm uninstall ", NotTest, apkGoogle, 2);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Delete packages (Normal):");
            LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>();
            for (Map.Entry<String, String> apk : apkNormal.entrySet()) {
                dexNormal.put(apk.getKey(), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
            }
            damage(adb, "rm ", NotTest, dexNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete packages (Google):");
                LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>();
                for (Map.Entry<String, String> apk : apkGoogle.entrySet()) {
                    dexGoogle.put(apk.getKey(), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
                }
                damage(adb, "rm ", NotTest, dexGoogle, 1);
            }
        }

        if (NotTest) {
            run(adb, "-s", lastdevice, "reboot");
        }
        System.out.println();
        System.out.println("FINISH :)");
    } catch (SAXException e) {
        System.out.println("Error parsing list: " + e);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:MersenneTwisterFast.java

/**
 * Tests the code./*from  w w  w.  ja  va  2  s  .c  om*/
 */
public static void main(String args[]) {
    int j;

    MersenneTwisterFast r;

    // CORRECTNESS TEST
    // COMPARE WITH http://www.math.keio.ac.jp/matumoto/CODES/MT2002/mt19937ar.out

    r = new MersenneTwisterFast(new int[] { 0x123, 0x234, 0x345, 0x456 });
    System.out.println("Output of MersenneTwisterFast with new (2002/1/26) seeding mechanism");
    for (j = 0; j < 1000; j++) {
        // first, convert the int from signed to "unsigned"
        long l = (long) r.nextInt();
        if (l < 0)
            l += 4294967296L; // max int value
        String s = String.valueOf(l);
        while (s.length() < 10)
            s = " " + s; // buffer
        System.out.print(s + " ");
        if (j % 5 == 4)
            System.out.println();
    }

    // SPEED TEST

    final long SEED = 4357;

    int xx;
    long ms;
    System.out.println("\nTime to test grabbing 100000000 ints");

    Random rr = new Random(SEED);
    xx = 0;
    ms = System.currentTimeMillis();
    for (j = 0; j < 100000000; j++)
        xx += rr.nextInt();
    System.out
            .println("java.util.Random: " + (System.currentTimeMillis() - ms) + "          Ignore this: " + xx);

    r = new MersenneTwisterFast(SEED);
    ms = System.currentTimeMillis();
    xx = 0;
    for (j = 0; j < 100000000; j++)
        xx += r.nextInt();
    System.out.println(
            "Mersenne Twister Fast: " + (System.currentTimeMillis() - ms) + "          Ignore this: " + xx);

    // TEST TO COMPARE TYPE CONVERSION BETWEEN
    // MersenneTwisterFast.java AND MersenneTwister.java

    System.out.println("\nGrab the first 1000 booleans");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean() + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab 1000 booleans of increasing probability using nextBoolean(double)");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean((double) (j / 999.0)) + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab 1000 booleans of increasing probability using nextBoolean(float)");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean((float) (j / 999.0f)) + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    byte[] bytes = new byte[1000];
    System.out.println("\nGrab the first 1000 bytes using nextBytes");
    r = new MersenneTwisterFast(SEED);
    r.nextBytes(bytes);
    for (j = 0; j < 1000; j++) {
        System.out.print(bytes[j] + " ");
        if (j % 16 == 15)
            System.out.println();
    }
    if (!(j % 16 == 15))
        System.out.println();

    byte b;
    System.out.println("\nGrab the first 1000 bytes -- must be same as nextBytes");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print((b = r.nextByte()) + " ");
        if (b != bytes[j])
            System.out.print("BAD ");
        if (j % 16 == 15)
            System.out.println();
    }
    if (!(j % 16 == 15))
        System.out.println();

    System.out.println("\nGrab the first 1000 shorts");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextShort() + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab the first 1000 ints");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextInt() + " ");
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 ints of different sizes");
    r = new MersenneTwisterFast(SEED);
    int max = 1;
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextInt(max) + " ");
        max *= 2;
        if (max <= 0)
            max = 1;
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 longs");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextLong() + " ");
        if (j % 3 == 2)
            System.out.println();
    }
    if (!(j % 3 == 2))
        System.out.println();

    System.out.println("\nGrab the first 1000 longs of different sizes");
    r = new MersenneTwisterFast(SEED);
    long max2 = 1;
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextLong(max2) + " ");
        max2 *= 2;
        if (max2 <= 0)
            max2 = 1;
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 floats");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextFloat() + " ");
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 doubles");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextDouble() + " ");
        if (j % 3 == 2)
            System.out.println();
    }
    if (!(j % 3 == 2))
        System.out.println();

    System.out.println("\nGrab the first 1000 gaussian doubles");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextGaussian() + " ");
        if (j % 3 == 2)
            System.out.println();
    }
    if (!(j % 3 == 2))
        System.out.println();

}

From source file:edu.usc.qufd.Main.java

/**
 * The main method.//w w  w  .  ja  v a  2 s . com
 *
 * @param args the arguments
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void main(String[] args) throws IOException {
    if (parseInputs(args) == false) {
        System.exit(-1); //The input files do not exist
    }

    /*
     * Parsing inputs: fabric & qasm file
     */
    PrintWriter outputFile;
    RandomAccessFile raf = null;
    String latencyPlaceHolder;
    if (RuntimeConfig.OUTPUT_TO_FILE) {
        latencyPlaceHolder = "Total Latency: " + Long.MAX_VALUE + " us" + System.lineSeparator();
        raf = new RandomAccessFile(outputFileAddr, "rws");
        //removing the old values in the file
        raf.setLength(0);
        //writing a place holder for the total latency
        raf.writeBytes(latencyPlaceHolder);
        raf.close();

        outputFile = new PrintWriter(new BufferedWriter(new FileWriter(outputFileAddr, true)), true);
    } else { //writing to stdout
        outputFile = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true);
    }
    /* parsing the input*/
    layout = LayoutParser.parse(pmdFileAddr);
    qasm = QASMParser.QASMParser(qasmFileAddr, layout);

    long totalLatency = qufd(outputFile);

    if (RuntimeConfig.OUTPUT_TO_FILE) {
        outputFile.close();
        //Over writing the place holder with the actual latency
        String latencyActual = "Total Latency: " + totalLatency + " " + layout.getTimeUnit();
        latencyActual = StringUtils.rightPad(latencyActual,
                latencyPlaceHolder.length() - System.lineSeparator().length());
        raf = new RandomAccessFile(outputFileAddr, "rws");
        //Writing to the top of a file
        raf.seek(0);
        //writing the actual total latency in the at the top of the output file
        raf.writeBytes(latencyActual + System.lineSeparator());
        raf.close();
    } else {
        outputFile.flush();
        System.out.println("Total Latency: " + totalLatency + " " + layout.getTimeUnit());
    }

    if (RuntimeConfig.VERBOSE) {
        System.out.println("Done.");
    }
    outputFile.close();
}

From source file:MersenneTwisterFast.java

/**
 * Tests the code./*from w  w w . jav  a2  s . c o  m*/
 * @param args arguments
 */
@SuppressWarnings({ "ConstantConditions" })
public static void main(String args[]) {
    int j;

    MersenneTwisterFast r;

    // CORRECTNESS TEST
    // COMPARE WITH http://www.math.keio.ac.jp/matumoto/CODES/MT2002/mt19937ar.out

    r = new MersenneTwisterFast(new int[] { 0x123, 0x234, 0x345, 0x456 });
    System.out.println("Output of MersenneTwisterFast with new (2002/1/26) seeding mechanism");
    for (j = 0; j < 1000; j++) {
        // first, convert the int from signed to "unsigned"
        long l = (long) r.nextInt();
        if (l < 0)
            l += 4294967296L; // max int value
        String s = String.valueOf(l);
        while (s.length() < 10)
            s = " " + s; // buffer
        System.out.print(s + " ");
        if (j % 5 == 4)
            System.out.println();
    }

    // SPEED TEST

    final long SEED = 4357;

    int xx;
    long ms;
    System.out.println("\nTime to test grabbing 100000000 ints");

    Random rr = new Random(SEED);
    xx = 0;
    ms = System.currentTimeMillis();
    for (j = 0; j < 100000000; j++)
        xx += rr.nextInt();
    System.out
            .println("java.util.Random: " + (System.currentTimeMillis() - ms) + "          Ignore this: " + xx);

    r = new MersenneTwisterFast(SEED);
    ms = System.currentTimeMillis();
    xx = 0;
    for (j = 0; j < 100000000; j++)
        xx += r.nextInt();
    System.out.println(
            "Mersenne Twister Fast: " + (System.currentTimeMillis() - ms) + "          Ignore this: " + xx);

    // TEST TO COMPARE TYPE CONVERSION BETWEEN
    // MersenneTwisterFast.java AND MersenneTwister.java

    System.out.println("\nGrab the first 1000 booleans");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean() + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab 1000 booleans of increasing probability using nextBoolean(double)");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean(j / 999.0) + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab 1000 booleans of increasing probability using nextBoolean(float)");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextBoolean(j / 999.0f) + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    byte[] bytes = new byte[1000];
    System.out.println("\nGrab the first 1000 bytes using nextBytes");
    r = new MersenneTwisterFast(SEED);
    r.nextBytes(bytes);
    for (j = 0; j < 1000; j++) {
        System.out.print(bytes[j] + " ");
        if (j % 16 == 15)
            System.out.println();
    }
    if (!(j % 16 == 15))
        System.out.println();

    byte b;
    System.out.println("\nGrab the first 1000 bytes -- must be same as nextBytes");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print((b = r.nextByte()) + " ");
        if (b != bytes[j])
            System.out.print("BAD ");
        if (j % 16 == 15)
            System.out.println();
    }
    if (!(j % 16 == 15))
        System.out.println();

    System.out.println("\nGrab the first 1000 shorts");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextShort() + " ");
        if (j % 8 == 7)
            System.out.println();
    }
    if (!(j % 8 == 7))
        System.out.println();

    System.out.println("\nGrab the first 1000 ints");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextInt() + " ");
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 ints of different sizes");
    r = new MersenneTwisterFast(SEED);
    int max = 1;
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextInt(max) + " ");
        max *= 2;
        if (max <= 0)
            max = 1;
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 longs");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextLong() + " ");
        if (j % 3 == 2)
            System.out.println();
    }
    if (!(j % 3 == 2))
        System.out.println();

    System.out.println("\nGrab the first 1000 longs of different sizes");
    r = new MersenneTwisterFast(SEED);
    long max2 = 1;
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextLong(max2) + " ");
        max2 *= 2;
        if (max2 <= 0)
            max2 = 1;
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 floats");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextFloat() + " ");
        if (j % 4 == 3)
            System.out.println();
    }
    if (!(j % 4 == 3))
        System.out.println();

    System.out.println("\nGrab the first 1000 doubles");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextDouble() + " ");
        if (j % 3 == 2)
            System.out.println();

    }
    if (!(j % 3 == 2))
        System.out.println();

    System.out.println("\nGrab the first 1000 gaussian doubles");
    r = new MersenneTwisterFast(SEED);
    for (j = 0; j < 1000; j++) {
        System.out.print(r.nextGaussian() + " ");
        if (j % 3 == 2)
            System.out.println();
    }
    if (!(j % 3 == 2))
        System.out.println();

}

From source file:tap.Tap.java

/**
 * Usage:<BR> FIXME?// ww  w.j  a  v a  2s.  c  o  m
 *       java votebox.Tap [serial] [report address] [port]
 *
 * @param args      arguments to be used
 *
 * @throws RuntimeException if there is an issue parsing values, the port used is bad,
 *                          or there is an interruption in the process
 */
public static void main(String[] args) {

    IAuditoriumParams params = new AuditoriumParams("tap.conf");

    System.out.println(params.getReportAddress());

    String reportAddr;

    int serial;
    int port;
    String launchCode;

    /* See if there isn't a full argument set */
    if (args.length != 4) {

        int p = 0;

        /* Assign the default serial */
        serial = params.getDefaultSerialNumber();

        /* If the serial is still bad... */
        if (serial == -1) {

            /* Try the first of the given arguments */
            try {
                serial = Integer.parseInt(args[p]);
                p++;
            } catch (Exception e) {
                throw new RuntimeException(
                        "usage: Tap [serial] [report address] [port]\nExpected valid serial.");
            }
        }

        /* Assign the report address */
        reportAddr = params.getReportAddress();

        /* If no valid address... */
        if (reportAddr.length() == 0) {

            /* Try one of the given arguments (first or second, depending) */
            try {
                reportAddr = args[p];
                p++;
            } catch (Exception e) {
                throw new RuntimeException("usage: Tap [serial] [report address] [port]");
            }
        }

        /* Assign the port */
        //port = params.getPort();
        port = Integer.parseInt(args[p]);

        /* If the port is still bad... */
        if (port == -1) {

            /* Try one of the given arguments (first, second, or third, depending) */
            try {
                port = Integer.parseInt(args[p]);
            } catch (Exception e) {
                throw new RuntimeException("usage: Tap [serial] [report address] [port]\nExpected valid port.");
            }
        }

        launchCode = "0000000000";
    }

    /* If there is a full argument set... */
    else {

        /* Try to load up the args */
        try {
            serial = Integer.parseInt(args[0]);
            reportAddr = args[1];
            port = Integer.parseInt(args[2]);
            launchCode = args[3];
        } catch (Exception e) {
            throw new RuntimeException("usage: Tap [serial] [report address] [port]");
        }
    }

    try {

        /* Create a new socket address */
        System.out.println(reportAddr + port);
        InetSocketAddress addr = new InetSocketAddress(reportAddr, port);

        /* Loop until an exception or tap is started */
        while (true) {

            try {

                /* Try to establish a socket connection */
                Socket localCon = new Socket();
                localCon.connect(addr);

                /* Start the tap */
                (new Tap(serial, localCon.getOutputStream(), launchCode, params)).start();
                System.out.println("Connection successful to " + addr);
                break;
            } catch (IOException e) { /* If no good, retry */
                System.out.println("Connection failed: " + e.getMessage());
                System.out.println("Retry in 5 seconds...");
                Thread.sleep(5000);
            }
        }
    } catch (NumberFormatException e) {
        throw new RuntimeException(
                "usage: Tap [serial] [report address] [port]; where port is between 1 and 65335 & [serial] is a positive integer",
                e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    /* TEST CODE */

    testMethod();

    /* END TEST CODE */

}