Example usage for java.lang Throwable getMessage

List of usage examples for java.lang Throwable getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:it.cnr.icar.eric.client.xml.registry.infomodel.RegistryPackageTest.java

public static void main(String[] args) {
    try {//from   ww  w  .  j  av a  2  s .c o m
        TestRunner.run(suite());
    } catch (Throwable t) {
        System.out.println("Throwable: " + t.getClass().getName() + " Message: " + t.getMessage());
        t.printStackTrace();
    }
}

From source file:com.ibm.iotf.connector.Connector.java

public static void main(String[] args) {
    userDir = System.getProperty("user.dir");
    resourceDir = null;//from w  w  w  . j a  v a2  s  .com
    isBluemix = false;

    IoTFSubscriber subscriber = null;
    MHubPublisher publisher = null;

    isBluemix = new File(userDir + File.separator + ".java-buildpack").exists();

    try {
        if (isBluemix) {
            logger.log(Level.INFO, "Running in Bluemix mode.");

            resourceDir = userDir + File.separator + "Connector-MessageHub-1.0" + File.separator + "bin"
                    + File.separator + "resources";

            if (System.getProperty(JAAS_CONFIG_PROPERTY) == null) {
                System.setProperty(JAAS_CONFIG_PROPERTY, resourceDir + File.separator + "jaas.conf");
            }

            // Attempt to retrieve the environment configuration for the IoTF and Message Hub services
            IoTFEnvironment iotEnv = parseIoTFEnv();

            if (iotEnv == null) {
                logger.log(Level.FATAL, "Unable to retrieve the IoTF environment configuration.");
                System.exit(1);
            }

            MessageHubEnvironment messageHubEnv = parseProducerProps();

            if (messageHubEnv == null) {
                logger.log(Level.FATAL, "Unable to retrieve the Message Hub environment configuration.");
                System.exit(1);
            }

            // update the JAAS configuration with auth details from the environment
            // configuration we have just parsed
            updateJaasConfiguration(messageHubEnv.getCredentials());

            // create a single subscriber/producer
            subscriber = new IoTFSubscriber(iotEnv);
            publisher = new MHubPublisher(messageHubEnv);
            // configure the subscriber to hand off events to the publisher
            subscriber.setPublisher(publisher);

        } else {
            logger.log(Level.INFO, "Running in standalone mode - not currently supported.");
            System.exit(1);
        }

    } catch (Throwable t) {
        logger.log(Level.FATAL,
                "An error occurred while configuring and starting the environment: " + t.getMessage(), t);
        System.exit(1);
    }

    logger.log(Level.INFO, "Starting the subscriber run loop.");
    // The subscriber run method + the thread(s) used by the IoT client libraries will keep
    // the application alive.
    subscriber.run();
}

From source file:com.acceleratedio.pac_n_zoom.UploadVideo.java

/**
 * Upload the user-selected video to the user's YouTube channel. The code
 * looks for the video in the application's project folder and uses OAuth
 * 2.0 to authorize the API request./*w w w . j a  v a 2  s. c o  m*/
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {

    MakePostRequest get_video = new MakePostRequest();
    get_video.execute();

    // This OAuth 2.0 access scope allows an application to upload files
    // to the authenticated user's YouTube channel, but doesn't allow
    // other types of access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");

    String vidFileName = PickAnmActivity.fil_nams[position].replace('/', '?') + ".mp4";
    String httpAddrs = "http://www.pnzanimate.me/Droid/db_rd.php?";
    httpAddrs += vidFileName;

    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadvideo");

        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-uploadvideo-sample").build();

        System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME);

        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();

        // Set the video to be publicly visible. This is the default
        // setting. Other supporting settings are "unlisted" and "private."
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);

        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();

        // This code uses a Calendar instance to create a unique name and
        // description for test purposes so that you can easily upload
        // multiple files. You should remove this code from your project
        // and use your own standard names instead.
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription(
                "Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());

        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);

        // Add the completed snippet object to the video resource.
        videoObjectDefiningMetadata.setSnippet(snippet);

        InputStreamContent mediaContent = new InputStreamContent("mp4",
                UploadVideo.class.getResourceAsStream("/sample-video.mp4"));

        // Insert the video. The command sends three arguments. The first
        // specifies which information the API request is setting and which
        // information the API response should return. The second argument
        // is the video resource that contains metadata about the new video.
        // The third argument is the actual video content.
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status",
                videoObjectDefiningMetadata, mediaContent);

        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();

        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        uploader.setDirectUploadEnabled(false);

        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    System.out.println("Initiation Started");
                    break;
                case INITIATION_COMPLETE:
                    System.out.println("Initiation Completed");
                    break;
                case MEDIA_IN_PROGRESS:
                    System.out.println("Upload in progress");
                    System.out.println("Upload percentage: " + uploader.getProgress());
                    break;
                case MEDIA_COMPLETE:
                    System.out.println("Upload Completed!");
                    break;
                case NOT_STARTED:
                    System.out.println("Upload Not Started!");
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

        // Call the API and upload the video.
        Video returnedVideo = videoInsert.execute();

        // Print data about the newly inserted video from the API response.
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());

    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

From source file:de.codesourcery.eve.skills.ui.utils.ParallelUITasksRunner.java

public static void main(String[] args) {

    SpringBeanInjector.setInstance(new SpringBeanInjector());

    final ApplicationThreadManager threadManager = new ApplicationThreadManager();

    final UITask parent = new UITask() {

        @Override//from  ww w .jav a 2s . co  m
        public String getId() {
            return "parent task";
        }

        @Override
        public void cancellationHook() {
            System.err.println("Parent task cancelled.");
            threadManager.shutdown(false);
        }

        @Override
        public void successHook() throws Exception {
            System.out.println("Parent task completed.");
            threadManager.shutdown(false);
        }

        @Override
        public void failureHook(Throwable t) throws Exception {
            System.err.println("Parent task caught exception " + t.getMessage());
            threadManager.shutdown(false);
        }

        @Override
        public void run() throws Exception {
            System.out.println("Parent task has started.");
            threadManager.shutdown(false);
        }
    };

    final UITask[] children = new UITask[] { createChild(1), createChild(2), createChild(3) };

    boolean submitted = submitParallelTasks(threadManager, parent, children);

    if (!submitted) {
        System.err.println("Failed to submit parent task");
    }
}

From source file:fedora.server.utilities.rebuild.Rebuild.java

public static void main(String[] args) {
    // tell commons-logging to use log4j
    System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.Log4jFactory");
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
    // log4j//from   w  w  w .j a v a 2 s . c  o  m
    // File log4jConfig = new File(new File(homeDir), "config/log4j.xml");
    // DOMConfigurator.configure(log4jConfig.getPath());
    String profile = null;
    if (args.length > 0) {
        profile = args[0];
    }
    if (args.length > 1) {
        fail("Too many arguments", true, true);
    }
    try {
        File serverDir = new File(new File(Constants.FEDORA_HOME), "server");
        ServerConfiguration serverConfig = getServerConfig(serverDir, profile);
        System.err.println();
        System.err.println("                       Fedora Rebuild Utility");
        System.err.println("                     ..........................");
        System.err.println();
        System.err.println("WARNING: Live rebuilds are not currently supported.");
        System.err.println("         Make sure your server is stopped before continuing.");
        System.err.println();
        System.err.println("Server directory is " + serverDir.toString());
        if (profile != null) {
            System.err.print("Server profile is " + profile);
        }
        System.err.println();
        System.err.println("---------------------------------------------------------------------");
        System.err.println();
        Rebuilder rebuilder = getRebuilder();
        Map<String, String> options = getUserInput(rebuilder, serverDir, serverConfig);
        new Rebuild(rebuilder, options, serverConfig);
    } catch (Throwable th) {
        String msg = th.getMessage();
        if (msg == null) {
            msg = th.getClass().getName();
        }
        fail(msg, false, false);
        th.printStackTrace();
    }
}

From source file:com.googlecode.icegem.cacheutils.Launcher.java

/**
 * The entry point of the application.// w ww. j ava 2s . c  o m
 * 
 * @param args
 *            - All arguments.
 * @throws Exception
 */
public static void main(String[] args) {
    try {
        int commandIndex = findCommandIndex(args);

        if (commandIndex < 0) {
            printHelp();
        }

        String[] launcherArgs = extractLauncherArgs(args, commandIndex);
        String[] commandArgs = extractCommandArgs(args, commandIndex);

        parseCommandLineArguments(launcherArgs);

        debug("Launcher#main(): args = " + Arrays.asList(args));
        debug("Launcher#main(): launcherArgs = " + Arrays.asList(launcherArgs));
        debug("Launcher#main(): commandArgs = " + Arrays.asList(commandArgs));

        String commandName = args[commandIndex];

        Executable tool = Command.getUtil(commandName);

        if (tool != null) {
            tool.execute(commandArgs, debugEnabled, quiet);
        } else {
            debug("Launcher#main(): Command \"" + commandName + "\" not found");

            printHelp();
        }
    } catch (Throwable t) {
        debug("Launcher#main(): Throwable caught with message = " + t.getMessage(), t);

        Utils.exitWithFailure("Unexpected throwable", t);
    }
}

From source file:com.github.rvesse.github.pr.stats.PullRequestStats.java

public static void main(String[] args) throws MalformedURLException, IOException {
    SingleCommand<PullRequestStats> parser = SingleCommand.singleCommand(PullRequestStats.class);
    try {//from ww  w .j  ava2  s.c o  m
        ParseResult<PullRequestStats> results = parser.parseWithResult(args);
        if (results.wasSuccessful()) {
            // Run the command
            results.getCommand().run();
        } else {
            // Display errors
            int errNum = 1;
            for (ParseException e : results.getErrors()) {
                System.err.format("Error #%d: %s\n", errNum, e.getMessage());
                errNum++;
            }
            System.err.println();

            // Show help
            Help.help(parser.getCommandMetadata(), System.out);
        }
        System.exit(0);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    } catch (Throwable t) {
        System.err.println(t.getMessage());
        t.printStackTrace(System.err);
        System.exit(2);
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.InfomodelFactoryTest.java

public static void main(String[] args) {
    try {/*from w w  w.ja  va 2s.  c  o  m*/
        junit.textui.TestRunner.run(suite());
    } catch (Throwable t) {
        System.out.println("\nThrowable: " + t.getClass().getName() + " Message: " + t.getMessage());
        t.printStackTrace();
    }
}

From source file:com.amazonaws.services.iot.demo.danbo.rpi.Danbo.java

public static void main(String[] args) throws Exception {
    log.debug("starting");

    // uses pin 6 for the red Led
    final Led redLed = new Led(6);
    // uses pin 26 for the green Led
    final Led greenLed = new Led(26);

    // turns the red led on initially
    redLed.on();//from w w w  .j a  v  a2 s . c o  m

    // turns the green led off initially
    greenLed.off();

    // loads properties from danbo.properties file - make sure this file is
    // available on the pi's home directory
    InputStream input = new FileInputStream("/home/pi/danbo/danbo.properties");
    Properties properties = new Properties();
    properties.load(input);
    endpoint = properties.getProperty("awsiot.endpoint");
    rootCA = properties.getProperty("awsiot.rootCA");
    privateKey = properties.getProperty("awsiot.privateKey");
    certificate = properties.getProperty("awsiot.certificate");
    url = protocol + endpoint + ":" + port;

    log.debug("properties loaded");

    // turns off both eyes
    RGBLed rgbLed = new RGBLed("RGBLed1", Danbo.pinLayout1, Danbo.pinLayout2, new Color(0, 0, 0),
            new Color(0, 0, 0), 0, 100);
    new Thread(rgbLed).start();

    // resets servo to initial positon
    Servo servo = new Servo("Servo", 1);
    new Thread(servo).start();

    // gets the Pi serial number and uses it as part of the thing
    // registration name
    clientId = clientId + getSerialNumber();

    // AWS IoT things shadow topics
    updateTopic = "$aws/things/" + clientId + "/shadow/update";
    deltaTopic = "$aws/things/" + clientId + "/shadow/update/delta";
    rejectedTopic = "$aws/things/" + clientId + "/shadow/update/rejected";

    // AWS IoT controller things shadow topic (used to register new things)
    controllerUpdateTopic = "$aws/things/Controller/shadow/update";

    // defines an empty danbo shadow POJO
    final DanboShadow danboShadow = new DanboShadow();
    DanboShadow.State state = danboShadow.new State();
    final DanboShadow.State.Reported reported = state.new Reported();
    reported.setEyes("readyToBlink");
    reported.setHead("readyToMove");
    reported.setMouth("readyToSing");
    reported.setName(clientId);
    state.setReported(reported);
    danboShadow.setState(state);

    // defines an empty controller shadow POJO
    final ControllerShadow controllerShadow = new ControllerShadow();
    ControllerShadow.State controllerState = controllerShadow.new State();
    final ControllerShadow.State.Reported controllerReported = controllerState.new Reported();
    controllerReported.setThingName(clientId);
    controllerState.setReported(controllerReported);
    controllerShadow.setState(controllerState);

    try {
        log.debug("registering");

        // registers the thing (creates a new thing) by updating the
        // controller
        String message = gson.toJson(controllerShadow);
        MQTTPublisher controllerUpdatePublisher = new MQTTPublisher(controllerUpdateTopic, qos, message, url,
                clientId + "-controllerupdate" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(controllerUpdatePublisher).start();

        log.debug("registered");

        // clears the thing status (in case the thing already existed)
        Danbo.deleteStatus("initialDelete");

        // creates an MQTT subscriber to the things shadow delta topic
        // (command execution notification)
        MQTTSubscriber deltaSubscriber = new MQTTSubscriber(new DanboShadowDeltaCallback(), deltaTopic, qos,
                url, clientId + "-delta" + rand.nextInt(100000), cleanSession, rootCA, privateKey, certificate);
        new Thread(deltaSubscriber).start();

        // creates an MQTT subscriber to the things shadow error topic
        MQTTSubscriber errorSubscriber = new MQTTSubscriber(new DanboShadowRejectedCallback(), rejectedTopic,
                qos, url, clientId + "-rejected" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(errorSubscriber).start();

        // turns the red LED off
        redLed.off();

        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // turns the green LED on
                greenLed.on();

                log.debug("running publish state thread");

                int temp = -300;
                int humid = -300;

                reported.setTemperature(new Integer(temp).toString());
                reported.setHumidity(new Integer(humid).toString());

                try {
                    // reads the temperature and humidity data
                    Set<Sensor> sensors = Sensors.getSensors();
                    log.debug(sensors.size());

                    for (Sensor sensor : sensors) {
                        log.debug(sensor.getPhysicalQuantity());
                        log.debug(sensor.getValue());
                        if (sensor.getPhysicalQuantity().toString().equals("Temperature")) {
                            temp = sensor.getValue().intValue();
                        }
                        if (sensor.getPhysicalQuantity().toString().equals("Humidity")) {
                            humid = sensor.getValue().intValue();
                        }
                    }

                    log.debug("temperature: " + temp);
                    log.debug("humidity: " + humid);
                    reported.setTemperature(new Integer(temp).toString());
                    reported.setHumidity(new Integer(humid).toString());
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                try {
                    // reports current state - last temperature and humidity
                    // read
                    String message = gson.toJson(danboShadow);
                    MQTTPublisher updatePublisher = new MQTTPublisher(updateTopic, qos, message, url,
                            clientId + "-update" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                            certificate);
                    new Thread(updatePublisher).start();
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                // turns the green LED off
                greenLed.off();
            }
        }, 0, 5, TimeUnit.SECONDS); // runs this thread every 5 seconds,
        // with an initial delay of 5 seconds
    } catch (MqttException me) {
        // Display full details of any exception that occurs
        log.error("reason " + me.getReasonCode());
        log.error("msg " + me.getMessage());
        log.error("loc " + me.getLocalizedMessage());
        log.error("cause " + me.getCause());
        log.error("excep " + me);
        me.printStackTrace();
    } catch (Throwable th) {
        log.error("msg " + th.getMessage());
        log.error("loc " + th.getLocalizedMessage());
        log.error("cause " + th.getCause());
        log.error("excep " + th);
        th.printStackTrace();
    }
}

From source file:cz.hobrasoft.pdfmu.Main.java

/**
 * The main entry point of PDFMU//w  w  w. j  a  v  a  2 s. c o  m
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int exitStatus = 0; // Default: 0 (normal termination)

    // Create a map of operations
    Map<String, Operation> operations = new LinkedHashMap<>();
    operations.put("inspect", OperationInspect.getInstance());
    operations.put("update-version", OperationVersionSet.getInstance());
    operations.put("update-properties", OperationMetadataSet.getInstance());
    operations.put("attach", OperationAttach.getInstance());
    operations.put("sign", OperationSignatureAdd.getInstance());

    // Create a command line argument parser
    ArgumentParser parser = createFullParser(operations);

    // Parse command line arguments
    Namespace namespace = null;
    try {
        // If help is requested,
        // `parseArgs` prints help message and throws `ArgumentParserException`
        // (so `namespace` stays null).
        // If insufficient or invalid `args` are given,
        // `parseArgs` throws `ArgumentParserException`.
        namespace = parser.parseArgs(args);
    } catch (HelpScreenException e) {
        parser.handleError(e); // Do nothing
    } catch (UnrecognizedCommandException e) {
        exitStatus = PARSER_UNRECOGNIZED_COMMAND.getCode();
        parser.handleError(e); // Print the error in human-readable format
    } catch (UnrecognizedArgumentException e) {
        exitStatus = PARSER_UNRECOGNIZED_ARGUMENT.getCode();
        parser.handleError(e); // Print the error in human-readable format
    } catch (ArgumentParserException ape) {
        OperationException oe = apeToOe(ape);
        exitStatus = oe.getCode();
        // We could also write `oe` as a JSON document,
        // but we do not know whether JSON output was requested,
        // so we use the text output (default).

        parser.handleError(ape); // Print the error in human-readable format
    }

    if (namespace == null) {
        System.exit(exitStatus);
    }

    assert exitStatus == 0;

    // Handle command line arguments
    WritingMapper wm = null;

    // Extract operation name
    String operationName = namespace.getString("operation");
    assert operationName != null; // The argument "operation" is a sub-command, thus it is required

    // Select the operation from `operations`
    assert operations.containsKey(operationName); // Only supported operation names are allowed
    Operation operation = operations.get(operationName);
    assert operation != null;

    // Choose the output format
    String outputFormat = namespace.getString("output_format");
    switch (outputFormat) {
    case "json":
        // Disable loggers
        disableLoggers();
        // Initialize the JSON serializer
        wm = new WritingMapper();
        operation.setWritingMapper(wm); // Configure the operation
        break;
    case "text":
        // Initialize the text output
        TextOutput to = new TextOutput(System.err); // Bind to `System.err`
        operation.setTextOutput(to); // Configure the operation
        break;
    default:
        assert false; // The option has limited choices
    }

    // Execute the operation
    try {
        operation.execute(namespace);
    } catch (OperationException ex) {
        exitStatus = ex.getCode();

        // Log the exception
        logger.severe(ex.getLocalizedMessage());
        Throwable cause = ex.getCause();
        if (cause != null && cause.getMessage() != null) {
            logger.severe(cause.getLocalizedMessage());
        }

        if (wm != null) {
            // JSON output is enabled
            ex.writeInWritingMapper(wm);
        }
    }
    System.exit(exitStatus);
}