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:bixo.tools.LengthenUrlsTool.java

/**
 * @param args - URL to fetch, or path to file of URLs
 *///w  ww  . jav  a2 s.  c  o m
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
    try {
        String url = null;
        if (args.length == 0) {
            System.out.print("URL to lengthen: ");
            url = readInputLine();
            if (url.length() == 0) {
                System.exit(0);
            }

            if (!url.startsWith("http://")) {
                url = "http://" + url;
            }
        } else if (args.length != 1) {
            System.out.print("A single URL or filename parameter is allowed");
            System.exit(0);
        } else {
            url = args[0];
        }

        String filename;
        if (!url.startsWith("http://")) {
            // It's a path to a file of URLs
            filename = url;
        } else {
            // We have a URL that we need to write to a temp file.
            File tempFile = File.createTempFile("LengthenUrlsTool", "txt");
            filename = tempFile.getAbsolutePath();
            FileWriter fw = new FileWriter(tempFile);
            IOUtils.write(url, fw);
            fw.close();
        }

        System.setProperty("bixo.root.level", "TRACE");
        // Uncomment this to see the wire log for HttpClient
        // System.setProperty("bixo.http.level", "DEBUG");

        BaseFetcher fetcher = UrlLengthener.makeFetcher(10, ConfigUtils.BIXO_TOOL_AGENT);

        Pipe pipe = new Pipe("urls");
        pipe = new Each(pipe, new UrlLengthener(fetcher));
        pipe = new Each(pipe, new Debug());

        BixoPlatform platform = new BixoPlatform(LengthenUrlsTool.class, Platform.Local);
        BasePath filePath = platform.makePath(filename);
        TextLine textLineLocalScheme = new TextLine(new Fields("url"));
        Tap sourceTap = platform.makeTap(textLineLocalScheme, filePath, SinkMode.KEEP);
        SinkTap sinkTap = new NullSinkTap(new Fields("url"));

        FlowConnector flowConnector = platform.makeFlowConnector();
        Flow flow = flowConnector.connect(sourceTap, sinkTap, pipe);

        flow.complete();
    } catch (Exception e) {
        System.err.println("Exception running tool: " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(-1);
    }
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.FormFileUploaderClientApplication.java

/**
 * Run the program./*from ww  w. ja  va 2  s  . c  o  m*/
 * 
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl);
        FileBody bin = new FileBody(uploadFile);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, bin).build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder("Response data received:");
                while ((output = in.readLine()) != null) {
                    sb.append(System.getProperty("line.separator"));
                    sb.append(output);
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}

From source file:interoperabilite.webservice.client.ClientWithRequestFuture.java

public static void main(String[] args) throws Exception {
    // the simplest way to create a HttpAsyncClientWithFuture
    HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build();
    ExecutorService execService = Executors.newFixedThreadPool(5);
    FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient,
            execService);/*from w w w . j a  va 2 s . c  om*/
    try {
        // Because things are asynchronous, you must provide a ResponseHandler
        ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
            @Override
            public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                // simply return true if the status was OK
                return response.getStatusLine().getStatusCode() == 200;
            }
        };

        // Simple request ...
        HttpGet request1 = new HttpGet("http://httpbin.org/get");
        HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1,
                HttpClientContext.create(), handler);
        Boolean wasItOk1 = futureTask1.get();
        System.out.println("It was ok? " + wasItOk1);

        // Cancel a request
        try {
            HttpGet request2 = new HttpGet("http://httpbin.org/get");
            HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2,
                    HttpClientContext.create(), handler);
            futureTask2.cancel(true);
            Boolean wasItOk2 = futureTask2.get();
            System.out.println("It was cancelled so it should never print this: " + wasItOk2);
        } catch (CancellationException e) {
            System.out.println("We cancelled it, so this is expected");
        }

        // Request with a timeout
        HttpGet request3 = new HttpGet("http://httpbin.org/get");
        HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3,
                HttpClientContext.create(), handler);
        Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk3);

        FutureCallback<Boolean> callback = new FutureCallback<Boolean>() {
            @Override
            public void completed(Boolean result) {
                System.out.println("completed with " + result);
            }

            @Override
            public void failed(Exception ex) {
                System.out.println("failed with " + ex.getMessage());
            }

            @Override
            public void cancelled() {
                System.out.println("cancelled");
            }
        };

        // Simple request with a callback
        HttpGet request4 = new HttpGet("http://httpbin.org/get");
        // using a null HttpContext here since it is optional
        // the callback will be called when the task completes, fails, or is cancelled
        HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4,
                HttpClientContext.create(), handler, callback);
        Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk4);
    } finally {
        requestExecService.close();
    }
}

From source file:SmtpTalk.java

/**
 * A simple main program showing the class in action.
 * //from  w  w w .  j ava 2 s  . c  o m
 * TODO generalize to accept From arg, read msg on stdin
 */
public static void main(String[] argv) {
    if (argv.length != 2) {
        System.err.println("Usage: java SmtpTalk host user");
        System.exit(1);
    }

    try {
        SmtpTalk st = new SmtpTalk(argv[0]);

        System.out.println("SMTP Talker ready");

        st.converse("MAILER-DAEMON@daroad.darwinsys.com", argv[1], "Test message", "Hello there");
    } catch (Exception ig) {
        System.err.println(ig.getMessage());
        System.exit(0);
    }
}

From source file:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java

/**
 * Run the program./*from   w ww .j a v  a  2  s . co m*/
 *
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl + "false");
        FileBody bin = new FileBody(uploadFile);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(FITS_FORM_FIELD_DATAFILE, bin);
        HttpEntity reqEntity = builder.build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder();
                while ((output = in.readLine()) != null) {
                    sb.append(output);
                    sb.append(System.getProperty("line.separator"));
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}

From source file:com.dhenton9000.screenshots.ScreenShotLauncher.java

/**
 * main launching method that takes command line arguments
 *
 * @param args/*from   w  ww. j a  va  2 s .  co  m*/
 */
public static void main(String[] args) {

    final String[] actions = { ACTIONS.source.toString(), ACTIONS.target.toString(),
            ACTIONS.compare.toString() };
    final List actionArray = Arrays.asList(actions);

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("action").hasArg().isRequired().withArgName("action").create());
    HelpFormatter formatter = new HelpFormatter();

    String header = "Process screenshots\n" + "--action=source   create source screenshots\n"
            + "--action=target     create the screenshots for comparison\n"
            + "--action=compare  compare the images\n" + "%s\n\n";

    String action = null;
    try {
        // parse the command line arguments
        CommandLineParser parser = new PosixParser();
        CommandLine line = parser.parse(options, args);

        // validate that action option has been set
        if (line.hasOption("action")) {
            action = line.getOptionValue("action");
            LOG.debug("action '" + action + "'");
            if (!actionArray.contains(action)) {

                formatter.printHelp(ScreenShotLauncher.class.getName(),
                        String.format(header, String.format("action option '%s' is invalid", action)), options,
                        "\n\n", true);
                System.exit(1);

            }

        } else {
            formatter.printHelp(ScreenShotLauncher.class.getName(), String.format(header, "not found"), options,
                    "\n\n", false);
            System.exit(1);
        }
    } catch (ParseException exp) {
        formatter.printHelp(ScreenShotLauncher.class.getName(),
                String.format(header, "problem " + exp.getMessage()), options, "\n\n", false);
        System.exit(1);

    }
    ACTIONS actionEnum = ACTIONS.valueOf(action);
    ScreenShotLauncher launcher = new ScreenShotLauncher();
    try {
        launcher.handleRequest(actionEnum);
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);

    }
}

From source file:de.uni_freiburg.informatik.ultimate.licence_manager.Main.java

public static void main(final String[] args) {
    final Options cliOptions = createOptions();
    sOptions = parseArguments(args, cliOptions);
    if (sOptions == null) {
        System.exit(1);//w w  w  .ja va2  s .  c  o m
        return;
    }

    if (hasOption(OPTION_HELP)) {
        printHelp(cliOptions);
        System.exit(0);
        return;
    }

    // check required parameters
    final String[] requiredOptions = new String[] { OPTION_DIRECTORY, OPTION_TEMPLATE_NAME };
    for (final String requiredOption : requiredOptions) {
        if (!hasOption(requiredOption)) {
            System.err.print("Missing parameter \"" + requiredOption + "\"");
            printHelp(cliOptions);
            System.exit(1);
            return;
        }
    }

    try {

        final String[] fileendings = new String[] { ".java", "pom.xml" };
        final LicenceManager licenceManager = new LicenceManager(getOptionValue(OPTION_DIRECTORY), fileendings,
                getOptionValue(OPTION_TEMPLATE_NAME));

        if (hasOption(OPTION_DRY_RUN)) {
            System.out.println("This is a dry run:");
            if (hasOption(OPTION_DELETE)) {
                licenceManager.deleteDry();
            } else {
                licenceManager.writeDry();
            }
        } else {
            if (hasOption(OPTION_DELETE)) {
                licenceManager.delete();
            } else {
                licenceManager.write();
            }
        }
        System.out.println();
        System.out.println("Found the following authors:");
        Authors.getCollectedAuthorNames().forEach(System.out::println);
        System.exit(0);
        return;
    } catch (Exception ex) {
        System.err.println(ex.getMessage());
        System.exit(1);
        return;
    }

}

From source file:net.mitnet.tools.pdf.book.openoffice.ui.cli.OpenOfficeReportBuilderCLI.java

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

    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);
    CommandLineHelper commandLineHelper = new CommandLineHelper(commandLine);

    if (!commandLineHelper.hasOption(CliOptions.OPTION_INPUT_TEMPLATE_FILE)) {
        System.err.println("Must specify " + CliOptions.OPTION_INPUT_TEMPLATE_FILE.getDescription());
        showHelp();//w w  w .  ja v a 2  s. c  o  m
    }
    File sourceTemplateFile = commandLineHelper.getOptionValueAsFile(CliOptions.OPTION_INPUT_TEMPLATE_FILE);

    if (!commandLineHelper.hasOption(CliOptions.OPTION_INPUT_DATA_FILE)) {
        System.err.println("Must specify " + CliOptions.OPTION_INPUT_DATA_FILE.getDescription());
        showHelp();
    }
    File sourceDataFile = commandLineHelper.getOptionValueAsFile(CliOptions.OPTION_INPUT_DATA_FILE);

    if (!commandLineHelper.hasOption(CliOptions.OPTION_OUTPUT_REPORT_FILE)) {
        System.err.println("Must specify " + CliOptions.OPTION_OUTPUT_REPORT_FILE.getDescription());
        showHelp();
    }
    File outputReportFile = commandLineHelper.getOptionValueAsFile(CliOptions.OPTION_OUTPUT_REPORT_FILE);

    boolean verbose = false;
    if (commandLineHelper.hasOption(CliOptions.OPTION_VERBOSE)) {
        verbose = true;
    }

    try {
        System.out.println("Source template file is " + sourceTemplateFile);
        System.out.println("Source data file is " + sourceDataFile);
        System.out.println("Output report file is " + outputReportFile);
        System.out.println("Building report ...");
        // ProgressMonitor progressMonitor = new ConsoleProgressMonitor();
        OpenOfficeReportBuilder reportBuilder = new OpenOfficeReportBuilder();
        reportBuilder.buildReport(sourceTemplateFile, sourceDataFile, outputReportFile);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.err.println("Error building report: " + e.getMessage());
        System.exit(SystemExitValues.EXIT_CODE_ERROR);
    }
    System.out.println("Finished converting files.");
}

From source file:it.codestudio.callbyj.CallByJ.java

/**
 * The main method.//from  w w  w  .  ja  v  a 2  s.c o m
 *
 * @param args the arguments
 */
public static void main(String[] args) {
    options.addOption("aCom", "audio_com", true,
            "Specify serial COM port for audio streaming (3G APPLICATION ...)");
    options.addOption("cCom", "command_com", true,
            "Specify serial COM port for modem AT command (PC UI INTERFACE ...)");
    options.addOption("p", "play_message", false,
            "Play recorded message instead to respond with audio from mic");
    options.addOption("h", "help", false, "Print help for this application");
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String audioCOM = "";
        String commandCOM = "";
        Boolean playMessage = false;
        args = Utils.fitlerNullString(args);
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("aCom")) {
            audioCOM = cmd.getOptionValue("aCom");
            ;
        }
        if (cmd.hasOption("cCom")) {
            commandCOM = cmd.getOptionValue("cCom");
            ;
        }
        if (cmd.hasOption("p")) {
            playMessage = true;
        }
        if (audioCOM != null && commandCOM != null && !audioCOM.isEmpty() && !commandCOM.isEmpty()) {
            comManager = ComManager.getInstance(commandCOM, audioCOM, playMessage);
        } else {
            HelpFormatter f = new HelpFormatter();
            f.printHelp("\r Exaple: CallByJ -aCom COM11 -cCom COM10 \r OptionsTip", options);
            return;
        }
        options = new Options();
        options.addOption("h", "help", false, "Print help for this application");
        options.addOption("p", "pin", true, "Specify pin of device, if present");
        options.addOption("c", "call", true, "Start call to specified number");
        options.addOption("e", "end", false, "End all active call");
        options.addOption("t", "terminate", false, "Terminate application");
        options.addOption("r", "respond", false, "Respond to incoming call");
        comManager.startModemCommandManager();
        while (true) {
            try {
                String[] commands = { br.readLine() };
                commands = Utils.fitlerNullString(commands);
                cmd = parser.parse(options, commands);
                if (cmd.hasOption('h')) {
                    HelpFormatter f = new HelpFormatter();
                    f.printHelp("OptionsTip", options);
                }
                if (cmd.hasOption('p')) {
                    String devicePin = cmd.getOptionValue("p");
                    comManager.insertPin(devicePin);
                }
                if (cmd.hasOption('c')) {
                    String numberToCall = cmd.getOptionValue("c");
                    comManager.sendCommandToModem(ATCommands.CALL, numberToCall);
                }
                if (cmd.hasOption('r')) {
                    comManager.respondToIncomingCall();
                }
                if (cmd.hasOption('e')) {
                    comManager.sendCommandToModem(ATCommands.END_CALL);
                }
                if (cmd.hasOption('t')) {
                    comManager.sendCommandToModem(ATCommands.END_CALL);
                    comManager.terminate();
                    System.out.println("CallByJ closed!");
                    break;
                    //System.exit(0);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (comManager != null)
            comManager.terminate();
    }
}

From source file:com.aerospike.osm.Around.java

public static void main(String[] args) {
    try {/*from www .j av  a 2 s  .co  m*/
        run(args);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        ex.printStackTrace();
    }
}