Example usage for java.lang Boolean parseBoolean

List of usage examples for java.lang Boolean parseBoolean

Introduction

In this page you can find the example usage for java.lang Boolean parseBoolean.

Prototype

public static boolean parseBoolean(String s) 

Source Link

Document

Parses the string argument as a boolean.

Usage

From source file:ca.uqac.info.Job.Launcher.JobLauncher.java

public static void main(final String[] args) {
    // Parse command line arguments
    Options options = setupOptions();//from   ww w .j ava2s.c  o m
    CommandLine c_line = setupCommandLine(args, options);

    String batFolder = "";
    String outFolderStr = "";

    File folderBat = null;
    File[] listOfFiles = null;
    String files = "";

    String username = "";
    String password = "";
    String recipient = "";
    String message = "";

    boolean emailOpt = false;
    GoogleMail Gmail = null;

    if (c_line.hasOption("e")) {
        emailOpt = Boolean.parseBoolean(c_line.getOptionValue("email"));
    }

    if (emailOpt == true) {
        Gmail = new GoogleMail();
    }

    // boolean nextJob = true;

    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }

    //Contains a bat folder
    if (c_line.hasOption("b")) {
        batFolder = c_line.getOptionValue("BatFolder");
    } else {
        System.err.println("No Bat Folder in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    //Contains a Output folder
    if (c_line.hasOption("o")) {
        outFolderStr = c_line.getOptionValue("OutputFolder");
    } else {
        System.err.println("No Output Folder in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    //Use the email option
    if (emailOpt == true) {
        //Contains the username
        if (c_line.hasOption("username")) {
            username = c_line.getOptionValue("u");
        } else {
            System.err.println("No username in Arguments");
            System.exit(ERR_ARGUMENTS);
        }

        //Contains the password
        if (c_line.hasOption("password")) {
            password = c_line.getOptionValue("p");
        } else {
            System.err.println("No password in Arguments");
            System.exit(ERR_ARGUMENTS);
        }

        //Contains the recipient Email
        if (c_line.hasOption("recipientEmail")) {
            recipient = c_line.getOptionValue("r");
        } else {
            System.err.println("No recipient Email in Arguments");
            System.exit(ERR_ARGUMENTS);
        }
    }

    folderBat = new File(batFolder);
    listOfFiles = folderBat.listFiles();

    File outFolder = new File(outFolderStr);

    //Make sure to test all of the files
    for (int i = 0; i < listOfFiles.length; i++) {

        if (listOfFiles[i].isFile()) {
            files = listOfFiles[i].getName();
            String outName = outFolderStr + "\\Results_" + files + ".txt";
            message = outName;

            //Make sure to use only the bat files
            if (files.endsWith(".bat") || files.endsWith(".Bat")) {
                try {
                    String StartDay = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date());
                    long timeBefore = new Date().getTime();

                    int exitStatus = launchJob(listOfFiles[i].getAbsolutePath(), outName, outFolder);

                    long timeAfter = new Date().getTime();
                    String EndDay = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date());
                    long timeLaunch = timeAfter - timeBefore;

                    if (exitStatus != 0)// An error arrived in the job launch
                    {
                        message += " exitStatus : " + exitStatus;
                        message += " \n Total : " + timeLaunch + " ms";
                        message += " \n Start : " + StartDay;
                        message += "\n End : " + EndDay;

                        //Send the email to tell the launch job status
                        sendEmail(Gmail, emailOpt, username, password, recipient, "Error :" + files, message);
                    } else // Every things is fine 
                    {
                        message += " \n Total : " + timeLaunch + " ms";
                        message += " \n Start : " + StartDay;
                        message += "\n End : " + EndDay;

                        //Send the email to tell the launch job status
                        sendEmail(Gmail, emailOpt, username, password, recipient, files + " Done !!!", message);
                    }
                } catch (Exception e) {
                    //Send a email for the error from the launch of the job
                    sendEmail(Gmail, emailOpt, username, password, recipient, "Error :" + files,
                            "Launch Job and/or SMTP error !!!");

                    e.printStackTrace();
                }
            } // if files .bat
        } // if isFile
    } // For listOfFiles

}

From source file:com.kantenkugel.discordbot.Main.java

public static void main(String[] args) {
    boolean isDbBot = false;
    if (args.length == 2 && Boolean.parseBoolean(args[1])) {
        isDbBot = true;/*w w  w. ja  va  2 s. c  om*/
    } else if (args.length < 4) {
        System.out.println("Missing arguments!");
        return;
    }

    if (!BotConfig.load()) {
        System.out.println("Bot config created/updated. Please populate/check it before restarting the Bot");
        System.exit(Statics.NORMAL_EXIT_CODE);
    }

    if (BotConfig.get("logToFiles", true)) {
        try {
            SimpleLog.addFileLogs(new File("logs/main.txt"), new File("logs/err.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (!isDbBot) {
        Statics.START_TIME = Long.parseLong(args[1]);
        Statics.VERSION = Integer.parseInt(args[3]);
    }

    if (!isDbBot && args.length > 4) {
        Statics.CHANGES = StringUtils.join(args, '\n', 4, args.length);
    } else {
        Statics.CHANGES = null;
    }

    if (isDbBot) {
        if ("".equals(BotConfig.get("historyBase"))) {
            Statics.LOG.fatal("Please specify a history-base in the config");
            System.exit(Statics.NORMAL_EXIT_CODE);
        }
        if (!DbEngine.init()) {
            Statics.LOG.fatal("Could not connect to db! shutting down");
            System.exit(Statics.NORMAL_EXIT_CODE);
        }
    } else {
        DocParser.init();
        Module.init();
    }
    try {
        JDABuilder jdaBuilder = new JDABuilder().setBotToken(args[0]).setAudioEnabled(false);
        if (isDbBot)
            jdaBuilder.addListener(new DbListener());
        else
            jdaBuilder.addListener(new StatusListener()).addListener(new InviteListener())
                    .addListener(new MessageListener());
        if (!isDbBot && !args[2].equals("-")) {
            boolean success = Boolean.parseBoolean(args[2]);
            if (success) {
                checker = UpdateValidator.getInstance();
                checker.start();
            }
            jdaBuilder.addListener(new UpdatePrintListener(success));
        }
        Statics.jdaInstance = jdaBuilder.buildAsync();
        if (!isDbBot)
            CommandRegistry.loadCommands(Statics.jdaInstance);
        new UpdateWatcher(Statics.jdaInstance);
    } catch (LoginException e) {
        Statics.LOG.fatal("Login informations were incorrect!");
        System.err.flush();
    }
}

From source file:com.github.sakserv.Main.java

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

    // Parse the cmdline args and property file
    propertyParser = CmdLineUtils.parseCmdLineAndProps(args, propertyParser);

    // Get a JDBC connection, without the database
    String connectionString = JdbcUtils.getConnectionString(
            propertyParser.getProperty(ConfigVars.JDBC_CONNECTION_STRING_PREFIX_KEY),
            propertyParser.getProperty(ConfigVars.JDBC_HOSTNAME_KEY),
            propertyParser.getProperty(ConfigVars.JDBC_PORT_KEY));
    connection = JdbcUtils.getConnection(connectionString, propertyParser.getProperty(ConfigVars.JDBC_USER_KEY),
            propertyParser.getProperty(ConfigVars.JDBC_PASSWORD_KEY));

    // Create the grants
    if (!Boolean.parseBoolean(propertyParser.getProperty(ConfigVars.JDBC_SKIP_GRANTS_KEY))) {
        JdbcUtils.createGrants(connection);
    }//  w  w w  .j a va 2 s  .co m

    // Create the database, if required
    createDatabase(connection);

    // Get a connection, with the database specified
    connection = getConnection();

    // Create the table
    // TODO: Make table definitions more abstract
    createTable(connection);

    /*        // Populate the table
            populateTable(connection);*/

    // Display success message if we got this far
    logSuccessMessage();

}

From source file:com.redhat.red.koji.build.Main.java

public static void main(String[] args) {
    String noExit = System.getProperty(NO_EXIT);
    boolean exit = noExit == null || !Boolean.parseBoolean(noExit);
    Integer result = null;//from   w w w  .  j  a  v a  2s. c  om

    Options opts = new Options();
    try {
        if (!opts.parseArgs(args)) {
            result = 0;
        }
    } catch (CmdLineException e) {
        e.printStackTrace();
        result = PARSE_ERROR;
    }

    if (result == null) {
        result = new Main(opts).run();
    }

    if (exit) {
        System.exit(result);
    }
}

From source file:cht.Parser.java

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

    // TODO get from google drive
    boolean isUnicode = false;
    boolean isRemoveInputFileOnComplete = false;
    int rowNum;/*from  ww w  .j a  va2 s .  c  o  m*/
    int colNum;
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream("config.txt"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    String inputFilePath = prop.getProperty("inputFile");
    String outputDirectory = prop.getProperty("outputDirectory");
    System.out.println(outputDirectory);
    // optional
    String unicode = prop.getProperty("unicode");
    String removeInputFileOnComplete = prop.getProperty("removeInputFileOnComplete");

    inputFilePath = inputFilePath.trim();
    outputDirectory = outputDirectory.trim();

    if (unicode != null) {
        isUnicode = Boolean.parseBoolean(unicode.trim());
    }
    if (removeInputFileOnComplete != null) {
        isRemoveInputFileOnComplete = Boolean.parseBoolean(removeInputFileOnComplete.trim());
    }

    Writer out = null;
    FileInputStream in = null;
    final String newLine = System.getProperty("line.separator").toString();
    final String separator = File.separator;
    try {
        in = new FileInputStream(inputFilePath);

        Workbook workbook = new XSSFWorkbook(in);

        Sheet sheet = workbook.getSheetAt(0);

        rowNum = sheet.getLastRowNum() + 1;
        colNum = sheet.getRow(0).getPhysicalNumberOfCells();

        for (int j = 1; j < colNum; ++j) {
            String outputFilename = sheet.getRow(0).getCell(j).getStringCellValue();
            // guess directory
            int slash = outputFilename.indexOf('/');
            if (slash != -1) { // has directory
                outputFilename = outputFilename.substring(0, slash) + separator
                        + outputFilename.substring(slash + 1);
            }

            String outputPath = FilenameUtils.concat(outputDirectory, outputFilename);
            System.out.println("--Writing " + outputPath);
            out = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8");
            TreeMap<String, Object> map = new TreeMap<String, Object>();
            for (int i = 1; i < rowNum; i++) {
                try {
                    String key = sheet.getRow(i).getCell(0).getStringCellValue();
                    //String value = "";
                    Cell tmp = sheet.getRow(i).getCell(j);
                    if (tmp != null) {
                        // not empty string!
                        value = sheet.getRow(i).getCell(j).getStringCellValue();
                    }
                    if (!key.equals("") && !key.startsWith("#") && !key.startsWith(".")) {
                        value = isUnicode ? StringEscapeUtils.escapeJava(value) : value;

                        int firstdot = key.indexOf(".");
                        String keyName, keyAttribute;
                        if (firstdot > 0) {// a.b.c.d 
                            keyName = key.substring(0, firstdot); // a
                            keyAttribute = key.substring(firstdot + 1); // b.c.d
                            TreeMap oldhash = null;
                            Object old = null;
                            if (map.get(keyName) != null) {
                                old = map.get(keyName);
                                if (old instanceof TreeMap == false) {
                                    System.out.println("different type of key:" + key);
                                    continue;
                                }
                                oldhash = (TreeMap) old;
                            } else {
                                oldhash = new TreeMap();
                            }

                            int firstdot2 = keyAttribute.indexOf(".");
                            String rootName, childName;
                            if (firstdot2 > 0) {// c, d.f --> d, f
                                rootName = keyAttribute.substring(0, firstdot2);
                                childName = keyAttribute.substring(firstdot2 + 1);
                            } else {// c, d  -> d, null
                                rootName = keyAttribute;
                                childName = null;
                            }

                            TreeMap<String, Object> object = myPut(oldhash, rootName, childName);
                            map.put(keyName, object);

                        } else {// c, d  -> d, null
                            keyName = key;
                            keyAttribute = null;
                            // simple string mode
                            map.put(key, value);
                        }

                    }

                } catch (Exception e) {
                    // just ingore empty rows
                }

            }
            String json = gson.toJson(map);
            // output json
            out.write(json + newLine);
            out.close();
        }
        in.close();

        System.out.println("\n---Complete!---");
        System.out.println("Read input file from " + inputFilePath);
        System.out.println(colNum - 1 + " output files ate generated at " + outputDirectory);
        System.out.println(rowNum + " records are generated for each output file.");
        System.out.println("output file is ecoded as unicode? " + (isUnicode ? "yes" : "no"));
        if (isRemoveInputFileOnComplete) {
            File input = new File(inputFilePath);
            input.deleteOnExit();
            System.out.println("Deleted " + inputFilePath);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            in.close();
        }
    }

}

From source file:com.bluexml.tools.miscellaneous.PrepareSIDEModulesMigration.java

/**
 * @param args/*from   w  w w  .ja  v a 2s.  com*/
 */
public static void main(String[] args) {
    boolean inplace = false;

    String workspace = "/Users/davidabad/workspaces/SIDE-Modules/";
    String frameworkmodulesPath = "/Volumes/Data/SVN/side/HEAD/S-IDE/FrameworksModules/trunk/";
    String classifier_base = "enterprise";
    String version_base = "3.4.6";
    String classifier_target = "enterprise";
    String version_target = "3.4.11";
    String frameworkmodulesInplace = "/Volumes/Data/SVN/projects/Ifremer/IfremerV5/src/modules/mavenProjects";

    Properties props = new Properties();
    try {
        InputStream resourceAsStream = PrepareSIDEModulesMigration.class
                .getResourceAsStream("config.properties");
        if (resourceAsStream != null) {
            props.load(resourceAsStream);

            inplace = Boolean.parseBoolean(props.getProperty("inplace", Boolean.toString(inplace)));
            workspace = props.getProperty("workspace", workspace);
            frameworkmodulesPath = props.getProperty("frameworkmodulesPath", frameworkmodulesPath);
            classifier_base = props.getProperty("classifier_base", classifier_base);
            version_base = props.getProperty("version_base", version_base);
            classifier_target = props.getProperty("classifier_target", classifier_target);
            version_target = props.getProperty("version_target", version_target);
            frameworkmodulesInplace = props.getProperty("frameworkmodulesInplace", frameworkmodulesInplace);
        } else {
            System.out.println("no configuration founded in classpath config.properties");
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }

    System.out.println("properties :");
    Enumeration<?> propertyNames = props.propertyNames();
    while (propertyNames.hasMoreElements()) {
        String nextElement = propertyNames.nextElement().toString();
        System.out.println("\t " + nextElement + " : " + props.getProperty(nextElement));
    }

    File workspaceFile = new File(workspace);

    File targetHome = new File(workspaceFile, MIGRATION_FOLDER);
    if (targetHome.exists()) {
        try {
            FileUtils.deleteDirectory(targetHome);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    final String versionInProjectName = getVersionInProjectName(classifier_base, version_base);
    String versionInProjectName2 = getVersionInProjectName(classifier_target, version_target);

    if (frameworkmodulesPath.contains(",")) {
        // this is a list of paths
        String[] split = frameworkmodulesPath.split(",");
        for (String string : split) {
            if (StringUtils.trimToNull(string) != null) {
                executeInpath(inplace, string, classifier_base, version_base, classifier_target, version_target,
                        frameworkmodulesInplace, workspaceFile, versionInProjectName, versionInProjectName2);
            }
        }
    } else {
        executeInpath(inplace, frameworkmodulesPath, classifier_base, version_base, classifier_target,
                version_target, frameworkmodulesInplace, workspaceFile, versionInProjectName,
                versionInProjectName2);
    }

    System.out.println("Job's done !");
    System.out.println("Please check " + MIGRATION_FOLDER);
    System.out.println(
            "If all is ok you can use commit.sh in a terminal do : cd " + MIGRATION_FOLDER + "; sh commit.sh");
    System.out.println(
            "This script will create new svn projet and commit resources, add 'target' to svn:ignore ...");

}

From source file:com.adobe.aem.demomachine.Checksums.java

public static void main(String[] args) {

    String rootFolder = null;//from   w w w .j  ava 2 s  .com

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Demo Machine root folder");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            rootFolder = cmd.getOptionValue("f");
        }

    } catch (Exception e) {
        System.exit(-1);
    }

    Properties md5properties = new Properties();
    List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths);
    for (String[] path : listPaths) {
        if (path.length == 5) {
            logger.debug(path[1]);
            File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : ""));
            if (pathFolder.exists()) {
                String md5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]), false);
                logger.debug("MD5 is: " + md5);
                md5properties.setProperty("demo.path." + path[0], path[1]);
                md5properties.setProperty("demo.md5." + path[0], md5);
            } else {
                logger.error("Folder cannot be found");
            }
        }
    }

    File md5 = new File(rootFolder + File.separator + "conf" + File.separator + "checksums.properties");
    try {

        @SuppressWarnings("serial")
        Properties tmpProperties = new Properties() {
            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(new TreeSet<Object>(super.keySet()));
            }
        };
        tmpProperties.putAll(md5properties);
        tmpProperties.store(new FileOutputStream(md5), null);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }

    System.out.println("MD5 checkums generated");

}

From source file:com.github.xbn.examples.io.non_xbn.ReadInActiveAccountsFromFile.java

public static final void main(String[] rqdInputPathInStrArray) {
    //Read command-line
    String sSrc = null;//from ww w .j  a  v  a2  s.c  om
    try {
        sSrc = rqdInputPathInStrArray[0];
    } catch (IndexOutOfBoundsException ibx) {
        System.out.println("Missing one-and-only required parameter: The full path to Java source-code file.");
        return;
    }

    //Open input file
    File inputFile = new File(sSrc);
    Iterator<String> lineItr = null;
    try {
        lineItr = FileUtils.lineIterator(inputFile);
    } catch (IOException iox) {
        System.out.println("Cannot open \"" + sSrc + "\". " + iox);
        return;
    }

    while (lineItr.hasNext()) {
        String line = lineItr.next();
        String[] userPassIsActive = line.split(" ");
        String username = userPassIsActive[0];
        String password = userPassIsActive[1];
        boolean isActive = Boolean.parseBoolean(userPassIsActive[2]);

        System.out.println("username=" + username + ", password=" + password + ", isActive=" + isActive + "");
    }
}

From source file:com.alibaba.rocketmq.example.benchmark.Consumer.java

public static void main(String[] args) throws MQClientException {
    Options options = ServerUtil.buildCommandlineOptions(new Options());
    CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkConsumer", args,
            buildCommandlineOptions(options), new PosixParser());
    if (null == commandLine) {
        System.exit(-1);//  w w w.  j a  v  a2s  .  c  o m
    }

    final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest";
    final String groupPrefix = commandLine.hasOption('g') ? commandLine.getOptionValue('g').trim()
            : "benchmark_consumer";
    final String isPrefixEnable = commandLine.hasOption('p') ? commandLine.getOptionValue('p').trim() : "true";
    String group = groupPrefix;
    if (Boolean.parseBoolean(isPrefixEnable)) {
        group = groupPrefix + "_" + Long.toString(System.currentTimeMillis() % 100);
    }

    System.out.printf("topic %s group %s prefix %s%n", topic, group, isPrefixEnable);

    final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmarkConsumer.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long consumeTps = (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageB2CRT = (end[2] - begin[2]) / (double) (end[1] - begin[1]);
                final double averageS2CRT = (end[3] - begin[3]) / (double) (end[1] - begin[1]);

                System.out.printf(
                        "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d%n",
                        consumeTps, averageB2CRT, averageS2CRT, end[4], end[5]);
            }
        }

        @Override
        public void run() {
            try {
                this.printStats();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group);
    consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

    consumer.subscribe(topic, "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            MessageExt msg = msgs.get(0);
            long now = System.currentTimeMillis();

            statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet();

            long born2ConsumerRT = now - msg.getBornTimestamp();
            statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT);

            long store2ConsumerRT = now - msg.getStoreTimestamp();
            statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT);

            compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT);

            compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT);

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.printf("Consumer Started.%n");
}

From source file:com.xiangzhurui.util.email.POP3Mail.java

public static void main(String[] args) {
    if (args.length < 3) {
        System.err/*from www  .  j  a  va2  s .c o m*/
                .println("Usage: POP3Mail <pop3 server hostname> <username> <password> [TLS [true=implicit]]");
        System.exit(1);
    }

    String server = args[0];
    String username = args[1];
    String password = args[2];

    String proto = args.length > 3 ? args[3] : null;
    boolean implicit = args.length > 4 && Boolean.parseBoolean(args[4]);

    POP3Client pop3;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        pop3 = new POP3SClient(proto, implicit);
    } else {
        pop3 = new POP3Client();
    }
    System.out.println("Connecting to server " + server + " on " + pop3.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    // suppress login details
    pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        pop3.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        if (!pop3.login(username, password)) {
            System.err.println("Could not login to server.  Check password.");
            pop3.disconnect();
            System.exit(1);
        }

        POP3MessageInfo[] messages = pop3.listMessages();

        if (messages == null) {
            System.err.println("Could not retrieve message list.");
            pop3.disconnect();
            return;
        } else if (messages.length == 0) {
            System.out.println("No messages");
            pop3.logout();
            pop3.disconnect();
            return;
        }

        for (POP3MessageInfo msginfo : messages) {
            BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0);

            if (reader == null) {
                System.err.println("Could not retrieve message header.");
                pop3.disconnect();
                System.exit(1);
            }
            printMessageInfo(reader, msginfo.number);
        }

        pop3.logout();
        pop3.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}