Example usage for java.lang String startsWith

List of usage examples for java.lang String startsWith

Introduction

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

Prototype

public boolean startsWith(String prefix) 

Source Link

Document

Tests if this string starts with the specified prefix.

Usage

From source file:mvm.rya.indexing.external.ExternalIndexMain.java

public static void main(String[] args) throws Exception {
    Preconditions.checkArgument(args.length == 6, "java " + ExternalIndexMain.class.getCanonicalName()
            + " sparqlFile cbinstance cbzk cbuser cbpassword rdfTablePrefix.");

    final String sparqlFile = args[0];

    instStr = args[1];/*from   w w  w.  jav a2  s .  c o m*/
    zooStr = args[2];
    userStr = args[3];
    passStr = args[4];
    tablePrefix = args[5];

    String queryString = FileUtils.readFileToString(new File(sparqlFile));

    // Look for Extra Indexes
    Instance inst = new ZooKeeperInstance(instStr, zooStr);
    Connector c = inst.getConnector(userStr, passStr.getBytes());

    System.out.println("Searching for Indexes");
    Map<String, String> indexTables = Maps.newLinkedHashMap();
    for (String table : c.tableOperations().list()) {
        if (table.startsWith(tablePrefix + "INDEX_")) {
            Scanner s = c.createScanner(table, new Authorizations());
            s.setRange(Range.exact(new Text("~SPARQL")));
            for (Entry<Key, Value> e : s) {
                indexTables.put(table, e.getValue().toString());
            }
        }
    }

    List<ExternalTupleSet> index = Lists.newArrayList();

    if (indexTables.isEmpty()) {
        System.out.println("No Index found");
    } else {
        for (String table : indexTables.keySet()) {
            String indexSparqlString = indexTables.get(table);
            System.out.println("====================== INDEX FOUND ======================");
            System.out.println(" table : " + table);
            System.out.println(" sparql : ");
            System.out.println(indexSparqlString);

            index.add(new AccumuloIndexSet(indexSparqlString, c, table));
        }
    }

    // Connect to Rya
    Sail s = getRyaSail();
    SailRepository repo = new SailRepository(s);
    repo.initialize();

    // Perform Query

    CountingTupleQueryResultHandler count = new CountingTupleQueryResultHandler();

    SailRepositoryConnection conn;
    if (index.isEmpty()) {
        conn = repo.getConnection();

    } else {
        ExternalProcessor processor = new ExternalProcessor(index);

        Sail processingSail = new ExternalSail(s, processor);
        SailRepository smartSailRepo = new SailRepository(processingSail);
        smartSailRepo.initialize();

        conn = smartSailRepo.getConnection();
    }

    startTime = System.currentTimeMillis();
    lastTime = startTime;
    System.out.println("Query Started");
    conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate(count);

    System.out.println("Count of Results found : " + count.i);
    System.out.println("Total query time (s) : " + (System.currentTimeMillis() - startTime) / 1000.);
}

From source file:registry.java

public static void main(String[] args) {
    Properties props = new Properties();

    // set smtp and imap to be our default 
    // transport and store protocols, respectively
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.store.protocol", "imap");

    // /*  ww w. ja  v  a  2 s. co m*/
    props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
    props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");

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

    // Retrieve all configured providers from the Session
    System.out.println("\n------ getProviders()----------");
    Provider[] providers = session.getProviders();
    for (int i = 0; i < providers.length; i++) {
        System.out.println("** " + providers[i]);

        // let's remember some providers so that we can use them later
        // (I'm explicitly showing multiple ways of testing Providers)
        // BTW, no Provider "ACME Corp" will be found in the default
        // setup b/c its not in any javamail.providers resource files
        String s = null;
        if (((s = providers[i].getVendor()) != null) && s.startsWith("ACME Corp")) {
            _aProvider = providers[i];
        }

        // this Provider won't be found by default either
        if (providers[i].getClassName().endsWith("application.smtp"))
            _bProvider = providers[i];

        // this Provider will be found since com.sun.mail.imap.IMAPStore
        // is configured in javamail.default.providers
        if (providers[i].getClassName().equals("com.sun.mail.imap.IMAPStore")) {
            _sunIMAP = providers[i];
        }

        // this Provider will be found as well since there is an
        // Oracle SMTP transport configured by 
        // default in javamail.default.providers
        if (((s = providers[i].getVendor()) != null) && s.startsWith("Oracle")
                && providers[i].getType() == Provider.Type.TRANSPORT
                && providers[i].getProtocol().equalsIgnoreCase("smtp")) {
            _sunSMTP = providers[i];
        }
    }

    System.out.println("\n------ initial protocol defaults -------");
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
        // the NNTP provider will fail since we don't have one configured
        System.out.println("nntp: " + session.getProvider("nntp"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> This exception is OK since there is no NNTP Provider configured by default");
        mex.printStackTrace();
    }

    System.out.println("\n------ set new protocol defaults ------");
    // set some new defaults
    try {
        // since _aProvider isn't configured, this will fail
        session.setProvider(_aProvider); // will fail
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: _aProvider is null");
        mex.printStackTrace();
    }
    try {
        // _sunIMAP provider should've configured correctly; should work
        session.setProvider(_sunIMAP);
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    System.out.println("\n\n----- get some stores ---------");
    // multiple ways to retrieve stores. these will print out the
    // string "imap:" since its the URLName for the store
    try {
        System.out.println("getStore(): " + session.getStore());
        System.out.println("getStore(Provider): " + session.getStore(_sunIMAP));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    try {
        System.out.println("getStore(imap): " + session.getStore("imap"));
        // pop3 will fail since it doesn't exist
        System.out.println("getStore(pop3): " + session.getStore("pop3"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: no pop3 provider");
        mex.printStackTrace();
    }

    System.out.println("\n\n----- now for transports/addresses ---------");
    // retrieve transports; these will print out "smtp:" (like stores did)
    try {
        System.out.println("getTransport(): " + session.getTransport());
        System.out.println("getTransport(Provider): " + session.getTransport(_sunSMTP));
        System.out.println("getTransport(smtp): " + session.getTransport("smtp"));
        System.out.println(
                "getTransport(Address): " + session.getTransport(new InternetAddress("mspivak@apilon")));
        // News will fail since there's no news provider configured
        System.out.println("getTransport(News): " + session.getTransport(new NewsAddress("rec.humor")));
    } catch (MessagingException mex) {
        System.out.println(">> Exception expected: no news provider configured");
        mex.printStackTrace();
    }
}

From source file:test.TestJavaService.java

/**
 * Main.  The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag.  If it is specified,
 *   we test code on the AWS instance.  If it is not, we test code running locally.
 * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file
 *   org.qcert.javasrc.Main.  Remaining non-flag arguments are file names.  There must be at least one.  The number of such 
 *   arguments and what they should contain depends on the verb.
 * @throws Exception//from  w w  w  .  ja v a2  s.  c  o m
 */
public static void main(String[] args) throws Exception {
    /* Parse command line */
    List<String> files = new ArrayList<>();
    String loc = "localhost", verb = null;
    for (String arg : args) {
        if (arg.equals("-remote"))
            loc = REMOTE_LOC;
        else if (arg.startsWith("-"))
            illegal();
        else if (verb == null)
            verb = arg;
        else
            files.add(arg);
    }
    /* Simple consistency checks and verb-specific parsing */
    if (files.size() == 0)
        illegal();
    String file = files.remove(0);
    String schema = null;
    switch (verb) {
    case "parseSQL":
    case "serialRule2CAMP":
    case "sqlSchema2JSON":
        if (files.size() != 0)
            illegal();
        break;
    case "techRule2CAMP":
        if (files.size() != 1)
            illegal();
        schema = files.get(0);
        break;
    case "csv2JSON":
        if (files.size() < 1)
            illegal();
        break;
    default:
        illegal();
    }

    /* Assemble information from arguments */
    String url = String.format("http://%s:9879?verb=%s", loc, verb);
    byte[] contents = Files.readAllBytes(Paths.get(file));
    String toSend;
    if ("serialRule2CAMP".equals(verb))
        toSend = Base64.getEncoder().encodeToString(contents);
    else
        toSend = new String(contents);
    if ("techRule2CAMP".equals(verb))
        toSend = makeSpecialJson(toSend, schema);
    else if ("csv2JSON".equals(verb))
        toSend = makeSpecialJson(toSend, files);
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    StringEntity entity = new StringEntity(toSend);
    entity.setContentType("text/plain");
    post.setEntity(entity);
    HttpResponse resp = client.execute(post);
    int code = resp.getStatusLine().getStatusCode();
    if (code == HttpStatus.SC_OK) {
        HttpEntity answer = resp.getEntity();
        InputStream s = answer.getContent();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(s));
        String line = rdr.readLine();
        while (line != null) {
            System.out.println(line);
            line = rdr.readLine();
        }
        rdr.close();
        s.close();
    } else
        System.out.println(resp.getStatusLine());
}

From source file:it.alidays.mapengine.codegenerator.MapperEngineCodeGenerator.java

public static void main(String[] args) throws MapperEngineCodeGeneratorException {
    if (args.length != 2) {
        printUsage();/*www  .  j  av  a2 s . co  m*/
    } else {
        String destinationDir = null;
        String[] engineDirectivesSources = null;

        for (String arg : args) {
            if (arg.startsWith("-d")) {
                destinationDir = arg.substring(2);
            } else if (arg.startsWith("-s")) {
                engineDirectivesSources = arg.substring(2).split("\\|");
            }
        }

        if (destinationDir == null || destinationDir.isEmpty() || engineDirectivesSources == null
                || engineDirectivesSources.length == 0) {
            printUsage();
        } else {
            for (String engineDirectivesSource : engineDirectivesSources) {
                run(new File(destinationDir), MapperEngineCodeGenerator.class.getClassLoader()
                        .getResourceAsStream(engineDirectivesSource));
            }
        }
    }
}

From source file:ArraySet.java

public static void main(String[] args) throws java.io.IOException {
    ArraySet set = new ArraySet();
    java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
    while (true) {
        System.out.print(set.size() + ":"); //OK
        for (Iterator it = set.iterator(); it.hasNext();) {
            System.out.print(" " + it.next()); //OK
        }/*w  w  w  . j  a va  2s. c om*/
        System.out.println(); //OK
        System.out.print("> "); //OK
        String cmd = in.readLine();
        if (cmd == null)
            break;
        cmd = cmd.trim();
        if (cmd.equals("")) {
            ;
        } else if (cmd.startsWith("+")) {
            set.add(cmd.substring(1));
        } else if (cmd.startsWith("-")) {
            set.remove(cmd.substring(1));
        } else if (cmd.startsWith("?")) {
            boolean ret = set.contains(cmd.substring(1));
            System.out.println("  " + ret); //OK
        } else {
            System.out.println("unrecognized command"); //OK
        }
    }
}

From source file:eu.fbk.dkm.sectionextractor.PageClassMerger.java

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

    CommandLineWithLogger commandLineWithLogger = new CommandLineWithLogger();
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("WikiData ID file").isRequired().withLongOpt("wikidata-id").create("i"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("Airpedia Person file").isRequired().withLongOpt("airpedia").create("a"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Output file")
            .isRequired().withLongOpt("output").create("o"));
    CommandLine commandLine = null;//from  w ww .j av a2s  .c  om
    try {
        commandLine = commandLineWithLogger.getCommandLine(args);
        PropertyConfigurator.configure(commandLineWithLogger.getLoggerProps());
    } catch (Exception e) {
        System.exit(1);
    }

    String wikiIDFileName = commandLine.getOptionValue("wikidata-id");
    String airpediaFileName = commandLine.getOptionValue("airpedia");
    String outputFileName = commandLine.getOptionValue("output");

    HashMap<Integer, String> wikiIDs = new HashMap<>();
    HashSet<Integer> airpediaClasses = new HashSet<>();

    List<String> strings;

    logger.info("Loading file " + wikiIDFileName);
    strings = Files.readLines(new File(wikiIDFileName), Charsets.UTF_8);
    for (String line : strings) {
        line = line.trim();
        if (line.length() == 0) {
            continue;
        }
        if (line.startsWith("#")) {
            continue;
        }

        String[] parts = line.split("\t");
        if (parts.length < 2) {
            continue;
        }

        int id;
        try {
            id = Integer.parseInt(parts[0]);
        } catch (Exception e) {
            continue;
        }
        wikiIDs.put(id, parts[1]);
    }

    logger.info("Loading file " + airpediaFileName);
    strings = Files.readLines(new File(airpediaFileName), Charsets.UTF_8);
    for (String line : strings) {
        line = line.trim();
        if (line.length() == 0) {
            continue;
        }
        if (line.startsWith("#")) {
            continue;
        }

        String[] parts = line.split("\t");
        if (parts.length < 2) {
            continue;
        }

        int id;
        try {
            id = Integer.parseInt(parts[0]);
        } catch (Exception e) {
            continue;
        }
        airpediaClasses.add(id);
    }

    logger.info("Saving information");
    BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName));
    for (int i : wikiIDs.keySet()) {
        if (!airpediaClasses.contains(i)) {
            continue;
        }

        writer.append(wikiIDs.get(i)).append("\n");
    }
    writer.close();
}

From source file:MiniCluster.java

/**
 * Runs the {@link MiniAccumuloCluster} given a -p argument with a property file. Establishes a shutdown port for asynchronous operation.
 * //w ww  .ja  v  a  2  s. co m
 * @param args
 *          An optional -p argument can be specified with the path to a valid properties file.
 */
public static void main(String[] args) throws Exception {
    Opts opts = new Opts();
    opts.parseArgs(MiniCluster.class.getName(), args);

    if (opts.printProps) {
        printProperties();
        System.exit(0);
    }

    int shutdownPort = 4445;

    final File miniDir;

    if (opts.prop.containsKey(DIRECTORY_PROP))
        miniDir = new File(opts.prop.getProperty(DIRECTORY_PROP));
    else
        miniDir = Files.createTempDir();

    String rootPass = opts.prop.containsKey(ROOT_PASSWORD_PROP) ? opts.prop.getProperty(ROOT_PASSWORD_PROP)
            : "secret";
    String instanceName = opts.prop.containsKey(INSTANCE_NAME_PROP) ? opts.prop.getProperty(INSTANCE_NAME_PROP)
            : "accumulo";
    MiniAccumuloConfig config = new MiniAccumuloConfig(miniDir, instanceName, rootPass);

    if (opts.prop.containsKey(NUM_T_SERVERS_PROP))
        config.setNumTservers(Integer.parseInt(opts.prop.getProperty(NUM_T_SERVERS_PROP)));
    if (opts.prop.containsKey(ZOO_KEEPER_PORT_PROP))
        config.setZooKeeperPort(Integer.parseInt(opts.prop.getProperty(ZOO_KEEPER_PORT_PROP)));
    //    if (opts.prop.containsKey(JDWP_ENABLED_PROP))
    //      config.setJDWPEnabled(Boolean.parseBoolean(opts.prop.getProperty(JDWP_ENABLED_PROP)));
    //    if (opts.prop.containsKey(ZOO_KEEPER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(ZOO_KEEPER_MEMORY_PROP), ServerType.ZOOKEEPER);
    //    if (opts.prop.containsKey(TSERVER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(TSERVER_MEMORY_PROP), ServerType.TABLET_SERVER);
    //    if (opts.prop.containsKey(MASTER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(MASTER_MEMORY_PROP), ServerType.MASTER);
    //    if (opts.prop.containsKey(DEFAULT_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(DEFAULT_MEMORY_PROP));
    //    if (opts.prop.containsKey(SHUTDOWN_PORT_PROP))
    //      shutdownPort = Integer.parseInt(opts.prop.getProperty(SHUTDOWN_PORT_PROP));

    Map<String, String> siteConfig = new HashMap<String, String>();
    for (Map.Entry<Object, Object> entry : opts.prop.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith("site."))
            siteConfig.put(key.replaceFirst("site.", ""), (String) entry.getValue());
    }

    config.setSiteConfig(siteConfig);

    final MiniAccumuloCluster accumulo = new MiniAccumuloCluster(config);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                accumulo.stop();
                FileUtils.deleteDirectory(miniDir);
                System.out.println("\nShut down gracefully on " + new Date());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    accumulo.start();

    printInfo(accumulo, shutdownPort);

    // start a socket on the shutdown port and block- anything connected to this port will activate the shutdown
    ServerSocket shutdownServer = new ServerSocket(shutdownPort);
    shutdownServer.accept();

    System.exit(0);
}

From source file:QueueRoundTrip.java

public static void main(String argv[]) {
    // Values to be read from parameters
    String broker = DEFAULT_BROKER_NAME;
    String username = DEFAULT_USER_NAME;
    String password = DEFAULT_PASSWORD;
    int numTests = DEFAULT_NUM_TESTS;

    // Check parameters
    if (argv.length > 0) {
        for (int i = 0; i < argv.length; i++) {
            String arg = argv[i];

            // Options
            if (!arg.startsWith("-")) {
                System.err.println("error: unexpected argument - " + arg);
                printUsage();//from www.j  a va2 s.c  om
                System.exit(1);
            } else {
                if (arg.equals("-b")) {
                    if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                        System.err.println("error: missing broker name:port");
                        System.exit(1);
                    }
                    broker = argv[++i];
                    continue;
                }

                if (arg.equals("-u")) {
                    if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                        System.err.println("error: missing user name");
                        System.exit(1);
                    }
                    username = argv[++i];
                    continue;
                }

                if (arg.equals("-p")) {
                    if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                        System.err.println("error: missing password");
                        System.exit(1);
                    }
                    password = argv[++i];
                    continue;
                }
                if (arg.equals("-n")) {
                    if (i == argv.length - 1 || argv[i + 1].startsWith("-")) {
                        System.err.println("error: missing number of test to run.");
                        System.exit(1);
                    }
                    numTests = (new Integer(argv[++i])).intValue();
                    continue;
                }

                if (arg.equals("-h")) {
                    printUsage();
                    System.exit(1);
                }
            }
        }
    }

    // create the payload
    byte charToWrite = (0x30);
    for (int i = 0; i < msgSize; i++) {
        msgBody[i] = charToWrite;
        charToWrite = (byte) ((int) charToWrite + (int) 0x01);
        if (charToWrite == (0x39)) {
            charToWrite = (0x30);
        }
    }

    // Start the JMS client for the test.
    QueueRoundTrip queueRoundTripper = new QueueRoundTrip();
    queueRoundTripper.QueueRoundTripper(broker, username, password, numTests);

}

From source file:herddb.server.ServerMain.java

public static void main(String... args) {
    try {/*from   w w  w .  j  ava 2s  .c  o  m*/
        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:registry.java

public static void main(String[] args) {
    Properties props = new Properties();

    // set smtp and imap to be our default
    // transport and store protocols, respectively
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.store.protocol", "imap");

    // /*from ww w . j a  v a  2s .co  m*/
    props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
    props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");

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

    // Retrieve all configured providers from the Session
    System.out.println("\n------ getProviders()----------");
    Provider[] providers = session.getProviders();
    for (int i = 0; i < providers.length; i++) {
        System.out.println("** " + providers[i]);

        // let's remember some providers so that we can use them later
        // (I'm explicitly showing multiple ways of testing Providers)
        // BTW, no Provider "ACME Corp" will be found in the default
        // setup b/c its not in any javamail.providers resource files
        String s = null;
        if (((s = providers[i].getVendor()) != null) && s.startsWith("ACME Corp")) {
            _aProvider = providers[i];
        }

        // this Provider won't be found by default either
        if (providers[i].getClassName().endsWith("application.smtp"))
            _bProvider = providers[i];

        // this Provider will be found since com.sun.mail.imap.IMAPStore
        // is configured in javamail.default.providers
        if (providers[i].getClassName().equals("com.sun.mail.imap.IMAPStore")) {
            _sunIMAP = providers[i];
        }

        // this Provider will be found as well since there is a
        // Sun Microsystems SMTP transport configured by
        // default in javamail.default.providers
        if (((s = providers[i].getVendor()) != null) && s.startsWith("Sun Microsystems")
                && providers[i].getType() == Provider.Type.TRANSPORT
                && providers[i].getProtocol().equalsIgnoreCase("smtp")) {
            _sunSMTP = providers[i];
        }
    }

    System.out.println("\n------ initial protocol defaults -------");
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
        // the NNTP provider will fail since we don't have one configured
        System.out.println("nntp: " + session.getProvider("nntp"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> This exception is OK since there is no NNTP Provider configured by default");
        mex.printStackTrace();
    }

    System.out.println("\n------ set new protocol defaults ------");
    // set some new defaults
    try {
        // since _aProvider isn't configured, this will fail
        session.setProvider(_aProvider); // will fail
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: _aProvider is null");
        mex.printStackTrace();
    }
    try {
        // _sunIMAP provider should've configured correctly; should work
        session.setProvider(_sunIMAP);
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    System.out.println("\n\n----- get some stores ---------");
    // multiple ways to retrieve stores. these will print out the
    // string "imap:" since its the URLName for the store
    try {
        System.out.println("getStore(): " + session.getStore());
        System.out.println("getStore(Provider): " + session.getStore(_sunIMAP));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    try {
        System.out.println("getStore(imap): " + session.getStore("imap"));
        // pop3 will fail since it doesn't exist
        System.out.println("getStore(pop3): " + session.getStore("pop3"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: no pop3 provider");
        mex.printStackTrace();
    }

    System.out.println("\n\n----- now for transports/addresses ---------");
    // retrieve transports; these will print out "smtp:" (like stores did)
    try {
        System.out.println("getTransport(): " + session.getTransport());
        System.out.println("getTransport(Provider): " + session.getTransport(_sunSMTP));
        System.out.println("getTransport(smtp): " + session.getTransport("smtp"));
        System.out.println(
                "getTransport(Address): " + session.getTransport(new InternetAddress("mspivak@apilon")));
        // News will fail since there's no news provider configured
        System.out.println("getTransport(News): " + session.getTransport(new NewsAddress("rec.humor")));
    } catch (MessagingException mex) {
        System.out.println(">> Exception expected: no news provider configured");
        mex.printStackTrace();
    }
}