Example usage for java.lang System setProperty

List of usage examples for java.lang System setProperty

Introduction

In this page you can find the example usage for java.lang System setProperty.

Prototype

public static String setProperty(String key, String value) 

Source Link

Document

Sets the system property indicated by the specified key.

Usage

From source file:au.edu.uws.eresearch.cr8it.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/* w ww .j av a  2 s. com*/
 */
public static void main(final String... args) {

    String contextFilePath = "spring-integration-context.xml";
    String configFilePath = "config/config-file.groovy";
    String environment = System.getProperty("environment");

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n          Welcome to C8it Integration!                 "
                + "\n                                                         "
                + "\n    For more information please visit:                   "
                + "\n    http://www.springsource.org/spring-integration       "
                + "\n                                                         "
                + "\n=========================================================");
    }

    ConfigObject config = Config.getConfig(environment, configFilePath);
    Map configMap = config.flatten();
    System.setProperty("environment", environment);
    System.setProperty("cr8it.client.config.file", (String) configMap.get("file.runtimePath"));

    //final AbstractApplicationContext context =
    //new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/*-context.xml");

    String absContextPath = "config/integration/" + contextFilePath;
    File contextFile = new File(absContextPath);
    final AbstractApplicationContext context;
    if (!contextFile.exists()) {
        absContextPath = "classpath:" + absContextPath;
        context = new ClassPathXmlApplicationContext(absContextPath);
    } else {
        absContextPath = "file:" + absContextPath;
        context = new FileSystemXmlApplicationContext(absContextPath);
    }

    context.registerShutdownHook();

    SpringIntegrationUtils.displayDirectories(context);

    final Scanner scanner = new Scanner(System.in);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n    Please press 'q + Enter' to quit the application.    "
                + "\n                                                         "
                + "\n=========================================================");
    }

    while (!scanner.hasNext("q")) {
        //Do nothing unless user presses 'q' to quit.
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Exiting application...bye.");
    }

    System.exit(0);

}

From source file:com.lfv.lanzius.Main.java

public static void main(String[] args) {

    /*//w  ww.  ja  v  a  2 s .  c om
     * debug levels:
     * error - Runtime errors or unexpected conditions. Expect these to be immediately visible on a status console. See also Internationalization.
     * warn  - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console. See also Internationalization.
     * info  - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum. See also Internationalization.
     * debug - detailed information on the flow through the system. Expect these to be written to logs only.
     */

    Log log = null;
    DOMConfigurator conf = new DOMConfigurator();
    DOMConfigurator.configure("data/properties/loggingproperties.xml");
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

    try {
        if (args.length >= 1) {
            // Help
            if (args[0].startsWith("-h")) {
                printUsage();
                return;
            }
            // List devices
            else if (args[0].startsWith("-l")) {
                AudioTest.listDevices();
                return;
            }
            // Test seleted device
            else if (args[0].startsWith("-d")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn");
                try {
                    String option = "all";
                    if (args.length >= 4)
                        option = args[3];

                    if (option.equals("loop:direct"))
                        AudioTest.testDevicesDirect(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
                    else {
                        if (option.indexOf("debug") != -1)
                            System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "debug");

                        AudioTest.testDevices(Integer.parseInt(args[1]), Integer.parseInt(args[2]), option,
                                (args.length >= 5) ? args[4] : null, (args.length >= 6) ? args[5] : null,
                                (args.length >= 7) ? args[6] : null);
                    }
                } catch (Exception ex) {
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println(
                            "  yada.jar -d output_device input_device <option> <jitter_buffer> <output_buffer> <input_buffer>");
                    System.out.println("  option:");
                    System.out.println("    all(default)");
                    System.out.println("    clip");
                    System.out.println("    loop:jspeex");
                    System.out.println("    loop:null");
                    System.out.println("    loop:direct");
                    System.out.println("    loopdebug:jspeex");
                    System.out.println("    loopdebug:null");
                    System.out.println("  jitter_buffer:");
                    System.out.println("    size of jitter buffer in packets (1-20)");
                    System.out.println("  output_buffer:");
                    System.out.println("    size of output buffer in packets (1.0-4.0)");
                    System.out.println("  input_buffer:");
                    System.out.println("    size of input buffer in packets (1.0-4.0)");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                //System.out.println("Exiting...");
                return;
            } else if (args[0].startsWith("-m")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn");
                try {
                    AudioTest.testMicrophoneLevel(Integer.parseInt(args[1]));
                } catch (Exception ex) {
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println("  yada.jar -m input_device");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                return;
            } else if (args[0].startsWith("-s")) {
                Packet.randomSeed = 9182736455L ^ System.currentTimeMillis();
                if (args.length > 2 && args[1].startsWith("-configuration")) {
                    String configFilename = args[2];
                    if (args.length > 4 && args[3].startsWith("-exercise")) {
                        String exerciseFilename = args[4];

                        LanziusServer.start(configFilename, exerciseFilename);
                    } else {
                        LanziusServer.start(configFilename);
                    }
                } else {
                    LanziusServer.start();
                }
                return;
            } else if (args[0].startsWith("-f")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty(
                        "org.apache.commons.logging.simplelog.log.com.lfv.lanzius.application.FootSwitchController",
                        "debug");
                try {
                    System.out.println("Starting footswitch controller test using device " + args[1]);
                    try {
                        boolean inverted = false;
                        if (args.length >= 3)
                            inverted = args[2].toLowerCase().startsWith("inv");
                        FootSwitchController c = new FootSwitchController(null, args[1],
                                Constants.PERIOD_FTSW_CONNECTED, inverted);
                        c.start();
                        Thread.sleep(30000);
                    } catch (UnsatisfiedLinkError err) {
                        if (args.length > 1)
                            System.out.println("UnsatisfiedLinkError: " + err.getMessage());
                        else
                            throw new ArrayIndexOutOfBoundsException();
                        System.out.println("Missing ftsw library (ftsw.dll or libftsw.so)");
                        if (!args[1].equalsIgnoreCase("ftdi"))
                            System.out
                                    .println("Missing rxtxSerial library (rxtxSerial.dll or librxtxSerial.so)");
                        if (AudioTest.showStackTrace)
                            err.printStackTrace();
                    }
                } catch (Exception ex) {
                    if (ex instanceof NoSuchPortException)
                        System.out.println("The serial port " + args[1] + " does not exist!");
                    else if (ex instanceof PortInUseException)
                        System.out.println("The serial port " + args[1] + " is already in use!");
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println("  yada.jar -f interface <invert>");
                    System.out.println("  interface:");
                    System.out.println("    ftdi");
                    System.out.println("    comport (COMx or /dev/ttyx)");
                    System.out.println("  invert:");
                    System.out.println("    true");
                    System.out.println("    false (default)");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                return;
            } else if (args[0].startsWith("-c")) {
                Packet.randomSeed = 7233103157L ^ System.currentTimeMillis();
                if (args.length >= 2) {
                    try {
                        int id = Integer.valueOf(args[1]);
                        if (id <= 0)
                            throw new NumberFormatException();
                        Controller c = Controller.getInstance();
                        if (args.length >= 3) {
                            if (args[2].equalsIgnoreCase("test")) {
                                c.setAutoTester(true);
                            }
                        }
                        c.init(id);
                        return;
                    } catch (NumberFormatException ex) {
                        printUsage();
                    }
                } else {
                    Controller.getInstance().init(0);
                }
            } else
                printUsage();
        } else
            printUsage();
    } catch (Throwable t) {
        if (log == null)
            log = LogFactory.getLog(Main.class);
        log.error("Unhandled exception or error", t);
    }
}

From source file:edu.ehu.galan.lite.Example.java

public static void main(String[] args) {
    //initizalize ehcache system
    System.setProperty("net.sf.ehcache.enableShutdownHook", "true");
    if (CacheManager.getCacheManager("ehcacheLitet.xml") == null) {
        CacheManager.create("ehcacheLitet.xml");
    }/*from   w ww  .  jav a 2 s . c  o  m*/
    cache = CacheManager.getInstance().getCache("LiteCache");
    //load the corpus to process
    Corpus corpus = new Corpus("en");
    //we spedify the directory and the database mapping (wikipedia in this case)
    corpus.loadCorpus("testCorpus", Document.SourceType.wikipedia);
    //will read the document using Illinois NLP utilities
    PlainTextDocumentReaderLBJEn parser = new PlainTextDocumentReaderLBJEn();
    AlgorithmRunner runner = new AlgorithmRunner();
    String resources = System.getProperty("user.dir") + "/resources/";
    //algorithms initializacion
    CValueAlgortithm cvalue = new CValueAlgortithm();
    cvalue.addNewProcessingFilter(new AdjPrepNounFilter());
    TFIDFAlgorithm tf = new TFIDFAlgorithm(new CaseStemmer(CaseStemmer.CaseType.lowercase), "en");
    ShallowParsingGrammarAlgortithm sha = new ShallowParsingGrammarAlgortithm(
            System.getProperty("user.dir") + "/resources/lite/" + "grammars/Cg2EnGrammar.grammar", "cg3/");
    KPMinerAlgorithm kp = new KPMinerAlgorithm();
    RakeAlgorithm ex = new RakeAlgorithm();
    ex.loadStopWordsList("resources/lite/stopWordLists/RakeStopLists/SmartStopListEn");
    ex.loadPunctStopWord("resources/lite/stopWordLists/RakeStopLists/RakePunctDefaultStopList");
    //algorithm submitting to execute them in parallel
    runner.submitAlgorithm(kp);
    runner.submitAlgorithm(cvalue);
    runner.submitAlgorithm(tf);
    runner.submitAlgorithm(ex);
    runner.submitAlgorithm(sha);
    //load stop list
    List<String> standardStop = null;
    try {
        standardStop = Files.readAllLines(Paths.get(resources + "lite/stopWordLists/standardStopList"),
                StandardCharsets.UTF_8);

    } catch (IOException e1x) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, e1x);
    }
    //initialize Wikiminer helper (class that interacts with Wikiminer services)
    WikiminnerHelper helper = WikiminnerHelper.getInstance(resources);
    helper.setLanguage("en");
    //we may operate in local mode (using Wikiminer as API instead of interacting via REST api
    // helper.setLocalMode(false,"/home/angel/nfs/wikiminer/configs/wikipedia");
    WikiMinerMap wikimapping = new WikiMinerMap(resources, helper);
    CValueWikiDisambiguator disambiguator = new CValueWikiDisambiguator(resources, helper);
    CValueWikiRelationship relate = new CValueWikiRelationship(resources, helper);
    WikipediaData data = new WikipediaData(resources, helper);
    helper.openConnection();
    //process all the documents in the corpus
    while (!corpus.getDocQueue().isEmpty()) {
        Document doc = corpus.getDocQueue().poll();
        doc.setSource(Document.SourceType.wikipedia);
        parser.readSource(doc.getPath());
        doc.setSentenceList(parser.getSentenceList());
        doc.setTokenList(parser.getTokenizedSentenceList());
        System.out.println(doc.getName());
        runner.runAlgorihms(doc, resources);
        doc.applyGlobalStopWordList(standardStop);
        doc.mapThreshold(1.9f, new String[] { "CValue" });
        doc.mapThreshold(0.00034554f, new String[] { "TFIDF" });
        doc.removeAndMixTerms();
        //map document
        wikimapping.mapCorpus(doc);
        disambiguator.disambiguateTopics(doc);
        //we may disambiguate topics that do not disambiguated correctly
        DuplicateRemoval.disambiguationRemoval(doc);
        DuplicateRemoval.topicDuplicateRemoval(doc);
        //obtain the wiki links,labels, etc
        data.processDocument(doc);
        //measure domain relatedness
        relate.relate(doc);
        //save the results
        Document.saveJsonToDir("", doc);
    }
    //close wikiminer connection and caches
    helper.closeConnection();
    cache.dispose();
    CacheManager.getInstance().shutdown();
    System.exit(0);
}

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

public static void main(String[] args) {
    userDir = System.getProperty("user.dir");
    resourceDir = null;/*w  w  w .  ja v  a2s .  c  o m*/
    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:hdfs.MiniHDFS.java

public static void main(String[] args) throws Exception {
    if (args.length != 1 && args.length != 3) {
        throw new IllegalArgumentException(
                "Expected: MiniHDFS <baseDirectory> [<kerberosPrincipal> <kerberosKeytab>], " + "got: "
                        + Arrays.toString(args));
    }//from  w  w w. j  av  a  2  s.  com
    boolean secure = args.length == 3;

    // configure Paths
    Path baseDir = Paths.get(args[0]);
    // hadoop-home/, so logs will not complain
    if (System.getenv("HADOOP_HOME") == null) {
        Path hadoopHome = baseDir.resolve("hadoop-home");
        Files.createDirectories(hadoopHome);
        System.setProperty("hadoop.home.dir", hadoopHome.toAbsolutePath().toString());
    }
    // hdfs-data/, where any data is going
    Path hdfsHome = baseDir.resolve("hdfs-data");

    // configure cluster
    Configuration cfg = new Configuration();
    cfg.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsHome.toAbsolutePath().toString());
    // lower default permission: TODO: needed?
    cfg.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_PERMISSION_KEY, "766");

    // optionally configure security
    if (secure) {
        String kerberosPrincipal = args[1];
        String keytabFile = args[2];

        cfg.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
        cfg.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, "true");
        cfg.set(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_DATANODE_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY, keytabFile);
        cfg.set(DFSConfigKeys.DFS_DATANODE_KEYTAB_FILE_KEY, keytabFile);
        cfg.set(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, "true");
        cfg.set(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, "true");
        cfg.set(DFSConfigKeys.IGNORE_SECURE_PORTS_FOR_TESTING_KEY, "true");
    }

    UserGroupInformation.setConfiguration(cfg);

    // TODO: remove hardcoded port!
    MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(cfg);
    if (secure) {
        builder.nameNodePort(9998);
    } else {
        builder.nameNodePort(9999);
    }
    MiniDFSCluster dfs = builder.build();

    // Configure contents of the filesystem
    org.apache.hadoop.fs.Path esUserPath = new org.apache.hadoop.fs.Path("/user/elasticsearch");
    try (FileSystem fs = dfs.getFileSystem()) {

        // Set the elasticsearch user directory up
        fs.mkdirs(esUserPath);
        if (UserGroupInformation.isSecurityEnabled()) {
            List<AclEntry> acls = new ArrayList<>();
            acls.add(new AclEntry.Builder().setType(AclEntryType.USER).setName("elasticsearch")
                    .setPermission(FsAction.ALL).build());
            fs.modifyAclEntries(esUserPath, acls);
        }

        // Install a pre-existing repository into HDFS
        String directoryName = "readonly-repository";
        String archiveName = directoryName + ".tar.gz";
        URL readOnlyRepositoryArchiveURL = MiniHDFS.class.getClassLoader().getResource(archiveName);
        if (readOnlyRepositoryArchiveURL != null) {
            Path tempDirectory = Files.createTempDirectory(MiniHDFS.class.getName());
            File readOnlyRepositoryArchive = tempDirectory.resolve(archiveName).toFile();
            FileUtils.copyURLToFile(readOnlyRepositoryArchiveURL, readOnlyRepositoryArchive);
            FileUtil.unTar(readOnlyRepositoryArchive, tempDirectory.toFile());

            fs.copyFromLocalFile(true, true,
                    new org.apache.hadoop.fs.Path(
                            tempDirectory.resolve(directoryName).toAbsolutePath().toUri()),
                    esUserPath.suffix("/existing/" + directoryName));

            FileUtils.deleteDirectory(tempDirectory.toFile());
        }
    }

    // write our PID file
    Path tmp = Files.createTempFile(baseDir, null, null);
    String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    Files.write(tmp, pid.getBytes(StandardCharsets.UTF_8));
    Files.move(tmp, baseDir.resolve(PID_FILE_NAME), StandardCopyOption.ATOMIC_MOVE);

    // write our port file
    tmp = Files.createTempFile(baseDir, null, null);
    Files.write(tmp, Integer.toString(dfs.getNameNodePort()).getBytes(StandardCharsets.UTF_8));
    Files.move(tmp, baseDir.resolve(PORT_FILE_NAME), StandardCopyOption.ATOMIC_MOVE);
}

From source file:com.athena.peacock.agent.Starter.java

/**
 * <pre>//from   w  w  w .j a  v a  2s . c  om
 * 
 * </pre>
 * @param args
 */
@SuppressWarnings("resource")
public static void main(String[] args) {

    int rand = (int) (Math.random() * 100) % 50;
    System.setProperty("random.seconds", Integer.toString(rand));

    String configFile = null;

    try {
        configFile = PropertyUtil.getProperty(PeacockConstant.CONFIG_FILE_KEY);
    } catch (Exception e) {
        // nothing to do.
    } finally {
        if (StringUtils.isEmpty(configFile)) {
            configFile = "/peacock/agent/config/agent.conf";
        }
    }

    /**
     * ${peacock.agent.config.file.name} ?? load  ? ??   ? ?  ? .
     */
    String errorMsg = "\n\"" + configFile + "\" file does not exist or cannot read.\n" + "Please check \""
            + configFile + "\" file exists and can read.";

    Assert.isTrue(AgentConfigUtil.exception == null, errorMsg);
    Assert.notNull(AgentConfigUtil.getConfig(PeacockConstant.SERVER_IP), "ServerIP cannot be empty.");
    Assert.notNull(AgentConfigUtil.getConfig(PeacockConstant.SERVER_PORT), "ServerPort cannot be empty.");

    /**
     * Agent ID ??  ${peacock.agent.agent.file.name} ?   ?, 
     *  ?? ?   Agent ID ? ?? .
     */
    String agentFile = null;
    String agentId = null;

    try {
        agentFile = PropertyUtil.getProperty(PeacockConstant.AGENT_ID_FILE_KEY);
    } catch (Exception e) {
        // nothing to do.
    } finally {
        if (StringUtils.isEmpty(agentFile)) {
            agentFile = "/peacock/agent/.agent";
        }
    }

    File file = new File(agentFile);
    boolean isNew = false;

    if (file.exists()) {
        try {
            agentId = IOUtils.toString(file.toURI());

            // ? ? agent ID  agent ID? ? 36? ?   ?.
            if (StringUtils.isEmpty(agentId) || agentId.length() != 36) {
                throw new IOException();
            }
        } catch (IOException e) {
            logger.error(agentFile + " file cannot read or saved invalid agent ID.", e);

            agentId = PeacockAgentIDGenerator.generateId();
            isNew = true;
        }
    } else {
        agentId = PeacockAgentIDGenerator.generateId();
        isNew = true;
    }

    if (isNew) {
        logger.info("New Agent-ID({}) be generated.", agentId);

        try {
            file.setWritable(true);
            OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(file));
            output.write(agentId);
            file.setReadOnly();
            IOUtils.closeQuietly(output);
        } catch (UnsupportedEncodingException e) {
            logger.error("UnsupportedEncodingException has occurred : ", e);
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException has occurred : ", e);
        } catch (IOException e) {
            logger.error("IOException has occurred : ", e);
        }
    }

    // Spring Application Context Loading
    logger.debug("Starting application context...");
    AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "classpath:spring/context-*.xml");
    applicationContext.registerShutdownHook();
}

From source file:edu.mit.fss.examples.TDRSSFederate.java

/**
 * The main method. This configures the Orekit data path, creates the
 * SaudiComsat federate objects and launches the associated graphical user
 * interface.//from  w  w w. ja  v a 2  s  .  c om
 *
 * @param args the arguments
 * @throws RTIexception the RTI exception
 * @throws URISyntaxException 
 */
public static void main(String[] args) throws RTIexception, URISyntaxException {
    BasicConfigurator.configure();

    logger.debug("Setting Orekit data path.");
    System.setProperty(DataProvidersManager.OREKIT_DATA_PATH,
            new File(TDRSSFederate.class.getResource("/orekit-data.zip").toURI()).getAbsolutePath());

    logger.trace("Creating federate instance.");
    final TDRSSFederate federate = new TDRSSFederate();

    logger.trace("Setting minimum step duration and time step.");
    long timeStep = 60 * 1000, minimumStepDuration = 100;
    federate.setMinimumStepDuration(minimumStepDuration);
    federate.setTimeStep(timeStep);

    logger.debug("Loading TLE data from file.");
    final List<Component> panels = new ArrayList<Component>();
    for (String satName : Arrays.asList("TDRS 3", "TDRS 5", "TDRS 6", "TDRS 7", "TDRS 8", "TDRS 9", "TDRS 10",
            "TDRS 11")) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    federate.getClass().getClassLoader().getResourceAsStream("edu/mit/fss/examples/data.tle")));

            while (br.ready()) {
                if (br.readLine().matches(".*" + satName + ".*")) {
                    logger.debug("Found " + satName + " data.");

                    logger.trace("Adding " + satName + " supplier space system.");
                    SpaceSystem system = new SpaceSystem(satName, new TLE(br.readLine(), br.readLine()),
                            5123e3);
                    federate.addObject(system);

                    panels.add(new SpaceSystemPanel(federate, system));

                    try {
                        logger.trace("Setting inital time.");
                        federate.setInitialTime(system.getInitialState().getDate()
                                .toDate(TimeScalesFactory.getUTC()).getTime());
                    } catch (IllegalArgumentException | OrekitException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                    break;
                }
            }
            br.close();
        } catch (IllegalArgumentException | OrekitException | IOException e) {
            e.printStackTrace();
            logger.fatal(e);
        }
    }

    try {
        logger.trace("Adding WSGT ground station.");
        SurfaceSystem wsgt = new SurfaceSystem("WSGT",
                new GeodeticPoint(FastMath.toRadians(32.5007), FastMath.toRadians(-106.6086), 1474),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(wsgt);
        panels.add(new SurfaceSystemPanel(federate, wsgt));

        logger.trace("Adding STGT ground station.");
        SurfaceSystem stgt = new SurfaceSystem("STGT",
                new GeodeticPoint(FastMath.toRadians(32.5430), FastMath.toRadians(-106.6120), 1468),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(stgt);
        panels.add(new SurfaceSystemPanel(federate, stgt));

        logger.trace("Adding GRGT ground station.");
        SurfaceSystem grgt = new SurfaceSystem("GRGT",
                new GeodeticPoint(FastMath.toRadians(13.6148), FastMath.toRadians(144.8565), 142),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(grgt);
        panels.add(new SurfaceSystemPanel(federate, grgt));
    } catch (OrekitException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    logger.debug("Launching the graphical user interface.");
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                MemberFrame frame = new MemberFrame(federate, new MultiComponentPanel(panels));
                frame.pack();
                frame.setVisible(true);
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    logger.trace("Setting federate name, type, and FOM path.");
    federate.getConnection().setFederateName("TDRSS");
    federate.getConnection().setFederateType("FSS Supplier");
    federate.getConnection().setFederationName("FSS");
    federate.getConnection().setFomPath(
            new File(federate.getClass().getClassLoader().getResource("edu/mit/fss/hla/fss.xml").toURI())
                    .getAbsolutePath());
    federate.getConnection().setOfflineMode(false);
    federate.connect();
}

From source file:ch.astina.hesperid.agentbundle.Agent.java

public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("Usage: java -server agentbundle.jar configuration.xml");
        return;/*from   www . j a v  a2  s. c o m*/
    }

    try {
        XMLConfiguration xmlConfiguration = new XMLConfiguration(args[0]);
        Agent agent = new Agent(xmlConfiguration);
        agent.run();
    } catch (ConfigurationException e) {
        logger.error("Error while creating agent", e);
    } catch (Exception e) {
        logger.error("Error while creating agent", e);
    }

    System.setProperty("http.maxConnections", "1");
    System.setProperty("http.keepAlive", "false");
}

From source file:edu.mit.fss.examples.ISSFederate.java

/**
 * The main method. This configures the Orekit data path, creates the 
 * ISS federate objects and launches the associated graphical user 
 * interface.// w  w w .  j av a  2s  .c  om
 *
 * @param args the arguments
 * @throws RTIexception the RTI exception
 * @throws URISyntaxException 
 */
public static void main(String[] args) throws RTIexception, URISyntaxException {
    BasicConfigurator.configure();

    boolean headless = false;

    logger.debug("Setting Orekit data path.");
    System.setProperty(DataProvidersManager.OREKIT_DATA_PATH,
            new File(ISSFederate.class.getResource("/orekit-data.zip").toURI()).getAbsolutePath());

    logger.trace("Creating federate instance.");
    final ISSFederate federate = new ISSFederate();

    logger.trace("Setting minimum step duration and time step.");
    long timeStep = 60 * 1000, minimumStepDuration = 100;
    federate.setMinimumStepDuration(minimumStepDuration);
    federate.setTimeStep(timeStep);

    try {
        logger.debug("Loading TLE data from file.");
        BufferedReader br = new BufferedReader(new InputStreamReader(
                federate.getClass().getClassLoader().getResourceAsStream("edu/mit/fss/examples/data.tle")));

        final SpaceSystem satellite;
        final SurfaceSystem station1, station2, station3;

        while (br.ready()) {
            if (br.readLine().matches(".*ISS.*")) {
                logger.debug("Found ISS data.");

                logger.trace("Adding FSS supplier space system.");
                satellite = new SpaceSystem("FSS Supplier", new TLE(br.readLine(), br.readLine()), 5123e3);
                federate.addObject(satellite);

                logger.trace("Adding Keio ground station.");
                station1 = new SurfaceSystem("Keio",
                        new GeodeticPoint(FastMath.toRadians(35.551929), FastMath.toRadians(139.647119), 300),
                        satellite.getState().getDate(), 5123e3, 5);
                federate.addObject(station1);

                logger.trace("Adding SkolTech ground station.");
                station2 = new SurfaceSystem("SkolTech",
                        new GeodeticPoint(FastMath.toRadians(55.698679), FastMath.toRadians(37.571994), 200),
                        satellite.getState().getDate(), 5123e3, 5);
                federate.addObject(station2);

                logger.trace("Adding MIT ground station.");
                station3 = new SurfaceSystem("MIT",
                        new GeodeticPoint(FastMath.toRadians(42.360184), FastMath.toRadians(-71.093742), 100),
                        satellite.getState().getDate(), 5123e3, 5);
                federate.addObject(station3);

                try {
                    logger.trace("Setting inital time.");
                    federate.setInitialTime(
                            satellite.getInitialState().getDate().toDate(TimeScalesFactory.getUTC()).getTime());
                } catch (IllegalArgumentException | OrekitException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (!headless) {
                    logger.debug("Launching the graphical user interface.");
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            MemberFrame frame = new MemberFrame(federate,
                                    new MultiComponentPanel(
                                            Arrays.asList(new SpaceSystemPanel(federate, satellite),
                                                    new SurfaceSystemPanel(federate, station1),
                                                    new SurfaceSystemPanel(federate, station2),
                                                    new SurfaceSystemPanel(federate, station3))));
                            frame.pack();
                            frame.setVisible(true);
                        }
                    });
                }

                break;
            }
        }
        br.close();
    } catch (InvocationTargetException | InterruptedException | OrekitException | IOException e) {
        e.printStackTrace();
        logger.fatal(e);
    }

    logger.trace("Setting federate name, type, and FOM path.");
    federate.getConnection().setFederateName("ISS");
    federate.getConnection().setFederateType("FSS Supplier");
    federate.getConnection().setFederationName("FSS");
    federate.getConnection().setFomPath(
            new File(federate.getClass().getClassLoader().getResource("edu/mit/fss/hla/fss.xml").toURI())
                    .getAbsolutePath());
    federate.getConnection().setOfflineMode(false);
    federate.connect();

    if (headless) {
        federate.setMinimumStepDuration(10);
        federate.initialize();
        federate.run();
    }
}

From source file:com.epam.reportportal.auth.AuthServerApplication.java

public static void main(String[] args) {
    Optional.ofNullable(System.getenv("rp.profiles"))
            .ifPresent(p -> System.setProperty("spring.profiles.active", p));
    SpringApplication.run(AuthServerApplication.class, args);
}