Example usage for java.lang System getProperty

List of usage examples for java.lang System getProperty

Introduction

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

Prototype

public static String getProperty(String key) 

Source Link

Document

Gets the system property indicated by the specified key.

Usage

From source file:eu.fbk.utils.wikipedia.WikipediaPlainTextExtractor.java

public static void main(String args[]) throws IOException {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
        logConfig = "configuration/log-config.txt";
    }//  www  .  j  a  v  a2s  .  c o m

    PropertyConfigurator.configure(logConfig);

    Options options = new Options();
    try {
        Option wikipediaDumpOpt = OptionBuilder.withArgName("file").hasArg()
                .withDescription("wikipedia xml dump file").isRequired().withLongOpt("wikipedia-dump")
                .create("d");
        Option outputDirOpt = OptionBuilder.withArgName("dir").hasArg()
                .withDescription("output directory in which to store output files").isRequired()
                .withLongOpt("output-dir").create("o");
        Option numThreadOpt = OptionBuilder.withArgName("int").hasArg()
                .withDescription("number of threads (default " + Defaults.DEFAULT_THREADS_NUMBER + ")")
                .withLongOpt("num-threads").create("t");
        Option numPageOpt = OptionBuilder.withArgName("int").hasArg()
                .withDescription("number of pages to process (default all)").withLongOpt("num-pages")
                .create("p");
        Option notificationPointOpt = OptionBuilder.withArgName("int").hasArg()
                .withDescription("receive notification every n pages (default "
                        + Defaults.DEFAULT_NOTIFICATION_POINT + ")")
                .withLongOpt("notification-point").create("b");

        options.addOption(null, "text-only", false, "skipt title in file");

        options.addOption("h", "help", false, "print this message");
        options.addOption("v", "version", false, "output version information and exit");

        options.addOption(wikipediaDumpOpt);
        options.addOption(outputDirOpt);
        options.addOption(numThreadOpt);
        options.addOption(numPageOpt);
        options.addOption(notificationPointOpt);
        CommandLineParser parser = new PosixParser();
        CommandLine line = parser.parse(options, args);
        logger.debug(line);

        if (line.hasOption("help") || line.hasOption("version")) {
            throw new ParseException("");
        }

        int numThreads = Defaults.DEFAULT_THREADS_NUMBER;
        boolean textOnly = line.hasOption("text-only");
        if (line.hasOption("num-threads")) {
            numThreads = Integer.parseInt(line.getOptionValue("num-threads"));
        }

        int numPages = Defaults.DEFAULT_NUM_PAGES;
        if (line.hasOption("num-pages")) {
            numPages = Integer.parseInt(line.getOptionValue("num-pages"));
        }

        int notificationPoint = Defaults.DEFAULT_NOTIFICATION_POINT;
        if (line.hasOption("notification-point")) {
            notificationPoint = Integer.parseInt(line.getOptionValue("notification-point"));
        }

        ExtractorParameters extractorParameters = new ExtractorParameters(line.getOptionValue("wikipedia-dump"),
                line.getOptionValue("output-dir"));
        WikipediaPlainTextExtractor wikipediaPageParser = new WikipediaPlainTextExtractor(numThreads, numPages,
                extractorParameters.getLocale());
        wikipediaPageParser.setNotificationPoint(notificationPoint);
        //            wikipediaPageParser.setSkipTitle(textOnly);
        wikipediaPageParser.start(extractorParameters);

        logger.info("extraction ended " + new Date());

    } catch (ParseException e) {
        // oops, something went wrong
        System.out.println("Parsing failed: " + e.getMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(400,
                "java -cp dist/thewikimachine.jar org.fbk.cit.hlt.thewikimachine.xmldump.WikipediaTextExtractor",
                "\n", options, "\n", true);
    }
}

From source file:com.hpe.nv.samples.basic.BasicNVTest.java

public static void main(String[] args) {
    try {//from   ww  w  .ja v  a  2  s  .  co  m
        // program arguments
        Options options = new Options();
        options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP");
        options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port");
        options.addOption("u", "username", true, "[mandatory] NV username");
        options.addOption("w", "password", true, "[mandatory] NV password");
        options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false");
        options.addOption("y", "proxy", true, "[optional] Proxy server host:port");
        options.addOption("b", "browser", true,
                "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox");
        options.addOption("d", "debug", true,
                "[optional] Pass true to view console debug messages during execution. Default: false");
        options.addOption("h", "help", false, "[optional] Generates and prints help information");

        // parse and validate the command line arguments
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            // print help if help argument is passed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("BasicNVTest.java", options);
            return;
        }

        if (line.hasOption("server-ip")) {
            serverIp = line.getOptionValue("server-ip");
            if (serverIp.equals("0.0.0.0")) {
                throw new Exception(
                        "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP");
            }
        } else {
            throw new Exception("Missing argument -i/--server-ip <serverIp>");
        }

        if (line.hasOption("server-port")) {
            serverPort = Integer.parseInt(line.getOptionValue("server-port"));
        } else {
            throw new Exception("Missing argument -o/--server-port <serverPort>");
        }

        if (line.hasOption("username")) {
            username = line.getOptionValue("username");
        } else {
            throw new Exception("Missing argument -u/--username <username>");
        }

        if (line.hasOption("password")) {
            password = line.getOptionValue("password");
        } else {
            throw new Exception("Missing argument -w/--password <password>");
        }

        if (line.hasOption("ssl")) {
            ssl = Boolean.parseBoolean(line.getOptionValue("ssl"));
        }

        if (line.hasOption("proxy")) {
            proxySetting = line.getOptionValue("proxy");
        }

        if (line.hasOption("browser")) {
            browser = line.getOptionValue("browser");
        } else {
            browser = "Firefox";
        }

        if (line.hasOption("debug")) {
            debug = Boolean.parseBoolean(line.getOptionValue("debug"));
        }

        String newLine = System.getProperty("line.separator");
        String testDescription = "***   This sample demonstrates the use of the most basic NV methods.                               ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   First, the sample creates a TestManager object and initializes it.                           ***"
                + newLine
                + "***   The sample starts an NV test over an emulated \"3G Busy\" network.                             ***"
                + newLine
                + "***   (\"3G Busy\" is one of NV's built-in network profiles. A network profile specifies the         ***"
                + newLine
                + "***   network traffic behavior, including latency, packet loss, and incoming/outgoing bandwidth.   ***"
                + newLine
                + "***   Network profiles are used to emulate traffic over real-world networks.)                      ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   Next, the sample navigates to the home page in the HPE Network Virtualization website        ***"
                + newLine
                + "***   using the Selenium WebDriver.                                                                ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   Finally, the sample stops the NV test.                                                       ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   You can view the actual steps of this sample in the BasicNVTest.java file.                   ***"
                + newLine;

        // print the sample's description
        System.out.println(testDescription);

        // start console spinner
        if (!debug) {
            spinner = new Thread(new Spinner());
            spinner.start();
        }

        // sample execution steps
        /*****    Part 1 - Create a TestManager object and initialize it                                   *****/
        printPartDescription("\b------    Part 1 - Create a TestManager object and initialize it");
        initTestManager();
        printPartSeparator();
        /*****    Part 2 - Start the NV test with the "3G Busy" network scenario                           *****/
        printPartDescription("------    Part 2 - Start the NV test with the \"3G Busy\" network scenario");
        startTest();
        testRunning = true;
        printPartSeparator();
        /*****    Part 3 - Navigate to the HPE Network Virtualization website                              *****/
        printPartDescription("------    Part 3 - Navigate to the HPE Network Virtualization website");
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        driverCloseAndQuit();
        printPartSeparator();
        /*****    Part 4 - Stop the NV test                                                                *****/
        printPartDescription("------    Part 4 - Stop the NV test");
        stopTest();
        testRunning = false;
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}

From source file:com.zip.CreateZipWithOutputStreams.java

/**
 * @param args/* www  . j a va 2  s.  c o m*/
 * @throws UnsupportedEncodingException 
 */
public static void main(String[] args) throws UnsupportedEncodingException {
    //      new CreateZipWithOutputStreams();
    //      zipFilesAndEncrypt("D:\\test\\download","D:\\test\\download\\1.zip","12345");
    //      unzipFile("D:\\test\\download\\1.zip","D:\\test\\download",null);
    String str = "/usr/local/aiomni/27/temp/offLineFolder/admin8a21848b4056b2e4014056b533240000/??????_1.xls";
    System.out.println(new String(str.getBytes("ISO8859-1"), "GBK"));
    System.out.println(System.getProperty("file.encoding"));
}

From source file:fr.cs.examples.conversion.PropagatorConversion.java

/** Program entry point.
 * @param args program arguments (unused here)
 *///  w ww . ja va  2 s.  c o m
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();

        // gravity field
        NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(2, 0);
        double mu = provider.getMu();

        // inertial frame
        Frame inertialFrame = FramesFactory.getEME2000();

        // Initial date
        AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, TimeScalesFactory.getUTC());

        // Initial orbit (GTO)
        final double a = 24396159; // semi major axis in meters
        final double e = 0.72831215; // eccentricity
        final double i = FastMath.toRadians(7); // inclination
        final double omega = FastMath.toRadians(180); // perigee argument
        final double raan = FastMath.toRadians(261); // right ascention of ascending node
        final double lM = 0; // mean anomaly
        Orbit initialOrbit = new KeplerianOrbit(a, e, i, omega, raan, lM, PositionAngle.MEAN, inertialFrame,
                initialDate, mu);
        final double period = initialOrbit.getKeplerianPeriod();

        // Initial state definition
        final SpacecraftState initialState = new SpacecraftState(initialOrbit);

        // Adaptive step integrator with a minimum step of 0.001 and a maximum step of 1000
        final double minStep = 0.001;
        final double maxStep = 1000.;
        final double dP = 1.e-2;
        final OrbitType orbType = OrbitType.CARTESIAN;
        final double[][] tol = NumericalPropagator.tolerances(dP, initialOrbit, orbType);
        final AbstractIntegrator integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);

        // Propagator
        NumericalPropagator numProp = new NumericalPropagator(integrator);
        numProp.setInitialState(initialState);
        numProp.setOrbitType(orbType);

        // Force Models:
        // 1 - Perturbing gravity field (only J2 is considered here)
        ForceModel gravity = new HolmesFeatherstoneAttractionModel(
                FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider);

        // Add force models to the propagator
        numProp.addForceModel(gravity);

        // Propagator factory
        PropagatorBuilder builder = new KeplerianPropagatorBuilder(mu, inertialFrame, OrbitType.KEPLERIAN,
                PositionAngle.TRUE);

        // Propagator converter
        PropagatorConverter fitter = new FiniteDifferencePropagatorConverter(builder, 1.e-6, 5000);

        // Resulting propagator
        KeplerianPropagator kepProp = (KeplerianPropagator) fitter.convert(numProp, 2 * period, 251);

        // Step handlers
        StatesHandler numStepHandler = new StatesHandler();
        StatesHandler kepStepHandler = new StatesHandler();

        // Set up operating mode for the propagator as master mode
        // with fixed step and specialized step handler
        numProp.setMasterMode(60., numStepHandler);
        kepProp.setMasterMode(60., kepStepHandler);

        // Extrapolate from the initial to the final date
        numProp.propagate(initialDate.shiftedBy(10. * period));
        kepProp.propagate(initialDate.shiftedBy(10. * period));

        // retrieve the states
        List<SpacecraftState> numStates = numStepHandler.getStates();
        List<SpacecraftState> kepStates = kepStepHandler.getStates();

        // Print the results on the output file
        File output = new File(new File(System.getProperty("user.home")), "elements.dat");
        PrintStream stream = new PrintStream(output);
        stream.println("# date Anum Akep Enum Ekep Inum Ikep LMnum LMkep");
        for (SpacecraftState numState : numStates) {
            for (SpacecraftState kepState : kepStates) {
                if (numState.getDate().compareTo(kepState.getDate()) == 0) {
                    stream.println(numState.getDate() + " " + numState.getA() + " " + kepState.getA() + " "
                            + numState.getE() + " " + kepState.getE() + " "
                            + FastMath.toDegrees(numState.getI()) + " " + FastMath.toDegrees(kepState.getI())
                            + " " + FastMath.toDegrees(MathUtils.normalizeAngle(numState.getLM(), FastMath.PI))
                            + " "
                            + FastMath.toDegrees(MathUtils.normalizeAngle(kepState.getLM(), FastMath.PI)));
                    break;
                }
            }
        }
        stream.close();
        System.out.println("Results saved as file " + output);

        File output1 = new File(new File(System.getProperty("user.home")), "elts_pv.dat");
        PrintStream stream1 = new PrintStream(output1);
        stream.println("# date pxn pyn pzn vxn vyn vzn pxk pyk pzk vxk vyk vzk");
        for (SpacecraftState numState : numStates) {
            for (SpacecraftState kepState : kepStates) {
                if (numState.getDate().compareTo(kepState.getDate()) == 0) {
                    final double pxn = numState.getPVCoordinates().getPosition().getX();
                    final double pyn = numState.getPVCoordinates().getPosition().getY();
                    final double pzn = numState.getPVCoordinates().getPosition().getZ();
                    final double vxn = numState.getPVCoordinates().getVelocity().getX();
                    final double vyn = numState.getPVCoordinates().getVelocity().getY();
                    final double vzn = numState.getPVCoordinates().getVelocity().getZ();
                    final double pxk = kepState.getPVCoordinates().getPosition().getX();
                    final double pyk = kepState.getPVCoordinates().getPosition().getY();
                    final double pzk = kepState.getPVCoordinates().getPosition().getZ();
                    final double vxk = kepState.getPVCoordinates().getVelocity().getX();
                    final double vyk = kepState.getPVCoordinates().getVelocity().getY();
                    final double vzk = kepState.getPVCoordinates().getVelocity().getZ();
                    stream1.println(numState.getDate() + " " + pxn + " " + pyn + " " + pzn + " " + vxn + " "
                            + vyn + " " + vzn + " " + pxk + " " + pyk + " " + pzk + " " + vxk + " " + vyk + " "
                            + vzk);
                    break;
                }
            }
        }
        stream1.close();
        System.out.println("Results saved as file " + output1);

    } catch (OrekitException oe) {
        System.err.println(oe.getLocalizedMessage());
        System.exit(1);
    } catch (FileNotFoundException fnfe) {
        System.err.println(fnfe.getLocalizedMessage());
        System.exit(1);
    }
}

From source file:edu.nyupoly.cs6903.ag3671.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException, Exception {
    // MY CODE//  w  w w.  j a  va  2 s .c  om
    if (crypto(Collections.unmodifiableList(Arrays.asList(args)))) {
        return;
    }
    ;
    // MY CODE -- END

    boolean storeFile = false, binaryTransfer = true, error = false, listFiles = false, listNames = false,
            hidden = false;
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        }
        // Always use binary transfer 
        //            else if (args[base].equals("-b")) {
        //                binaryTransfer = true;
        //            }
        else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);
            // MY CODE
            byte[] bytes = IOUtils.toByteArray(input);
            InputStream encrypted = new ByteArrayInputStream(cryptor.encrypt(bytes));
            // MY CODE -- END
            ftp.storeFile(remote, encrypted);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            // MY CODE
            ByteArrayOutputStream remoteFile = new ByteArrayOutputStream();
            //InputStream byteIn = new ByteArrayInputStream(buf);
            ftp.retrieveFile(remote, remoteFile);
            remoteFile.flush();
            Optional<byte[]> opt = cryptor.decrypt(remoteFile.toByteArray());
            if (opt.isPresent()) {
                output.write(opt.get());
            }
            remoteFile.close();
            // MY CODE -- END
            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:CalcoloRitardiLotti.java

public static void main(String[] args) {
    String id_ref = "cbededce-269f-48d2-8c25-2359bf246f42";
    String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id="
            + id_ref;/*from w w  w . jav  a  2 s .  c o  m*/
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(requestString);
    try {

        HttpResponse response = client.execute(request);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String result = "";
        String resline = "";
        Calendar c = Calendar.getInstance();
        Date current = Date.valueOf(
                c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH));
        while ((resline = rd.readLine()) != null)
            result += resline;

        //System.out.println(jsonObject.toString());
        if (result != null) {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject resultJson = (JSONObject) jsonObject.get("result");
            JSONArray records = (JSONArray) resultJson.get("records");
            Date temp1, temp2;
            //System.out.printf(records.toString());
            long diffInizioFineLavori;
            long ritardo;
            long den = (24 * 60 * 60 * 1000);
            JSONObject temp;

            DefaultCategoryDataset cdata = new DefaultCategoryDataset();
            String partialQuery;
            DefaultPieDataset data = new DefaultPieDataset();

            String totalQuery = "";
            int countSospesi = 0;
            int countConclusi = 0;
            int countVerifica = 0;
            int countInCorso = 0;
            int countCollaudo = 0;
            String stato;
            for (int i = 0; i < records.length(); i++) {
                temp = (JSONObject) records.get(i);
                temp1 = Date.valueOf((temp.getString("Data Consegna Lavori")).substring(0, 10));
                temp2 = Date.valueOf((temp.getString("Data Fine lavori")).substring(0, 10));
                diffInizioFineLavori = (long) (temp2.getTime() - temp1.getTime()) / den;
                stato = temp.getString("STATO");
                if (stato.equals("Concluso"))
                    countConclusi++;
                else if (stato.equals("In corso"))
                    countInCorso++;
                else if (stato.contains("Verifiche"))
                    countVerifica++;
                else if (stato.contains("Collaudo sospeso") || stato.contains("sospeso"))
                    countSospesi++;
                else
                    countCollaudo++;

                if (!temp.getString("STATO").equals("Concluso") && temp2.getTime() < current.getTime())
                    ritardo = (long) (current.getTime() - temp2.getTime()) / den;
                else
                    ritardo = 0;

                cdata.setValue(ritardo, String.valueOf(i + 1), String.valueOf(i + 1));
                System.out.println(
                        "Opera: " + temp.getString("Oggetto del lotto") + " | id: " + temp.getInt("_id"));
                System.out.println("Data consegna lavoro: " + temp.getString("Data Consegna Lavori")
                        + " | Data fine lavoro: " + temp.getString("Data Fine lavori"));
                System.out.println("STATO: " + temp.getString("STATO"));
                System.out.println("Differenza in giorni: " + diffInizioFineLavori
                        + " | Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali"));
                System.out.println("Ritardo accumulato: " + ritardo);

                System.out.println("----------------------------------");

                partialQuery = "\nid: " + temp.getInt("_id") + "\nOpera:" + temp.getString("Oggetto del lotto")
                        + "\n" + "Data consegna lavoro: " + temp.getString("Data Consegna Lavori")
                        + "Data fine lavoro: " + temp.getString("Data Fine lavori") + "\n" + "STATO: "
                        + temp.getString("STATO") + "\n" + "Differenza in giorni: " + diffInizioFineLavori
                        + " - Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali")
                        + "\n" + "Ritardo accumulato: " + ritardo + "\n"
                        + "----------------------------------\n";
                totalQuery = totalQuery + partialQuery;

            }

            JFreeChart chart1 = ChartFactory.createBarChart3D("RITARDI AL " + current, "Id lotto",
                    "ritardo(in giorni)", cdata);
            ChartRenderingInfo info = null;
            ChartUtilities.saveChartAsPNG(
                    new File(System.getProperty("user.dir") + "/istogramma" + current + ".png"), chart1, 1500,
                    1500, info, true, 10);
            FileUtils.writeStringToFile(new File(current + "_1.txt"), totalQuery);

            data.setValue("Conclusi: " + countConclusi, countConclusi);
            data.setValue("Sospeso: " + countSospesi, countSospesi);
            data.setValue("In Corso: " + countInCorso, countInCorso);
            data.setValue("Verifica: " + countVerifica, countVerifica);
            data.setValue("Collaudo: " + countCollaudo, countCollaudo);
            JFreeChart chart2 = ChartFactory.createPieChart3D("Statistiche del " + current, data, true, true,
                    true);
            ChartUtilities.saveChartAsPNG(new File(System.getProperty("user.dir") + "/pie" + current + ".png"),
                    chart2, 800, 450);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.example.geomesa.authorizations.GeoServerAuthorizationsTutorial.java

/**
 * Main entry point. Executes queries against an existing GDELT dataset.
 *
 * @param args/*from   www  . j  a v  a  2  s . c  o m*/
 *
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // read command line options - this contains the path to geoserver and the data store to query
    CommandLineParser parser = new BasicParser();
    Options options = SetupUtil.getWfsOptions();
    CommandLine cmd = parser.parse(options, args);

    String geoserverHost = cmd.getOptionValue(SetupUtil.GEOSERVER_URL);
    if (!geoserverHost.endsWith("/")) {
        geoserverHost += "/";
    }

    // create the URL to GeoServer. Note that we need to point to the 'GetCapabilities' request,
    // and that we are using WFS version 1.0.0
    String geoserverUrl = geoserverHost + "wfs?request=GetCapabilities&version=1.0.0";

    // create the geotools configuration for a WFS data store
    Map<String, String> configuration = new HashMap<String, String>();
    configuration.put(WFSDataStoreFactory.URL.key, geoserverUrl);
    configuration.put(WFSDataStoreFactory.WFS_STRATEGY.key, "geoserver");
    configuration.put(WFSDataStoreFactory.TIMEOUT.key, cmd.getOptionValue(SetupUtil.TIMEOUT, "99999"));

    System.out.println("Executing query against '" + geoserverHost + "' with client keystore '"
            + System.getProperty("javax.net.ssl.keyStore") + "'");

    // verify we have gotten the correct datastore
    WFSDataStore wfsDataStore = (WFSDataStore) DataStoreFinder.getDataStore(configuration);
    assert wfsDataStore != null;

    // the geoserver data store to query
    String geoserverDataStore = cmd.getOptionValue(SetupUtil.FEATURE_STORE);

    executeQuery(geoserverDataStore, wfsDataStore);
}

From source file:com.clustercontrol.HinemosManagerMain.java

/**
 * Hinemos Manager?main<br/>/*from   w w w  .  j  a v a 2  s.  co  m*/
 * @param args
 * @throws Exception
 */
public static void main(String args[]) {

    try {
        try {
            if (System.getProperty("systime.iso") != null) {
                String oldVmName = System.getProperty("java.vm.name");

                //System?mock?????HotSpot??????????
                System.setProperty("java.vm.name", "HotSpot 64-Bit Server VM");

                Class.forName("com.clustercontrol.util.SystemTimeShifter");

                System.setProperty("java.vm.name", oldVmName);
            }
        } catch (Exception e) {
            log.error(e);
        } catch (Error e) {
            log.error(e);
        }

        long bootTime = System.currentTimeMillis();
        log.info("Hinemos Manager is starting." + " (startupMode=" + _startupMode + ", clustered="
                + _isClustered + ", locale=" + Locale.getDefault() + ")");

        // Hinemos(??????)???????
        // (???????????????????????)
        long offset = HinemosPropertyUtil.getHinemosPropertyNum("common.time.offset", Long.valueOf(0));
        HinemosTime.setTimeOffsetMillis(offset);

        // Hinemos?(UTC??)??/(??)
        int timeZoneOffset = HinemosPropertyUtil
                .getHinemosPropertyNum("common.timezone", Long.valueOf(TimeZone.getDefault().getRawOffset()))
                .intValue();
        HinemosTime.setTimeZoneOffset(timeZoneOffset);

        // ???HinemosPlugin??(create)?
        HinemosPluginService.getInstance().create();

        // ???HinemosPlugin?(activate)?
        HinemosPluginService.getInstance().activate();

        // Hinemos Manger????
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                log.info("shutdown hook called.");
                synchronized (shutdownLock) {
                    // Hinemos Manager???
                    String[] msgArgsShutdown = { _hostname };
                    AplLogger.put(PriorityConstant.TYPE_INFO, HinemosModuleConstant.HINEMOS_MANAGER_MONITOR,
                            MessageConstant.MESSAGE_SYS_002_MNG, msgArgsShutdown);

                    // ???HinemosPlugin??(deactivate)?
                    HinemosPluginService.getInstance().deactivate();

                    // ???HinemosPlugin?(destroy)?
                    HinemosPluginService.getInstance().destroy();

                    log.info("Hinemos Manager is stopped.");

                    shutdown = true;
                    shutdownLock.notify();
                }
            }
        });

        // ??
        long startupTime = System.currentTimeMillis();
        long initializeSec = (startupTime - bootTime) / 1000;
        long initializeMSec = (startupTime - bootTime) % 1000;
        log.info("Hinemos Manager Started in " + initializeSec + "s:" + initializeMSec + "ms");

        // Hinemos Manager??
        String[] msgArgsStart = { _hostname };
        AplLogger.put(PriorityConstant.TYPE_INFO, HinemosModuleConstant.HINEMOS_MANAGER_MONITOR,
                MessageConstant.MESSAGE_SYS_001_MNG, msgArgsStart);

        // Hinemos Manager???????
        synchronized (shutdownLock) {
            while (!shutdown) {
                try {
                    shutdownLock.wait();
                } catch (InterruptedException e) {
                    log.warn("shutdown lock interrupted.", e);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException sleepE) {
                    }
                    ;
                }
            }
        }

        System.exit(0);

    } catch (Throwable e) {
        log.error("unknown error occured.", e);
    }
}

From source file:Gen.java

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

    try {//from  w ww . j a v  a2s.  c  o  m

        File[] files = null;
        if (System.getProperty("dir") != null && !System.getProperty("dir").equals("")) {
            files = new File(System.getProperty("dir")).listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toUpperCase().endsWith(".XML");
                };
            });
        } else {
            String fileName = System.getProperty("file") != null && !System.getProperty("file").equals("")
                    ? System.getProperty("file")
                    : "rjmap.xml";
            files = new File[] { new File(fileName) };
        }

        log.info("files : " + Arrays.toString(files));

        if (files == null || files.length == 0) {
            log.info("no files to parse");
            System.exit(0);
        }

        boolean formatsource = true;
        if (System.getProperty("formatsource") != null && !System.getProperty("formatsource").equals("")
                && System.getProperty("formatsource").equalsIgnoreCase("false")) {
            formatsource = false;
        }

        GEN_ROOT = System.getProperty("outputdir");

        if (GEN_ROOT == null || GEN_ROOT.equals("")) {
            GEN_ROOT = new File(files[0].getAbsolutePath()).getParent() + FILE_SEPARATOR + "distrib";
        }

        GEN_ROOT = new File(GEN_ROOT).getAbsolutePath().replace('\\', '/');
        if (GEN_ROOT.endsWith("/"))
            GEN_ROOT = GEN_ROOT.substring(0, GEN_ROOT.length() - 1);

        System.out.println("GEN ROOT:" + GEN_ROOT);

        MAPPING_JAR_NAME = System.getProperty("mappingjar") != null
                && !System.getProperty("mappingjar").equals("") ? System.getProperty("mappingjar")
                        : "mapping.jar";
        if (!MAPPING_JAR_NAME.endsWith(".jar"))
            MAPPING_JAR_NAME += ".jar";

        GEN_ROOT_SRC = GEN_ROOT + FILE_SEPARATOR + "src";
        GEN_ROOT_LIB = GEN_ROOT + FILE_SEPARATOR + "";

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        domFactory.setValidating(false);
        DocumentBuilder documentBuilder = domFactory.newDocumentBuilder();

        for (int f = 0; f < files.length; ++f) {
            log.info("parsing file : " + files[f]);
            Document document = documentBuilder.parse(files[f]);

            Vector<Node> initNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "initScript",
                    initNodes);
            for (int i = 0; i < initNodes.size(); ++i) {
                NamedNodeMap attrs = initNodes.elementAt(i).getAttributes();
                boolean embed = attrs.getNamedItem("embed") != null
                        && attrs.getNamedItem("embed").getNodeValue().equalsIgnoreCase("true");
                StringBuffer vbuffer = new StringBuffer();
                if (attrs.getNamedItem("inline") != null) {
                    vbuffer.append(attrs.getNamedItem("inline").getNodeValue());
                    vbuffer.append('\n');
                } else {
                    String fname = attrs.getNamedItem("name").getNodeValue();
                    if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') {
                        String path = files[f].getAbsolutePath();
                        path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR));
                        fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath();
                    }
                    vbuffer.append(Utils.getFileAsStringBuffer(fname));
                }
                initScriptBuffer.append(vbuffer);
                if (embed)
                    embedScriptBuffer.append(vbuffer);
            }

            Vector<Node> packageInitNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "packageScript",
                    packageInitNodes);
            for (int i = 0; i < packageInitNodes.size(); ++i) {
                NamedNodeMap attrs = packageInitNodes.elementAt(i).getAttributes();
                String packageName = attrs.getNamedItem("package").getNodeValue();

                if (packageName.equals(""))
                    packageName = "rGlobalEnv";

                if (!packageName.endsWith("Function"))
                    packageName += "Function";
                if (packageEmbedScriptHashMap.get(packageName) == null) {
                    packageEmbedScriptHashMap.put(packageName, new StringBuffer());
                }
                StringBuffer vbuffer = packageEmbedScriptHashMap.get(packageName);

                // if (!packageName.equals("rGlobalEnvFunction")) {
                // vbuffer.append("library("+packageName.substring(0,packageName.lastIndexOf("Function"))+")\n");
                // }

                if (attrs.getNamedItem("inline") != null) {
                    vbuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n");
                    initScriptBuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n");
                } else {
                    String fname = attrs.getNamedItem("name").getNodeValue();
                    if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') {
                        String path = files[f].getAbsolutePath();
                        path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR));
                        fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath();
                    }
                    StringBuffer fileBuffer = Utils.getFileAsStringBuffer(fname);
                    vbuffer.append(fileBuffer);
                    initScriptBuffer.append(fileBuffer);
                }
            }

            Vector<Node> functionsNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "functions"), "function",
                    functionsNodes);
            for (int i = 0; i < functionsNodes.size(); ++i) {
                NamedNodeMap attrs = functionsNodes.elementAt(i).getAttributes();
                String functionName = attrs.getNamedItem("name").getNodeValue();

                boolean forWeb = attrs.getNamedItem("forWeb") != null
                        && attrs.getNamedItem("forWeb").getNodeValue().equalsIgnoreCase("true");

                String signature = (attrs.getNamedItem("signature") == null ? ""
                        : attrs.getNamedItem("signature").getNodeValue() + ",");
                String renameTo = (attrs.getNamedItem("renameTo") == null ? null
                        : attrs.getNamedItem("renameTo").getNodeValue());

                HashMap<String, FAttributes> sigMap = Globals._functionsToPublish.get(functionName);

                if (sigMap == null) {
                    sigMap = new HashMap<String, FAttributes>();
                    Globals._functionsToPublish.put(functionName, sigMap);

                    if (attrs.getNamedItem("returnType") == null) {
                        _functionsVector.add(new String[] { functionName });
                    } else {
                        _functionsVector.add(
                                new String[] { functionName, attrs.getNamedItem("returnType").getNodeValue() });
                    }

                }

                sigMap.put(signature, new FAttributes(renameTo, forWeb));

                if (forWeb)
                    _webPublishingEnabled = true;

            }

            if (System.getProperty("targetjdk") != null && !System.getProperty("targetjdk").equals("")
                    && System.getProperty("targetjdk").compareTo("1.5") < 0) {
                if (_webPublishingEnabled || (System.getProperty("ws.r.api") != null
                        && System.getProperty("ws.r.api").equalsIgnoreCase("true"))) {
                    log.info("be careful, web publishing disabled beacuse target JDK<1.5");
                }
                _webPublishingEnabled = false;
            } else {

                if (System.getProperty("ws.r.api") == null || System.getProperty("ws.r.api").equals("")
                        || !System.getProperty("ws.r.api").equalsIgnoreCase("false")) {
                    _webPublishingEnabled = true;
                }

                if (_webPublishingEnabled && System.getProperty("java.version").compareTo("1.5") < 0) {
                    log.info("be careful, web publishing disabled beacuse a JDK<1.5 is in use");
                    _webPublishingEnabled = false;
                }
            }

            Vector<Node> s4Nodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "s4classes"), "class", s4Nodes);

            if (s4Nodes.size() > 0) {
                String formalArgs = "";
                String signature = "";
                for (int i = 0; i < s4Nodes.size(); ++i) {
                    NamedNodeMap attrs = s4Nodes.elementAt(i).getAttributes();
                    String s4Name = attrs.getNamedItem("name").getNodeValue();
                    formalArgs += "p" + i + (i == s4Nodes.size() - 1 ? "" : ",");
                    signature += "'" + s4Name + "'" + (i == s4Nodes.size() - 1 ? "" : ",");
                }
                String genBeansScriptlet = "setGeneric('" + PUBLISH_S4_HEADER + "', function(" + formalArgs
                        + ") standardGeneric('" + PUBLISH_S4_HEADER + "'));" + "setMethod('" + PUBLISH_S4_HEADER
                        + "', signature(" + signature + ") , function(" + formalArgs + ") {   })";
                initScriptBuffer.append(genBeansScriptlet);
                _functionsVector.add(new String[] { PUBLISH_S4_HEADER, "numeric" });
            }

        }

        if (!new File(GEN_ROOT_LIB).exists())
            regenerateDir(GEN_ROOT_LIB);
        else {
            clean(GEN_ROOT_LIB, true);
        }

        for (int i = 0; i < rwebservicesScripts.length; ++i)
            DirectJNI.getInstance().getRServices().sourceFromResource(rwebservicesScripts[i]);

        String lastStatus = DirectJNI.getInstance().runR(new ExecutionUnit() {
            public void run(Rengine e) {
                DirectJNI.getInstance().toggleMarker();
                DirectJNI.getInstance().sourceFromBuffer(initScriptBuffer.toString());
                log.info(" init  script status : " + DirectJNI.getInstance().cutStatusSinceMarker());

                for (int i = 0; i < _functionsVector.size(); ++i) {

                    String[] functionPair = _functionsVector.elementAt(i);
                    log.info("dealing with : " + functionPair[0]);

                    regenerateDir(GEN_ROOT_SRC);

                    String createMapStr = "createMap(";
                    boolean isGeneric = e.rniGetBoolArrayI(
                            e.rniEval(e.rniParse("isGeneric(\"" + functionPair[0] + "\")", 1), 0))[0] == 1;

                    log.info("is Generic : " + isGeneric);
                    if (isGeneric) {
                        createMapStr += functionPair[0];
                    } else {
                        createMapStr += "\"" + functionPair[0] + "\"";
                    }
                    createMapStr += ", outputDirectory=\"" + GEN_ROOT_SRC
                            .substring(0, GEN_ROOT_SRC.length() - "/src".length()).replace('\\', '/') + "\"";
                    createMapStr += ", typeMode=\"robject\"";
                    createMapStr += (functionPair.length == 1 || functionPair[1] == null
                            || functionPair[1].trim().equals("") ? ""
                                    : ", S4DefaultTypedSig=TypedSignature(returnType=\"" + functionPair[1]
                                            + "\")");
                    createMapStr += ")";

                    log.info("------------------------------------------");
                    log.info("-- createMapStr=" + createMapStr);
                    DirectJNI.getInstance().toggleMarker();
                    e.rniEval(e.rniParse(createMapStr, 1), 0);
                    String createMapStatus = DirectJNI.getInstance().cutStatusSinceMarker();
                    log.info(" createMap status : " + createMapStatus);
                    log.info("------------------------------------------");

                    deleteDir(GEN_ROOT_SRC + "/org/kchine/r/rserviceJms");
                    compile(GEN_ROOT_SRC);
                    jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", null);

                    URL url = null;
                    try {
                        url = new URL(
                                "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar")
                                        .replace('\\', '/') + "!/");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    DirectJNI.generateMaps(url, true);
                }

            }
        });

        log.info(lastStatus);

        log.info(DirectJNI._rPackageInterfacesHash);
        regenerateDir(GEN_ROOT_SRC);
        for (int i = 0; i < _functionsVector.size(); ++i) {
            unjar(GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", GEN_ROOT_SRC);
        }

        regenerateRPackageClass(true);

        generateS4BeanRef();

        if (formatsource)
            applyJalopy(GEN_ROOT_SRC);

        compile(GEN_ROOT_SRC);

        for (String k : DirectJNI._rPackageInterfacesHash.keySet()) {
            Rmic rmicTask = new Rmic();
            rmicTask.setProject(_project);
            rmicTask.setTaskName("rmic_packages");
            rmicTask.setClasspath(new Path(_project, GEN_ROOT_SRC));
            rmicTask.setBase(new File(GEN_ROOT_SRC));
            rmicTask.setClassname(k + "ImplRemote");
            rmicTask.init();
            rmicTask.execute();
        }

        // DirectJNI._rPackageInterfacesHash=new HashMap<String,
        // Vector<Class<?>>>();
        // DirectJNI._rPackageInterfacesHash.put("org.bioconductor.packages.rGlobalEnv.rGlobalEnvFunction",new
        // Vector<Class<?>>());

        if (_webPublishingEnabled) {

            jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar", null);
            URL url = new URL(
                    "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").replace('\\', '/') + "!/");
            ClassLoader cl = new URLClassLoader(new URL[] { url }, Globals.class.getClassLoader());

            for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
                if (cl.loadClass(className + "Web").getDeclaredMethods().length == 0)
                    continue;
                log.info("######## " + className);

                WsGen wsgenTask = new WsGen();
                wsgenTask.setProject(_project);
                wsgenTask.setTaskName("wsgen");

                FileSet rjb_fileSet = new FileSet();
                rjb_fileSet.setProject(_project);
                rjb_fileSet.setDir(new File("."));
                rjb_fileSet.setIncludes("RJB.jar");

                DirSet src_dirSet = new DirSet();
                src_dirSet.setDir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                Path classPath = new Path(_project);
                classPath.addFileset(rjb_fileSet);
                classPath.addDirset(src_dirSet);
                wsgenTask.setClasspath(classPath);
                wsgenTask.setKeep(true);
                wsgenTask.setDestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                wsgenTask.setResourcedestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                wsgenTask.setSei(className + "Web");

                wsgenTask.init();
                wsgenTask.execute();
            }

            new File(GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").delete();

        }

        embedRScripts();

        HashMap<String, String> marker = new HashMap<String, String>();
        marker.put("RJBMAPPINGJAR", "TRUE");

        Properties props = new Properties();
        props.put("PACKAGE_NAMES", PoolUtils.objectToHex(DirectJNI._packageNames));
        props.put("S4BEANS_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMapping));
        props.put("S4BEANS_REVERT_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMappingRevert));
        props.put("FACTORIES_MAPPING", PoolUtils.objectToHex(DirectJNI._factoriesMapping));
        props.put("S4BEANS_HASH", PoolUtils.objectToHex(DirectJNI._s4BeansHash));
        props.put("R_PACKAGE_INTERFACES_HASH", PoolUtils.objectToHex(DirectJNI._rPackageInterfacesHash));
        props.put("ABSTRACT_FACTORIES", PoolUtils.objectToHex(DirectJNI._abstractFactories));
        new File(GEN_ROOT_SRC + "/" + "maps").mkdirs();
        FileOutputStream fos = new FileOutputStream(GEN_ROOT_SRC + "/" + "maps/rjbmaps.xml");
        props.storeToXML(fos, null);
        fos.close();

        jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME, marker);

        if (_webPublishingEnabled)
            genWeb();

        DirectJNI._mappingClassLoader = null;

    } finally {

        System.exit(0);

    }
}

From source file:edu.uthscsa.ric.papaya.builder.Builder.java

public static void main(final String[] args) {
    final Builder builder = new Builder();

    // process command line
    final CommandLine cli = builder.createCLI(args);
    builder.setUseSample(cli.hasOption(ARG_SAMPLE));
    builder.setUseAtlas(cli.hasOption(ARG_ATLAS));
    builder.setLocal(cli.hasOption(ARG_LOCAL));
    builder.setPrintHelp(cli.hasOption(ARG_HELP));
    builder.setUseImages(cli.hasOption(ARG_IMAGE));
    builder.setSingleFile(cli.hasOption(ARG_SINGLE));
    builder.setUseParamFile(cli.hasOption(ARG_PARAM_FILE));
    builder.setUseTitle(cli.hasOption(ARG_TITLE));

    // print help, if necessary
    if (builder.isPrintHelp()) {
        builder.printHelp();//from  w  ww.  ja v  a2  s  . co m
        return;
    }

    // find project root directory
    if (cli.hasOption(ARG_ROOT)) {
        try {
            builder.projectDir = (new File(cli.getOptionValue(ARG_ROOT))).getCanonicalFile();
        } catch (final IOException ex) {
            System.err.println("Problem finding root directory.  Reason: " + ex.getMessage());
        }
    }

    if (builder.projectDir == null) {
        builder.projectDir = new File(System.getProperty("user.dir"));
    }

    // clean output dir
    final File outputDir = new File(builder.projectDir + "/" + OUTPUT_DIR);
    System.out.println("Cleaning output directory...");
    try {
        builder.cleanOutputDir(outputDir);
    } catch (final IOException ex) {
        System.err.println("Problem cleaning build directory.  Reason: " + ex.getMessage());
    }

    if (builder.isLocal()) {
        System.out.println("Building for local usage...");
    }

    // write JS
    final File compressedFileJs = new File(outputDir, OUTPUT_JS_FILENAME);

    // build properties
    try {
        final File buildFile = new File(builder.projectDir + "/" + BUILD_PROP_FILE);

        builder.readBuildProperties(buildFile);
        builder.buildNumber++; // increment build number
        builder.writeBuildProperties(compressedFileJs, true);
        builder.writeBuildProperties(buildFile, false);
    } catch (final IOException ex) {
        System.err.println("Problem handling build properties.  Reason: " + ex.getMessage());
    }

    String htmlParameters = null;

    if (builder.isUseParamFile()) {
        final String paramFileArg = cli.getOptionValue(ARG_PARAM_FILE);

        if (paramFileArg != null) {
            try {
                System.out.println("Including parameters...");

                final String parameters = FileUtils.readFileToString(new File(paramFileArg), "UTF-8");
                htmlParameters = "var params = " + parameters + ";";
            } catch (final IOException ex) {
                System.err.println("Problem reading parameters file! " + ex.getMessage());
            }
        }
    }

    String title = null;
    if (builder.isUseTitle()) {
        String str = cli.getOptionValue(ARG_TITLE);
        if (str != null) {
            str = str.trim();
            str = str.replace("\"", "");
            str = str.replace("'", "");

            if (str.length() > 0) {
                title = str;
                System.out.println("Using title: " + title);
            }
        }
    }

    try {
        final JSONArray loadableImages = new JSONArray();

        // sample image
        if (builder.isUseSample()) {
            System.out.println("Including sample image...");

            final File sampleFile = new File(builder.projectDir + "/" + SAMPLE_IMAGE_NII_FILE);
            final String filename = Utilities
                    .replaceNonAlphanumericCharacters(Utilities.removeNiftiExtensions(sampleFile.getName()));

            if (builder.isLocal()) {
                loadableImages.put(new JSONObject("{\"nicename\":\"Sample Image\",\"name\":\"" + filename
                        + "\",\"encode\":\"" + filename + "\"}"));
                final String sampleEncoded = Utilities.encodeImageFile(sampleFile);
                FileUtils.writeStringToFile(compressedFileJs,
                        "var " + filename + "= \"" + sampleEncoded + "\";\n", "UTF-8", true);
            } else {
                loadableImages.put(new JSONObject("{\"nicename\":\"Sample Image\",\"name\":\"" + filename
                        + "\",\"url\":\"" + SAMPLE_IMAGE_NII_FILE + "\"}"));
                FileUtils.copyFile(sampleFile, new File(outputDir + "/" + SAMPLE_IMAGE_NII_FILE));
            }
        }

        // atlas
        if (builder.isUseAtlas()) {
            Atlas atlas = null;

            try {
                String atlasArg = cli.getOptionValue(ARG_ATLAS);

                if (atlasArg == null) {
                    atlasArg = (builder.projectDir + "/" + SAMPLE_DEFAULT_ATLAS_FILE);
                }

                final File atlasXmlFile = new File(atlasArg);

                System.out.println("Including atlas " + atlasXmlFile);

                atlas = new Atlas(atlasXmlFile);
                final File atlasJavaScriptFile = atlas.createAtlas(builder.isLocal());
                System.out.println("Using atlas image file " + atlas.getImageFile());

                if (builder.isLocal()) {
                    loadableImages.put(
                            new JSONObject("{\"nicename\":\"Atlas\",\"name\":\"" + atlas.getImageFileNewName()
                                    + "\",\"encode\":\"" + atlas.getImageFileNewName() + "\",\"hide\":true}"));
                } else {
                    final File atlasImageFile = atlas.getImageFile();
                    final String atlasPath = "data/" + atlasImageFile.getName();

                    loadableImages.put(new JSONObject("{\"nicename\":\"Atlas\",\"name\":\""
                            + atlas.getImageFileNewName() + "\",\"url\":\"" + atlasPath + "\",\"hide\":true}"));
                    FileUtils.copyFile(atlasImageFile, new File(outputDir + "/" + atlasPath));
                }

                builder.writeFile(atlasJavaScriptFile, compressedFileJs);
            } catch (final IOException ex) {
                System.err.println("Problem finding atlas file.  Reason: " + ex.getMessage());
            }
        }

        // additional images
        if (builder.isUseImages()) {
            final String[] imageArgs = cli.getOptionValues(ARG_IMAGE);

            if (imageArgs != null) {
                for (final String imageArg : imageArgs) {
                    final File file = new File(imageArg);
                    System.out.println("Including image " + file);

                    final String filename = Utilities
                            .replaceNonAlphanumericCharacters(Utilities.removeNiftiExtensions(file.getName()));

                    if (builder.isLocal()) {
                        loadableImages.put(new JSONObject(
                                "{\"nicename\":\"" + Utilities.removeNiftiExtensions(file.getName())
                                        + "\",\"name\":\"" + filename + "\",\"encode\":\"" + filename + "\"}"));
                        final String sampleEncoded = Utilities.encodeImageFile(file);
                        FileUtils.writeStringToFile(compressedFileJs,
                                "var " + filename + "= \"" + sampleEncoded + "\";\n", "UTF-8", true);
                    } else {
                        final String filePath = "data/" + file.getName();
                        loadableImages.put(new JSONObject(
                                "{\"nicename\":\"" + Utilities.removeNiftiExtensions(file.getName())
                                        + "\",\"name\":\"" + filename + "\",\"url\":\"" + filePath + "\"}"));
                        FileUtils.copyFile(file, new File(outputDir + "/" + filePath));
                    }
                }
            }
        }

        File tempFileJs = null;

        try {
            tempFileJs = builder.createTempFile();
        } catch (final IOException ex) {
            System.err.println("Problem creating temp write file.  Reason: " + ex.getMessage());
        }

        // write image refs
        FileUtils.writeStringToFile(tempFileJs,
                "var " + PAPAYA_LOADABLE_IMAGES + " = " + loadableImages.toString() + ";\n", "UTF-8", true);

        // compress JS
        tempFileJs = builder.concatenateFiles(JS_FILES, "js", tempFileJs);

        System.out.println("Compressing JavaScript... ");
        FileUtils.writeStringToFile(compressedFileJs, "\n", "UTF-8", true);
        builder.compressJavaScript(tempFileJs, compressedFileJs, new YuiCompressorOptions());
        //tempFileJs.deleteOnExit();
    } catch (final IOException ex) {
        System.err.println("Problem concatenating JavaScript.  Reason: " + ex.getMessage());
    }

    // compress CSS
    final File compressedFileCss = new File(outputDir, OUTPUT_CSS_FILENAME);

    try {
        final File concatFile = builder.concatenateFiles(CSS_FILES, "css", null);
        System.out.println("Compressing CSS... ");
        builder.compressCSS(concatFile, compressedFileCss, new YuiCompressorOptions());
        concatFile.deleteOnExit();
    } catch (final IOException ex) {
        System.err.println("Problem concatenating CSS.  Reason: " + ex.getMessage());
    }

    // write HTML
    try {
        System.out.println("Writing HTML... ");
        if (builder.singleFile) {
            builder.writeHtml(outputDir, compressedFileJs, compressedFileCss, htmlParameters, title);
        } else {
            builder.writeHtml(outputDir, htmlParameters, title);
        }
    } catch (final IOException ex) {
        System.err.println("Problem writing HTML.  Reason: " + ex.getMessage());
    }

    System.out.println("Done!  Output files located at " + outputDir);
}