List of usage examples for java.util Properties put
@Override public synchronized Object put(Object key, Object value)
From source file:WebCrawler.java
public static void main(String argv[]) { WebCrawler applet = new WebCrawler(); /*/*from www . j av a2 s . c o m*/ * Behind a firewall set your proxy and port here! */ Properties props = new Properties(System.getProperties()); props.put("http.proxySet", "true"); props.put("http.proxyHost", "webcache-cup"); props.put("http.proxyPort", "8080"); Properties newprops = new Properties(props); System.setProperties(newprops); }
From source file:sendfile.java
public static void main(String[] args) { if (args.length != 5) { System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false"); System.exit(1);/*from ww w. j a v a 2 s . c o m*/ } String to = args[0]; String from = args[1]; String host = args[2]; String filename = args[3]; boolean debug = Boolean.valueOf(args[4]).booleanValue(); String msgText1 = "Sending a file.\n"; String subject = "Sending a file"; // create some properties and get the default Session Properties props = System.getProperties(); 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(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(msgText1); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message mbp2.attachFile(filename); /* * Use the following approach instead of the above line if * you want to control the MIME type of the attached file. * Normally you should never need to do this. * FileDataSource fds = new FileDataSource(filename) { public String getContentType() { return "application/octet-stream"; } }; mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); */ // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); /* * If you want to control the Content-Transfer-Encoding * of the attached file, do the following. Normally you * should never need to do this. * msg.saveChanges(); mbp2.setHeader("Content-Transfer-Encoding", "base64"); */ // send the message Transport.send(msg); } catch (MessagingException mex) { mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); } } catch (IOException ioex) { ioex.printStackTrace(); } }
From source file:io.hops.examples.spark.kafka.StreamingLogs.java
public static void main(final String[] args) throws Exception { SparkConf sparkConf = new SparkConf().setAppName(Hops.getJobName()); JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, Durations.seconds(2)); //Use applicationId for sink folder final String appId = jssc.sparkContext().getConf().getAppId(); SparkSession sparkSession = SparkSession.builder().config(sparkConf).getOrCreate(); //Get consumer groups Properties props = new Properties(); props.put("value.deserializer", StringDeserializer.class.getName()); props.put("client.id", Hops.getJobName()); SparkConsumer consumer = Hops.getSparkConsumer(jssc, props); //Store processed offsets // Create direct kafka stream with topics JavaInputDStream<ConsumerRecord<String, String>> messages = consumer.createDirectStream(); //Convert line to JSON JavaDStream<NamenodeLogEntry> logEntries = messages .map(new Function<ConsumerRecord<String, String>, JSONObject>() { @Override// www. j a v a 2 s . com public JSONObject call(ConsumerRecord<String, String> record) throws SchemaNotFoundException, MalformedURLException, ProtocolException { LOG.log(Level.INFO, "record:{0}", record); return parser(record.value(), appId); } }).map(new Function<JSONObject, NamenodeLogEntry>() { @Override public NamenodeLogEntry call(JSONObject json) throws SchemaNotFoundException, MalformedURLException, ProtocolException, IOException { NamenodeLogEntry logEntry = new NamenodeLogEntry( json.getString("message").replace("\n\t", "\n").replace("\n", "---"), json.getString("priority"), json.getString("logger_name"), json.getString("timestamp"), json.getString("file")); LOG.log(Level.INFO, "NamenodeLogEntry:{0}", logEntry); return logEntry; } }); //logEntries.print(); logEntries.foreachRDD(new VoidFunction2<JavaRDD<NamenodeLogEntry>, Time>() { @Override public void call(JavaRDD<NamenodeLogEntry> rdd, Time time) throws Exception { Dataset<Row> row = sparkSession.createDataFrame(rdd, NamenodeLogEntry.class); if (!rdd.isEmpty()) { row.write().mode(SaveMode.Append) .parquet("/Projects/" + Hops.getProjectName() + "/Resources/LogAnalysis"); } } }); /* * Enable this to get all the streaming outputs. It creates a folder for * every microbatch slot. * /////////////////////////////////////////////////////////////////////// * wordCounts.saveAsHadoopFiles(args[1], "txt", String.class, * String.class, (Class) TextOutputFormat.class); * /////////////////////////////////////////////////////////////////////// */ // Start the computation jssc.start(); Hops.shutdownGracefully(jssc); }
From source file:edu.indiana.d2i.sloan.internal.CreateVMSimulator.java
public static void main(String[] args) { CreateVMSimulator simulator = new CreateVMSimulator(); CommandLineParser parser = new PosixParser(); try {//w w w . j a va2s. com CommandLine line = simulator.parseCommandLine(parser, args); String imagePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.IMAGE_PATH)); int vcpu = Integer.parseInt(line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU))); int mem = Integer.parseInt(line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM))); if (!HypervisorCmdSimulator.resourceExist(imagePath)) { logger.error(String.format("Cannot find requested image: %s", imagePath)); System.exit(ERROR_CODE.get(ERROR_STATE.IMAGE_NOT_EXIST)); } if (!hasEnoughCPUs(vcpu)) { logger.error(String.format("Don't have enough cpus, requested %d", vcpu)); System.exit(ERROR_CODE.get(ERROR_STATE.NOT_ENOUGH_CPU)); } if (!hasEnoughMem(mem)) { logger.error(String.format("Don't have enough memory, requested %d", mem)); System.exit(ERROR_CODE.get(ERROR_STATE.NOT_ENOUGH_MEM)); } String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR)); if (HypervisorCmdSimulator.resourceExist(wdir)) { logger.error(String.format("Working directory %s already exists ", wdir)); System.exit(ERROR_CODE.get(ERROR_STATE.VM_ALREADY_EXIST)); } // copy VM image to working directory File imageFile = new File(imagePath); FileUtils.copyFile(imageFile, new File(HypervisorCmdSimulator.cleanPath(wdir) + imageFile.getName())); // write state as property file so that we can query later Properties prop = new Properties(); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.IMAGE_PATH), imagePath); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU), String.valueOf(vcpu)); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM), String.valueOf(mem)); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR), wdir); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT))); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT))); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_USERNAME), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_USERNAME))); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_PASSWD), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_PASSWD))); // write VM state as shutdown prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.SHUTDOWN.toString()); // write VM mode as undefined prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), VMMode.NOT_DEFINED.toString()); prop.store( new FileOutputStream(new File( HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME)), ""); // do other related settings try { Thread.sleep(1000); } catch (InterruptedException e) { logger.error(e.getMessage()); } // success System.exit(0); } catch (ParseException e) { logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s", StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, ""))); System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS)); } catch (IOException e) { logger.error(e.getMessage(), e); System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR)); } }
From source file:com.singhasdev.calamus.app.sentimentanalysis.SentimentAnalyzer.java
public static void main(String[] args) throws Exception { Properties props = new Properties(); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "sentiment-analyzer"); 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()); props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass()); // 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"); TopologyBuilder builder = new TopologyBuilder(); builder.addSource("Source", "test"); builder.addProcessor("Process", new CalculateSentiment(), "Source"); builder.addStateStore(//from www . j a va2s . c o m Stores.create("SentimentAnalysis").withStringKeys().withStringValues().inMemory().build(), "Process"); builder.addSink("Sink", "test-output", "Process"); STREAMS = new KafkaStreams(builder, props); STREAMS.start(); Runtime.getRuntime().addShutdownHook(new Thread("MirrorMakerShutdownHook") { @Override public void run() { System.out.println("Closing Calamus sentiment-analyzer."); STREAMS.close(); } }); }
From source file:se.vgregion.portal.cs.util.CryptoUtilImpl.java
/** * Main method used for creating initial key file. * /*from w w w . j a v a2 s .c om*/ * @param args * - not used */ public static void main(String[] args) { final String keyFile = "./howto.key"; final String pwdFile = "./howto.properties"; CryptoUtilImpl cryptoUtils = new CryptoUtilImpl(); cryptoUtils.setKeyFile(new File(keyFile)); String clearPwd = "my_cleartext_pwd"; Properties p1 = new Properties(); Writer w = null; try { p1.put("user", "liferay"); String encryptedPwd = cryptoUtils.encrypt(clearPwd); p1.put("pwd", encryptedPwd); w = new FileWriter(pwdFile); p1.store(w, ""); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (w != null) { try { w.close(); } catch (IOException e) { e.printStackTrace(); } } } // ================== Properties p2 = new Properties(); Reader r = null; try { r = new FileReader(pwdFile); p2.load(r); String encryptedPwd = p2.getProperty("pwd"); System.out.println(encryptedPwd); System.out.println(cryptoUtils.decrypt(encryptedPwd)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } finally { if (r != null) { try { r.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:examples.KafkaStreamsDemo.java
public static void main(String[] args) throws InterruptedException, SQLException { /**/*from ww w. j ava2s . c o m*/ * The example assumes the following SQL schema * * DROP DATABASE IF EXISTS beer_sample_sql; * CREATE DATABASE beer_sample_sql CHARACTER SET utf8 COLLATE utf8_general_ci; * USE beer_sample_sql; * * CREATE TABLE breweries ( * id VARCHAR(256) NOT NULL, * name VARCHAR(256), * description TEXT, * country VARCHAR(256), * city VARCHAR(256), * state VARCHAR(256), * phone VARCHAR(40), * updated_at DATETIME, * PRIMARY KEY (id) * ); * * * CREATE TABLE beers ( * id VARCHAR(256) NOT NULL, * brewery_id VARCHAR(256) NOT NULL, * name VARCHAR(256), * category VARCHAR(256), * style VARCHAR(256), * description TEXT, * abv DECIMAL(10,2), * ibu DECIMAL(10,2), * updated_at DATETIME, * PRIMARY KEY (id) * ); */ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.err.println("Failed to load MySQL JDBC driver"); } Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/beer_sample_sql", "root", "secret"); final PreparedStatement insertBrewery = connection.prepareStatement( "INSERT INTO breweries (id, name, description, country, city, state, phone, updated_at)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE" + " name=VALUES(name), description=VALUES(description), country=VALUES(country)," + " country=VALUES(country), city=VALUES(city), state=VALUES(state)," + " phone=VALUES(phone), updated_at=VALUES(updated_at)"); final PreparedStatement insertBeer = connection.prepareStatement( "INSERT INTO beers (id, brewery_id, name, description, category, style, abv, ibu, updated_at)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE" + " brewery_id=VALUES(brewery_id), name=VALUES(name), description=VALUES(description)," + " category=VALUES(category), style=VALUES(style), abv=VALUES(abv)," + " ibu=VALUES(ibu), updated_at=VALUES(updated_at)"); String schemaRegistryUrl = "http://localhost:8081"; Properties props = new Properties(); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-test"); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181"); props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl); props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, KeyAvroSerde.class); props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, ValueAvroSerde.class); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); KStreamBuilder builder = new KStreamBuilder(); KStream<String, GenericRecord> source = builder.stream("streaming-topic-beer-sample"); KStream<String, JsonNode>[] documents = source.mapValues(new ValueMapper<GenericRecord, JsonNode>() { @Override public JsonNode apply(GenericRecord value) { ByteBuffer buf = (ByteBuffer) value.get("content"); try { JsonNode doc = MAPPER.readTree(buf.array()); return doc; } catch (IOException e) { return null; } } }).branch(new Predicate<String, JsonNode>() { @Override public boolean test(String key, JsonNode value) { return "beer".equals(value.get("type").asText()) && value.has("brewery_id") && value.has("name") && value.has("description") && value.has("category") && value.has("style") && value.has("abv") && value.has("ibu") && value.has("updated"); } }, new Predicate<String, JsonNode>() { @Override public boolean test(String key, JsonNode value) { return "brewery".equals(value.get("type").asText()) && value.has("name") && value.has("description") && value.has("country") && value.has("city") && value.has("state") && value.has("phone") && value.has("updated"); } }); documents[0].foreach(new ForeachAction<String, JsonNode>() { @Override public void apply(String key, JsonNode value) { try { insertBeer.setString(1, key); insertBeer.setString(2, value.get("brewery_id").asText()); insertBeer.setString(3, value.get("name").asText()); insertBeer.setString(4, value.get("description").asText()); insertBeer.setString(5, value.get("category").asText()); insertBeer.setString(6, value.get("style").asText()); insertBeer.setBigDecimal(7, new BigDecimal(value.get("abv").asText())); insertBeer.setBigDecimal(8, new BigDecimal(value.get("ibu").asText())); insertBeer.setDate(9, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime())); insertBeer.execute(); } catch (SQLException e) { System.err.println("Failed to insert record: " + key + ". " + e); } catch (ParseException e) { System.err.println("Failed to insert record: " + key + ". " + e); } } }); documents[1].foreach(new ForeachAction<String, JsonNode>() { @Override public void apply(String key, JsonNode value) { try { insertBrewery.setString(1, key); insertBrewery.setString(2, value.get("name").asText()); insertBrewery.setString(3, value.get("description").asText()); insertBrewery.setString(4, value.get("country").asText()); insertBrewery.setString(5, value.get("city").asText()); insertBrewery.setString(6, value.get("state").asText()); insertBrewery.setString(7, value.get("phone").asText()); insertBrewery.setDate(8, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime())); insertBrewery.execute(); } catch (SQLException e) { System.err.println("Failed to insert record: " + key + ". " + e); } catch (ParseException e) { System.err.println("Failed to insert record: " + key + ". " + e); } } }); final KafkaStreams streams = new KafkaStreams(builder, props); streams.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { streams.close(); } })); }
From source file:com.zimbra.cs.util.SmtpInject.java
public static void main(String[] args) { CliUtil.toolSetup();//from www. ja v a 2 s. com CommandLine cl = parseArgs(args); if (cl.hasOption("h")) { usage(null); } String file = null; if (!cl.hasOption("f")) { usage("no file specified"); } else { file = cl.getOptionValue("f"); } try { ByteUtil.getContent(new File(file)); } catch (IOException ioe) { usage(ioe.getMessage()); } String host = null; if (!cl.hasOption("a")) { usage("no smtp server specified"); } else { host = cl.getOptionValue("a"); } String sender = null; if (!cl.hasOption("s")) { usage("no sender specified"); } else { sender = cl.getOptionValue("s"); } String recipient = null; if (!cl.hasOption("r")) { usage("no recipient specified"); } else { recipient = cl.getOptionValue("r"); } boolean trace = false; if (cl.hasOption("T")) { trace = true; } boolean tls = false; if (cl.hasOption("t")) { tls = true; } boolean auth = false; String user = null; String password = null; if (cl.hasOption("A")) { auth = true; if (!cl.hasOption("u")) { usage("auth enabled, no user specified"); } else { user = cl.getOptionValue("u"); } if (!cl.hasOption("p")) { usage("auth enabled, no password specified"); } else { password = cl.getOptionValue("p"); } } if (cl.hasOption("v")) { mLog.info("SMTP server: " + host); mLog.info("Sender: " + sender); mLog.info("Recipient: " + recipient); mLog.info("File: " + file); mLog.info("TLS: " + tls); mLog.info("Auth: " + auth); if (auth) { mLog.info("User: " + user); char[] dummyPassword = new char[password.length()]; Arrays.fill(dummyPassword, '*'); mLog.info("Password: " + new String(dummyPassword)); } } Properties props = System.getProperties(); props.put("mail.smtp.host", host); if (auth) { props.put("mail.smtp.auth", "true"); } else { props.put("mail.smtp.auth", "false"); } if (tls) { props.put("mail.smtp.starttls.enable", "true"); } else { props.put("mail.smtp.starttls.enable", "false"); } // Disable certificate checking so we can test against // self-signed certificates props.put("mail.smtp.ssl.socketFactory", SocketFactories.dummySSLSocketFactory()); Session session = Session.getInstance(props, null); session.setDebug(trace); try { // create a message MimeMessage msg = new ZMimeMessage(session, new ZSharedFileInputStream(file)); InternetAddress[] address = { new JavaMailInternetAddress(recipient) }; msg.setFrom(new JavaMailInternetAddress(sender)); // attach the file to the message Transport transport = session.getTransport("smtp"); transport.connect(null, user, password); transport.sendMessage(msg, address); } catch (MessagingException mex) { mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.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"); // /* w w w . j a va 2 s.c om*/ 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: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"); // /*w ww . ja va 2 s . c om*/ 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(); } }