Example usage for java.util Properties Properties

List of usage examples for java.util Properties Properties

Introduction

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

Prototype

public Properties() 

Source Link

Document

Creates an empty property list with no default values.

Usage

From source file:main.java.com.google.api.services.samples.youtube.cmdline.YouTubeSample.java

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

    Properties properties = new Properties();
    try {/*from  w ww.  j  a v  a 2 s .  c o m*/
        InputStream in = YouTubeSample.class.getResourceAsStream("" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest arg0) throws IOException {
            // TODO Auto-generated method stub

        }
    }).setApplicationName("youtubeTest").build();

    YouTube.Videos.List videos = youtube.videos().list("snippet");

    String apiKey = properties.getProperty("youtube.apikey");
    videos.setKey(apiKey);
    videos.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
    videos.setChart("mostPopular");

    VideoListResponse response = videos.execute();

    java.util.List<Video> videoList = response.getItems();

    if (videoList != null) {
        prettyPrint(videoList.iterator());
    } else {
        System.out.println("There were  no results!");
    }

}

From source file:com.joliciel.talismane.TalismaneMain.java

public static void main(String[] args) throws Exception {
    Map<String, String> argsMap = StringUtils.convertArgs(args);
    OtherCommand otherCommand = null;//from w  w  w  .j av a  2s .  c om
    if (argsMap.containsKey("command")) {
        try {
            otherCommand = OtherCommand.valueOf(argsMap.get("command"));
            argsMap.remove("command");
        } catch (IllegalArgumentException e) {
            // not anotherCommand
        }
    }

    String sessionId = "";
    TalismaneServiceLocator locator = TalismaneServiceLocator.getInstance(sessionId);
    TalismaneService talismaneService = locator.getTalismaneService();
    TalismaneSession talismaneSession = talismaneService.getTalismaneSession();

    if (otherCommand == null) {
        // regular command
        TalismaneConfig config = talismaneService.getTalismaneConfig(argsMap, sessionId);
        if (config.getCommand() == null)
            return;

        Talismane talismane = config.getTalismane();

        talismane.process();
    } else {
        // other command
        String logConfigPath = argsMap.get("logConfigFile");
        if (logConfigPath != null) {
            argsMap.remove("logConfigFile");
            Properties props = new Properties();
            props.load(new FileInputStream(logConfigPath));
            PropertyConfigurator.configure(props);
        }

        switch (otherCommand) {
        case serializeLexicon: {
            LexiconSerializer serializer = new LexiconSerializer();
            serializer.serializeLexicons(argsMap);
            break;
        }
        case testLexicon: {
            String lexiconFilePath = null;
            String[] wordList = null;
            for (String argName : argsMap.keySet()) {
                String argValue = argsMap.get(argName);
                if (argName.equals("lexicon")) {
                    lexiconFilePath = argValue;
                } else if (argName.equals("words")) {
                    wordList = argValue.split(",");
                } else {
                    throw new TalismaneException("Unknown argument: " + argName);
                }
            }
            File lexiconFile = new File(lexiconFilePath);
            LexiconDeserializer lexiconDeserializer = new LexiconDeserializer(talismaneSession);
            List<PosTaggerLexicon> lexicons = lexiconDeserializer.deserializeLexicons(lexiconFile);
            for (PosTaggerLexicon lexicon : lexicons)
                talismaneSession.addLexicon(lexicon);
            PosTaggerLexicon mergedLexicon = talismaneSession.getMergedLexicon();
            for (String word : wordList) {
                LOG.info("################");
                LOG.info("Word: " + word);
                List<LexicalEntry> entries = mergedLexicon.getEntries(word);
                for (LexicalEntry entry : entries) {
                    LOG.info(entry + ", Full morph: " + entry.getMorphologyForCoNLL());
                }
            }
            break;
        }
        }
    }
}

From source file:com.mmounirou.spotirss.SpotiRss.java

/**
 * @param args/*from w w w  . j av  a2 s .  c  o  m*/
 * @throws IOException 
 * @throws ClassNotFoundException 
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 * @throws SpotifyClientException 
 * @throws ChartRssException 
 * @throws SpotifyException 
 */
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException,
        ClassNotFoundException, SpotifyClientException {
    if (args.length == 0) {
        System.err.println("usage : java -jar spotiboard.jar <charts-folder>");
        return;
    }

    Properties connProperties = new Properties();
    InputStream inStream = SpotiRss.class.getResourceAsStream("/spotify-server.properties");
    try {
        connProperties.load(inStream);
    } finally {
        IOUtils.closeQuietly(inStream);
    }

    String host = connProperties.getProperty("host");
    int port = Integer.parseInt(connProperties.getProperty("port"));
    String user = connProperties.getProperty("user");

    final SpotifyClient spotifyClient = new SpotifyClient(host, port, user);
    final Map<String, Playlist> playlistsByTitle = getPlaylistsByTitle(spotifyClient);

    final File outputDir = new File(args[0]);
    outputDir.mkdirs();
    TrackCache cache = new TrackCache();
    try {

        for (String strProvider : PROVIDERS) {
            String providerClassName = EntryToTrackConverter.class.getPackage().getName() + "."
                    + StringUtils.capitalize(strProvider);
            final EntryToTrackConverter converter = (EntryToTrackConverter) SpotiRss.class.getClassLoader()
                    .loadClass(providerClassName).newInstance();
            Iterable<String> chartsRss = getCharts(strProvider);
            final File resultDir = new File(outputDir, strProvider);
            resultDir.mkdir();

            final SpotifyHrefQuery hrefQuery = new SpotifyHrefQuery(cache);
            Iterable<String> results = FluentIterable.from(chartsRss).transform(new Function<String, String>() {

                @Override
                @Nullable
                public String apply(@Nullable String chartRss) {

                    try {

                        long begin = System.currentTimeMillis();
                        ChartRss bilboardChartRss = ChartRss.getInstance(chartRss, converter);
                        Map<Track, String> trackHrefs = hrefQuery.getTrackHrefs(bilboardChartRss.getSongs());

                        String strTitle = bilboardChartRss.getTitle();
                        File resultFile = new File(resultDir, strTitle);
                        List<String> lines = Lists.newLinkedList(FluentIterable.from(trackHrefs.keySet())
                                .transform(Functions.toStringFunction()));
                        lines.addAll(trackHrefs.values());
                        FileUtils.writeLines(resultFile, Charsets.UTF_8.displayName(), lines);

                        Playlist playlist = playlistsByTitle.get(strTitle);
                        if (playlist != null) {
                            playlist.getTracks().clear();
                            playlist.getTracks().addAll(trackHrefs.values());
                            spotifyClient.patch(playlist);
                            LOGGER.info(String.format("%s chart exported patched", strTitle));
                        }

                        LOGGER.info(String.format("%s chart exported in %s in %d s", strTitle,
                                resultFile.getAbsolutePath(),
                                (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - begin)));

                    } catch (Exception e) {
                        LOGGER.error(String.format("fail to export %s charts", chartRss), e);
                    }

                    return "";
                }
            });

            // consume iterables
            Iterables.size(results);

        }

    } finally {
        cache.close();
    }

}

From source file:de.cwclan.cwsa.serverendpoint.main.ServerEndpoint.java

/**
 * @param args the command line arguments
 *//*from ww  w. jav a  2 s.c o  m*/
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription(
            "Used to enter path of configfile. Default file is endpoint.properties. NOTE: If the file is empty or does not exsist, a default config is created.")
            .create("config"));
    options.addOption("h", "help", false, "displays this page");
    CommandLineParser parser = new PosixParser();
    Properties properties = new Properties();
    try {
        /*
         * parse default config shipped with jar
         */
        CommandLine cmd = parser.parse(options, args);

        /*
         * load default configuration
         */
        InputStream in = ServerEndpoint.class.getResourceAsStream("/endpoint.properties");
        if (in == null) {
            throw new IOException("Unable to load default config from JAR. This should not happen.");
        }
        properties.load(in);
        in.close();
        log.debug("Loaded default config base: {}", properties.toString());
        if (cmd.hasOption("help")) {
            printHelp(options);
            System.exit(0);
        }

        /*
         * parse cutom config if exists, otherwise create default cfg
         */
        if (cmd.hasOption("config")) {
            File file = new File(cmd.getOptionValue("config", "endpoint.properties"));
            if (file.exists() && file.canRead() && file.isFile()) {
                in = new FileInputStream(file);
                properties.load(in);
                log.debug("Loaded custom config from {}: {}", file.getAbsoluteFile(), properties);
            } else {
                log.warn("Config file does not exsist. A default file will be created.");
            }
            FileWriter out = new FileWriter(file);
            properties.store(out,
                    "Warning, this file is recreated on every startup to merge missing parameters.");
        }

        /*
         * create and start endpoint
         */
        log.info("Config read successfull. Values are: {}", properties);
        ServerEndpoint endpoint = new ServerEndpoint(properties);
        Runtime.getRuntime().addShutdownHook(endpoint.getShutdownHook());
        endpoint.start();
    } catch (IOException ex) {
        log.error("Error while reading config.", ex);
    } catch (ParseException ex) {
        log.error("Error while parsing commandline options: {}", ex.getMessage());
        printHelp(options);
        System.exit(1);
    }
}

From source file:de.huberlin.german.korpling.laudatioteitool.App.java

public static void main(String[] args) {
    Options opts = new Options()
            .addOption(new Option("merge", true,
                    messages.getString("MERGE CONTENT FROM INPUT DIRECTORY INTO ONE TEI HEADER")))
            .addOption(new Option("split", true,
                    messages.getString("SPLIT ONE TEI HEADER INTO SEVERAL HEADER FILES")))
            .addOption(new Option("validate", true, messages.getString("VALIDATE DIRECTORY OR FILE")))
            .addOption(new Option("config", true, messages.getString("CONFIG FILE LOCATION")))
            .addOption(new Option("schemecorpus", true, messages.getString("CORPUS SCHEME LOCATION")))
            .addOption(new Option("schemedoc", true, messages.getString("DOCUMENT SCHEME LOCATION")))
            .addOption(new Option("schemeprep", true, messages.getString("PREPARATION SCHEME LOCATION")))
            .addOption(new Option("help", false, messages.getString("SHOW THIS HELP")));

    HelpFormatter fmt = new HelpFormatter();
    String usage = "java -jar teitool.jar [options] [output directory/file]";
    String header = messages.getString("HELP HEADER");
    String footer = messages.getString("HELP FOOTER");

    try {//from   w ww  .  ja  v  a  2s  .  c  o  m
        CommandLineParser cliParser = new PosixParser();

        CommandLine cmd = cliParser.parse(opts, args);

        Properties props = new Properties();
        if (cmd.hasOption("config")) {
            props = readConfig(cmd.getOptionValue("config"));
        } // end if "config" given
        fillPropertiesFromCommandLine(props, cmd);

        if (cmd.hasOption("help")) {
            fmt.printHelp(usage, header, opts, footer);
        } else if (cmd.hasOption("validate")) {
            validate(cmd.getOptionValue("validate"), props.getProperty("schemecorpus"),
                    props.getProperty("schemedoc"), props.getProperty("schemeprep"));
        } else if (cmd.hasOption("merge")) {
            if (cmd.getArgs().length != 1) {
                System.out.println(messages.getString("YOU NEED TO GIVE AT AN OUTPUT FILE AS ARGUMENT"));
                System.exit(-1);
            }
            MergeTEI merge = new MergeTEI(new File(cmd.getOptionValue("merge")), new File(cmd.getArgs()[0]),
                    props.getProperty("schemecorpus"), props.getProperty("schemedoc"),
                    props.getProperty("schemeprep"));
            merge.merge();

            System.exit(0);
        } else if (cmd.hasOption("split")) {
            if (cmd.getArgs().length != 1) {
                System.out.println(messages.getString("YOU NEED TO GIVE AT AN OUTPUT DIRECTORY AS ARGUMENT"));
                System.exit(-1);
            }
            SplitTEI split = new SplitTEI(new File(cmd.getOptionValue("split")), new File(cmd.getArgs()[0]),
                    props.getProperty("schemecorpus"), props.getProperty("schemedoc"),
                    props.getProperty("schemeprep"));
            split.split();
            System.exit(0);
        } else {
            fmt.printHelp(usage, header, opts, footer);
        }

    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        fmt.printHelp(usage, header, opts, footer);
    } catch (LaudatioException ex) {
        System.err.println(ex.getMessage());
    } catch (UnsupportedOperationException ex) {
        System.err.println(ex.getMessage());
    }

    System.exit(1);

}

From source file:com.msd.gin.halyard.tools.HalyardUpdate.java

/**
 * Main of the HalyardUpdate//from w w  w  .  jav  a2  s  . co  m
 * @param args String command line arguments
 * @throws Exception throws Exception in case of any problem
 */
public static void main(final String args[]) throws Exception {
    if (conf == null)
        conf = new Configuration();
    Options options = new Options();
    options.addOption(newOption("h", null, "Prints this help"));
    options.addOption(newOption("v", null, "Prints version"));
    options.addOption(newOption("s", "source_htable", "Source HBase table with Halyard RDF store"));
    options.addOption(
            newOption("q", "sparql_query", "SPARQL tuple or graph query executed to export the data"));
    try {
        CommandLine cmd = new PosixParser().parse(options, args);
        if (args.length == 0 || cmd.hasOption('h')) {
            printHelp(options);
            return;
        }
        if (cmd.hasOption('v')) {
            Properties p = new Properties();
            try (InputStream in = HalyardUpdate.class
                    .getResourceAsStream("/META-INF/maven/com.msd.gin.halyard/hbasesail/pom.properties")) {
                if (in != null)
                    p.load(in);
            }
            System.out.println("Halyard Update version " + p.getProperty("version", "unknown"));
            return;
        }
        if (!cmd.getArgList().isEmpty())
            throw new ParseException("Unknown arguments: " + cmd.getArgList().toString());
        for (char c : "sq".toCharArray()) {
            if (!cmd.hasOption(c))
                throw new ParseException("Missing mandatory option: " + c);
        }
        for (char c : "sq".toCharArray()) {
            String s[] = cmd.getOptionValues(c);
            if (s != null && s.length > 1)
                throw new ParseException("Multiple values for option: " + c);
        }

        SailRepository rep = new SailRepository(
                new HBaseSail(conf, cmd.getOptionValue('s'), false, 0, true, 0, null));
        rep.initialize();
        try {
            Update u = rep.getConnection().prepareUpdate(QueryLanguage.SPARQL, cmd.getOptionValue('q'));
            LOG.info("Update execution started");
            u.execute();
            LOG.info("Update finished");
        } finally {
            rep.shutDown();
        }

    } catch (Exception exp) {
        System.out.println(exp.getMessage());
        printHelp(options);
        throw exp;
    }
}

From source file:ape.Main.java

public static void main(String[] args) {
    // Creating the Properties object for log4j
    Properties ppt = new Properties();
    ppt.setProperty("log4j.rootLogger", "INFO, appender1");
    ppt.setProperty("log4j.appender.appender1", "org.apache.log4j.DailyRollingFileAppender");
    ppt.setProperty("log4j.appender.appender1.File", "/var/log/ape.log");
    ppt.setProperty("log4j.appender.appender1.DatePattern", ".yyyy-MM-dd");
    ppt.setProperty("log4j.appender.appender1.layout", "org.apache.log4j.PatternLayout");

    // Configuring log4j to use the Properties object created above
    PropertyConfigurator.configure(ppt);

    // Log the current date and time
    logger.info("\n---------------------------------\nStarting time:");
    logTime();//www .  ja  v a  2  s .  c  om

    // Initialize all of the Option objects for each command (these are used by the CLI parser)
    createOptions();

    // There should be an array of strings passed in as an argument (even if it's empty)
    // If we get null, we exit
    if (args == null) {
        System.err
                .println("Invalid arguments.  main(String[] args) method expected array of strings, got null.");
        logger.info("Invalid arguments.  main(String[] args) method expected array of strings, got null");
        printHelp();
        return;
    }

    // If an empty array is passed in, print the help dialog and exit
    if (args.length == 0) {
        printHelp();
        return;
    }

    // Use the CLI parser to attempt to parse the command into a series of Option objects
    try {
        System.out.println(Arrays.toString(args));
        logger.info(Arrays.toString(args));
        line = getCommand(args);
        //System.out.println(line.toString());   
    } catch (MissingArgumentException e) {
        System.out.println("Missing an argument.  Check your syntax.");
        logger.info("Missing an argument.");
        logger.info("Dumping args array:");
        for (int i = 0; i < args.length; i++) {
            logger.info(i + ": " + args[i]);
        }
        printHelp();
        return;
    } catch (ParseException e) {
        System.out.println("Parsing error, see help dialog:");
        logger.info("Parsing error, see help dialog.");
        printHelp();
        return;
    }

    // Get the array of options that were parsed from the command line 
    Option[] options = line.getOptions();

    if (line.hasOption("v")) {
        MAX_OPTION_LENGTH = 3;
    } else {
        MAX_OPTION_LENGTH = 2;
    }

    if (options == null || options.length > MAX_OPTION_LENGTH || options.length < 1) {
        System.out.println("Too many options");
        logger.info("Too many options");
        printHelp();
        return;
    }

    if (line.hasOption("v")) {
        VERBOSE = true;
        logger.info("Executing Ape verbosely.");
        System.out.println("Executing Ape verbosely");
    }

    //Find which option is cmd, which is -local/-remote, order might be disturbed
    for (int k = 0; k < options.length; k++) {
        if (VERBOSE) {
            System.out.println(options[k]);
            logger.info(options[k]);
        }
        if (!options[k].getOpt().equals("v")) {
            if (options[k].getOpt() == "L" || options[k].getOpt() == "R") {
                modeN = k;
            } else
                cmdN = k;
        }
    }

    // If the version flag was in the command, print the version and exit
    if (line.hasOption("V")) {
        logger.info("Printing out current version: " + VERSION);
        System.out.println("ChaosMonkey version: " + VERSION);
        return;
    }

    if (line.hasOption('h') || options.length < 1 || modeN == cmdN || modeN == -1 || cmdN == -1) {
        if (cmdN == -1) {
            System.out.println("Failure commands were not specified.");
            logger.info("Failure commands were not specified.");
        }
        System.out.println("Exiting ...");
        logger.info("Exiting ...");
        printHelp();
        return;
    }

    if (VERBOSE) {
        System.out.println("Mode is " + options[modeN].getLongOpt());

        if (options[modeN].getOpt() == "R") {
            System.out.println("List of Hosts:");
            for (int j = 0; j < line.getOptionValues("R").length; j++) {
                System.out.println(line.getOptionValues("R")[j]);
            }
        }

        System.out.println("Command is " + options[cmdN].getLongOpt());

        if (line.getOptionValues(options[cmdN].getOpt()) != null) {
            for (int l = 0; l < line.getOptionValues(options[cmdN].getOpt()).length; l++)
                System.out.println("Command Argument: " + line.getOptionValues(options[cmdN].getOpt())[l]);
        }
    }

    logger.info("Type of Event " + options[cmdN].getLongOpt());

    // Remote command execution
    if (line.hasOption("R")) {
        //go to remote
        String[] passIn = line.getOptionValues("R");
        logger.info("Executing a command remotely");
        logger.info("hosts: ");

        for (int k = 0; k < passIn.length; k++) {
            logger.info(passIn[k]);
        }

        CommunicationInterface r = new PDSHCommunication(options[cmdN].getOpt(),
                line.getOptionValues(options[cmdN].getOpt()), passIn);
        try {
            // If the command executed successfully
            if (r.execute()) {
                logger.info("End time");

                logTime();

                System.out.println("Running Remote Command Succeeded");
            }
            // If the command exited with an error
            else {
                System.out.println("Running remote command failed");
                logger.info("Running remote command failed");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        return;

    }
    // Local command execution
    else if (line.hasOption("L")) {
        logger.info("Running Locally");

        ApeCommand ac = ApeCommand.getCommand(options[cmdN].getLongOpt());
        if (ac == null) {
            System.out.println(options[cmdN].getLongOpt() + " is not a valid command.");
            System.out.println(
                    "This can occur if a new command class is added but an entry is not added in the ApeCommand file.");
            System.out.println(
                    "See src/main/resources/META-INF/services/ape.ApeCommand and ensure that the command's class is there.");
            logger.info(options[cmdN].getLongOpt() + " is not a valid command.");

            return;
        }

        try {
            String[] cmdArgs = line.getOptionValues(options[cmdN].getOpt());
            if (ac.exec(cmdArgs)) {
                System.out.println("Running local command succeeded");
                logger.info("End time");

                logTime();

            } else {
                System.out.println("Running local command failed");
                logger.info("Running local command failed");
            }
            return;
        } catch (ParseException e) {
            if (Main.VERBOSE) {
                System.out.println("VERBOSE: A parse exception was thrown.  ");
                System.out.println(
                        "VERBOSE: Interpreting this as an invalid number of arguments for a particular flag and printing the help dialog.");
                System.out.println("VERBOSE: Stack trace:");
                e.printStackTrace();
                logger.info("VERBOSE: A parse exception was thrown.  ");
                logger.info(
                        "VERBOSE: Interpreting this as an invalid number of arguments for a particular flag and printing the help dialog.");
                logger.info("VERBOSE: Stack trace:");
                logger.info(e);
            }
            System.out.println("Invalid number of arguments.");
            logger.info("Invalid number of arguments");
            printHelp();
        } catch (IOException e) {
            System.out.println("Running local command failed");
            logger.info("Running local command failed");
            e.printStackTrace();
        }
    }
    // If the local or remote flags were not used then print the help dialog
    else {
        printHelp();
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    if (args.length != 4) {
        usage();//  www . j  a  va2  s .c o  m
        System.exit(1);
    }

    System.out.println();

    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    if (debug)
        props.put("mail.debug", args[3]);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(args[0]) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail APIs Test");
        msg.setSentDate(new Date());
        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(msgText);

        Transport.send(msg);
    } catch (MessagingException mex) {
        System.out.println("\n--Exception handling in msgsendsample.java");

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++)
                            System.out.println("         " + invalid[i]);
                    }
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++)
                            System.out.println("         " + validUnsent[i]);
                    }
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++)
                            System.out.println("         " + validSent[i]);
                    }
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

From source file:com.welocalize.dispatcherMW.client.Main.java

public static void main(String[] args) throws InterruptedException, IOException {
    if (args.length >= 3) {
        String type = args[0];//from  w  ww.java 2  s  .  c  o  m
        if (TYPE_TRANSLATE.equalsIgnoreCase(type)) {
            setbasicURl(args[1]);
            doJob(args[2], args[3]);
            return;
        } else if (TYPE_CHECK_STATUS.equalsIgnoreCase(type)) {
            setbasicURl(args[1]);
            checkJobStaus(args[2]);
            return;
        } else if (TYPE_DOWNLOAD.equalsIgnoreCase(type)) {
            setbasicURl(args[1]);
            downloadJob(args[2], args[3]);
            return;
        }
    } else if (args.length == 1) {
        Properties properties = new Properties();
        properties.load(new FileInputStream(args[0]));
        String type = properties.getProperty("type");
        setbasicURl(properties.getProperty("URL"));
        String securityCode = properties.getProperty(JSONPN_SECURITY_CODE);
        String filePath = properties.getProperty("filePath");
        String jobID = properties.getProperty(JSONPN_JOBID);
        if (TYPE_TRANSLATE.equalsIgnoreCase(type)) {
            doJob(securityCode, filePath);
            return;
        } else if (TYPE_CHECK_STATUS.equalsIgnoreCase(type)) {
            String status = checkJobStaus(jobID);
            System.out.println("The Status of Job:" + jobID + " is " + status + ". ");
            return;
        } else if (TYPE_DOWNLOAD.equalsIgnoreCase(type)) {
            downloadJob(jobID, securityCode);
            System.out.println("Download Job:" + jobID);
            return;
        }
    }

    // Print Help Message
    StringBuffer msg = new StringBuffer();
    msg.append("The Input is incorrect.").append("\n");
    msg.append("If you want to translate the XLF file, use this command:").append("\n");
    msg.append(" translate $URL $securityCode $filePath").append("\n");
    msg.append("If you only want to check job status, use this command:").append("\n");
    msg.append(" checkStatus $URL $jobID").append("\n");
    msg.append("If you only want to download the job file, use this command:").append("\n");
    msg.append(" download $URL $jobID $securityCode").append("\n");
    System.out.println(msg.toString());
}

From source file:org.atomserver.utils.jetty.StandAloneAtomServer.java

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

    // the System Property "atomserver.home" defines the home directory for the standalone app
    String atomserverHome = System.getProperty("atomserver.home");
    if (StringUtils.isEmpty(atomserverHome)) {
        log.error("The variable \"atomserver.home\" must be defined");
        System.exit(-1);//from   w w w .j  a v  a  2s  .c  om
    }
    File atomserverHomeDir = new File(atomserverHome);
    if (!atomserverHomeDir.exists() && !atomserverHomeDir.isDirectory()) {
        log.error("The variable \"atomserver.home\" (" + atomserverHome
                + ") must point to a directory that exists");
    }

    // instantiate the Jetty Server
    Server server = new Server();

    // create a new connector on the declared port, and set it onto the server
    log.debug("atomserver.port = " + System.getProperty("atomserver.port"));
    Connector connector = new SelectChannelConnector();
    connector.setPort(Integer.getInteger("atomserver.port", DEFAULT_PORT));
    server.setConnectors(new Connector[] { connector });

    // create a ClassLoader that points at the conf directories
    log.debug("atomserver.conf.dir = " + System.getProperty("atomserver.conf.dir"));
    log.debug("atomserver.ops.conf.dir = " + System.getProperty("atomserver.ops.conf.dir"));
    ClassLoader classLoader = new ConfigurationAwareClassLoader(StandAloneAtomServer.class.getClassLoader());

    // load the version from the version.properties file
    Properties versionProps = new Properties();
    versionProps.load(classLoader.getResourceAsStream(DEFAULT_VERSIONS_FILE));
    String version = versionProps.getProperty("atomserver.version");

    // create a new webapp, rooted at webapps/atomserver-${version}, with the configured
    // context name
    String servletContextName = System.getProperty("atomserver.servlet.context");
    log.debug("atomserver.servlet.context = " + servletContextName);
    WebAppContext webapp = new WebAppContext(atomserverHome + "/webapps/atomserver-" + version,
            "/" + servletContextName);

    // set the webapp's ClassLoader to be the one that loaded THIS class.  the REASON that
    // this needs to be set is so that when we extract the web application context below we can
    // cast it to WebApplicationContext here
    webapp.setClassLoader(StandAloneAtomServer.class.getClassLoader());

    // set the Jetty server's webapp and start it
    server.setHandler(webapp);
    server.start();

    // if the seed system property was set, use the DBSeeder to populate the server
    String seedDB = System.getProperty("seed.database.with.pets");
    log.debug("seed.database.with.pets = " + seedDB);
    if (!StringUtils.isEmpty(seedDB)) {
        if (Boolean.valueOf(seedDB)) {
            Thread.sleep(2000);

            WebApplicationContext webappContext = WebApplicationContextUtils
                    .getWebApplicationContext(webapp.getServletContext());

            DBSeeder.getInstance(webappContext).seedPets();
        }
    }

    server.join();
}