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:MainClass.java

public static void main(String[] args) {
    if (args.length != 4) {
        System.out.println("usage: java msgmultisend <to> <from> <smtp> true|false");
        return;//  ww  w . j a  v  a 2s. c  o m
    }

    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);

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

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail APIs Multipart Test");
        msg.setSentDate(new Date());

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create and fill the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // Use setText(text, charset), to show it off !
        mbp2.setText(msgText2, "us-ascii");

        // create the Multipart and its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // send the message
        Transport.send(msg);
    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:org.key2gym.client.Main.java

/**
 * The main method which performs all the task described in the class
 * description./* w  ww . j  av a 2 s . com*/
 * 
 * @param args an array of arguments
 */
public static void main(String[] args) {

    /*
     * Configures the logger using 'etc/logging.properties' or the default
     * logging properties file.
     */
    try (InputStream input = new FileInputStream(PATH_LOGGING_PROPERTIES)) {
        PropertyConfigurator.configure(input);
    } catch (IOException ex) {
        try (InputStream input = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(RESOURCE_DEFAULT_LOGGING_PROPERTIES)) {
            PropertyConfigurator.configure(input);

            /*
             * Notify that the default logging properties file has been
             * used.
             */
            logger.info("Could not load the logging properties file");
        } catch (IOException ex2) {
            throw new RuntimeException("Failed to initialize logging system", ex2);
        }
    }

    logger.info("Starting...");

    /*
     * Loads the built-in default properties file.
     */
    try (InputStream input = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(RESOURCE_DEFAULT_CLIENT_PROPERTIES)) {
        Properties defaultProperties = null;
        defaultProperties = new Properties();
        defaultProperties.load(input);
        properties.putAll(defaultProperties);
    } catch (IOException ex) {
        throw new RuntimeException("Failed to load the default client properties file", ex);
    }

    /*
     * Loads the local client properties file.
     */
    try (FileInputStream input = new FileInputStream(PATH_APPLICATION_PROPERTIES)) {
        Properties localProperties = null;
        localProperties = new Properties();
        localProperties.load(input);
        properties.putAll(localProperties);
    } catch (IOException ex) {
        if (logger.isEnabledFor(Level.DEBUG)) {
            logger.debug("Failed to load the client properties file", ex);
        } else {
            logger.info("Could not load the local client properties file");
        }

        /*
         * It's okay to start without the local properties file.
         */
    }

    logger.debug("Effective properties: " + properties);

    if (properties.containsKey(PROPERTY_LOCALE_COUNTRY) && properties.containsKey(PROPERTY_LOCALE_LANGUAGE)) {

        /*
         * Changes the application's locale.
         */
        Locale.setDefault(new Locale(properties.getProperty(PROPERTY_LOCALE_LANGUAGE),
                properties.getProperty(PROPERTY_LOCALE_COUNTRY)));

    } else {
        logger.debug("Using the default locale");
    }

    /*
     * Changes the application's L&F.
     */
    String ui = properties.getProperty(PROPERTY_UI);
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if (ui.equalsIgnoreCase(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | UnsupportedLookAndFeelException ex) {
        logger.error("Failed to change the L&F:", ex);
    }

    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);

    // Loads the client application context
    context = new ClassPathXmlApplicationContext("META-INF/client.xml");

    logger.info("Started!");
    launchAndWaitMainFrame();
    logger.info("Shutting down!");

    context.close();
}

From source file:kafka.benchmark.AdvertisingTopology.java

public static void main(final String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption("conf", true, "Path to the config file.");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(opts, args);
    String configPath = cmd.getOptionValue("conf");
    Map<?, ?> conf = Utils.findAndReadConfigFile(configPath, true);

    Map<String, ?> benchmarkParams = getKafkaConfs(conf);

    LOG.info("conf: {}", conf);
    LOG.info("Parameters used: {}", benchmarkParams);

    KStreamBuilder builder = new KStreamBuilder();
    //        builder.addStateStore(
    //                Stores.create("config-params")
    //                .withStringKeys().withStringValues()
    //                .inMemory().maxEntries(10).build(), "redis");

    String topicsArr[] = { (String) benchmarkParams.get("topic") };
    KStream<String, ?> source1 = builder.stream(topicsArr);

    Properties props = new Properties();
    props.putAll(benchmarkParams);//from   w  ww  .  j  a  v  a  2 s .co m
    //        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafka-benchmarks");
    //        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    ////        props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());

    // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data
    //        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    source1
            // Parse the String as JSON
            .mapValues(input -> {
                JSONObject obj = new JSONObject(input.toString());
                //System.out.println(obj.toString());
                String[] tuple = { obj.getString("user_id"), obj.getString("page_id"), obj.getString("ad_id"),
                        obj.getString("ad_type"), obj.getString("event_type"), obj.getString("event_time"),
                        obj.getString("ip_address") };
                return tuple;
            })

            // Filter the records if event type is "view"
            .filter(new Predicate<String, String[]>() {
                @Override
                public boolean test(String key, String[] value) {
                    return value[4].equals("view"); // "event_type"
                }
            })

            // project the event
            .mapValues(input -> {
                String[] arr = (String[]) input;
                return new String[] { arr[2], arr[5] }; // "ad_id" and "event_time"
            })

            // perform join with redis data
            .transformValues(new RedisJoinBolt(benchmarkParams)).filter((key, value) -> value != null)

            // create key from value
            .map((key, value) -> {
                String[] arr = (String[]) value;
                return new KeyValue<String, String[]>(arr[0], arr);
            })

            // process campaign
            .aggregateByKey(new Initializer<List<String[]>>() {
                @Override
                public List<String[]> apply() {
                    return new ArrayList<String[]>();
                }
            }, new Aggregator<String, String[], List<String[]>>() {
                @Override
                public List<String[]> apply(String aggKey, String[] value, List<String[]> aggregate) {
                    aggregate.add(value);
                    return aggregate;
                }
            },
                    // UnlimitedWindows.of("kafka-test-unlim"),
                    // HoppingWindows.of("kafka-test-hopping").with(12L).every(5L),
                    TumblingWindows.of("kafka-test-tumbling").with(WINDOW_SIZE), strSerde, arrSerde)
            .toStream().process(new CampaignProcessor(benchmarkParams));

    KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();
}

From source file:com.textocat.textokit.postagger.opennlp.OpenNLPPosTaggerTrainerCLI.java

public static void main(String[] args) throws Exception {
    OpenNLPPosTaggerTrainerCLI cli = new OpenNLPPosTaggerTrainerCLI();
    new JCommander(cli, args);
    ///* w  w  w . j a v  a2  s.  c o  m*/
    OpenNLPPosTaggerTrainer trainer = new OpenNLPPosTaggerTrainer();
    trainer.setLanguageCode(cli.languageCode);
    trainer.setModelOutFile(cli.modelOutFile);
    // train params
    {
        FileInputStream fis = FileUtils.openInputStream(cli.trainParamsFile);
        TrainingParameters trainParams;
        try {
            trainParams = new TrainingParameters(fis);
        } finally {
            IOUtils.closeQuietly(fis);
        }
        trainer.setTrainingParameters(trainParams);
    }
    // feature extractors
    {
        FileInputStream fis = FileUtils.openInputStream(cli.extractorParams);
        Properties props = new Properties();
        try {
            props.load(fis);
        } finally {
            IOUtils.closeQuietly(fis);
        }
        MorphDictionary morphDict = getMorphDictionaryAPI().getCachedInstance().getResource();
        trainer.setTaggerFactory(new POSTaggerFactory(DefaultFeatureExtractors.from(props, morphDict)));
    }
    // input sentence stream
    {
        ExternalResourceDescription morphDictDesc = getMorphDictionaryAPI()
                .getResourceDescriptionForCachedInstance();
        TypeSystemDescription tsd = createTypeSystemDescription(
                "com.textocat.textokit.commons.Commons-TypeSystem", TokenizerAPI.TYPESYSTEM_TOKENIZER,
                SentenceSplitterAPI.TYPESYSTEM_SENTENCES, PosTaggerAPI.TYPESYSTEM_POSTAGGER);
        CollectionReaderDescription colReaderDesc = CollectionReaderFactory.createReaderDescription(
                XmiCollectionReader.class, tsd, XmiCollectionReader.PARAM_INPUTDIR, cli.trainingXmiDir);
        AnalysisEngineDescription posTrimmerDesc = PosTrimmingAnnotator
                .createDescription(cli.gramCategories.toArray(new String[cli.gramCategories.size()]));
        bindExternalResource(posTrimmerDesc, PosTrimmingAnnotator.RESOURCE_GRAM_MODEL, morphDictDesc);
        AnalysisEngineDescription tagAssemblerDesc = TagAssembler.createDescription();
        bindExternalResource(tagAssemblerDesc, GramModelBasedTagMapper.RESOURCE_GRAM_MODEL, morphDictDesc);
        AnalysisEngineDescription aeDesc = createEngineDescription(posTrimmerDesc, tagAssemblerDesc);
        Iterator<Sentence> sentIter = AnnotationIteratorOverCollection.createIterator(Sentence.class,
                colReaderDesc, aeDesc);
        SpanStreamOverCollection<Sentence> sentStream = new SpanStreamOverCollection<Sentence>(sentIter);
        trainer.setSentenceStream(sentStream);
    }
    trainer.train();
}

From source file:com.vikram.kdtree.ElementalHttpServer.java

public static void main(String[] args) throws Exception {
    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();/*from  w ww  . j  av a 2s  .  co m*/

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpPostReceiver());

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    Properties properties = new Properties();
    properties.load(new FileInputStream("Config.properties"));

    Thread t = new RequestListenerThread(Integer.valueOf(properties.getProperty("requestPort")), httpService,
            null);
    t.setDaemon(false);
    t.start();
}

From source file:com.mgreau.jboss.as7.cli.CliLauncher.java

public static void main(String[] args) throws Exception {
    int exitCode = 0;
    CommandContext cmdCtx = null;/*w  w w  .j  a  v a  2s . c o m*/
    boolean gui = false;
    String appName = "";
    try {
        String argError = null;
        List<String> commands = null;
        File file = null;
        boolean connect = false;
        String defaultControllerProtocol = "http-remoting";
        String defaultControllerHost = null;
        int defaultControllerPort = -1;
        boolean version = false;
        String username = null;
        char[] password = null;
        int connectionTimeout = -1;

        //App deployment
        boolean isAppDeployment = false;
        final Properties props = new Properties();

        for (String arg : args) {
            if (arg.startsWith("--controller=") || arg.startsWith("controller=")) {
                final String fullValue;
                final String value;
                if (arg.startsWith("--")) {
                    fullValue = arg.substring(13);
                } else {
                    fullValue = arg.substring(11);
                }
                final int protocolEnd = fullValue.lastIndexOf("://");
                if (protocolEnd == -1) {
                    value = fullValue;
                } else {
                    value = fullValue.substring(protocolEnd + 3);
                    defaultControllerProtocol = fullValue.substring(0, protocolEnd);
                }

                String portStr = null;
                int colonIndex = value.lastIndexOf(':');
                if (colonIndex < 0) {
                    // default port
                    defaultControllerHost = value;
                } else if (colonIndex == 0) {
                    // default host
                    portStr = value.substring(1);
                } else {
                    final boolean hasPort;
                    int closeBracket = value.lastIndexOf(']');
                    if (closeBracket != -1) {
                        //possible ip v6
                        if (closeBracket > colonIndex) {
                            hasPort = false;
                        } else {
                            hasPort = true;
                        }
                    } else {
                        //probably ip v4
                        hasPort = true;
                    }
                    if (hasPort) {
                        defaultControllerHost = value.substring(0, colonIndex).trim();
                        portStr = value.substring(colonIndex + 1).trim();
                    } else {
                        defaultControllerHost = value;
                    }
                }

                if (portStr != null) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(portStr);
                        if (port < 0) {
                            argError = "The port must be a valid non-negative integer: '" + args + "'";
                        } else {
                            defaultControllerPort = port;
                        }
                    } catch (NumberFormatException e) {
                        argError = "The port must be a valid non-negative integer: '" + arg + "'";
                    }
                }
            } else if ("--connect".equals(arg) || "-c".equals(arg)) {
                connect = true;
            } else if ("--version".equals(arg)) {
                version = true;
            } else if ("--gui".equals(arg)) {
                gui = true;
            } else if (arg.startsWith("--appDeployment=") || arg.startsWith("appDeployment=")) {
                isAppDeployment = true;
                appName = arg.startsWith("--") ? arg.substring(16) : arg.substring(14);
            } else if (arg.startsWith("--file=") || arg.startsWith("file=")) {
                if (file != null) {
                    argError = "Duplicate argument '--file'.";
                    break;
                }
                if (commands != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }

                final String fileName = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
                if (!fileName.isEmpty()) {
                    file = new File(fileName);
                    if (!file.exists()) {
                        argError = "File " + file.getAbsolutePath() + " doesn't exist.";
                        break;
                    }
                } else {
                    argError = "Argument '--file' is missing value.";
                    break;
                }
            } else if (arg.startsWith("--commands=") || arg.startsWith("commands=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(11) : arg.substring(9);
                commands = Util.splitCommands(value);
            } else if (arg.startsWith("--command=") || arg.startsWith("command=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(10) : arg.substring(8);
                commands = Collections.singletonList(value);
            } else if (arg.startsWith("--user=")) {
                username = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
            } else if (arg.startsWith("--password=")) {
                password = (arg.startsWith("--") ? arg.substring(11) : arg.substring(9)).toCharArray();
            } else if (arg.startsWith("--timeout=")) {
                if (connectionTimeout > 0) {
                    argError = "Duplicate argument '--timeout'";
                    break;
                }
                final String value = arg.substring(10);
                try {
                    connectionTimeout = Integer.parseInt(value);
                } catch (final NumberFormatException e) {
                    //
                }
                if (connectionTimeout <= 0) {
                    argError = "The timeout must be a valid positive integer: '" + value + "'";
                }
            } else if (arg.equals("--help") || arg.equals("-h")) {
                commands = Collections.singletonList("help");
            } else if (arg.startsWith("--properties=")) {
                final String value = arg.substring(13);
                final File propertiesFile = new File(value);
                if (!propertiesFile.exists()) {
                    argError = "File doesn't exist: " + propertiesFile.getAbsolutePath();
                    break;
                }

                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(propertiesFile);
                    props.load(fis);
                } catch (FileNotFoundException e) {
                    argError = e.getLocalizedMessage();
                    break;
                } catch (java.io.IOException e) {
                    argError = "Failed to load properties from " + propertiesFile.getAbsolutePath() + ": "
                            + e.getLocalizedMessage();
                    break;
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (java.io.IOException e) {
                        }
                    }
                }
                for (final Object prop : props.keySet()) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        public Object run() {
                            System.setProperty((String) prop, (String) props.get(prop));
                            return null;
                        }
                    });
                }
            } else if (!(arg.startsWith("-D") || arg.equals("-XX:"))) {// skip system properties and jvm options
                // assume it's commands
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time: "
                            + arg;
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                commands = Util.splitCommands(arg);
            }
        }

        if (argError != null) {
            System.err.println(argError);
            exitCode = 1;
            return;
        }

        if (version) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            VersionHandler.INSTANCE.handle(cmdCtx);
            return;
        }

        if (file != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processFile(file, cmdCtx, isAppDeployment, appName, props);
            return;
        }

        if (commands != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processCommands(commands, cmdCtx);
            return;
        }

        // Interactive mode
        cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                username, password, true, connect, connectionTimeout);
        cmdCtx.interact();
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 1;
    } finally {
        if (cmdCtx != null && cmdCtx.getExitCode() != 0) {
            exitCode = cmdCtx.getExitCode();
        }
        if (!gui) {
            System.exit(exitCode);
        }
    }
    System.exit(exitCode);
}

From source file:herddb.server.ServerMain.java

public static void main(String... args) {
    try {/*from  w  ww .  j a v  a 2 s .  c om*/
        LOG.log(Level.INFO, "Starting HerdDB version {0}", herddb.utils.Version.getVERSION());
        Properties configuration = new Properties();

        boolean configFileFromParameter = false;
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (!arg.startsWith("-")) {
                File configFile = new File(args[i]).getAbsoluteFile();
                LOG.log(Level.INFO, "Reading configuration from {0}", configFile);
                try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile),
                        StandardCharsets.UTF_8)) {
                    configuration.load(reader);
                }
                configFileFromParameter = true;
            } else if (arg.equals("--use-env")) {
                System.getenv().forEach((key, value) -> {
                    System.out.println("Considering env as system property " + key + " -> " + value);
                    System.setProperty(key, value);
                });
            } else if (arg.startsWith("-D")) {
                int equals = arg.indexOf('=');
                if (equals > 0) {
                    String key = arg.substring(2, equals);
                    String value = arg.substring(equals + 1);
                    System.setProperty(key, value);
                }
            }
        }
        if (!configFileFromParameter) {
            File configFile = new File("conf/server.properties").getAbsoluteFile();
            LOG.log(Level.INFO, "Reading configuration from {0}", configFile);
            if (configFile.isFile()) {
                try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile),
                        StandardCharsets.UTF_8)) {
                    configuration.load(reader);
                }
            }
        }

        System.getProperties().forEach((k, v) -> {
            String key = k + "";
            if (!key.startsWith("java") && !key.startsWith("user")) {
                configuration.put(k, v);
            }
        });

        LogManager.getLogManager().readConfiguration();

        Runtime.getRuntime().addShutdownHook(new Thread("ctrlc-hook") {

            @Override
            public void run() {
                System.out.println("Ctrl-C trapped. Shutting down");
                ServerMain _brokerMain = runningInstance;
                if (_brokerMain != null) {
                    _brokerMain.close();
                }
            }

        });
        runningInstance = new ServerMain(configuration);
        runningInstance.start();

        runningInstance.join();

    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

From source file:com.chiralbehaviors.CoRE.kernel.Bootstrap.java

public static void main(String[] argv) throws Exception {
    if (argv.length != 2) {
        System.err.println("Usage: Bootstrap <jpa.properties> <output file>");
        System.exit(1);//w w  w. j  a va2 s. c o m
    }
    Properties properties = new Properties();
    try (InputStream is = new FileInputStream(new File(argv[0]))) {
        properties.load(is);
    }

    EntityManagerFactory emf = Persistence.createEntityManagerFactory(WellKnownObject.CORE, properties);
    EntityManager em = emf.createEntityManager();
    Bootstrap bootstrap = new Bootstrap(em);
    bootstrap.clear();
    em.getTransaction().begin();
    bootstrap.bootstrap();
    em.getTransaction().commit();
    em.clear();
    bootstrap.serialize(argv[1]);
}

From source file:transport.java

public static void main(String[] args) {
    Properties props = new Properties();
    // parse the arguments
    InternetAddress[] addrs = null;//from  w  w w . j  a v a  2 s  .c o m
    InternetAddress from;
    boolean debug = false;
    if (args.length != 4) {
        usage();
        return;
    } else {
        props.put("mail.smtp.host", args[2]);
        if (args[3].equals("true")) {
            debug = true;
        } else if (args[3].equals("false")) {
            debug = false;
        } else {
            usage();
            return;
        }

        // parse the destination addresses
        try {
            addrs = InternetAddress.parse(args[0], false);
            from = new InternetAddress(args[1]);
        } catch (AddressException aex) {
            System.out.println("Invalid Address");
            aex.printStackTrace();
            return;
        }
    }
    // create some properties and get a Session
    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    transport t = new transport();
    t.go(session, addrs, from);
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

public static void main(String[] args) {
    try {// ww w .ja va  2 s. c o  m
        Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        File home = args.length > 0 ? new File(args[0]) : new File(".");

        Protocol.registerProtocol("easyhttps", easyhttps);
        File submitFile = new File(home, ".submit");
        File submitUserFile = new File(home, ".submitUser");
        File submitIgnoreFile = new File(home, ".submitIgnore");
        File cvsIgnoreFile = new File(home, ".cvsignore");

        if (!submitFile.canRead()) {
            System.out.println("Must perform submit from a directory containing a \".submit\" file");
            System.out.println("No such file found at " + submitFile.getCanonicalPath());
            System.exit(1);
        }

        Properties p = new Properties();
        p.load(new FileInputStream(submitFile));
        String submitURL = p.getProperty("submitURL");
        if (submitURL == null) {
            System.out.println(".submit file does not contain a submitURL");
            System.exit(1);
        }
        String courseName = p.getProperty("courseName");
        String courseKey = p.getProperty("courseKey");
        String semester = p.getProperty("semester");
        String projectNumber = p.getProperty("projectNumber");
        String authenticationType = p.getProperty("authentication.type");
        String baseURL = p.getProperty("baseURL");

        System.out.println("Submitting contents of " + home.getCanonicalPath());
        System.out.println(" as project " + projectNumber + " for course " + courseName);
        FilesToIgnore ignorePatterns = new FilesToIgnore();
        addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns);
        addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns);

        FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern());
        Collection<File> files = find.getAllFiles();

        boolean createdSubmitUser = false;
        Properties userProps = new Properties();
        if (submitUserFile.canRead()) {
            userProps.load(new FileInputStream(submitUserFile));
        }
        if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null
                || userProps.getProperty("oneTimePassword") == null) {
            System.out.println();
            System.out.println(
                    "We need to authenticate you and create a .submitUser file so you can submit your project");

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            createdSubmitUser = true;
            userProps.load(new FileInputStream(submitUserFile));
        }

        MultipartPostMethod filePost = createFilePost(p, find, files, userProps);
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);
        int status = client.executeMethod(filePost);
        System.out.println(filePost.getResponseBodyAsString());
        if (status == 500 && !createdSubmitUser) {
            System.out.println("Let's try reauthenticating you");
            System.out.println();

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            userProps.load(new FileInputStream(submitUserFile));
            filePost = createFilePost(p, find, files, userProps);
            client = new HttpClient();
            client.setConnectionTimeout(HTTP_TIMEOUT);
            status = client.executeMethod(filePost);
            System.out.println(filePost.getResponseBodyAsString());
        }
        if (status != HttpStatus.SC_OK) {
            System.out.println("Status code: " + status);
            System.exit(1);
        }
        System.out.println("Submission accepted");
    } catch (Exception e) {
        System.out.println();
        System.out.println("An Error has occured during submission!");
        System.out.println();
        System.out.println("[DETAILS]");
        System.out.println(e.getMessage());
        e.printStackTrace(System.out);
        System.out.println();
    }
}