/** * Creates a new Socket connected to the given IP address. The method uses connection settings * supplied in the constructor for connecting the socket. * * @param address the IP address to connect to * @return connected socket * @throws java.net.UnknownHostException if the hostname of the address or the proxy cannot be * resolved * @throws java.io.IOException if an I/O error occured while connecting to the remote end or to * the proxy */ private Socket createSocket(InetSocketAddress address, int timeout) throws IOException { String socksProxyHost = System.getProperty("socksProxyHost"); System.getProperties().remove("socksProxyHost"); try { ConnectivitySettings cs = lastKnownSettings.get(address); if (cs != null) { try { return createSocket(cs, address, timeout); } catch (IOException e) { // not good anymore, try all proxies lastKnownSettings.remove(address); } } URI uri = addressToURI(address, "socket"); try { return createSocket(uri, address, timeout); } catch (IOException e) { // we will also try https } uri = addressToURI(address, "https"); return createSocket(uri, address, timeout); } finally { if (socksProxyHost != null) { System.setProperty("socksProxyHost", socksProxyHost); } } }
public void setActive(boolean b) { // the function is called 3 times when leaving this perspective this odd // logic is here so it doesn't reload the data when leaving this perspective if (b) { if (!this.isActive) { System.out.println("create eclResults setActive"); if (System.getProperties().getProperty("resultsFile") != null && !System.getProperties().getProperty("resultsFile").equals("")) { String xmlFile = System.getProperties().getProperty("resultsFile"); ArrayList<String> resultFiles = parseData("resultsFile"); for (int i = 0; i < resultFiles.size(); i++) { openResultsXML(resultFiles.get(i)); } // openResultsXML(xmlFile); System.getProperties().setProperty("resultsFile", ""); } int len = folder.getItemCount(); folder.setSelection(len - 1); this.isActive = true; } else { this.isActive = false; } } else { System.out.println("create eclResults setActive -- deactivate"); } }
/** * Sets the Logfile * * @param aLogFile The logFile to set. * * @return The logfile to write into */ public static synchronized PrintWriter setLogFile(PrintWriter aLogFile) { System.getProperties().put(IZPACK_LOGFILE, aLogFile); PrintWriter logfile = (PrintWriter) System.getProperties().get(IZPACK_LOGFILE); if (logfile == null) { System.err.println("Set::logfile == null"); } return logfile; }
public static void main(String[] args) throws MessagingException, IOException { IMAPFolder folder = null; Store store = null; String subject = null; Flag flag = null; try { Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imap.host", "imap.googlemail.com"); SimpleAuthenticator authenticator = new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy"); Session session = Session.getDefaultInstance(props, null); // Session session = Session.getDefaultInstance(props, authenticator); store = session.getStore("imaps"); // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy"); // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy"); store.connect("*****@*****.**", "hhy8611hhy"); // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email // account folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account if (!folder.isOpen()) folder.open(Folder.READ_WRITE); Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages(); System.out.println("No of get Messages : " + messages.length); System.out.println("No of Messages : " + folder.getMessageCount()); System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount()); System.out.println("No of New Messages : " + folder.getNewMessageCount()); System.out.println(messages.length); for (int i = 0; i < messages.length; i++) { System.out.println( "*****************************************************************************"); System.out.println("MESSAGE " + (i + 1) + ":"); Message msg = messages[i]; // System.out.println(msg.getMessageNumber()); // Object String; // System.out.println(folder.getUID(msg) subject = msg.getSubject(); System.out.println("Subject: " + subject); System.out.println("From: " + msg.getFrom()[0]); System.out.println("To: " + msg.getAllRecipients()[0]); System.out.println("Date: " + msg.getReceivedDate()); System.out.println("Size: " + msg.getSize()); System.out.println(msg.getFlags()); System.out.println("Body: \n" + msg.getContent()); System.out.println(msg.getContentType()); } } finally { if (folder != null && folder.isOpen()) { folder.close(true); } if (store != null) { store.close(); } } }
public static String getNSSLibDir() throws Exception { Properties props = System.getProperties(); String osName = props.getProperty("os.name"); if (osName.startsWith("Win")) { osName = "Windows"; NSPR_PREFIX = "lib"; } String osid = osName + "-" + props.getProperty("os.arch") + "-" + props.getProperty("sun.arch.data.model"); String ostype = osMap.get(osid); if (ostype == null) { System.out.println("Unsupported OS, skipping: " + osid); return null; // throw new Exception("Unsupported OS " + osid); } if (ostype.length() == 0) { System.out.println("NSS not supported on this platform, skipping test"); return null; } String libdir = NSS_BASE + SEP + "lib" + SEP + ostype + SEP; System.setProperty("pkcs11test.nss.libdir", libdir); return libdir; }
public MiniFramework(Map<Object, Object> properties) { this.properties = new Properties(System.getProperties()); this.properties.putAll(properties); bundles.put(new Long(0), this); last = loader = getClass().getClassLoader(); }
/** * Add a name value pair to the project property set. Overwriting any existing value except system * properties. * * @param name the name of the property * @param value the value to set * @return an indicator if the name value pair was added. */ public boolean setProperty(String name, String value) { if (System.getProperties().containsKey(name)) { return false; } addPropertySubstitute(name, value); return true; }
public static void basic_putenv(Object name, Object value) { String name_string = SmartEiffelRuntime.NullTerminatedBytesToString(name); String value_string = SmartEiffelRuntime.NullTerminatedBytesToString(value); Properties props = System.getProperties(); props.put(name_string, value_string); System.setProperties(props); return; }
public static void copySystemProperties(Properties configProps) { for (Enumeration e = System.getProperties().propertyNames(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); if (key.startsWith("felix.") || key.startsWith("org.osgi.framework.")) { configProps.setProperty(key, System.getProperty(key)); } } }
/** sometimes call by sample application, at that time normally set some properties directly */ private Configure() { Properties p = new Properties(); Map args = new HashMap(); args.putAll(System.getenv()); args.putAll(System.getProperties()); p.putAll(args); this.property = p; reload(false); }
public static void printSystemProperties() { java.util.Enumeration e = System.getProperties().propertyNames(); while (e.hasMoreElements()) { String prop = (String) e.nextElement(); String out = prop; out += " = "; out += System.getProperty(prop); out += "\n"; System.out.println(out); } }
public static void dumpSystemProperties() { out("System Properties:"); Properties props = System.getProperties(); Iterator it = props.keySet().iterator(); while (it.hasNext()) { String name = (String) it.next(); out("\t".concat(name).concat(" = '").concat(props.get(name).toString()).concat("'")); } }
public void sendEMailToUser(ICFSecuritySecUserObj toUser, String msgSubject, String msgBody) throws IOException, MessagingException, NamingException { final String S_ProcName = "sendEMailToUser"; Properties props = System.getProperties(); Context ctx = new InitialContext(); String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFInternet25SmtpEmailFrom"); if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpEmailFrom"); } smtpUsername = (String) ctx.lookup("java:comp/env/CFInternet25SmtpUsername"); if ((smtpUsername == null) || (smtpUsername.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpUsername"); } smtpPassword = (String) ctx.lookup("java:comp/env/CFInternet25SmtpPassword"); if ((smtpPassword == null) || (smtpPassword.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpPassword"); } Session emailSess = Session.getInstance( props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUsername, smtpPassword); } }); MimeMessage msg = new MimeMessage(emailSess); msg.setFrom(new InternetAddress(smtpEmailFrom)); InternetAddress mailTo[] = InternetAddress.parse(toUser.getRequiredEMailAddress(), false); msg.setRecipient(Message.RecipientType.TO, mailTo[0]); msg.setSubject((msgSubject != null) ? msgSubject : "No subject"); msg.setSentDate(new Date()); msg.setContent(msgBody, "text/html"); msg.saveChanges(); Transport.send(msg); }
/** Start the JobTracker process, listen on the indicated port */ JobTracker(Configuration conf) throws IOException { // // Grab some static constants // maxCurrentTasks = conf.getInt("mapred.tasktracker.tasks.maximum", 2); RETIRE_JOB_INTERVAL = conf.getLong("mapred.jobtracker.retirejob.interval", 24 * 60 * 60 * 1000); RETIRE_JOB_CHECK_INTERVAL = conf.getLong("mapred.jobtracker.retirejob.check", 60 * 1000); TASK_ALLOC_EPSILON = conf.getFloat("mapred.jobtracker.taskalloc.loadbalance.epsilon", 0.2f); PAD_FRACTION = conf.getFloat("mapred.jobtracker.taskalloc.capacitypad", 0.1f); MIN_SLOTS_FOR_PADDING = 3 * maxCurrentTasks; // This is a directory of temporary submission files. We delete it // on startup, and can delete any files that we're done with this.conf = conf; JobConf jobConf = new JobConf(conf); this.systemDir = jobConf.getSystemDir(); this.fs = FileSystem.get(conf); FileUtil.fullyDelete(fs, systemDir); fs.mkdirs(systemDir); // Same with 'localDir' except it's always on the local disk. jobConf.deleteLocalFiles(SUBDIR); // Set ports, start RPC servers, etc. InetSocketAddress addr = getAddress(conf); this.localMachine = addr.getHostName(); this.port = addr.getPort(); this.interTrackerServer = RPC.getServer(this, addr.getPort(), 10, false, conf); this.interTrackerServer.start(); Properties p = System.getProperties(); for (Iterator it = p.keySet().iterator(); it.hasNext(); ) { String key = (String) it.next(); String val = (String) p.getProperty(key); LOG.info("Property '" + key + "' is " + val); } this.infoPort = conf.getInt("mapred.job.tracker.info.port", 50030); this.infoServer = new JobTrackerInfoServer(this, infoPort); this.infoServer.start(); this.startTime = System.currentTimeMillis(); new Thread(this.expireTrackers).start(); new Thread(this.retireJobs).start(); new Thread(this.initJobs).start(); }
private String standardName() { packageName = new String("tcapmodel"); for (Object i : System.getProperties().keySet()) { if (i != null) { // System.out.println(i + " = " + System.getProperties().get(i)); } } // The Eclipse "environment" tab doesn't seem to add variables as advertised. System.setProperty( "tcapmodelEclipse", "C:\\u\\My Documents\\eclipse31\\workspace\\oncotcap4\\src\\"); if (System.getProperty("tcapmodelEclipse") != null) packageBaseName = new String(System.getProperty("tcapmodelEclipse")); else packageBaseName = new String(Oncotcap.getTempPath()); packagePath = packageBaseName + packageName; return (packagePath); }
void configureProxy() { if (Prefs.useSystemProxies) { try { System.setProperty("java.net.useSystemProxies", "true"); } catch (Exception e) { } } else { String server = Prefs.get("proxy.server", null); if (server == null || server.equals("")) return; int port = (int) Prefs.get("proxy.port", 0); if (port == 0) return; Properties props = System.getProperties(); props.put("proxySet", "true"); props.put("http.proxyHost", server); props.put("http.proxyPort", "" + port); } // new ProxySettings().logProperties(); }
private void sendEmail(Task.Status exitStatus, File logFile) throws IOException, MessagingException, TemplateException { String smtpServer = RepoxContextUtil.getRepoxManager().getConfiguration().getSmtpServer(); if (smtpServer == null || smtpServer.isEmpty()) { return; } String fromEmail = RepoxContextUtil.getRepoxManager().getConfiguration().getDefaultEmail(); String recipientsEmail = RepoxContextUtil.getRepoxManager().getConfiguration().getAdministratorEmail(); String adminMailPass = RepoxContextUtil.getRepoxManager().getConfiguration().getMailPassword(); String subject = "REPOX Data Source ingesting finished. Exit status: " + exitStatus.toString(); EmailSender emailSender = new EmailSender(); String pathIngestFile = URLDecoder.decode( Thread.currentThread().getContextClassLoader().getResource("ingest.html.ftl").getFile(), "ISO-8859-1"); emailSender.setTemplate( pathIngestFile.substring(0, pathIngestFile.lastIndexOf("/")) + "/ingest"); HashMap map = new HashMap<String, String>(); map.put("exitStatus", exitStatus.toString()); map.put("id", id); JavaMailSenderImpl mail = new JavaMailSenderImpl(); // mail.setUsername(fromEmail); mail.setUsername(recipientsEmail); mail.setPassword(adminMailPass); mail.setPort(25); Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); mail.setJavaMailProperties(props); emailSender.setMailSender(mail); emailSender.sendEmail(recipientsEmail, fromEmail, subject, map, logFile.getAbsolutePath()); }
public static void showServerInfo(PrintStream out) { out.println("Server Info"); out.println( " getDocumentBuilderFactoryVersion(): " + XMLEntityResolver.getDocumentBuilderFactoryVersion()); out.println(); Properties sysp = System.getProperties(); Enumeration e = sysp.propertyNames(); List<String> list = Collections.list(e); Collections.sort(list); out.println("System Properties:"); for (String name : list) { String value = System.getProperty(name); out.println(" " + name + " = " + value); } out.println(); }
private Object receiveMail() throws Exception { Folder folder = null; Store store = null; ConfigurationPropertyManager configManager = ConfigurationPropertyManager.getConfigurationPropertyManager(); final String email_address = configManager.getPropValues("gmail_address"); final String password = configManager.getPropValues("gmail_pw"); try { Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); // Session session = Session.getDefaultInstance(props, null); Session session = Session.getInstance(props, new GMailAuthenticator(email_address, password)); store = session.getStore("imaps"); store.connect("imap.gmail.com", email_address, password); folder = store.getFolder("Inbox"); folder.open(Folder.READ_WRITE); // Message messages[] = folder.getMessages(); // search for all "unseen" messages Flags seen = new Flags(Flags.Flag.SEEN); FlagTerm unseenFlagTerm = new FlagTerm(seen, false); Message messages[] = folder.search(unseenFlagTerm); for (int i = 0; i < messages.length; i++) { folder.getMessage( messages[i].getMessageNumber()); // this will mark the retrieved messages as READ } String s = updateEmailrepository(messages); // System.out.println(s); StringTerm st = new StringTermImpl(s); return st; } catch (Exception e) { System.out.println(e.toString()); } finally { if (folder != null) { folder.close(true); } } return null; }
public static void main(String[] args) throws Exception { String smtpServer = RepoxContextUtil.getRepoxManager().getConfiguration().getSmtpServer(); if (smtpServer == null || smtpServer.isEmpty()) { return; } String fromEmail = RepoxContextUtil.getRepoxManager().getConfiguration().getDefaultEmail(); String recipientsEmail = RepoxContextUtil.getRepoxManager().getConfiguration().getAdministratorEmail(); String adminMailPass = RepoxContextUtil.getRepoxManager().getConfiguration().getMailPassword(); String subject = "REPOX Data Source ingesting finished. Exit status: "; EmailSender emailSender = new EmailSender(); String pathIngestFile = URLDecoder.decode( Thread.currentThread().getContextClassLoader().getResource("ingest.html.ftl").getFile(), "ISO-8859-1"); emailSender.setTemplate( pathIngestFile.substring(0, pathIngestFile.lastIndexOf("/")) + "/ingest"); HashMap map = new HashMap<String, String>(); map.put("exitStatus", "OK"); map.put("id", "1111"); JavaMailSenderImpl mail = new JavaMailSenderImpl(); mail.setUsername(recipientsEmail); mail.setPassword(adminMailPass); mail.setPort(25); Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "false"); mail.setJavaMailProperties(props); emailSender.setMailSender(mail); emailSender.sendEmail( recipientsEmail, fromEmail, subject, map, "C:\\Users\\GPedrosa\\Desktop\\indexSec.txt"); }
protected void initProperties(String propFileName) { // Create instance of Class Properties props = new Properties(System.getProperties()); // Try to load property list try { props.load(new BufferedInputStream(new FileInputStream(propFileName))); } catch (IOException ex) { ex.printStackTrace(); System.out.println("Exception in SpaceAccessor"); System.exit(-3); } // Output property list (can be ommitted - testing only) System.out.println("jiniURL = " + props.getProperty("jiniURL")); // Assign values to fields jiniURL = props.getProperty("jiniURL"); }
public final void init() { try { if (getParameter("forcems").equals("1") && System.getProperties().getProperty("java.vendor").toLowerCase().indexOf("sun") != -1) { forcems = true; fms = getImage(new URL(getCodeBase(), "switch.gif")); return; } } catch (Exception _ex) { } socketthread = false; Thread thread = new Thread(this); thread.start(); while (!socketthread) try { Thread.sleep(100L); } catch (Exception _ex) { } Thread thread1 = new Thread(this); thread1.start(); }
public static void main(String args[]) throws Exception { // String host = args[0]; // String username = args[1]; // String password = args[2]; String host = "triggeremails.com"; String username = "******"; String password = "******"; // Get session Session session = Session.getInstance(System.getProperties(), null); // Get the store Store store = session.getStore("pop3"); store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // Get directory Message message[] = folder.getMessages(); for (int i = 0, n = message.length; i < n; i++) { System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject()); System.out.println("Do you want to delete message? [YES to delete]"); String line = reader.readLine(); // Mark as deleted if appropriate if ("YES".equals(line)) { message[i].setFlag(Flags.Flag.DELETED, true); } } // Close connection folder.close(true); store.close(); }
private HttpProxyConfig getHttpProxyConfigData() { Properties p = provider.getContext().getCustomProperties(); HttpProxyConfig httpProxyConfig = null; if (p != null && p.getProperty("proxyHost") != null && p.getProperty("proxyPort") != null) { if (p.getProperty("proxyPort").length() > 0) { httpProxyConfig = new HttpProxyConfig( p.getProperty("proxyHost"), Integer.parseInt(p.getProperty("proxyPort"))); } } else { p = System.getProperties(); if (p != null && p.getProperty("proxyHost") != null && p.getProperty("proxyPort") != null) { if (p.getProperty("proxyPort").length() > 0) { httpProxyConfig = new HttpProxyConfig( p.getProperty("proxyHost"), Integer.parseInt(p.getProperty("proxyPort"))); } } } return httpProxyConfig; }
/** * Creates a new empty DataStore that will retrieve it's data from a remote dataserver. * * @param url The url of the RemoteDataStore. Remote DataStores urls follow the following * convention http://hostname/servlet/DataServer/Application/RemoteDataStore * @param userID The user id to use. * @param passWord The password to use. * @param proxyHost The host name of a proxy server to use * @param proxyPort The port number of a proxy server to use * @param proxyUser The user id to get through the proxy server * @param proxyPassword The password to get through the proxy server * @param criteria Additional criteria to pass to the server * @param useCompression Use zip compression to transfer data back from the server */ public DataStoreProxy( String url, String userID, String passWord, String proxyHost, String proxyPort, String proxyUser, String proxyPassword, String criteria, boolean useCompression) throws DataStoreException { super(); if (proxyHost != null) { Properties p = System.getProperties(); p.put("proxySet", "true"); p.put("proxyHost", proxyHost); p.put("proxyPort", proxyPort); } _dataSource = new DSDataSourceProxy( url, null, userID, passWord, proxyUser, proxyPassword, criteria, this); }
/** * Starts Grid instance. Note that if grid is already started, then it will be looked up and * returned from this method. * * @return Started grid. */ private Grid startGrid() { Properties props = System.getProperties(); gridName = props.getProperty(GRIDGAIN_NAME.name()); if (!props.containsKey(GRIDGAIN_NAME.name()) || G.state(gridName) != GridFactoryState.STARTED) { selfStarted = true; // Set class loader for the spring. ClassLoader curCl = Thread.currentThread().getContextClassLoader(); // Add no-op logger to remove no-appender warning. Appender app = new NullAppender(); Logger.getRootLogger().addAppender(app); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); Grid grid = G.start(cfgPath); gridName = grid.name(); System.setProperty(GRIDGAIN_NAME.name(), grid.name()); return grid; } catch (GridException e) { throw new GridRuntimeException("Failed to start grid: " + cfgPath, e); } finally { Logger.getRootLogger().removeAppender(app); Thread.currentThread().setContextClassLoader(curCl); } } return G.grid(gridName); }
public static void ClaimsMsgShow( java.lang.String argvs[], Folder folder, Store store, biz.systempartners.claims.ClaimsViewer claimsViewer) { if (claimsViewer == null) {} int msgnum = -1; int optind = 0; InputStream msgStream = System.in; if (argvs != null) { for (optind = 0; optind < argvs.length; optind++) { if (argvs[optind].equals("-T")) { protocol = argvs[++optind]; } else if (argvs[optind].equals("-H")) { host = argvs[++optind]; } else if (argvs[optind].equals("-U")) { user = argvs[++optind]; } else if (argvs[optind].equals("-P")) { password = argvs[++optind]; } else if (argvs[optind].equals("-v")) { verbose = true; } else if (argvs[optind].equals("-D")) { debug = true; } else if (argvs[optind].equals("-f")) { mbox = argvs[++optind]; } else if (argvs[optind].equals("-L")) { url = argvs[++optind]; } else if (argvs[optind].equals("-p")) { port = Integer.parseInt(argvs[++optind]); } else if (argvs[optind].equals("-s")) { showStructure = true; } else if (argvs[optind].equals("-S")) { saveAttachments = true; } else if (argvs[optind].equals("-m")) { showMessage = true; } else if (argvs[optind].equals("-a")) { showAlert = true; } else if (argvs[optind].equals("--")) { optind++; break; } else if (argvs[optind].startsWith("-")) { System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]"); System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]"); System.out.println("or msgshow -m [-v] [-D] [-s] [-S] < msg"); System.exit(1); } else { break; } } } try { if (optind < argvs.length) msgnum = Integer.parseInt(argvs[optind]); // msgnum = 1; // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); session.setDebug(debug); if (showMessage) { MimeMessage msg = new MimeMessage(session, msgStream); dumpPart(msg, claimsViewer); // System.exit(0); } /* // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); if (showAlert) { store.addStoreListener(new StoreListener() { public void notification(StoreEvent e) { String s; if (e.getMessageType() == StoreEvent.ALERT) s = "ALERT: "; else s = "NOTICE: "; System.out.println(s + e.getMessage()); } }); } store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, port, user, password); else store.connect(); } // Open the Folder Folder folder = store.getDefaultFolder(); if (folder == null) { System.out.println("No default folder"); System.exit(1); } */ // folder = folder.getFolder(mbox); if (folder == null) { System.out.println("Invalid folder"); System.exit(1); } // try to open read/write and if that fails try read-only try { folder.open(Folder.READ_WRITE); } catch (MessagingException ex) { folder.open(Folder.READ_ONLY); } int totalMessages = folder.getMessageCount(); if (totalMessages == 0) { System.out.println("Empty folder"); folder.close(false); store.close(); System.exit(1); } if (verbose) { int newMessages = folder.getNewMessageCount(); System.out.println("Total messages = " + totalMessages); System.out.println("New messages = " + newMessages); System.out.println("-------------------------------"); } if (msgnum == -1) { // Attributes & Flags for all messages .. Message[] msgs = folder.getMessages(); // Use a suitable FetchProfile FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(msgs, fp); for (int i = 0; i < msgs.length; i++) { System.out.println("--------------------------"); System.out.println("MESSAGE #" + (i + 1) + ":"); dumpEnvelope(msgs[i]); // dumpPart(msgs[i]); } } else { Message[] msgs = folder.getMessages(); for (int n = 0; n < msgs.length; n++) { System.out.println("Getting message number: " + n + 1); Message m = null; try { m = folder.getMessage(msgnum + 1); // m.setDisposition( dumpPart(m, claimsViewer); // m.setExpunged(true); } catch (IndexOutOfBoundsException iex) { System.out.println("Message number out of range"); } } folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true); } // folder.expunge(); folder.close(true); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); // System.exit(1); } // System.exit(0); }
/* * Accepts a new request from the HTTP server and creates * a conventional execution environment for the request. * If the application was invoked as a FastCGI server, * the first call to FCGIaccept indicates that the application * has completed its initialization and is ready to accept * a request. Subsequent calls to FCGI_accept indicate that * the application has completed its processing of the * current request and is ready to accept a new request. * If the application was invoked as a CGI program, the first * call to FCGIaccept is essentially a no-op and the second * call returns EOF (-1) as does an error. Application should exit. * * If the application was invoked as a FastCGI server, * and this is not the first call to this procedure, * FCGIaccept first flushes any buffered output to the HTTP server. * * On every call, FCGIaccept accepts the new request and * reads the FCGI_PARAMS stream into System.props. It also creates * streams that understand FastCGI protocol and take input from * the HTTP server send output and error output to the HTTP server, * and assigns these new streams to System.in, System.out and * System.err respectively. * * For now, we will just return an int to the caller, which is why * this method catches, but doen't throw Exceptions. * */ public int FCGIaccept() { int acceptResult = 0; /* * If first call, mark it and if fcgi save original system properties, * If not first call, and we are cgi, we should be gone. */ if (!acceptCalled) { isFCGI = System.getenv("FCGI_PORT") != null; acceptCalled = true; if (isFCGI) { /* * save original system properties (nonrequest) * and get a server socket */ startupProps = new Properties(System.getProperties()); String str = new String(System.getenv("FCGI_PORT")); if (str.length() <= 0) { return -1; } int portNum = Integer.parseInt(str); try { srvSocket = new ServerSocket(portNum); } catch (IOException e) { if (request != null) { request.socket = null; } srvSocket = null; request = null; return -1; } } } else { if (!isFCGI) { return -1; } } /* * If we are cgi, just leave everything as is, otherwise set up env */ if (isFCGI) { try { acceptResult = FCGIAccept(); } catch (IOException e) { return -1; } if (acceptResult < 0) { return -1; } /* * redirect stdin, stdout and stderr to fcgi socket */ System.setIn(new BufferedInputStream(request.inStream, 8192)); System.setOut(new PrintStream(new BufferedOutputStream(request.outStream, 8192))); System.setErr(new PrintStream(new BufferedOutputStream(request.errStream, 512))); System.setProperties(request.params); } return 0; }
/** * HTML 형식으로 된 메일을 보낸다. * * @param mailTo 받는사람 주소 * @param mailFrom 보내는 사람 주소 * @param subject 메일 제목 * @param content HTML 메일 컨텐츠 * @throws MessagingException * @throws UnsupportedEncodingException */ public void sendHtmlMail(String mailTo, String mailFrom, String subject, String content) throws MessagingException, UnsupportedEncodingException { // properties object 얻기 Properties props = System.getProperties(); // SMTP host property 정의 // props.put(smtpProps, smtpHost); props.put(SMTP_PROPS, SMTP_HOST); log.debug("[" + className + "]-SMTP_HOST =" + SMTP_HOST); // javax mail 을 디버깅 모드로 설정 props.put(SMTP_DEBUG, SMTP_TRUE); log.debug("[" + className + "]-SMTP_TRUE =" + SMTP_TRUE); if (MarConstants.getServerName() == MarConstants.SERVER_LOCAL) { // gmail smtp 서비스 포트 설정 props.put(SMTP_PORT, SMTP_PORTV2); props.put("type", "javax.mail.Session"); // 해도 그만 안해도 그만 props.put("auth", "Application"); // 해도 그만 안해도 그만 log.debug("[" + className + "]-SMTP_PORTV2 =" + SMTP_PORTV2); // 로그인할때 Transport Layer Security (TLS) 를 사용할것인지 설정 gmail 에선 tls가 필수가 아니므로 해도그만 안해도 그만이다. props.put(SMTP_TLS, SMTP_TRUE); props.put(SMTP_TRANS, SMTP_PROTOCOL); // 프로토콜 설정 log.debug("[" + className + "]-filename =" + SMTP_TRUE); log.debug("[" + className + "]-filename =" + SMTP_PROTOCOL); // gmail 인증용 Secure Sockets Layer (SSL) 설정 // gmail 에서 인증? 사용해주므로 요건 안해주면 안됨 props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } else { props.put(SMTP_PORT, SMTP_PORTV); log.debug("[" + className + "]-filename =" + SMTP_PORTV); } // session 얻기 Session session = null; if (MarConstants.getServerName() == MarConstants.SERVER_LOCAL) { // smtp 인증 을 설정 props.put("mail.smtp.auth", "true"); Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication("*****@*****.**", "vlffldzm2102"); return new PasswordAuthentication("*****@*****.**", ""); } }; // session 얻기 session = Session.getDefaultInstance(props, auth); // log.debug("["+className+"]-session ="+session); } else { session = Session.getDefaultInstance(props, null); // log.debug("["+className+"]-session ="+session); } if (log.isDebugEnabled()) { session.setDebug(true); } log.debug("[" + className + "]-mailFrom =" + mailFrom); log.debug("[" + className + "]-mailTo =" + mailTo); // 새로운 message object 생성 MimeMessage message = new MimeMessage(session); // MimeUtility.encodeText(subject, "KSC5601", "B"); message.setHeader("Content-Type", "text/html; charset=" + MAIL_ENCODING); message.setHeader("Content-Transfer-Encoding", MAIL_ENCODING64); message.setSubject(subject); // 일반적인 message object 채우기 // message.setContent(content, "text/html; charset=" + MAIL_ENCODING); // message.setContent(content, "text/html; charset=UTF-8"); message.setContent(content, "text/html;charset=UTF-8"); message.setFrom(new InternetAddress(mailFrom)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo)); // message 보내기 Transport.send(message); log.debug("[" + className + "]-Send Mail Success"); }
public static void setProperty(String key, String val) { Properties props = System.getProperties(); props.put(key, val); System.setProperties(props); }