Example usage for java.lang Exception getMessage

List of usage examples for java.lang Exception getMessage

Introduction

In this page you can find the example usage for java.lang Exception getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:isi.pasco2.Main.java

public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    Option undelete = new Option("d", "Undelete activity records");
    options.addOption(undelete);//w  w  w .j a va2 s  . c  o  m
    Option disableAllocation = new Option("M", "Disable allocation detection");
    options.addOption(disableAllocation);
    Option fieldDelimeter = OptionBuilder.withArgName("field-delimeter").hasArg()
            .withDescription("Field Delimeter (TAB by default)").create("t");
    options.addOption(fieldDelimeter);

    Option timeFormat = OptionBuilder.withArgName("time-format").hasArg()
            .withDescription("xsd or standard (pasco1 compatible)").create("f");
    options.addOption(timeFormat);

    Option fileTypeOption = OptionBuilder.withArgName("file-type").hasArg()
            .withDescription("The type of file: cache or history").create("T");

    options.addOption(fileTypeOption);

    try {
        CommandLine line = parser.parse(options, args);
        boolean undeleteMethod = false;
        String delimeter = null;
        String format = null;
        String fileType = null;
        boolean disableAllocationTest = false;

        if (line.hasOption("d")) {
            undeleteMethod = true;
        }

        if (line.hasOption('t')) {
            delimeter = line.getOptionValue('t');
        }

        if (line.hasOption('M')) {
            disableAllocationTest = true;
        }

        if (line.hasOption('T')) {
            fileType = line.getOptionValue('T');
        }

        if (line.hasOption('f')) {
            format = line.getOptionValue('f');
        }

        if (line.getArgs().length != 1) {
            System.err.println("No file specified.");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("pasco2", options);
            System.exit(1);
        }
        String fileName = line.getArgs()[0];

        try {
            IndexFile fr = new FastReadIndexFile(fileName, "r");

            CountingCacheHandler handler = null;

            if (fileType == null) {
                handler = new CountingCacheHandler();
            }
            if (fileType == null) {
                handler = new CountingCacheHandler();
            } else if (fileType.equals("cache")) {
                handler = new CountingCacheHandler();
            } else if (fileType.equals("history")) {
                handler = new Pasco2HistoryHandler();
            }

            if (format != null) {
                if (format.equals("pasco")) {
                    DateFormat regularDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS");
                    handler.setDateFormat(regularDateFormat);
                    TimeZone tz = TimeZone.getTimeZone("Australia/Brisbane");
                    regularDateFormat.setTimeZone(tz);

                } else if (format.equals("standard")) {
                    DateFormat xsdDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                    handler.setDateFormat(xsdDateFormat);
                    xsdDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                } else {
                    System.err.println("Format not supported.");
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("pasco2", options);
                    System.exit(1);
                }
            }

            if (delimeter != null) {
                handler.setDelimeter(delimeter);
            }

            IEIndexFileParser logparser = null;
            if (fileType == null) {
                System.err.println("Using cache file parser.");
                logparser = new IECacheFileParser(fileName, fr, handler);
            } else if (fileType.equals("cache")) {
                logparser = new IECacheFileParser(fileName, fr, handler);
            } else if (fileType.equals("history")) {
                logparser = new IEHistoryFileParser(fileName, fr, handler);
            } else {
                System.err.println("Unsupported file type.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("pasco2", options);
                System.exit(1);
            }
            if (disableAllocationTest) {
                logparser.setDisableAllocationTest(true);
            }
            logparser.parseFile();

        } catch (Exception ex) {
            System.err.println(ex.getMessage());
            ex.printStackTrace();
        }

    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
    }
}

From source file:edu.msu.cme.rdp.readseq.utils.RmDupSeqs.java

public static void main(String[] args) throws Exception {
    String inFile;//from w w  w  . ja  v a  2 s  .c  o  m
    String outFile;
    int length = 0;
    boolean debug = false;
    boolean removeDuplicates = false;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("duplicates")) {
            removeDuplicates = true;
        }
        if (line.hasOption("min_seq_length")) {
            length = Integer.parseInt(line.getOptionValue("min_seq_length"));
        }
        if (line.hasOption("infile")) {
            inFile = line.getOptionValue("infile");
        } else {
            throw new Exception("infile is required");
        }
        if (line.hasOption("outfile")) {
            outFile = line.getOptionValue("outfile");
        } else {
            throw new Exception("outfile is required");
        }
        if (line.hasOption("debug")) {
            debug = true;
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp(120, "RmRedundantSeqs [options]", "", options, "");
        System.err.println("ERROR: " + e.getMessage());
        return;
    }
    if (!removeDuplicates) {
        filterByLength(inFile, outFile, length);
    } else {
        filterDuplicates(inFile, outFile, length, debug);
    }

}

From source file:MainClass.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);

    PrintDialog dialog = new PrintDialog(shell);
    PrinterData printerData = dialog.open();
    if (printerData != null) {
        // Create the printer
        Printer printer = new Printer(printerData);

        try {//from w w  w. ja v a 2 s.  com
            // Print the contents of the file
            new WrappingPrinter(printer).print();
        } catch (Exception e) {
            MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
            mb.setMessage(e.getMessage());
            mb.open();
        }

        // Dispose the printer
        printer.dispose();
    }

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

From source file:edu.harvard.med.screensaver.io.libraries.LibraryCreator.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    CommandLineApplication app = new CommandLineApplication(args);
    try {/*from  ww  w  .  j a v a 2  s  .com*/
        DateTimeFormatter dateFormat = DateTimeFormat.forPattern(CommandLineApplication.DEFAULT_DATE_PATTERN);

        app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("library name")
                .withLongOpt("name").withDescription("full, official name for the library").create("n"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().isRequired().withArgName("short name").withLongOpt("short-name")
                        .withDescription("a short name for identifying the library").create("s"));
        app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("library type")
                .withLongOpt("library-type").withDescription(StringUtils.makeListString(Lists.transform(
                        Lists.newArrayList(LibraryType.values()), new Function<LibraryType, String>() {
                            @Override
                            public String apply(LibraryType arg0) {
                                return arg0.name();
                            }
                        }), ", "))
                .create("lt"));
        app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("screen type")
                .withLongOpt("screen-type").withDescription(StringUtils.makeListString(Lists
                        .transform(Lists.newArrayList(ScreenType.values()), new Function<ScreenType, String>() {
                            @Override
                            public String apply(ScreenType arg0) {
                                return arg0.name();
                            }
                        }), ", "))
                .create("st"));
        app.addCommandLineOption(OptionBuilder.hasArg(false).withLongOpt("is-pool")
                .withDescription("well contents are pools of reagents (only valid when library-type=RNAI)")
                .create("ip"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().isRequired().withArgName("#").withLongOpt("start-plate").create("sp"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().isRequired().withArgName("#").withLongOpt("end-plate").create("ep"));

        app.addCommandLineOption(
                OptionBuilder.hasArg().withArgName("name").withLongOpt("provider").create("lp"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().withArgName("text").withLongOpt("description").create("d"));
        app.addCommandLineOption(OptionBuilder.hasArg().withArgName(CommandLineApplication.DEFAULT_DATE_PATTERN)
                .withLongOpt("date-received").create("dr"));
        app.addCommandLineOption(OptionBuilder.hasArg().withArgName(CommandLineApplication.DEFAULT_DATE_PATTERN)
                .withLongOpt("date-screenable").create("ds"));
        app.addCommandLineOption(OptionBuilder.hasArg().withArgName("plate size")
                .withDescription(StringUtils.makeListString(Lists
                        .transform(Lists.newArrayList(PlateSize.values()), new Function<PlateSize, String>() {
                            @Override
                            public String apply(PlateSize arg0) {
                                return arg0.name();
                            }
                        }), ", "))
                .withLongOpt("plate-size").create("ps"));

        app.processOptions(true, true);

        String libraryName = app.getCommandLineOptionValue("n");
        String shortName = app.getCommandLineOptionValue("s");
        LibraryType libraryType = app.getCommandLineOptionEnumValue("lt", LibraryType.class);
        boolean isPool = app.isCommandLineFlagSet("ip");
        ScreenType screenType = app.getCommandLineOptionEnumValue("st", ScreenType.class);
        int startPlate = app.getCommandLineOptionValue("sp", Integer.class);
        int endPlate = app.getCommandLineOptionValue("ep", Integer.class);
        String vendor = app.isCommandLineFlagSet("lp") ? app.getCommandLineOptionValue("lp") : null;
        String description = app.isCommandLineFlagSet("d") ? app.getCommandLineOptionValue("d") : null;
        LocalDate dateReceived = app.isCommandLineFlagSet("dr")
                ? app.getCommandLineOptionValue("dr", dateFormat).toLocalDate()
                : null;
        LocalDate dateScreenable = app.isCommandLineFlagSet("ds")
                ? app.getCommandLineOptionValue("ds", dateFormat).toLocalDate()
                : null;
        PlateSize plateSize = app.isCommandLineFlagSet("ps")
                ? app.getCommandLineOptionEnumValue("ps", PlateSize.class)
                : ScreensaverConstants.DEFAULT_PLATE_SIZE;

        Library library = new Library(app.findAdministratorUser(), libraryName, shortName, screenType,
                libraryType, startPlate, endPlate, plateSize);
        library.setPool(isPool);
        library.setDescription(description);
        library.setProvider(vendor);
        library.setDateReceived(dateReceived);
        library.setDateScreenable(dateScreenable);

        edu.harvard.med.screensaver.service.libraries.LibraryCreator libraryCreator = (edu.harvard.med.screensaver.service.libraries.LibraryCreator) app
                .getSpringBean("libraryCreator");
        libraryCreator.createLibrary(library);
        log.info("library succesfully added to database");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e.toString());
        System.err.println("error: " + e.getMessage());
        System.exit(1);
    }
}

From source file:org.eclipse.lyo.client.oslc.samples.DMFormSample.java

/**
 * Login to the DM server and perform some OSLC actions
 * @param args//ww w . j  a  v  a2s . co m
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {

    Options options = new Options();

    options.addOption("url", true, "url");
    options.addOption("user", true, "user ID");
    options.addOption("password", true, "password");
    options.addOption("project", true, "project area");

    CommandLineParser cliParser = new GnuParser();

    //Parse the command line
    CommandLine cmd = cliParser.parse(options, args);

    if (!validateOptions(cmd)) {
        logger.severe(
                "Syntax:  java <class_name> -url https://<server>:port/<context>/ -user <user> -password <password> -project \"<project_area>\"");
        logger.severe(
                "Example: java DMFormSample -url https://exmple.com:9443/dm -user ADMIN -password ADMIN -project \"JKE Banking (Design Management)\"");
        return;
    }

    String webContextUrl = cmd.getOptionValue("url");
    String user = cmd.getOptionValue("user");
    String passwd = cmd.getOptionValue("password");
    String projectArea = cmd.getOptionValue("project");

    try {

        //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the ArchitectureManagement catalog
        JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl, OSLCConstants.OSLC_AM_V2);

        //STEP 2: Create a new Form Auth client with the supplied user/password
        //RRC is a fronting server, so need to use the initForm() signature which allows passing of an authentication URL.
        //For RRC, use the JTS for the authorization URL

        //Set the URL to access to authorize the user.  For DM, this is the JTS context.
        //This is a bit of a hack for readability.  It is assuming DM is at context /dm.  Could use a regex or UriBuilder instead.
        String authUrl = webContextUrl.replaceFirst("/dm", "/jts");
        JazzFormAuthClient client = helper.initFormClient(user, passwd, authUrl);

        //STEP 3: Login in to Jazz Server
        if (client.formLogin() == HttpStatus.SC_OK) {

            //STEP 4: Get the URL of the OSLC ChangeManagement catalog
            String catalogUrl = helper.getCatalogUrl();
            //WORKAROUND:  The IBM Rational Design Manager app requires an initial GET of a protected resource using */* as the Accept type
            client.getResource(catalogUrl, "*/*").consumeContent();

            //STEP 5: Find the OSLC Service Provider for the project area we want to work with
            String serviceProviderUrl = client.lookupServiceProviderUrl(catalogUrl, projectArea);

            //STEP 6: Get the Query Capabilities URL so that we can run some OSLC queries
            //WORKAROUND:  DM defect 39535 prevents OSLC4J from reading the DM Service Provider resource correctly
            //As a workaround, for now, you can hardcode the queryCapability URL.

            String queryCapability = client.lookupQueryCapability(serviceProviderUrl, OSLCConstants.OSLC_AM_V2,
                    OSLCConstants.AM_RESOURCE_TYPE);

            //SCENARIO A: Run a query for all AM Resources with OSLC paging of 10 items per
            //page turned on and list the members of the result

            OslcQueryParameters queryParams = new OslcQueryParameters();

            OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams);

            OslcQueryResult result = query.submit();

            boolean processAsJavaObjects = true;
            processPagedQueryResults(result, client, processAsJavaObjects);

            System.out.println("\n------------------------------\n");

            //TODO:  Add more DM scenarios
        }
    } catch (RootServicesException re) {
        logger.log(Level.SEVERE,
                "Unable to access the Jazz rootservices document at: " + webContextUrl + "/rootservices", re);
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:io.druid.server.sql.SQLRunner.java

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

    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", false, "verbose");
    options.addOption("e", "host", true, "endpoint [hostname:port]");

    CommandLine cmd = new GnuParser().parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SQLRunner", options);
        System.exit(2);// w w w  .j  a  va 2s  .c  o m
    }

    String hostname = cmd.getOptionValue("e", "localhost:8080");
    String sql = cmd.getArgs().length > 0 ? cmd.getArgs()[0] : STATEMENT;

    ObjectMapper objectMapper = new DefaultObjectMapper();
    ObjectWriter jsonWriter = objectMapper.writerWithDefaultPrettyPrinter();

    CharStream stream = new ANTLRInputStream(sql);
    DruidSQLLexer lexer = new DruidSQLLexer(stream);
    TokenStream tokenStream = new CommonTokenStream(lexer);
    DruidSQLParser parser = new DruidSQLParser(tokenStream);
    lexer.removeErrorListeners();
    parser.removeErrorListeners();

    lexer.addErrorListener(ConsoleErrorListener.INSTANCE);
    parser.addErrorListener(ConsoleErrorListener.INSTANCE);

    try {
        DruidSQLParser.QueryContext queryContext = parser.query();
        if (parser.getNumberOfSyntaxErrors() > 0)
            throw new IllegalStateException();
        //      parser.setBuildParseTree(true);
        //      System.err.println(q.toStringTree(parser));
    } catch (Exception e) {
        String msg = e.getMessage();
        if (msg != null)
            System.err.println(e);
        System.exit(1);
    }

    final Query query;
    final TypeReference typeRef;
    boolean groupBy = false;
    if (parser.groupByDimensions.isEmpty()) {
        query = Druids.newTimeseriesQueryBuilder().dataSource(parser.getDataSource())
                .aggregators(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .postAggregators(parser.postAggregators).intervals(parser.intervals)
                .granularity(parser.granularity).filters(parser.filter).build();

        typeRef = new TypeReference<List<Result<TimeseriesResultValue>>>() {
        };
    } else {
        query = GroupByQuery.builder().setDataSource(parser.getDataSource())
                .setAggregatorSpecs(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .setPostAggregatorSpecs(parser.postAggregators).setInterval(parser.intervals)
                .setGranularity(parser.granularity).setDimFilter(parser.filter)
                .setDimensions(new ArrayList<DimensionSpec>(parser.groupByDimensions.values())).build();

        typeRef = new TypeReference<List<Row>>() {
        };
        groupBy = true;
    }

    String queryStr = jsonWriter.writeValueAsString(query);
    if (cmd.hasOption("v"))
        System.err.println(queryStr);

    URL url = new URL(String.format("http://%s/druid/v2/?pretty", hostname));
    final URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("content-type", MediaType.APPLICATION_JSON);
    urlConnection.getOutputStream().write(StringUtils.toUtf8(queryStr));
    BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(urlConnection.getInputStream(), Charsets.UTF_8));

    Object res = objectMapper.readValue(stdInput, typeRef);

    Joiner tabJoiner = Joiner.on("\t");

    if (groupBy) {
        List<Row> rows = (List<Row>) res;
        Iterable<String> dimensions = Iterables.transform(parser.groupByDimensions.values(),
                new Function<DimensionSpec, String>() {
                    @Override
                    public String apply(@Nullable DimensionSpec input) {
                        return input.getOutputName();
                    }
                });

        System.out.println(
                tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), dimensions, parser.fields)));
        for (final Row r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(
                    Lists.newArrayList(parser.granularity.toDateTime(r.getTimestampFromEpoch())),
                    Iterables.transform(parser.groupByDimensions.values(),
                            new Function<DimensionSpec, String>() {
                                @Override
                                public String apply(@Nullable DimensionSpec input) {
                                    return Joiner.on(",").join(r.getDimension(input.getOutputName()));
                                }
                            }),
                    Iterables.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getFloatMetric(input);
                        }
                    }))));
        }
    } else {
        List<Result<TimeseriesResultValue>> rows = (List<Result<TimeseriesResultValue>>) res;
        System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), parser.fields)));
        for (final Result<TimeseriesResultValue> r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList(r.getTimestamp()),
                    Lists.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getValue().getMetric(input);
                        }
                    }))));
        }
    }

    CloseQuietly.close(stdInput);
}

From source file:com.flaptor.hounder.indexer.RmiIndexerStub.java

public static void main(String[] args) {

    // create the parser
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;/*from w  w w.j a v a  2  s . com*/
    Options options = getOptions();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("RmiIndexerStub -h <hostName> -p <basePort> [options] ", options);
        System.exit(1);
    }

    boolean doOptimize = line.hasOption("optimize");
    boolean doCheckpoint = line.hasOption("checkpoint");
    boolean doStop = line.hasOption("stop");
    Integer port = ((Long) line.getOptionObject("port")).intValue();
    String host = line.getOptionValue("host");

    try {
        RmiIndexerStub stub = new RmiIndexerStub(port, host);

        if (line.hasOption("deleteUrl")) {
            String url = line.getOptionValue("deleteUrl");
            Document dom = generateDeleteDocument(url);
            indexOrFail(stub, dom, "Could not delete " + url);
            System.out.println("delete " + url + " command accepted by indexer");
        }

        if (line.hasOption("deleteFile")) {

            BufferedReader reader = new BufferedReader(new FileReader(line.getOptionValue("deleteFile")));
            while (reader.ready()) {
                String url = reader.readLine();
                if (url.length() > 0 && url.charAt(0) != '#') { // ignore empty lines and comments
                    Document dom = generateDeleteDocument(url);
                    indexOrFail(stub, dom, "Could not delete " + url);
                    System.out.println("delete " + url + " command accepted by indexer");
                }
            }
            reader.close();
        }

        if (doOptimize) {
            Document dom = generateCommandDocument("optimize");
            indexOrFail(stub, dom, "Could not send optimize command.");
            System.out.println("optimize command accepted by indexer");
        }

        if (doCheckpoint) {
            Document dom = generateCommandDocument("checkpoint");
            indexOrFail(stub, dom, "Could not send checkpoint command.");
            System.out.println("checkpoint command accepted by indexer");

        }
        if (doStop) {
            Document dom = generateCommandDocument("close");
            indexOrFail(stub, dom, "Could not send stop command.");
            System.out.println("stop command accepted by indexer");
        }
    } catch (Exception e) {
        System.err.println("An error occurred: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:dk.hippogrif.prettyxml.app.Main.java

/**
 * Application using commandline options or running GUI if no options.
 */// w  ww .  ja  va2  s  .  co  m
public static void main(String[] args) {
    try {
        PrettyPrint prettyPrint = new PrettyPrint();
        version = prettyPrint.getVersion();
        if (args.length == 0) {
            MainJFrame.run(version);
        } else {
            go(args);
        }
    } catch (Exception e) {
        logger.log(Level.FINE, "main", e);
        System.err.println(e.getMessage());
    }
}

From source file:AmazonSESSample.java

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

    // Construct an object to contain the recipient address.
    //Destination destination = new Destination().withToAddresses(new String[]{TO}).withCcAddresses((String[])CC.toArray());

    // Create the subject and body of the message.
    //Content subject = new Content().withData(SUBJECT);
    //Content textBody = new Content().withData(BODY);
    //Body body = new Body().withText(textBody);

    // Create a message with the specified subject and body.
    //Message message = new Message().withSubject(subject).withBody(body);

    // Assemble the email.
    //SendEmailRequest request = new SendEmailRequest().withSource(FROM).withDestination(destination).withMessage(message);
    /*SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest()
        .withSource(FROM).withDestinations(destination.getToAddresses())
        //.withDestinations(destination.getCcAddresses())
        .withRawMessage(getRawMessage());*/

    try {// w  w  w  .j a  v a  2  s .co m
        System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java...");

        /*
         * The ProfileCredentialsProvider will return your [default]
         * credential profile by reading from the credentials file located at
         * (~/.aws/credentials).
         *
         * TransferManager manages a pool of threads, so we create a
         * single instance and share it throughout our application.
         */
        AWSCredentials credentials;
        try {
            credentials = new ProfileCredentialsProvider().getCredentials();
        } catch (Exception e) {
            throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                    + "Please make sure that your credentials file is at the correct "
                    + "location (~/.aws/credentials), and is in valid format.", e);
        }

        // Instantiate an Amazon SES client, which will make the service call with the supplied AWS credentials.
        AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials);

        // Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your production
        // access status, sending limits, and Amazon SES identity-related settings are specific to a given
        // AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using
        // the US East (N. Virginia) region. Examples of other regions that Amazon SES supports are US_WEST_2
        // and EU_WEST_1. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html
        Region REGION = Region.getRegion(Regions.US_WEST_2);
        client.setRegion(REGION);

        // Send the email.
        //client.sendEmail(request);
        //System.out.println("Sending raw email: " + rawEmailRequest.toString());
        SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(getRawMessage());
        rawEmailRequest.setDestinations(Arrays.asList(TO));
        rawEmailRequest.setSource(FROM);
        SendRawEmailResult rawEmailResult = client.sendRawEmail(rawEmailRequest);
        System.out.println("Email Result = " + rawEmailResult.toString());
        // System.out.println("Email sent!");

    } catch (Exception ex) {
        System.out.println("The email was not sent.");
        System.out.println("Error message: " + ex.getMessage());
    }
}

From source file:au.org.ala.layers.stats.ObjectsStatsGenerator.java

public static void main(String[] args) {
    long start = System.currentTimeMillis();

    String fid = null;//from  w w w  . j  a va 2s  . c  o m

    logger.info(
            "args[0] = threadcount, args[1] = db connection string, args[2] = db username, args[3] = password");
    if (args.length >= 4) {
        CONCURRENT_THREADS = Integer.parseInt(args[0]);
        db_url = args[1];
        db_usr = args[2];
        db_pwd = args[3];
    }
    if (args.length > 4) {
        fid = args[4];
    }

    Connection c = getConnection();
    //String count_sql = "select count(*) as cnt from objects where bbox is null or area_km is null";
    String count_sql = "select count(*) as cnt from objects where area_km is null and st_geometrytype(the_geom) <> 'ST_Point' ";
    if (StringUtils.isEmpty(fid)) {
        count_sql = count_sql + " and fid = '" + fid + "'";
    }

    int count = 0;
    try {
        Statement s = c.createStatement();
        ResultSet rs = s.executeQuery(count_sql);
        while (rs.next()) {
            count = rs.getInt("cnt");
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    int iter = count / 200000;

    logger.info("Breaking into " + iter + " iterations");
    for (int i = 0; i <= iter; i++) {
        long iterStart = System.currentTimeMillis();
        //  updateBbox();
        updateArea(fid);
        logger.info("iteration " + i + " completed after " + (System.currentTimeMillis() - iterStart) + "ms");
        logger.info("total time taken is " + (System.currentTimeMillis() - start) + "ms");
    }
}