Example usage for java.util Properties put

List of usage examples for java.util Properties put

Introduction

In this page you can find the example usage for java.util Properties put.

Prototype

@Override
    public synchronized Object put(Object key, Object value) 

Source Link

Usage

From source file:se.vgregion.incidentreport.pivotaltracker.impl.PivotalTrackerServiceImpl.java

public static void main(String[] args) {
    Properties p = new Properties();
    p.put(TYCK_TILL_PT_USER_KEY, "TyckTill");
    p.put(TYCKTILL_PT_PWD_KEY, "tycktill3333");

    PivotalTrackerServiceImpl ptc = new PivotalTrackerServiceImpl(p);
    String token = ptc.getUserToken("TyckTill", "tycktill3333");
    String projId = "35420";
    // ptc.getStoriesForProject(projId, token);

    PTStory story = new PTStory();
    story.setDescription("Testar attachments");
    story.setName("AttachTest");
    story.setRequestedBy("TyckTill");
    story.setType("bug");

    List<Attachment> attachments = new ArrayList<Attachment>();
    Attachment att1 = new Attachment();
    att1.setFilename("Fil3.gif");
    // att1.setData(new FileInputStream(
    // new File("C:\\Documents and Settings\\carlssonul\\My Documents\\fil3.gif")));

    story.setAttachments(attachments);/*from  w  w w  .  j a v a 2s .  c  o  m*/

    // String url = ptc.addStoryForProject(projId, story);
    // System.out.println("URL:*" + url);
    // int sidIndex = url.lastIndexOf("/");
    // String storyId = url.substring(sidIndex + 1);
    story.setStoryId("2282828");
    // System.out.println("storyID=" + story.getStoryId());
    ptc.addAttachmentToStory(projId, story);

}

From source file:WebCrawler.java

public static void main(String argv[]) {
    Frame f = new Frame("WebFrame");
    WebCrawler applet = new WebCrawler();
    f.add("Center", applet);

    /*    Behind a firewall set your proxy and port here!
    *///from   w  w  w  . java  2  s .  c  o  m
    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);
    /**/

    applet.init();
    applet.start();
    f.pack();
    f.show();
}

From source file:transport.java

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

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

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

From source file:transport.java

public static void main(String[] args) {
    Properties props = System.getProperties();
    // parse the arguments
    InternetAddress[] addrs = null;/*from   www  .  ja  v a2s .  com*/
    InternetAddress from;
    boolean debug = false;
    if (args.length != 4) {
        usage();
        return;
    } else {
        props.put("mail.smtp.host", args[2]);
        if (args[3].equals("true")) {
            debug = true;
        } else if (args[3].equals("false")) {
            debug = false;
        } else {
            usage();
            return;
        }

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

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

From source file:org.objectrepository.MessageConsumerDaemon.java

/**
 * main/*from  w ww  .jav  a  2  s.com*/
 * <p/>
 * Accepts one folder as argument:  -messageQueues
 * That folder ought to contain one or more folders ( or symbolic links ) to the files
 * The folder has the format: [foldername] or [foldername].[maxTasks]
 * MaxTasks is to indicate the total number of jobs being able to run.
 *
 * long
 *
 * @param argv
 */
public static void main(String[] argv) {

    if (instance == null) {
        final Properties properties = new Properties();

        if (argv.length > 0) {
            for (int i = 0; i < argv.length; i += 2) {
                try {
                    properties.put(argv[i], argv[i + 1]);
                } catch (ArrayIndexOutOfBoundsException arr) {
                    System.out.println("Missing value after parameter " + argv[i]);
                    System.exit(-1);
                }
            }
        } else {
            log.fatal("Usage: pmq-agent.jar -messageQueues [queues] -heartbeatInterval [interval in ms]\n"
                    + "The queues is a folder that contains symbolic links to the startup scripts.");
            System.exit(-1);
        }

        if (log.isInfoEnabled()) {
            log.info("Arguments set: ");
            for (String key : properties.stringPropertyNames()) {
                log.info("'" + key + "'='" + properties.getProperty(key) + "'");
            }
        }

        if (!properties.containsKey("-messageQueues")) {
            log.fatal("Expected case sensitive parameter: -messageQueues");
            System.exit(-1);
        }

        final File messageQueues = new File((String) properties.get("-messageQueues"));
        if (!messageQueues.exists()) {
            log.fatal("Cannot find folder for messageQueues: " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        if (messageQueues.isFile()) {
            log.fatal(
                    "-messageQueues should point to a folder, not a file: " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        long heartbeatInterval = 600000;
        if (properties.containsKey("-heartbeatInterval")) {
            heartbeatInterval = Long.parseLong((String) properties.get("heartbeatInterval"));
        }

        String identifier = null;
        if (properties.containsKey("-id")) {
            identifier = (String) properties.get("-id");
        } else if (properties.containsKey("-identifier")) {
            identifier = (String) properties.get("-identifier");
        }

        final File[] files = messageQueues.listFiles();
        final String[] scriptNames = (properties.containsKey("-startup"))
                ? new String[] { properties.getProperty("-startup") }
                : new String[] { "/startup.sh", "\\startup.bat" };
        final List<Queue> queues = new ArrayList<Queue>();
        for (File file : files) {
            final String name = file.getName();
            final String[] split = name.split("\\.", 2);
            final String queueName = split[0];
            for (String scriptName : scriptNames) {
                final String shellScript = file.getAbsolutePath() + scriptName;
                final int maxTask = (split.length == 1) ? 1 : Integer.parseInt(split[1]);
                log.info("Candidate mq client for " + queueName + " maxTasks " + maxTask);
                if (new File(shellScript).exists()) {
                    final Queue queue = new Queue(queueName, shellScript, false);
                    queue.setCorePoolSize(1);
                    queue.setMaxPoolSize(maxTask);
                    queue.setQueueCapacity(1);
                    queues.add(queue);
                    break;
                } else {
                    log.warn("... skipping, because no startup script found at " + shellScript);
                }
            }
        }

        if (queues.size() == 0) {
            log.fatal("No queue folders seen in " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        // Add the system queue
        queues.add(new Queue("Connection", null, true));

        getInstance(queues, identifier, heartbeatInterval).run();
    }
    System.exit(0);
}

From source file:com.google.oacurl.Login.java

public static void main(String[] args) throws Exception {
    LoginOptions options = new LoginOptions();
    try {/*from  w  w w  . j  a v a 2  s.co  m*/
        options.parse(args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    }

    if (options.isHelp()) {
        new HelpFormatter().printHelp(" ", options.getOptions());
        System.exit(0);
    }

    if (options.isInsecure()) {
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
    }

    LoggingConfig.init(options.isVerbose());
    if (options.isWirelogVerbose()) {
        LoggingConfig.enableWireLog();
    }

    ServiceProviderDao serviceProviderDao = new ServiceProviderDao();
    ConsumerDao consumerDao = new ConsumerDao(options);
    AccessorDao accessorDao = new AccessorDao();

    String serviceProviderFileName = options.getServiceProviderFileName();
    if (serviceProviderFileName == null) {
        if (options.isBuzz()) {
            // Buzz has its own provider because it has a custom authorization URL
            serviceProviderFileName = "BUZZ";
        } else if (options.getVersion() == OAuthVersion.V2) {
            serviceProviderFileName = "GOOGLE_V2";
        } else {
            serviceProviderFileName = "GOOGLE";
        }
    }

    // We have a wee library of service provider properties files bundled into
    // the resources, so we set up the PropertiesProvider to search for them
    // if the file cannot be found.
    OAuthServiceProvider serviceProvider = serviceProviderDao.loadServiceProvider(
            new PropertiesProvider(serviceProviderFileName, ServiceProviderDao.class, "services/").get());
    OAuthConsumer consumer = consumerDao
            .loadConsumer(new PropertiesProvider(options.getConsumerFileName()).get(), serviceProvider);
    OAuthAccessor accessor = accessorDao.newAccessor(consumer);

    OAuthClient client = new OAuthClient(new HttpClient4());

    LoginCallbackServer callbackServer = null;

    boolean launchedBrowser = false;

    try {
        if (!options.isNoServer()) {
            callbackServer = new LoginCallbackServer(options);
            callbackServer.start();
        }

        String callbackUrl;
        if (options.getCallback() != null) {
            callbackUrl = options.getCallback();
        } else if (callbackServer != null) {
            callbackUrl = callbackServer.getCallbackUrl();
        } else {
            callbackUrl = null;
        }

        OAuthEngine engine;
        switch (options.getVersion()) {
        case V1:
            engine = new V1OAuthEngine();
            break;
        case V2:
            engine = new V2OAuthEngine();
            break;
        case WRAP:
            engine = new WrapOAuthEngine();
            break;
        default:
            throw new IllegalArgumentException("Unknown version: " + options.getVersion());
        }

        do {
            String authorizationUrl = engine.getAuthorizationUrl(client, accessor, options, callbackUrl);

            if (!options.isNoServer()) {
                callbackServer.setAuthorizationUrl(authorizationUrl);
            }

            if (!launchedBrowser) {
                String url = options.isDemo() ? callbackServer.getDemoUrl() : authorizationUrl;

                if (options.isNoBrowser()) {
                    System.out.println(url);
                    System.out.flush();
                } else {
                    launchBrowser(options, url);
                }

                launchedBrowser = true;
            }

            accessor.accessToken = null;

            logger.log(Level.INFO, "Waiting for verification token...");
            String verifier;
            if (options.isNoServer()) {
                System.out.print("Verification token: ");
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                verifier = "";
                while (verifier.isEmpty()) {
                    String line = reader.readLine();
                    if (line == null) {
                        System.exit(-1);
                    }
                    verifier = line.trim();
                }
            } else {
                verifier = callbackServer.waitForVerifier(accessor, -1);
                if (verifier == null) {
                    System.err.println("Wait for verifier interrupted");
                    System.exit(-1);
                }
            }
            logger.log(Level.INFO, "Verification token received: " + verifier);

            boolean success = engine.getAccessToken(accessor, client, callbackUrl, verifier);

            if (success) {
                if (callbackServer != null) {
                    callbackServer.setTokenStatus(TokenStatus.VALID);
                }

                Properties loginProperties = new Properties();
                accessorDao.saveAccessor(accessor, loginProperties);
                consumerDao.saveConsumer(consumer, loginProperties);
                loginProperties.put("oauthVersion", options.getVersion().toString());
                new PropertiesProvider(options.getLoginFileName()).overwrite(loginProperties);
            } else {
                if (callbackServer != null) {
                    callbackServer.setTokenStatus(TokenStatus.INVALID);
                }
            }
        } while (options.isDemo());
    } catch (OAuthProblemException e) {
        OAuthUtil.printOAuthProblemException(e);
    } finally {
        if (callbackServer != null) {
            callbackServer.stop();
        }
    }
}

From source file:msgsend.java

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from ww w.j  a  v  a 2 s .c  o m
    String mailer = "msgsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-a attach-file] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        /*
         * Construct the message and send it.
         */
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        /*
         * Save a copy of the message, if requested.
         */
        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                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, user, password);
                else
                    store.connect();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:smtpsend.java

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from w  w w.  j a  va 2  s. com
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    boolean ssl = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            ssl = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);
        if (auth)
            props.put("mail.smtp.auth", "true");

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        /*
         * The simple way to send a message is this:
         * 
         * Transport.send(msg);
         * 
         * But we're going to use some SMTP-specific features for demonstration
         * purposes so we need to manage the Transport object explicitly.
         */
        SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        try {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
            t.close();
        }

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                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, user, password);
                else
                    store.connect();
            }

            // Get record Folder. Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}

From source file:eu.ensure.aging.AgingSimulator.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("n", "flip-bit-in-name", true, "Flip bit in first byte of name of first file");
    options.addOption("u", "flip-bit-in-uname", true, "Flip bit in first byte of username of first file");
    options.addOption("c", "update-checksum", true, "Update header checksum (after prior bit flips)");

    Properties properties = new Properties();
    CommandLineParser parser = new PosixParser();
    try {/*from  ww  w.  j av a 2 s .c  o  m*/
        CommandLine line = parser.parse(options, args);

        //
        if (line.hasOption("flip-bit-in-name")) {
            properties.put("flip-bit-in-name", line.getOptionValue("flip-bit-in-name"));
        } else {
            // On by default (if not explicitly de-activated above)
            properties.put("flip-bit-in-name", "true");
        }

        //
        if (line.hasOption("flip-bit-in-uname")) {
            properties.put("flip-bit-in-uname", line.getOptionValue("flip-bit-in-uname"));
        } else {
            properties.put("flip-bit-in-uname", "false");
        }

        //
        if (line.hasOption("update-checksum")) {
            properties.put("update-checksum", line.getOptionValue("update-checksum"));
        } else {
            properties.put("update-checksum", "false");
        }

        String[] fileArgs = line.getArgs();

        if (fileArgs.length < 1) {
            printHelp(options, System.err);
            System.exit(1);
        }

        String srcPath = fileArgs[0];

        File srcAIP = new File(srcPath);
        if (!srcAIP.exists()) {
            String info = "The source path does not locate a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (srcAIP.isDirectory()) {
            String info = "The source path locates a directory, not a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (!srcAIP.canRead()) {
            String info = "Cannot read source file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        boolean doReplace = false;
        File destAIP = null;

        if (fileArgs.length > 1) {
            String destPath = fileArgs[1];
            destAIP = new File(destPath);

            if (destAIP.exists()) {
                String info = "The destination path locates an existing file: " + destPath;
                System.err.println(info);
                System.exit(1);
            }
        } else {
            doReplace = true;
            try {
                destAIP = File.createTempFile("tmp-aged-aip-", ".tar");
            } catch (IOException ioe) {
                String info = "Failed to create temporary file: ";
                info += ioe.getMessage();
                System.err.println(info);
                System.exit(1);
            }
        }

        String info = "Age simulation\n";
        info += "  Reading from " + srcAIP.getName() + "\n";
        if (doReplace) {
            info += "  and replacing it's content";
        } else {
            info += "  Writing to " + destAIP.getName();
        }
        System.out.println(info);

        //
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new BufferedInputStream(new FileInputStream(srcAIP));
            os = new BufferedOutputStream(new FileOutputStream(destAIP));

            simulateAging(srcAIP.getName(), is, os, properties);

        } catch (FileNotFoundException fnfe) {
            info = "Could not locate file: " + fnfe.getMessage();
            System.err.println(info);
        } finally {
            try {
                if (null != os)
                    os.close();
                if (null != is)
                    is.close();
            } catch (IOException ignore) {
            }
        }

        //
        if (doReplace) {
            File renamedOriginal = new File(srcAIP.getName() + "-backup");
            srcAIP.renameTo(renamedOriginal);

            ReadableByteChannel rbc = null;
            WritableByteChannel wbc = null;
            try {
                rbc = Channels.newChannel(new FileInputStream(destAIP));
                wbc = Channels.newChannel(new FileOutputStream(srcAIP));
                FileIO.fastChannelCopy(rbc, wbc);
            } catch (FileNotFoundException fnfe) {
                info = "Could not locate temporary output file: " + fnfe.getMessage();
                System.err.println(info);
            } catch (IOException ioe) {
                info = "Could not copy temporary output file over original AIP: " + ioe.getMessage();
                System.err.println(info);
            } finally {
                try {
                    if (null != wbc)
                        wbc.close();
                    if (null != rbc)
                        rbc.close();

                    destAIP.delete();
                } catch (IOException ignore) {
                }
            }
        }
    } catch (ParseException pe) {
        String info = "Failed to parse command line: " + pe.getMessage();
        System.err.println(info);
        printHelp(options, System.err);
        System.exit(1);
    }
}

From source file:smtpsend.java

/**
 * Example of how to extend the SMTPTransport class.
 * This example illustrates how to issue the XACT
 * command before the SMTPTransport issues the DATA
 * command./* w w  w . j av a 2 s. com*/
 *
public static class SMTPExtension extends SMTPTransport {
public SMTPExtension(Session session, URLName url) {
   super(session, url);
   // to check that we're being used
   System.out.println("SMTPExtension: constructed");
}
        
protected synchronized OutputStream data() throws MessagingException {
   if (supportsExtension("XACCOUNTING"))
  issueCommand("XACT", 250);
   return super.data();
}
}
 */

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    String prot = "smtp";
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            prot = "smtps";
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail." + prot + ".host", mailhost);
        if (auth)
            props.put("mail." + prot + ".auth", "true");

        /*
         * Create a Provider representing our extended SMTP transport
         * and set the property to use our provider.
         *
        Provider p = new Provider(Provider.Type.TRANSPORT, prot,
        "smtpsend$SMTPExtension", "JavaMail demo", "no version");
        props.put("mail." + prot + ".class", "smtpsend$SMTPExtension");
         */

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        /*
         * Register our extended SMTP transport.
         *
        session.addProvider(p);
         */

        /*
         * Construct the message and send it.
         */
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        /*
         * The simple way to send a message is this:
         *
        Transport.send(msg);
         *
         * But we're going to use some SMTP-specific features for
         * demonstration purposes so we need to manage the Transport
         * object explicitly.
         */
        SMTPTransport t = (SMTPTransport) session.getTransport(prot);
        try {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
            t.close();
        }

        System.out.println("\nMail was sent successfully.");

        /*
         * Save a copy of the message, if requested.
         */
        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                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, user, password);
                else
                    store.connect();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        /*
         * Handle SMTP-specific exceptions.
         */
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}