List of usage examples for java.io FileReader close
public void close() throws IOException
From source file:MainClass.java
public static void main(String args[]) { try {/*from w ww. java2s . co m*/ FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); StreamTokenizer st = new StreamTokenizer(br); st.ordinaryChar('.'); st.wordChars('\'', '\''); while (st.nextToken() != StreamTokenizer.TT_EOF) { switch (st.ttype) { case StreamTokenizer.TT_WORD: System.out.println(st.lineno() + ") " + st.sval); break; case StreamTokenizer.TT_NUMBER: System.out.println(st.lineno() + ") " + st.nval); break; default: System.out.println(st.lineno() + ") " + (char) st.ttype); } } fr.close(); } catch (Exception e) { System.out.println("Exception: " + e); } }
From source file:org.eclipse.birt.build.mavenrepogen.RepoGen.java
public static void main(final String[] args) throws IOException { final String propsFileName; if (args.length >= 1) propsFileName = args[0];/* w w w . j av a 2s . co m*/ else propsFileName = "./repoGen.properties"; String passphrase = null; if (args.length >= 2) passphrase = args[1]; final Properties properties = new Properties(); final FileReader fr = new FileReader(propsFileName); try { properties.load(fr); } finally { fr.close(); } final String libDirName = properties.getProperty("libDir"); final String repoDirName = properties.getProperty("repoDir"); final String groupId = properties.getProperty("groupId"); if (passphrase == null) passphrase = properties.getProperty("passphrase"); final boolean clean = "true".equalsIgnoreCase(properties.getProperty("clean")); final boolean genSnapshot = "true".equalsIgnoreCase(properties.getProperty("snapshot")); final boolean genRelease = "true".equalsIgnoreCase(properties.getProperty("release")); final String rootFileName = properties.getProperty("rootFile"); final String readmeFilePath = properties.getProperty("readmeFile"); final RepoGen repoGen = new RepoGen(new File(libDirName), new File(repoDirName), groupId, passphrase, genSnapshot, genRelease, clean, rootFileName, readmeFilePath); repoGen.generate(); }
From source file:MainClass.java
public static void main(String args[]) { try {//from w w w . ja v a 2s .co m // Create a file reader FileReader fr = new FileReader(args[0]); // Create a buffered reader BufferedReader br = new BufferedReader(fr); // Create a stream tokenizer StreamTokenizer st = new StreamTokenizer(br); // Process tokens while (st.nextToken() != StreamTokenizer.TT_EOF) { switch (st.ttype) { case StreamTokenizer.TT_WORD: System.out.println(st.lineno() + ") " + st.sval); break; case StreamTokenizer.TT_NUMBER: System.out.println(st.lineno() + ") " + st.nval); break; default: System.out.println(st.lineno() + ") " + (char) st.ttype); } } // Close file reader fr.close(); } catch (Exception e) { System.out.println("Exception: " + e); } }
From source file:org.apache.metron.dataservices.Main.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("homeDir", true, "Home directory for the service"); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); Properties configProps = new Properties(); String homeDir = cmd.getOptionValue("homeDir"); if (homeDir.endsWith("/")) { homeDir = homeDir.substring(0, homeDir.length() - 1); }/* w ww. j av a2 s . co m*/ DOMConfigurator.configure(homeDir + "/log4j.xml"); logger.warn("DataServices Server starting..."); File configFile = new File(homeDir + "/config.properties"); FileReader configFileReader = new FileReader(configFile); try { configProps.load(configFileReader); Option[] cmdOptions = cmd.getOptions(); for (Option opt : cmdOptions) { String argName = opt.getOpt(); String argValue = opt.getValue(); configProps.put(argName, argValue); } } finally { if (configFileReader != null) { configFileReader.close(); } } WebAppContext context = new WebAppContext(); Injector injector = Guice.createInjector(new DefaultServletModule(configProps), new AlertsServerModule(configProps), new DefaultShiroWebModule(configProps, context.getServletContext()), new AbstractModule() { @Override protected void configure() { binder().requireExplicitBindings(); bind(GuiceFilter.class); bind(GuiceResteasyBootstrapServletContextListener.class); bind(EnvironmentLoaderListener.class); } }); injector.getAllBindings(); injector.createChildInjector().getAllBindings(); Server server = new Server(port); /*************************************************** *************** enable SSL ************************ ***************************************************/ // HTTP Configuration HttpConfiguration http_config = new HttpConfiguration(); http_config.setSecureScheme("https"); http_config.setSecurePort(8443); http_config.setOutputBufferSize(32768); http_config.setRequestHeaderSize(8192); http_config.setResponseHeaderSize(8192); http_config.setSendServerVersion(true); http_config.setSendDateHeader(false); // httpConfig.addCustomizer(new ForwardedRequestCustomizer()) // SSL Context Factory SslContextFactory sslContextFactory = new SslContextFactory(); String sslKeystorePath = configProps.getProperty("sslKeystorePath", "/keystore"); logger.debug("sslKeystorePath: " + sslKeystorePath); sslContextFactory.setKeyStorePath(homeDir + sslKeystorePath); String sslKeystorePassword = configProps.getProperty("sslKeystorePassword"); sslContextFactory.setKeyStorePassword(sslKeystorePassword); String sslKeyManagerPassword = configProps.getProperty("sslKeyManagerPassword"); if (sslKeyManagerPassword != null && !sslKeyManagerPassword.isEmpty()) { sslContextFactory.setKeyManagerPassword(sslKeyManagerPassword); } String sslTruststorePath = configProps.getProperty("sslTruststorePath"); if (sslTruststorePath != null && !sslTruststorePath.isEmpty()) { sslContextFactory.setTrustStorePath(homeDir + sslTruststorePath); } String sslTruststorePassword = configProps.getProperty("sslTruststorePassword"); if (sslTruststorePassword != null && !sslTruststorePassword.isEmpty()) { sslContextFactory.setTrustStorePassword(sslTruststorePassword); } sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"); // SSL HTTP Configuration HttpConfiguration https_config = new HttpConfiguration(http_config); https_config.addCustomizer(new SecureRequestCustomizer()); // SSL Connector ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config)); sslConnector.setPort(8443); server.addConnector(sslConnector); FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class)); /** For JSP support. Used only for testing and debugging for now. This came come out * once the real consumers for this service are in place */ URL indexUri = Main.class.getResource(WEBROOT_INDEX); if (indexUri == null) { throw new FileNotFoundException("Unable to find resource " + WEBROOT_INDEX); } // Points to wherever /webroot/ (the resource) is URI baseUri = indexUri.toURI(); // Establish Scratch directory for the servlet context (used by JSP compilation) File tempDir = new File(System.getProperty("java.io.tmpdir")); File scratchDir = new File(tempDir.toString(), "embedded-jetty-jsp"); if (!scratchDir.exists()) { if (!scratchDir.mkdirs()) { throw new IOException("Unable to create scratch directory: " + scratchDir); } } // Set JSP to use Standard JavaC always System.setProperty("org.apache.jasper.compiler.disablejsr199", "false"); context.setAttribute("javax.servlet.context.tempdir", scratchDir); context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager()); //Ensure the jsp engine is initialized correctly JettyJasperInitializer sci = new JettyJasperInitializer(); ServletContainerInitializersStarter sciStarter = new ServletContainerInitializersStarter(context); ContainerInitializer initializer = new ContainerInitializer(sci, null); List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>(); initializers.add(initializer); context.setAttribute("org.eclipse.jetty.containerInitializers", initializers); context.addBean(sciStarter, true); // Set Classloader of Context to be sane (needed for JSTL) // JSP requires a non-System classloader, this simply wraps the // embedded System classloader in a way that makes it suitable // for JSP to use // new URL( "file:///home/prhodes/.m2/repository/javax/servlet/jsp/javax.servlet.jsp-api/2.3.1/javax.servlet.jsp-api-2.3.1.jar" ) ClassLoader jspClassLoader = new URLClassLoader(new URL[] {}, Thread.currentThread().getContextClassLoader()); context.setClassLoader(jspClassLoader); // Add JSP Servlet (must be named "jsp") ServletHolder holderJsp = new ServletHolder("jsp", JspServlet.class); holderJsp.setInitOrder(0); holderJsp.setInitParameter("logVerbosityLevel", "DEBUG"); holderJsp.setInitParameter("fork", "false"); holderJsp.setInitParameter("xpoweredBy", "false"); holderJsp.setInitParameter("compilerTargetVM", "1.7"); holderJsp.setInitParameter("compilerSourceVM", "1.7"); holderJsp.setInitParameter("keepgenerated", "true"); context.addServlet(holderJsp, "*.jsp"); //context.addServlet(holderJsp,"*.jspf"); //context.addServlet(holderJsp,"*.jspx"); // Add Default Servlet (must be named "default") ServletHolder holderDefault = new ServletHolder("default", DefaultServlet.class); holderDefault.setInitParameter("resourceBase", baseUri.toASCIIString()); holderDefault.setInitParameter("dirAllowed", "true"); context.addServlet(holderDefault, "/"); /** end "for JSP support */ context.setResourceBase(baseUri.toASCIIString()); context.setInitParameter("resteasy.guice.modules", "org.apache.metron.dataservices.modules.guice.RestEasyModule"); context.setInitParameter("resteasy.servlet.mapping.prefix", "/rest"); context.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class)); context.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class)); server.setHandler(context); server.start(); AlertsProcessingServer alertsServer = injector.getInstance(AlertsProcessingServer.class); alertsServer.startProcessing(); server.join(); }
From source file:org.b3log.latke.client.LatkeClient.java
/** * Main entry.//from w w w .ja va 2 s . com * * @param args the specified command line arguments * @throws Exception exception */ public static void main(String[] args) throws Exception { // Backup Test: // args = new String[] { // "-h", "-backup", "-repository_names", "-verbose", "-s", "localhost:8080", "-u", "xxx", "-p", "xxx", "-backup_dir", // "C:/b3log_backup", "-w", "true"}; // args = new String[] { // "-h", "-restore", "-create_tables", "-verbose", "-s", "localhost:8080", "-u", "xxx", "-p", "xxx", "-backup_dir", // "C:/b3log_backup"}; final Options options = getOptions(); final CommandLineParser parser = new PosixParser(); try { final CommandLine cmd = parser.parse(options, args); serverAddress = cmd.getOptionValue("s"); backupDir = new File(cmd.getOptionValue("backup_dir")); if (!backupDir.exists()) { backupDir.mkdir(); } userName = cmd.getOptionValue("u"); if (cmd.hasOption("verbose")) { verbose = true; } password = cmd.getOptionValue("p"); if (verbose) { System.out.println("Requesting server[" + serverAddress + "]"); } final HttpClient httpClient = new DefaultHttpClient(); if (cmd.hasOption("repository_names")) { getRepositoryNames(); } if (cmd.hasOption("create_tables")) { final List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("userName", userName)); qparams.add(new BasicNameValuePair("password", password)); final URI uri = URIUtils.createURI("http", serverAddress, -1, CREATE_TABLES, URLEncodedUtils.format(qparams, "UTF-8"), null); final HttpPut request = new HttpPut(); request.setURI(uri); if (verbose) { System.out.println("Starting create tables"); } final HttpResponse httpResponse = httpClient.execute(request); final InputStream contentStream = httpResponse.getEntity().getContent(); final String content = IOUtils.toString(contentStream).trim(); if (verbose) { printResponse(content); } } if (cmd.hasOption("w")) { final String writable = cmd.getOptionValue("w"); final List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("userName", userName)); qparams.add(new BasicNameValuePair("password", password)); qparams.add(new BasicNameValuePair("writable", writable)); final URI uri = URIUtils.createURI("http", serverAddress, -1, SET_REPOSITORIES_WRITABLE, URLEncodedUtils.format(qparams, "UTF-8"), null); final HttpPut request = new HttpPut(); request.setURI(uri); if (verbose) { System.out.println("Setting repository writable[" + writable + "]"); } final HttpResponse httpResponse = httpClient.execute(request); final InputStream contentStream = httpResponse.getEntity().getContent(); final String content = IOUtils.toString(contentStream).trim(); if (verbose) { printResponse(content); } } if (cmd.hasOption("backup")) { System.out.println("Make sure you have disabled repository writes with [-w false], continue? (y)"); final Scanner scanner = new Scanner(System.in); final String input = scanner.next(); scanner.close(); if (!"y".equals(input)) { return; } if (verbose) { System.out.println("Starting backup data"); } final Set<String> repositoryNames = getRepositoryNames(); for (final String repositoryName : repositoryNames) { // You could specify repository manually // if (!"archiveDate_article".equals(repositoryName)) { // continue; // } int requestPageNum = 1; // Backup interrupt recovery final List<File> backupFiles = getBackupFiles(repositoryName); if (!backupFiles.isEmpty()) { final File latestBackup = backupFiles.get(backupFiles.size() - 1); final String latestPageSize = getBackupFileNameField(latestBackup.getName(), "${pageSize}"); if (!PAGE_SIZE.equals(latestPageSize)) { // The 'latestPageSize' should be less or equal to 'PAGE_SIZE', if they are not the same that indicates // the latest backup file is the last of this repository, the repository backup had completed if (verbose) { System.out.println("Repository [" + repositoryName + "] backup have completed"); } continue; } final String latestPageNum = getBackupFileNameField(latestBackup.getName(), "${pageNum}"); // Prepare for the next page to request requestPageNum = Integer.parseInt(latestPageNum) + 1; if (verbose) { System.out.println( "Start tot backup interrupt recovery [pageNum=" + requestPageNum + "]"); } } int totalPageCount = requestPageNum + 1; for (; requestPageNum <= totalPageCount; requestPageNum++) { final List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("userName", userName)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("repositoryName", repositoryName)); params.add(new BasicNameValuePair("pageNum", String.valueOf(requestPageNum))); params.add(new BasicNameValuePair("pageSize", PAGE_SIZE)); final URI uri = URIUtils.createURI("http", serverAddress, -1, GET_DATA, URLEncodedUtils.format(params, "UTF-8"), null); final HttpGet request = new HttpGet(uri); if (verbose) { System.out.println("Getting data from repository [" + repositoryName + "] with pagination [pageNum=" + requestPageNum + ", pageSize=" + PAGE_SIZE + "]"); } final HttpResponse httpResponse = httpClient.execute(request); final InputStream contentStream = httpResponse.getEntity().getContent(); final String content = IOUtils.toString(contentStream, "UTF-8").trim(); contentStream.close(); if (verbose) { printResponse(content); } final JSONObject resp = new JSONObject(content); final JSONObject pagination = resp.getJSONObject("pagination"); totalPageCount = pagination.getInt("paginationPageCount"); final JSONArray results = resp.getJSONArray("rslts"); final String backupPath = backupDir.getPath() + File.separatorChar + repositoryName + File.separatorChar + requestPageNum + '_' + results.length() + '_' + System.currentTimeMillis() + ".json"; final File backup = new File(backupPath); final FileWriter fileWriter = new FileWriter(backup); IOUtils.write(results.toString(), fileWriter); fileWriter.close(); if (verbose) { System.out.println("Backup file[path=" + backupPath + "]"); } } } } if (cmd.hasOption("restore")) { System.out.println("Make sure you have enabled repository writes with [-w true], continue? (y)"); final Scanner scanner = new Scanner(System.in); final String input = scanner.next(); scanner.close(); if (!"y".equals(input)) { return; } if (verbose) { System.out.println("Starting restore data"); } final Set<String> repositoryNames = getRepositoryNamesFromBackupDir(); for (final String repositoryName : repositoryNames) { // You could specify repository manually // if (!"archiveDate_article".equals(repositoryName)) { // continue; // } final List<File> backupFiles = getBackupFiles(repositoryName); if (verbose) { System.out.println("Restoring repository[" + repositoryName + ']'); } for (final File backupFile : backupFiles) { final FileReader backupFileReader = new FileReader(backupFile); final String dataContent = IOUtils.toString(backupFileReader); backupFileReader.close(); final List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("userName", userName)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("repositoryName", repositoryName)); final URI uri = URIUtils.createURI("http", serverAddress, -1, PUT_DATA, URLEncodedUtils.format(params, "UTF-8"), null); final HttpPost request = new HttpPost(uri); final List<NameValuePair> data = new ArrayList<NameValuePair>(); data.add(new BasicNameValuePair("data", dataContent)); final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, "UTF-8"); request.setEntity(entity); if (verbose) { System.out.println("Data[" + dataContent + "]"); } final HttpResponse httpResponse = httpClient.execute(request); final InputStream contentStream = httpResponse.getEntity().getContent(); final String content = IOUtils.toString(contentStream, "UTF-8").trim(); contentStream.close(); if (verbose) { printResponse(content); } final String pageNum = getBackupFileNameField(backupFile.getName(), "${pageNum}"); final String pageSize = getBackupFileNameField(backupFile.getName(), "${pageSize}"); final String backupTime = getBackupFileNameField(backupFile.getName(), "${backupTime}"); final String restoredPath = backupDir.getPath() + File.separatorChar + repositoryName + File.separatorChar + pageNum + '_' + pageSize + '_' + backupTime + '_' + System.currentTimeMillis() + ".json"; final File restoredFile = new File(restoredPath); backupFile.renameTo(restoredFile); if (verbose) { System.out.println("Backup file[path=" + restoredPath + "]"); } } } } if (cmd.hasOption("v")) { System.out.println(VERSION); } if (cmd.hasOption("h")) { printHelp(options); } // final File backup = new File(backupDir.getPath() + File.separatorChar + repositoryName + pageNum + '_' + pageSize + '_' // + System.currentTimeMillis() + ".json"); // final FileEntity fileEntity = new FileEntity(backup, "application/json; charset=\"UTF-8\""); } catch (final ParseException e) { System.err.println("Parsing args failed, caused by: " + e.getMessage()); printHelp(options); } catch (final ConnectException e) { System.err.println("Connection refused"); } }
From source file:Main.java
public static void main(String[] argv) throws Exception { FileReader rd = new FileReader("filename.java"); StreamTokenizer st = new StreamTokenizer(rd); st.parseNumbers();/*from w ww .j a v a 2s .c o m*/ st.wordChars('_', '_'); st.eolIsSignificant(true); st.ordinaryChars(0, ' '); st.slashSlashComments(true); st.slashStarComments(true); int token = st.nextToken(); while (token != StreamTokenizer.TT_EOF) { token = st.nextToken(); switch (token) { case StreamTokenizer.TT_NUMBER: double num = st.nval; System.out.println(num); break; case StreamTokenizer.TT_WORD: String word = st.sval; System.out.println(word); break; case '"': String dquoteVal = st.sval; System.out.println(dquoteVal); break; case '\'': String squoteVal = st.sval; System.out.println(squoteVal); break; case StreamTokenizer.TT_EOL: break; case StreamTokenizer.TT_EOF: break; default: char ch = (char) st.ttype; System.out.println(ch); break; } } rd.close(); }
From source file:bariopendatalab.ImportData.java
/** * @param args the command line arguments */// ww w. ja va 2 s.c o m public static void main(String[] args) { int i = 0; try { MongoClient client = new MongoClient("localhost", 27017); DBAccess dbaccess = new DBAccess(client); dbaccess.dropDB(); dbaccess.createDB(); FileReader reader = new FileReader(new File(args[0])); Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().withIgnoreEmptyLines().withDelimiter(',') .parse(reader); i = 2; for (CSVRecord record : records) { String type = record.get("Tipologia"); if (type == null || type.length() == 0) { Logger.getLogger(ImportData.class.getName()).log(Level.WARNING, "No type in line {0}", i); } String description = record.get("Nome"); if (description != null && description.length() == 0) { description = null; } String address = record.get("Indirizzo"); if (address != null && address.length() == 0) { address = null; } String civ = record.get("Civ"); if (civ != null && civ.length() == 0) { civ = null; } if (address != null && civ != null) { address += ", " + civ; } String note = record.get("Note"); if (note != null && note.length() == 0) { note = null; } String longitudine = record.get("Longitudine"); String latitudine = record.get("Latitudine"); if (longitudine != null && latitudine != null) { if (longitudine.length() > 0 && latitudine.length() > 0) { try { dbaccess.insert(type, description, address, note, Utils .get2DPoint(Double.parseDouble(latitudine), Double.parseDouble(longitudine))); } catch (NumberFormatException nex) { dbaccess.insert(type, description, address, note, null); } } else { dbaccess.insert(type, description, address, note, null); } } else { dbaccess.insert(type, description, address, note, null); } i++; } reader.close(); } catch (Exception ex) { Logger.getLogger(ImportData.class.getName()).log(Level.SEVERE, "Error line " + i, ex); } }
From source file:com.xiangzhurui.util.email.SMTPMail.java
public static void main(String[] args) { String sender, recipient, subject, filename, server, cc; List<String> ccList = new ArrayList<String>(); BufferedReader stdin;/*from w w w . j a v a 2s . c om*/ FileReader fileReader = null; Writer writer; SimpleSMTPHeader header; SMTPClient client; if (args.length < 1) { System.err.println("Usage: mail smtpserver"); System.exit(1); } server = args[0]; stdin = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("From: "); System.out.flush(); sender = stdin.readLine(); System.out.print("To: "); System.out.flush(); recipient = stdin.readLine(); System.out.print("Subject: "); System.out.flush(); subject = stdin.readLine(); header = new SimpleSMTPHeader(sender, recipient, subject); while (true) { System.out.print("CC <enter one address per line, hit enter to end>: "); System.out.flush(); cc = stdin.readLine(); if (cc == null || cc.length() == 0) { break; } header.addCC(cc.trim()); ccList.add(cc.trim()); } System.out.print("Filename: "); System.out.flush(); filename = stdin.readLine(); try { fileReader = new FileReader(filename); } catch (FileNotFoundException e) { System.err.println("File not found. " + e.getMessage()); } client = new SMTPClient(); client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); client.connect(server); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); System.err.println("SMTP server refused connection."); System.exit(1); } client.login(); client.setSender(sender); client.addRecipient(recipient); for (String recpt : ccList) { client.addRecipient(recpt); } writer = client.sendMessageData(); if (writer != null) { writer.write(header.toString()); Util.copyReader(fileReader, writer); writer.close(); client.completePendingCommand(); } if (fileReader != null) { fileReader.close(); } client.logout(); client.disconnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
From source file:org.apache.common.net.examples.mail.SMTPMail.java
public final static void main(String[] args) { String sender, recipient, subject, filename, server, cc; List<String> ccList = new ArrayList<String>(); BufferedReader stdin;/*from ww w . jav a2 s . c o m*/ FileReader fileReader = null; Writer writer; SimpleSMTPHeader header; SMTPClient client; if (args.length < 1) { System.err.println("Usage: mail smtpserver"); System.exit(1); } server = args[0]; stdin = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("From: "); System.out.flush(); sender = stdin.readLine(); System.out.print("To: "); System.out.flush(); recipient = stdin.readLine(); System.out.print("Subject: "); System.out.flush(); subject = stdin.readLine(); header = new SimpleSMTPHeader(sender, recipient, subject); while (true) { System.out.print("CC <enter one address per line, hit enter to end>: "); System.out.flush(); cc = stdin.readLine(); if (cc == null || cc.length() == 0) { break; } header.addCC(cc.trim()); ccList.add(cc.trim()); } System.out.print("Filename: "); System.out.flush(); filename = stdin.readLine(); try { fileReader = new FileReader(filename); } catch (FileNotFoundException e) { System.err.println("File not found. " + e.getMessage()); } client = new SMTPClient(); client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); client.connect(server); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); System.err.println("SMTP server refused connection."); System.exit(1); } client.login(); client.setSender(sender); client.addRecipient(recipient); for (String recpt : ccList) { client.addRecipient(recpt); } writer = client.sendMessageData(); if (writer != null) { writer.write(header.toString()); Util.copyReader(fileReader, writer); writer.close(); client.completePendingCommand(); } if (fileReader != null) { fileReader.close(); } client.logout(); client.disconnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
From source file:org.apache.commons.net.examples.mail.SMTPMail.java
public static void main(String[] args) { String sender, recipient, subject, fileName, server, cc; List<String> ccList = new ArrayList<String>(); BufferedReader stdin;//from w ww . j a va 2s . c o m FileReader fileReader = null; Writer writer; SimpleSMTPHeader header; SMTPClient client; if (args.length < 1) { System.err.println("Usage: SMTPMail <smtpserver>"); System.exit(1); } server = args[0]; stdin = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("From: "); System.out.flush(); sender = stdin.readLine(); System.out.print("To: "); System.out.flush(); recipient = stdin.readLine(); System.out.print("Subject: "); System.out.flush(); subject = stdin.readLine(); header = new SimpleSMTPHeader(sender, recipient, subject); while (true) { System.out.print("CC <enter one address per line, hit enter to end>: "); System.out.flush(); cc = stdin.readLine(); if (cc == null || cc.length() == 0) { break; } header.addCC(cc.trim()); ccList.add(cc.trim()); } System.out.print("Filename: "); System.out.flush(); fileName = stdin.readLine(); try { fileReader = new FileReader(fileName); } catch (FileNotFoundException e) { System.err.println("File not found. " + e.getMessage()); } client = new SMTPClient(); client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); client.connect(server); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); System.err.println("SMTP server refused connection."); System.exit(1); } client.login(); client.setSender(sender); client.addRecipient(recipient); for (String recpt : ccList) { client.addRecipient(recpt); } writer = client.sendMessageData(); if (writer != null) { writer.write(header.toString()); Util.copyReader(fileReader, writer); writer.close(); client.completePendingCommand(); } if (fileReader != null) { fileReader.close(); } client.logout(); client.disconnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }