Example usage for java.lang Throwable getLocalizedMessage

List of usage examples for java.lang Throwable getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:Main.java

public static void main(String[] argv) {
    Throwable t = new Exception("from java2s.com");

    System.out.println(t.getLocalizedMessage());

}

From source file:utilities.HashPassword.java

public static void main(String[] args) throws IOException {
    Md5PasswordEncoder encoder;/*w w  w .  ja  va2 s.  c  om*/
    ConsoleReader reader;
    String line, hash;

    try {
        System.out.printf("HashPassword 1.3%n");
        System.out.printf("----------------%n%n");

        encoder = new Md5PasswordEncoder();
        reader = new ConsoleReader();

        line = reader.readLine();
        while (!line.equals("quit")) {
            hash = encoder.encodePassword(line, null);
            System.out.println(hash);
            line = reader.readLine();
        }
    } catch (Throwable oops) {
        System.out.flush();
        System.err.printf("%n%s%n", oops.getLocalizedMessage());
        //oops.printStackTrace(System.out);         
    }
}

From source file:utilities.MinPopulateDatabase.java

public static void main(String[] args) {
    ApplicationContext populationContext;
    DatabaseUtil databaseUtil;/*w w w .ja va  2s  . co  m*/

    databaseUtil = null;

    try {
        System.out.printf("MinPopulateDatabase 1.3%n");
        System.out.printf("--------------------%n%n");

        System.out.printf("Initialising persistence context `%s'...%n", DatabaseConfig.PersistenceUnit);
        databaseUtil = new DatabaseUtil();

        System.out.printf("Creating database `%s' (%s)...%n", databaseUtil.getDatabaseName(),
                databaseUtil.getDatabaseDialectName());
        databaseUtil.recreateDatabase();

        System.out.printf("Reading configuration file `%s'...%n", "MinPopulateDatabase.xml");
        populationContext = new ClassPathXmlApplicationContext("classpath:minPopulateDatabase.xml");

        System.out.printf("Persisting %d entities...%n%n", populationContext.getBeanDefinitionCount());
        databaseUtil.openTransaction();
        for (Entry<String, Object> entry : populationContext.getBeansWithAnnotation(Entity.class).entrySet()) {
            String beanName;
            DomainEntity entity;

            beanName = entry.getKey();
            entity = (DomainEntity) entry.getValue();
            System.out.printf("> %s: %s", beanName, entity.getClass().getName());
            databaseUtil.persist(entity);
            System.out.printf(" -> id = %d, version = %d%n", entity.getId(), entity.getVersion());
        }
        databaseUtil.commitTransaction();
    } catch (Throwable oops) {
        System.out.flush();
        System.err.printf("%n%s%n", oops.getLocalizedMessage());
        oops.printStackTrace(System.err);
    } finally {
        if (databaseUtil != null)
            databaseUtil.close();
    }
}

From source file:utilities.QueryDatabase.java

public static void main(String[] args) throws Throwable {
    DatabaseUtil databaseUtil;//from  w w  w .  j  av  a 2  s .c om
    ConsoleReader reader;
    String line;
    boolean quit;

    databaseUtil = null;

    try {
        System.out.printf("QueryDatabase 1.3%n");
        System.out.printf("-----------------%n%n");

        System.out.printf("Initialising persistence context `%s'...%n", DatabaseConfig.PersistenceUnit);
        databaseUtil = new DatabaseUtil();

        reader = new ConsoleReader();

        do {
            line = reader.readCommand();
            quit = interpretLine(databaseUtil, line);
        } while (!quit);
    } catch (Throwable oops) {
        System.out.flush();
        System.err.printf("%n%s%n", oops.getLocalizedMessage());
        //oops.printStackTrace(System.out);         
    } finally {
        databaseUtil.close();
    }
}

From source file:com.googlecode.flickrandroid.oauth.test.OAuthTest.java

/**
 * @param args/*from  w  w  w . ja v  a 2s .com*/
 */
public static void main(String[] args) {
    try {
        Flickr f = new Flickr("da4fadd0084ea1799ad33048f0d6a5c5", "186b04791439c326");
        /*OAuthToken oauthToken = f.getOAuthInterface().getRequestToken("http://localhost");
        System.out.println(oauthToken);
        System.out.println(f.getOAuthInterface().buildAuthenticationUrl(Permission.DELETE, oauthToken));
        String tokenVerifier = readParamFromCommand("Enter Token Verifier: ");
        OAuth oauth = f.getOAuthInterface().getAccessToken(oauthToken.getOauthToken(), 
            oauthToken.getOauthTokenSecret(), tokenVerifier);
        System.out.println(oauth);
        RequestContext.getRequestContext().setOAuth(oauth);*/

        //oauthToken=72157627458295241-83050bfaaeffd445, oauthTokenSecret=07c38a749dc7d36e
        OAuth auth = new OAuth();
        User user = new User();
        user.setId("8308954@N06");
        user.setUsername("Yang and Yun's Album");
        auth.setToken(new OAuthToken("72157627458295241-83050bfaaeffd445", "07c38a749dc7d36e"));
        //auth.setToken(new OAuthToken("72157627641862382-904dfd0d8fb0294e", "07c38a749dc7d36e"));
        RequestContext.getRequestContext().setOAuth(auth);
        //f.getGalleriesInterface().getListForPhoto("5772049100", 0, 0);
        System.out.println(f.getOAuthInterface().testLogin());
        //f.getPhotosInterface().addTags("5772049100", new String[]{"Hello", "World"});
        //f.getCommentsInterface().addComment("5772049100", "Hello World");
        //Collection<Exif> exifs = f.getPhotosInterface().getExif("5772049100", null);
        //f.getPhotosInterface().getInfo("6024664723", null);
        //f.getCommentsInterface().getList("6024664723");
        //         System.out.println(f.getActivityInterface().userComments(0, 0));
        //         System.out.println(f.getActivityInterface().userPhotos(1, 1, null));
        //         System.out.println(f.getBlogsInterface().getServices());
        //         System.out.println(f.getBlogsInterface().getList());
        //         System.out.println(f.getCommonsInterface().getInstitutions());
        //         System.out.println(f.getContactsInterface().getList());
        //         System.out.println(f.getContactsInterface().getPublicList("8308954@N06"));
        //         System.out.println(f.getContactsInterface().getListRecentlyUploaded(
        //               new Date(System.currentTimeMillis() - 24L * 60L * 60L * 1000L), null));

        //Photoset ID: 72157626738803062
        //         Photoset set = f.getPhotosetsInterface().getList("8308954@N06").getPhotosets().iterator().next();
        //         System.out.println(f.getPhotosetsInterface().getInfo(set.getId()));
        //         System.out.println(f.getPhotosetsInterface().getPhotos("72157626738803062", 0, 0));
        //         System.out.println(f.getPhotosetsInterface().getContext("5726077435", "72157626738803062"));
        //photo ID: 6024664723
        //f.getFavoritesInterface().add(photo.getId());
        //         System.out.println("Favourites List: \n" + f.getFavoritesInterface().getList("8308954@N06", 0, 0, null));
        //         System.out.println("Favourites Public List: \n" + f.getFavoritesInterface().getPublicList("8308954@N06", 0, 0, null));
        //group ID: 95014477@N00
        //         Group group = f.getGroupsInterface().search("Nikon", 0, 0).iterator().next();
        //         System.out.println(f.getGroupsInterface().getInfo(group.getId()));
        //         System.out.println(f.getMembersInterface().getList(group.getId(), null, 0, 0));
        //         System.out.println(f.getGeoInterface().getLocation("6024664723"));
        //         System.out.println(f.getGeoInterface().getPerms("6024664723"));
        //         System.out.println(f.getLicensesInterface().getInfo());
        //         Place place = f.getPlacesInterface().find("Shanghai").get(0);
        //         System.out.println(place.getName() + ": " + place.getPlaceId());
        //shanghai place ID: JAJiM7JTU78IjzqC
        //         System.out.println(f.getPlacesInterface().getInfoByUrl(place.getPlaceUrl()));
        //         System.out.println(f.getPlacesInterface().getInfo(place.getPlaceId(), place.getWoeId()));

        //         System.out.println(f.getUrlsInterface().lookupUser(f.getUrlsInterface().getUserProfile("8308954@N06")));
        //         System.out.println(f.getUrlsInterface().getUserPhotos("8308954@N06"));
        //         System.out.println(f.getUrlsInterface().lookupGroup(f.getUrlsInterface().getGroup("95014477@N00")));

        //         System.out.println(f.getTagsInterface().getClusters("nikon"));
        //         System.out.println(f.getTagsInterface().getListPhoto("6024664723"));
        //         System.out.println(f.getTagsInterface().getListUser("8308954@N06"));
        //         System.out.println(f.getTagsInterface().getListUserPopular("8308954@N06"));
        //         System.out.println(f.getTagsInterface().getListUserRaw(null));
        //         System.out.println(f.getTagsInterface().getRelated("nikon"));

        //         System.out.println(f.getTestInterface().login());
        //         f.getTestInterface().null_();
        //         System.out.println(f.getTestInterface().echo(Arrays.asList(
        //               new Parameter[]{new Parameter("hello", "nikon")})));

        //         System.out.println(f.getReflectionInterface().getMethods());
        //         System.out.println(f.getReflectionInterface().getMethodInfo("flickr.photos.delete"));

        //         System.out.println(f.getPhotosInterface().getAllContexts("5772049100"));
        //         System.out.println(f.getPhotosInterface().getContext("5772049100"));
        //         System.out.println(f.getPhotosInterface().getFavorites("5772049100", 0, 0));
        //         System.out.println(f.getPhotosInterface().getExif("5772049100", null));
        //         System.out.println(f.getPhotosInterface().getUntagged(0, 0));
        //         System.out.println(f.getPhotosInterface().getRecent(null, 0, 0));
        //System.out.println(f.getPhotosInterface().getContactsPhotos(10, false, false, false));
    } catch (Throwable e) {
        // TODO Auto-generated catch block
        LoggerFactory.getLogger(OAuthTest.class).error(e.getLocalizedMessage(), e);
    }
}

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 a 2 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 ww .  ja v  a  2s .com*/
 *
 * @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);
}

From source file:fr.inria.atlanmod.dag.instantiator.Launcher.java

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

    ResourceSetImpl resourceSet = new ResourceSetImpl();
    { // initializing the registry

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX,
                new EcoreResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME,
                NeoEMFResourceFactory.eINSTANCE);

    }//from ww w.j av  a2 s  .c  om

    Options options = new Options();

    configureOptions(options);

    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        //         String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS);
        //         
        //         LOGGER.info("Start loading the package");
        //         Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class);
        //         EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null);
        //         
        //         Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy"));
        //          metamodelResource.getContents().add(_package);
        //          LOGGER.info("Finish loading the package");

        int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE;
        if (commandLine.hasOption(SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(SIZE);
            size = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        float variation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION,
                        number.floatValue()));
            }
            variation = number.floatValue();
        }

        float propVariation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(PROP_VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}",
                        PROP_VARIATION, number.floatValue()));
            }
            propVariation = number.floatValue();
        }

        long seed = System.currentTimeMillis();
        if (commandLine.hasOption(SEED)) {
            seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
        }

        Range<Integer> range = Range.between(Math.round(size * (1 - variation)),
                Math.round(size * (1 + variation)));

        ISpecimenConfiguration config = new DagMetamodelConfig(range, seed);
        IGenerator generator = new DagGenerator(config, config.getSeed());

        GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(generator);

        if (commandLine.hasOption(OUTPUT_PATH)) {
            String outDir = commandLine.getOptionValue(OUTPUT_PATH);
            //java.net.URI intermediateURI = java.net.URI.create(outDir);
            modelGen.setSamplesPath(outDir);
        }

        int numberOfModels = 1;
        if (commandLine.hasOption(N_MODELS)) {
            numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
        }

        int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE);
            valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE;
        if (commandLine.hasOption(DEGREE)) {
            Number number = (Number) commandLine.getParsedOptionValue(DEGREE);
            referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        config.setValuesRange(Math.round(valuesSize * (1 - propVariation)),
                Math.round(valuesSize * (1 + propVariation)));

        config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        long start = System.currentTimeMillis();
        modelGen.runGeneration(resourceSet, numberOfModels, size, variation);
        long end = System.currentTimeMillis();
        LOGGER.info(
                MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000)));

        //         for (Resource rsc : resourceSet.getResources()) {
        //            if (rsc.getContents().get(0) instanceof DAG) {
        //               
        //            }
        //               
        //         }

        if (commandLine.hasOption(DIAGNOSE)) {
            for (Resource resource : resourceSet.getResources()) {
                LOGGER.info(
                        MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI()));
                BasicDiagnostic diagnosticChain = diagnoseResource(resource);
                if (!isFailed(diagnosticChain)) {
                    LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''",
                            resource.getURI()));
                } else {
                    LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''",
                            diagnosticChain.getChildren().size(), resource.getURI()));
                    for (Diagnostic diagnostic : diagnosticChain.getChildren()) {
                        LOGGER.fine(diagnostic.getMessage());
                    }
                }
            }
            LOGGER.info("Validation finished");
        }

    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80));
        } catch (Throwable t) {
            LOGGER.warning("Unable to get console information");
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
        System.exit(ERROR);
    } catch (Throwable t) {
        System.err.println("ERROR: " + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(t);
        LOGGER.severe(stringWriter.toString());
        System.exit(ERROR);
    }
}

From source file:fr.inria.atlanmod.instantiator.neoEMF.Launcher.java

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

    ResourceSetImpl resourceSet = new ResourceSetImpl();
    { // initializing the registry

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX,
                new EcoreResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME,
                NeoEMFResourceFactory.eINSTANCE);

    }//from  w  ww.  j  a  va2s. c om

    Options options = new Options();

    configureOptions(options);

    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS);

        LOGGER.info("Start loading the package");
        Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class);
        EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null);

        Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy"));
        metamodelResource.getContents().add(_package);
        LOGGER.info("Finish loading the package");

        int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE;
        if (commandLine.hasOption(SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(SIZE);
            size = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        float variation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION,
                        number.floatValue()));
            }
            variation = number.floatValue();
        }

        float propVariation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(PROP_VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}",
                        PROP_VARIATION, number.floatValue()));
            }
            propVariation = number.floatValue();
        }

        long seed = System.currentTimeMillis();
        if (commandLine.hasOption(SEED)) {
            seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
        }

        Range<Integer> range = Range.between(Math.round(size * (1 - variation)),
                Math.round(size * (1 + variation)));

        GenericMetamodelConfig config = new GenericMetamodelConfig(metamodelResource, range, seed);
        GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(config);

        if (commandLine.hasOption(OUTPUT_PATH)) {
            String outDir = commandLine.getOptionValue(OUTPUT_PATH);
            //java.net.URI intermediateURI = java.net.URI.create(outDir);
            modelGen.setSamplesPath(outDir);
        }

        int numberOfModels = 1;
        if (commandLine.hasOption(N_MODELS)) {
            numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
        }

        int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE);
            valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(DEGREE);
            referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        config.setValuesRange(Math.round(valuesSize * (1 - propVariation)),
                Math.round(valuesSize * (1 + propVariation)));

        config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        long start = System.currentTimeMillis();
        modelGen.runGeneration(resourceSet, numberOfModels, size, variation);
        long end = System.currentTimeMillis();
        LOGGER.info(
                MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000)));

        if (commandLine.hasOption(DIAGNOSE)) {
            for (Resource resource : resourceSet.getResources()) {
                LOGGER.info(
                        MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI()));
                BasicDiagnostic diagnosticChain = diagnoseResource(resource);
                if (!isFailed(diagnosticChain)) {
                    LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''",
                            resource.getURI()));
                } else {
                    LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''",
                            diagnosticChain.getChildren().size(), resource.getURI()));
                    for (Diagnostic diagnostic : diagnosticChain.getChildren()) {
                        LOGGER.fine(diagnostic.getMessage());
                    }
                }
            }
            LOGGER.info("Validation finished");
        }

    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80));
        } catch (Throwable t) {
            LOGGER.warning("Unable to get console information");
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
        System.exit(ERROR);
    } catch (ClassNotFoundException t) {
        System.err.println("ERROR: Unable to load class" + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(stringWriter.toString());
    } catch (Throwable t) {
        System.err.println("ERROR: " + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(t);
        LOGGER.severe(stringWriter.toString());
        System.exit(ERROR);
    }
}

From source file:org.sd.cluster.config.Admin.java

/**
 * common usages://w  w w .  j  a  v  a  2s.  co m
 * <br>
 * <p>  # deploy and start cluster
 * <p>  Admin -c &lt;cluster-name&gt; -d -s
 * <br>
 * <p>  # stop cluster
 * <p>  Admin -c &lt;cluster-name&gt; -k
 * <br>
 * <p>  # stop and purge cluster
 * <p>  Admin -c &lt;cluster-name&gt; -k -p
 *
 */
public static void main(String[] args) throws IOException {

    final PropertiesParser pp = new PropertiesParser(args, true);
    final Properties properties = pp.getProperties();
    args = pp.getArgs();

    final Options options = new Options();

    // define options
    options.addOption(OptionBuilder.withArgName("clusters").withLongOpt("set clusters root").hasArg()
            .isRequired(false).create('R'));
    options.addOption(OptionBuilder.withArgName("cluster").withLongOpt("set cluster").hasArg().isRequired(false)
            .create('c'));
    options.addOption(OptionBuilder.withArgName("machines").withLongOpt("set cluster machines").hasArg()
            .isRequired(false).create('m'));
    options.addOption(OptionBuilder.withArgName("nodes").withLongOpt("set targeted nodes").hasArg()
            .isRequired(false).create('n'));
    options.addOption(OptionBuilder.withArgName("gateway").withLongOpt("set cluster gateway").hasArg()
            .isRequired(false).create('g'));
    options.addOption(
            OptionBuilder.withArgName("user").withLongOpt("set user").hasArg().isRequired(false).create('u'));
    options.addOption(OptionBuilder.withArgName("heap").withLongOpt("set cluster heap memory").hasArg()
            .isRequired(false).create('h'));
    options.addOption(OptionBuilder.withArgName("root").withLongOpt("set cluster root (home) dir").hasArg()
            .isRequired(false).create('r'));
    options.addOption(OptionBuilder.withArgName("deploy").withLongOpt("deploy code to cluster")
            .isRequired(false).create('d'));
    options.addOption(
            OptionBuilder.withArgName("start").withLongOpt("start cluster").isRequired(false).create('s'));
    options.addOption(
            OptionBuilder.withArgName("stop").withLongOpt("stop cluster").isRequired(false).create('k'));
    options.addOption(
            OptionBuilder.withArgName("ping").withLongOpt("ping cluster").isRequired(false).create('a'));
    options.addOption(OptionBuilder.withArgName("jobs").withLongOpt("view jobs").isRequired(false).create('j'));
    options.addOption(
            OptionBuilder.withArgName("purge").withLongOpt("purge cluster").isRequired(false).create('p'));
    options.addOption(OptionBuilder.withArgName("execute").withLongOpt("execute cluster message")
            .isRequired(false).create('e'));
    options.addOption(OptionBuilder.withArgName("configure").withLongOpt("configure cluster").isRequired(false)
            .create('C'));

    // initialize parameters
    final CommandLineParser parser = new PosixParser();
    Admin admin = null;

    try {
        final CommandLine commandLine = parser.parse(options, args);

        // get args
        final String clustersDir = commandLine.getOptionValue('R'); // clusters directory (default Config.class/resources/clusters directory)
        final String clusterName = commandLine.getOptionValue('c');
        final String machines = commandLine.getOptionValue('m');
        final String nodes = commandLine.getOptionValue('n');
        final String gateway = commandLine.getOptionValue('g');
        final String userName = commandLine.getOptionValue('u');
        final String heapSize = commandLine.getOptionValue('h');
        final String rootDir = commandLine.getOptionValue('r'); // root directory for deployed cluster "~/cluster"

        final boolean deployOption = commandLine.hasOption('d');
        final boolean startOption = commandLine.hasOption('s');
        final boolean stopOption = commandLine.hasOption('k');
        final boolean pingOption = commandLine.hasOption('a');
        final boolean jobsOption = commandLine.hasOption('j');
        final boolean purgeOption = commandLine.hasOption('p');
        final boolean executeOption = commandLine.hasOption('e');
        final boolean configureOption = commandLine.hasOption('C'); // creat configuration files in ClusterDevDir
        //todo: implement execute option w/something like sendMessage only not static

        String[] theMachines = null;
        if (machines != null && machines.length() > 0) {
            theMachines = machines.split("\\s*,\\s*");
        }

        String[] theNodes = null;
        if (nodes != null && nodes.length() > 0) {
            theNodes = nodes.split("\\s*,\\s*");
        }

        if (rootDir != null) {
            ConfigUtil.setClusterRootDir(rootDir);
        }

        if (deployOption) {
            // when we deploy, we need to rely on environment settings, not
            // on the override file. If we have overridden and now are not
            // overriding, then this file needs to disappear for proper function.
            clearPortOverrideFile();
        }

        if (gateway != null && gateway.length() > 0) {
            properties.setProperty(ClusterDefinition.CLUSTER_GATEWAY_PROPERTY, gateway);
        }
        if (clustersDir != null && !"".equals(clustersDir.trim())) {
            properties.setProperty(ClusterDefinition.CLUSTERS_DIR_PROPERTY, clustersDir);
        }
        if (clusterName != null && clusterName.length() > 0) {
            properties.setProperty(ClusterDefinition.CLUSTER_DEFINITION_NAME_PROPERTY, clusterName);
        }
        if (machines != null && machines.length() > 0) {
            properties.setProperty(ClusterDefinition.CLUSTER_MACHINES_PROPERTY, machines);
        }
        if (userName != null && userName.length() > 0) {
            properties.setProperty(ClusterDefinition.CLUSTER_USER_PROPERTY, userName);
        }

        final ClusterRunner cr = new ClusterRunner(!deployOption, properties); // useActiveCluster unless deploying

        // check for valid clusterDef
        final ClusterDefinition clusterDef = cr.getClusterDefinition();
        if (clusterDef == null || !clusterDef.isValid()) {
            throw new IllegalArgumentException("Invalid or missing cluster named '" + clusterName + "'!");
        }

        //todo: configure dif't print stream than System.out
        admin = new Admin(clusterDef, System.out);

        // perform requested operations
        if (configureOption) {
            System.out.println("configuring cluster (only).");
            admin.configure(heapSize);
        } else {
            if (deployOption)
                admin.deploy(heapSize);
            if (startOption)
                admin.start(heapSize);
            if (stopOption)
                admin.stop(theNodes);
            if (pingOption)
                admin.ping(theNodes);
            if (jobsOption)
                admin.jobs(theNodes);
            if (purgeOption)
                admin.purge(theNodes);
        }
    } catch (ParseException e) {
        System.err.println("Command line error: " + e.getLocalizedMessage());
        e.printStackTrace(System.err);
        usage();
    } catch (IllegalArgumentException e) {
        System.err.println("argument error: " + e.getLocalizedMessage());
        e.printStackTrace(System.err);
        usage();
    } catch (Throwable t) {
        System.err.println("Unexpected error!:" + t.getLocalizedMessage());
        t.printStackTrace(System.err);
        //      usage();
    } finally {
        if (admin != null)
            admin.shutdown();
    }
}