Example usage for java.lang System arraycopy

List of usage examples for java.lang System arraycopy

Introduction

In this page you can find the example usage for java.lang System arraycopy.

Prototype

@HotSpotIntrinsicCandidate
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

Source Link

Document

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

Usage

From source file:it.doqui.index.ecmengine.test.AllTests.java

public static void main(String[] args) {
    Log logger = LogFactory.getLog(ECMENGINE_TEST_LOG_CATEGORY);
    logger.debug("[AllTests::main] BEGIN");
    String runner;//from   w  w w. java2 s. c  o  m
    int i;
    String arguments[];
    Class cls;

    runner = null;
    for (i = 0; (i < args.length) && (null == runner); i++) {
        if (args[i].equalsIgnoreCase("-text"))
            runner = "junit.textui.TestRunner";
        else if (args[i].equalsIgnoreCase("-awt"))
            runner = "junit.awtui.TestRunner";
        else if (args[i].equalsIgnoreCase("-swing"))
            runner = "junit.swingui.TestRunner";
    }
    if (null != runner) {
        // remove it from the arguments
        arguments = new String[args.length - 1];
        System.arraycopy(args, 0, arguments, 0, i - 1);
        System.arraycopy(args, i, arguments, i - 1, args.length - i);
        args = arguments;
    } else
        runner = "junit.swingui.TestRunner";

    // append the test class
    arguments = new String[args.length + 1];
    System.arraycopy(args, 0, arguments, 0, args.length);
    arguments[args.length] = "it.doqui.index.ecmengine.test.AllTests";

    // invoke main() of the test runner
    try {
        cls = Class.forName(runner);
        java.lang.reflect.Method method = cls.getDeclaredMethod("main", new Class[] { String[].class });
        method.invoke(null, new Object[] { arguments });
    } catch (Throwable t) {
        logger.debug("[AllTests::main] Problem in test execution : " + t);
    } finally {
        logger.debug("[AllTests::main] BEGIN");

    }
}

From source file:com.musicg.experiment.test.Test1.java

/**
 * @param args//from  w  w w .  ja  v a2s  .c  o m
 */
public static void main(String[] args) {

    String filename = "audio_work/lala.wav";

    // create a wave object
    Wave wave = null;
    try {
        wave = new Wave(filename);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // TimeDomainRepresentations
    int fftSampleSize = 1024;
    int overlapFactor = 1;
    Spectrogram spectrogram = new Spectrogram(wave, fftSampleSize, overlapFactor);

    int fps = spectrogram.getFramesPerSecond();
    double unitFrequency = spectrogram.getUnitFrequency();

    // set boundary
    int highPass = 100;
    int lowerBoundary = (int) (highPass / unitFrequency);
    int lowPass = 4000;
    int upperBoundary = (int) (lowPass / unitFrequency);
    // end set boundary

    double[][] spectrogramData = spectrogram.getNormalizedSpectrogramData();
    double[][] absoluteSpectrogramData = spectrogram.getAbsoluteSpectrogramData();
    double[][] boundedSpectrogramData = new double[spectrogramData.length][];

    // SpectralCentroid sc=new SpectralCentroid();
    StandardDeviation sd = new StandardDeviation();
    ArrayRankDouble arrayRankDouble = new ArrayRankDouble();

    // zrc
    short[] amps = wave.getSampleAmplitudes();
    int numFrame = amps.length / 1024;
    double[] zcrs = new double[numFrame];

    for (int i = 0; i < numFrame; i++) {
        short[] temp = new short[1024];
        System.arraycopy(amps, i * 1024, temp, 0, temp.length);

        int numZC = 0;
        int size = temp.length;

        for (int j = 0; j < size - 1; j++) {
            if ((temp[j] >= 0 && temp[j + 1] < 0) || (temp[j] < 0 && temp[j + 1] >= 0)) {
                numZC++;
            }
        }

        zcrs[i] = numZC;
    }

    // end zcr

    for (int i = 0; i < spectrogramData.length; i++) {
        double[] temp = new double[upperBoundary - lowerBoundary + 1];
        System.arraycopy(spectrogramData[i], lowerBoundary, temp, 0, temp.length);

        int maxIndex = arrayRankDouble.getMaxValueIndex(temp);
        // sc.setValues(temp);

        double sdValue = sd.evaluate(temp);

        System.out.println(i + " " + (double) i / fps + "s\t" + maxIndex + "\t" + sdValue + "\t" + zcrs[i]);
        boundedSpectrogramData[i] = temp;
    }

    // Graphic render
    GraphicRender render = new GraphicRender();
    render.setHorizontalMarker(61);
    render.setVerticalMarker(200);
    render.renderSpectrogramData(boundedSpectrogramData, filename + ".jpg");

    PitchHandler ph = new PitchHandler();

    for (int frame = 0; frame < absoluteSpectrogramData.length; frame++) {

        System.out.print("frame " + frame + ": ");

        double[] temp = new double[upperBoundary - lowerBoundary + 1];

        double sdValue = sd.evaluate(temp);
        double passSd = 0.1;

        if (sdValue < passSd) {
            System.arraycopy(spectrogramData[frame], lowerBoundary, temp, 0, temp.length);
            double maxFrequency = arrayRankDouble.getMaxValueIndex(temp) * unitFrequency;

            double passFrequency = 400;
            int numRobust = 2;

            double[] robustFrequencies = new double[numRobust];
            double nthValue = arrayRankDouble.getNthOrderedValue(temp, numRobust, false);
            int count = 0;
            for (int b = lowerBoundary; b <= upperBoundary; b++) {
                if (spectrogramData[frame][b] >= nthValue) {
                    robustFrequencies[count++] = b * unitFrequency;
                    if (count >= numRobust) {
                        break;
                    }
                }
            }

            double passIntensity = 1000;
            double intensity = 0;
            for (int i = 0; i < absoluteSpectrogramData[frame].length; i++) {
                intensity += absoluteSpectrogramData[frame][i];
            }
            intensity /= absoluteSpectrogramData[frame].length;
            System.out.print(" intensity: " + intensity + " pitch: " + maxFrequency);
            if (intensity > passIntensity && maxFrequency > passFrequency) {
                double p = ph.getHarmonicProbability(robustFrequencies);
                System.out.print(" P: " + p);
            }
        }
        System.out.print(" zcr:" + zcrs[frame]);
        System.out.println();
    }
}

From source file:com.cloudera.oryx.app.traffic.TrafficUtil.java

public static void main(String[] args) throws Exception {
    if (args.length < 3) {
        System.err.println("usage: TrafficUtil [hosts] [requestIntervalMS] [threads] [... other args]");
        return;/*from   w  ww . j av  a2 s  . c om*/
    }

    String[] hostStrings = COMMA.split(args[0]);
    Preconditions.checkArgument(hostStrings.length >= 1);
    int requestIntervalMS = Integer.parseInt(args[1]);
    Preconditions.checkArgument(requestIntervalMS >= 0);
    int numThreads = Integer.parseInt(args[2]);
    Preconditions.checkArgument(numThreads >= 1);

    String[] otherArgs = new String[args.length - 3];
    System.arraycopy(args, 3, otherArgs, 0, otherArgs.length);

    List<URI> hosts = Arrays.stream(hostStrings).map(URI::create).collect(Collectors.toList());

    int perClientRequestIntervalMS = numThreads * requestIntervalMS;

    Endpoints alsEndpoints = new Endpoints(ALSEndpoint.buildALSEndpoints());
    AtomicLong requestCount = new AtomicLong();
    AtomicLong serverErrorCount = new AtomicLong();
    AtomicLong clientErrorCount = new AtomicLong();
    AtomicLong exceptionCount = new AtomicLong();

    long start = System.currentTimeMillis();
    ExecUtils.doInParallel(numThreads, numThreads, true, i -> {
        RandomGenerator random = RandomManager.getRandom(Integer.toString(i).hashCode() ^ System.nanoTime());
        ExponentialDistribution msBetweenRequests;
        if (perClientRequestIntervalMS > 0) {
            msBetweenRequests = new ExponentialDistribution(random, perClientRequestIntervalMS);
        } else {
            msBetweenRequests = null;
        }

        ClientConfig clientConfig = new ClientConfig();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(numThreads);
        connectionManager.setDefaultMaxPerRoute(numThreads);
        clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
        clientConfig.connectorProvider(new ApacheConnectorProvider());
        Client client = ClientBuilder.newClient(clientConfig);

        try {
            while (true) {
                try {
                    WebTarget target = client.target("http://" + hosts.get(random.nextInt(hosts.size())));
                    Endpoint endpoint = alsEndpoints.chooseEndpoint(random);
                    Invocation invocation = endpoint.makeInvocation(target, otherArgs, random);

                    long startTime = System.currentTimeMillis();
                    Response response = invocation.invoke();
                    try {
                        response.readEntity(String.class);
                    } finally {
                        response.close();
                    }
                    long elapsedMS = System.currentTimeMillis() - startTime;

                    int statusCode = response.getStatusInfo().getStatusCode();
                    if (statusCode >= 400) {
                        if (statusCode >= 500) {
                            serverErrorCount.incrementAndGet();
                        } else {
                            clientErrorCount.incrementAndGet();
                        }
                    }

                    endpoint.recordTiming(elapsedMS);

                    if (requestCount.incrementAndGet() % 10000 == 0) {
                        long elapsed = System.currentTimeMillis() - start;
                        log.info("{}ms:\t{} requests\t({} client errors\t{} server errors\t{} exceptions)",
                                elapsed, requestCount.get(), clientErrorCount.get(), serverErrorCount.get(),
                                exceptionCount.get());
                        for (Endpoint e : alsEndpoints.getEndpoints()) {
                            log.info("{}", e);
                        }
                    }

                    if (msBetweenRequests != null) {
                        int desiredElapsedMS = (int) Math.round(msBetweenRequests.sample());
                        if (elapsedMS < desiredElapsedMS) {
                            Thread.sleep(desiredElapsedMS - elapsedMS);
                        }
                    }
                } catch (Exception e) {
                    exceptionCount.incrementAndGet();
                    log.warn("{}", e.getMessage());
                }
            }
        } finally {
            client.close();
        }
    });
}

From source file:cc.twittertools.index.ExtractTermStatisticsFromIndex.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("index").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("min").create(MIN_OPTION));

    CommandLine cmdline = null;/*  w  w w .j a v  a2  s. c o  m*/
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractTermStatisticsFromIndex.class.getName(), options);
        System.exit(-1);
    }

    String indexLocation = cmdline.getOptionValue(INDEX_OPTION);
    int min = cmdline.hasOption(MIN_OPTION) ? Integer.parseInt(cmdline.getOptionValue(MIN_OPTION)) : 1;

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexLocation)));
    Terms terms = SlowCompositeReaderWrapper.wrap(reader).terms(StatusField.TEXT.name);
    TermsEnum termsEnum = terms.iterator(TermsEnum.EMPTY);

    long missingCnt = 0;
    int skippedTerms = 0;
    BytesRef bytes = new BytesRef();
    while ((bytes = termsEnum.next()) != null) {
        byte[] buf = new byte[bytes.length];
        System.arraycopy(bytes.bytes, 0, buf, 0, bytes.length);
        String term = new String(buf, "UTF-8");
        int df = termsEnum.docFreq();
        long cf = termsEnum.totalTermFreq();

        if (df < min) {
            skippedTerms++;
            missingCnt += cf;
            continue;
        }

        out.println(term + "\t" + df + "\t" + cf);
    }

    reader.close();
    out.close();
    System.err.println("skipped terms: " + skippedTerms + ", cnt: " + missingCnt);
}

From source file:com.genentech.retrival.tabExport.TABExporter.java

public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();
    int nStruct = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("sqlFile", true, "sql-xml file");
    opt.setRequired(true);//from   w ww. ja  v  a 2 s  . com
    options.addOption(opt);

    opt = new Option("sqlName", true, "name of SQL element in xml file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("o", true, "output file");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("newLineReplacement", true,
            "If given newlines in fields will be replaced by this string.");
    options.addOption(opt);

    opt = new Option("noHeader", false, "Do not output header line");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    String outFile = cmd.getOptionValue("o");
    String sqlFile = cmd.getOptionValue("sqlFile");
    String sqlName = cmd.getOptionValue("sqlName");
    String newLineReplacement = cmd.getOptionValue("newLineReplacement");

    args = cmd.getArgs();

    try {
        PrintStream out = System.out;
        if (outFile != null)
            out = new PrintStream(outFile);

        SQLStatement stmt = SQLStatement.createFromFile(new File(sqlFile), sqlName);
        Object[] sqlArgs = args;
        if (stmt.getParamTypes().length != args.length) {
            System.err.printf(
                    "\nWarining sql statement needs %d parameters but got only %d. Filling up with NULLs.\n",
                    stmt.getParamTypes().length, args.length);
            sqlArgs = new Object[stmt.getParamTypes().length];
            System.arraycopy(args, 0, sqlArgs, 0, args.length);
        }

        Selecter sel = Selecter.factory(stmt);
        if (!sel.select(sqlArgs)) {
            System.err.println("No rows returned!");
            System.exit(0);
        }

        String[] fieldNames = sel.getFieldNames();
        if (fieldNames.length == 0) {
            System.err.println("Query did not return any columns");
            exitWithHelp(options);
        }

        if (!cmd.hasOption("noHeader")) {
            StringBuilder sb = new StringBuilder(200);
            for (String f : fieldNames)
                sb.append(f).append('\t');
            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String header = sb.toString();

            out.println(header);
        }

        StringBuilder sb = new StringBuilder(200);
        while (sel.hasNext()) {
            Record sqlRec = sel.next();
            sb.setLength(0);

            for (int i = 0; i < fieldNames.length; i++) {
                String fld = sqlRec.getStrg(i);
                if (newLineReplacement != null)
                    fld = NEWLinePattern.matcher(fld).replaceAll(newLineReplacement);

                sb.append(fld).append('\t');
            }

            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String row = sb.toString();

            out.println(row);

            nStruct++;
        }

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("TABExporter: Exported %d records in %dsec\n", nStruct,
                (System.currentTimeMillis() - start) / 1000);
    }
}

From source file:cz.muni.fi.xklinec.zipstream.App.java

/**
 * Entry point. //from www. j  a  va2 s . c o m
 * 
 * @param args
 * @throws FileNotFoundException
 * @throws IOException
 * @throws NoSuchFieldException
 * @throws ClassNotFoundException
 * @throws NoSuchMethodException 
 */
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchFieldException,
        ClassNotFoundException, NoSuchMethodException, InterruptedException {
    OutputStream fos = null;
    InputStream fis = null;

    if ((args.length != 0 && args.length != 2)) {
        System.err.println(String.format("Usage: app.jar source.apk dest.apk"));
        return;
    } else if (args.length == 2) {
        System.err.println(
                String.format("Will use file [%s] as input file and [%s] as output file", args[0], args[1]));
        fis = new FileInputStream(args[0]);
        fos = new FileOutputStream(args[1]);
    } else if (args.length == 0) {
        System.err.println(String.format("Will use file [STDIN] as input file and [STDOUT] as output file"));
        fis = System.in;
        fos = System.out;
    }

    final Deflater def = new Deflater(9, true);
    ZipArchiveInputStream zip = new ZipArchiveInputStream(fis);

    // List of postponed entries for further "processing".
    List<PostponedEntry> peList = new ArrayList<PostponedEntry>(6);

    // Output stream
    ZipArchiveOutputStream zop = new ZipArchiveOutputStream(fos);
    zop.setLevel(9);

    // Read the archive
    ZipArchiveEntry ze = zip.getNextZipEntry();
    while (ze != null) {

        ZipExtraField[] extra = ze.getExtraFields(true);
        byte[] lextra = ze.getLocalFileDataExtra();
        UnparseableExtraFieldData uextra = ze.getUnparseableExtraFieldData();
        byte[] uextrab = uextra != null ? uextra.getLocalFileDataData() : null;

        // ZipArchiveOutputStream.DEFLATED
        // 

        // Data for entry
        byte[] byteData = Utils.readAll(zip);
        byte[] deflData = new byte[0];
        int infl = byteData.length;
        int defl = 0;

        // If method is deflated, get the raw data (compress again).
        if (ze.getMethod() == ZipArchiveOutputStream.DEFLATED) {
            def.reset();
            def.setInput(byteData);
            def.finish();

            byte[] deflDataTmp = new byte[byteData.length * 2];
            defl = def.deflate(deflDataTmp);

            deflData = new byte[defl];
            System.arraycopy(deflDataTmp, 0, deflData, 0, defl);
        }

        System.err.println(String.format(
                "ZipEntry: meth=%d " + "size=%010d isDir=%5s " + "compressed=%07d extra=%d lextra=%d uextra=%d "
                        + "comment=[%s] " + "dataDesc=%s " + "UTF8=%s " + "infl=%07d defl=%07d " + "name [%s]",
                ze.getMethod(), ze.getSize(), ze.isDirectory(), ze.getCompressedSize(),
                extra != null ? extra.length : -1, lextra != null ? lextra.length : -1,
                uextrab != null ? uextrab.length : -1, ze.getComment(),
                ze.getGeneralPurposeBit().usesDataDescriptor(), ze.getGeneralPurposeBit().usesUTF8ForNames(),
                infl, defl, ze.getName()));

        final String curName = ze.getName();

        // META-INF files should be always on the end of the archive, 
        // thus add postponed files right before them
        if (curName.startsWith("META-INF") && peList.size() > 0) {
            System.err.println(
                    "Now is the time to put things back, but at first, I'll perform some \"facelifting\"...");

            // Simulate som evil being done
            Thread.sleep(5000);

            System.err.println("OK its done, let's do this.");
            for (PostponedEntry pe : peList) {
                System.err.println(
                        "Adding postponed entry at the end of the archive! deflSize=" + pe.deflData.length
                                + "; inflSize=" + pe.byteData.length + "; meth: " + pe.ze.getMethod());

                pe.dump(zop, false);
            }

            peList.clear();
        }

        // Capturing interesting files for us and store for later.
        // If the file is not interesting, send directly to the stream.
        if ("classes.dex".equalsIgnoreCase(curName) || "AndroidManifest.xml".equalsIgnoreCase(curName)) {
            System.err.println("### Interesting file, postpone sending!!!");

            PostponedEntry pe = new PostponedEntry(ze, byteData, deflData);
            peList.add(pe);
        } else {
            // Write ZIP entry to the archive
            zop.putArchiveEntry(ze);
            // Add file data to the stream
            zop.write(byteData, 0, infl);
            zop.closeArchiveEntry();
        }

        ze = zip.getNextZipEntry();
    }

    // Cleaning up stuff
    zip.close();
    fis.close();

    zop.finish();
    zop.close();
    fos.close();

    System.err.println("THE END!");
}

From source file:com.quanticate.opensource.pdftkbox.PDFtkBox.java

public static void main(String[] args) throws Exception {
    // For printing help
    Options optsHelp = new Options();
    optsHelp.addOption(Option.builder("help").required().desc("print this message").build());

    // Normal-style import/export
    Options optsNormal = new Options();
    OptionGroup normal = new OptionGroup();
    Option optExport = Option.builder("export").required().hasArg().desc("export bookmarks from pdf")
            .argName("source-pdf").build();
    normal.addOption(optExport);//w  w w .jav a 2s.  com
    Option optImport = Option.builder("import").required().hasArg().desc("import bookmarks into pdf")
            .argName("source-pdf").build();
    normal.addOption(optImport);
    optsNormal.addOptionGroup(normal);
    Option optBookmarks = Option.builder("bookmarks").hasArg().desc("bookmarks definition file")
            .argName("bookmarks").build();
    optsNormal.addOption(optBookmarks);
    Option optOutput = Option.builder("output").hasArg().desc("output to new pdf").argName("pdf").build();
    optsNormal.addOption(optOutput);

    // PDFtk style options
    Options optsPDFtk = new Options();
    OptionGroup pdftk = new OptionGroup();
    Option optDumpData = Option.builder("dump_data").required().desc("dump bookmarks from pdf").build();
    pdftk.addOption(optDumpData);
    Option optUpdateInfo = Option.builder("update_info").required().hasArg().desc("update bookmarks in pdf")
            .argName("bookmarks").build();
    pdftk.addOption(optUpdateInfo);
    optsPDFtk.addOptionGroup(pdftk);
    optsPDFtk.addOption(optOutput);

    // What are we doing?
    CommandLineParser parser = new DefaultParser();

    // Did they want help?
    try {
        parser.parse(optsHelp, args);

        // If we get here, they asked for help
        doPrintHelp(optsHelp, optsNormal, optsPDFtk);
        return;
    } catch (ParseException pe) {
    }

    // Normal-style import/export?
    try {
        CommandLine line = parser.parse(optsNormal, args);

        // Export
        if (line.hasOption(optExport.getOpt())) {
            doExport(line.getOptionValue(optExport.getOpt()), line.getOptionValue(optBookmarks.getOpt()),
                    line.getArgs());
            return;
        }
        // Import with explicit output filename
        if (line.hasOption(optImport.getOpt()) && line.hasOption(optOutput.getOpt())) {
            doImport(line.getOptionValue(optImport.getOpt()), line.getOptionValue(optBookmarks.getOpt()),
                    line.getOptionValue(optOutput.getOpt()), null);
            return;
        }
        // Import with implicit output filename
        if (line.hasOption(optImport.getOpt()) && line.getArgs().length > 0) {
            doImport(line.getOptionValue(optImport.getOpt()), line.getOptionValue(optBookmarks.getOpt()), null,
                    line.getArgs());
            return;
        }
    } catch (ParseException pe) {
    }

    // PDFtk-style
    if (args.length > 1) {
        // Nobble things for PDFtk-style options and Commons CLI
        for (int i = 1; i < args.length; i++) {
            for (Option opt : optsPDFtk.getOptions()) {
                if (args[i].equals(opt.getOpt())) {
                    args[i] = "-" + args[i];
                }
            }
        }
        try {
            // Input file comes first, then arguments
            String input = args[0];
            String[] pargs = new String[args.length - 1];
            System.arraycopy(args, 1, pargs, 0, pargs.length);

            // Parse what's left and check
            CommandLine line = parser.parse(optsPDFtk, pargs);

            if (line.hasOption(optDumpData.getOpt())) {
                doExport(input, line.getOptionValue(optOutput.getOpt()), line.getArgs());
                return;
            }
            if (line.hasOption(optUpdateInfo.getOpt())) {
                doImport(input, line.getOptionValue(optUpdateInfo.getOpt()),
                        line.getOptionValue(optOutput.getOpt()), line.getArgs());
                return;
            }
        } catch (ParseException pe) {
        }
    }

    // If in doubt, print help
    doPrintHelp(optsHelp, optsNormal, optsPDFtk);
}

From source file:com.twitter.distributedlog.tools.Tool.java

public static void main(String args[]) {
    int rc = -1;//from w  ww.  ja  v  a  2s . c o  m
    if (args.length <= 0) {
        System.err.println("No tool to run.");
        System.err.println("");
        System.err.println("Usage : Tool <tool_class_name> <options>");
        System.exit(-1);
    }
    String toolClass = args[0];
    try {
        Tool tool = ReflectionUtils.newInstance(toolClass, Tool.class);
        String[] newArgs = new String[args.length - 1];
        System.arraycopy(args, 1, newArgs, 0, newArgs.length);
        rc = tool.run(newArgs);
    } catch (Throwable t) {
        System.err.println("Fail to run tool " + toolClass + " : ");
        t.printStackTrace();
    }
    System.exit(rc);
}

From source file:com.michaelfitzmaurice.devtools.HeaderTool.java

/**
 * Runs the Header Tool. Supports optional system properties to
 * control the matching behaviour (default is full - see class
 * comments) and what to do with files that do not include the 
 * header (default is simply to report on them):
 * //from   w w w .  j a v a2  s .  c  o  m
 * <pre>
 *      -Dinsert-mode=true
 *      -Dfirst-line-match=true
 * </pre>
 * 
 * @param args Runtime arguments, which must include:
 *   <ol>
 *     <li>Full path to source directory</li>
 *     <li>Full path to header file</li>
 *     <li>Variable number of file extensions to check (space separated). 
 *         Passing only the * character provides wildcard extension 
 *         matching
 *      </li>
 *    </ol>
 *        
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

    File rootDir = new File(args[0]);
    File headerFile = new File(args[1]);
    String[] fileExtensions = new String[args.length - 2];
    System.arraycopy(args, 2, fileExtensions, 0, fileExtensions.length);
    if (asList(fileExtensions).contains(WILDCARD_FILE_EXTENSION)) {
        fileExtensions = null;
    }
    MatchMode matchMode = MatchMode.FULL_MATCH;
    if (Boolean.getBoolean(FIRST_LINE_MATCH_SYS_PROP) == true) {
        matchMode = MatchMode.FIRST_LINE_ONLY;
    }

    HeaderTool headerTool = new HeaderTool(headerFile, matchMode);
    Collection<File> filesWithNoHeader = headerTool.listFilesWithoutHeader(rootDir, fileExtensions);
    if (Boolean.getBoolean(INSERT_MODE_SYS_PROP) == true) {
        headerTool.insertHeader(filesWithNoHeader);
    }
}

From source file:com.pinterest.terrapin.tools.HFileGenerator.java

public static void main(String[] args) {
    Options options = getCommandLineOptions();
    CommandLineParser cmdParser = new PosixParser();
    if (args.length < 1) {
        printHelpMessage(options);/*w w w  .ja v a  2  s  . c  om*/
    } else {
        File outputFolder = new File(args[args.length - 1]);
        checkOutputFolder(outputFolder);
        String[] optionArgs = new String[args.length - 1];
        System.arraycopy(args, 0, optionArgs, 0, args.length - 1);
        try {
            CommandLine cmd = cmdParser.parse(options, optionArgs);
            if (hasHelp(cmd)) {
                printHelpMessage(options);
            } else {
                Configuration conf = new Configuration();
                FileSystem fs = FileSystem.get(conf);
                generateHFiles(fs, conf, outputFolder, getPartitionerType(cmd), getNumOfPartitions(cmd),
                        getNumOfKeys(cmd));
            }
        } catch (ParseException e) {
            printHelpMessage(options);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}