List of usage examples for java.io File getPath
public String getPath()
From source file:com.rjfun.cordova.httpd.NanoHTTPD.java
/** * Starts as a standalone file server and waits for Enter. *//*from w ww . ja va2 s .c om*/ public static void main(String[] args) { PrintStream myOut = System.out; PrintStream myErr = System.err; myOut.println("NanoHTTPD 1.25 (C) 2001,2005-2011 Jarno Elonen and (C) 2010 Konstantinos Togias\n" + "(Command line options: [-p port] [-d root-dir] [--licence])\n"); // Defaults int port = 80; File wwwroot = new File(".").getAbsoluteFile(); // Show licence if requested for (int i = 0; i < args.length; ++i) if (args[i].equalsIgnoreCase("-p")) port = Integer.parseInt(args[i + 1]); else if (args[i].equalsIgnoreCase("-d")) wwwroot = new File(args[i + 1]).getAbsoluteFile(); else if (args[i].toLowerCase().endsWith("licence")) { myOut.println(LICENCE + "\n"); break; } try { new NanoHTTPD(port, new AndroidFile(wwwroot.getPath())); } catch (IOException ioe) { myErr.println("Couldn't start server:\n" + ioe); System.exit(-1); } myOut.println("Now serving files in port " + port + " from \"" + wwwroot + "\""); myOut.println("Hit Enter to stop.\n"); try { System.in.read(); } catch (Throwable t) { } }
From source file:edu.oregonstate.eecs.mcplan.domains.cosmic.experiments.CosmicExperiments.java
/** * @param args// w w w . ja va 2 s.c o m * @throws IOException * @throws FileNotFoundException */ public static void main(final String[] args) throws FileNotFoundException, IOException { System.out.println("[Es beginnt!]"); final String experiment_file = args[0]; final File root_directory; if (args.length > 1) { root_directory = new File(args[1]); } else { root_directory = new File("."); } final CsvConfigurationParser csv_config = new CsvConfigurationParser(new FileReader(experiment_file)); final String experiment_name = FilenameUtils.getBaseName(experiment_file); final File expr_directory = new File(root_directory, experiment_name); expr_directory.mkdirs(); final KeyValueStore expr_config = csv_config.get(0); final Configuration config = new Configuration(root_directory.getPath(), experiment_name, expr_config); // Configure loggers LogAgent.setLevel(Level.valueOf(config.get("log.agent"))); LogDomain.setLevel(Level.valueOf(config.get("log.domain"))); LogWorld.setLevel(Level.valueOf(config.get("log.world"))); LogAgent.warn("log.agent working"); LogDomain.warn("log.domain working"); LogWorld.warn("log.world working"); try (final CosmicMatlabInterface cosmic = new CosmicMatlabInterface()) { System.out.println("[Matlab is alive]"); // Initialize Cosmic final CosmicMatlabInterface.Problem cosmic_case = config.createCase(cosmic); final CosmicParameters params = cosmic_case.params; LogDomain.info("params: {}", cosmic_case.params); LogDomain.info("s0: {}", cosmic_case.s0); LogDomain.info("s0.ps: {}", cosmic_case.s0.ps); try (final WorldTrajectoryConsumer data_out = new WorldTrajectoryConsumer(config, params)) { for (int episode = 0; episode < config.getInt("Nepisodes"); ++episode) { final CosmicState s = cosmic_case.s0.copy(); // Simulator final RandomGenerator world_rng = new MersenneTwister(config.getInt("seed.world")); final CosmicTransitionSimulator world = new CosmicTransitionSimulator("world", params); world.addSimulationListener(new SimulationListener<CosmicState, CosmicAction>() { int t = 0; @Override public void onInitialStateSample(final StateNode<CosmicState, CosmicAction> s0) { t = 0; LogWorld.info("world: t : {}", t); LogWorld.info("world: s : {}", s0.s); LogWorld.info("world: s.r: {}", s0.r); } @Override public void onTransitionSample(final ActionNode<CosmicState, CosmicAction> trans) { LogWorld.info("world: a : {}", trans.a); LogWorld.info("world: a.r: {}", trans.r); final StateNode<CosmicState, CosmicAction> sprime = Fn.head(trans.successors()); t += 1; LogWorld.info("world: t : {}", t); LogWorld.debug("world: s : {}", sprime.s); LogWorld.info("world: s.r: {}", sprime.r); // Note: show_memory() will cause a crash on the cluster! // cosmic.show_memory(); } }); // Agent final RandomGenerator agent_rng = new MersenneTwister(config.getInt("seed.agent")); final Policy<CosmicState, CosmicAction> agent = config.createAgent(agent_rng, params); // Fault scenario final CosmicAction fault_action; if (config.branch_set.length > 0) { fault_action = new TripBranchSetAction(config.branch_set); } else { fault_action = new CosmicNothingAction(); } // Note: 'Tstable - 1' because we want the agent to start // acting at t = Tstable. final Policy<CosmicState, CosmicAction> fault = new FaultPolicy(fault_action, config.Tstable - 1); // Top-level control policy final List<Policy<CosmicState, CosmicAction>> seq = new ArrayList<>(); seq.add(fault); seq.add(agent); final int[] switch_times = new int[] { config.Tstable }; final Policy<CosmicState, CosmicAction> pi = new SequencePolicy<>(seq, switch_times); // Do episode data_out.beginEpisode(world, episode); world.sampleTrajectory(world_rng, s, pi, config.T); data_out.endEpisode(); System.out.println("[Episode " + episode + " ok]"); } // for each episode } // RAII for data_out } // RAII for cosmic interface System.out.println("[Alles gut!]"); }
From source file:com.clustercontrol.agent.Agent.java
/** * ?//from w w w.j av a 2 s . c o m * * @param args ?? */ public static void main(String[] args) throws Exception { // ? if (args.length != 1) { System.out.println("Usage : java Agent [Agent.properties File Path]"); System.exit(1); } try { // System m_log.info("starting Hinemos Agent..."); m_log.info("java.vm.version = " + System.getProperty("java.vm.version")); m_log.info("java.vm.vendor = " + System.getProperty("java.vm.vendor")); m_log.info("java.home = " + System.getProperty("java.home")); m_log.info("os.name = " + System.getProperty("os.name")); m_log.info("os.arch = " + System.getProperty("os.arch")); m_log.info("os.version = " + System.getProperty("os.version")); m_log.info("user.name = " + System.getProperty("user.name")); m_log.info("user.dir = " + System.getProperty("user.dir")); m_log.info("user.country = " + System.getProperty("user.country")); m_log.info("user.language = " + System.getProperty("user.language")); m_log.info("file.encoding = " + System.getProperty("file.encoding")); // System(SET) String limitKey = "jdk.xml.entityExpansionLimit"; // TODO JRE??????????????????? System.setProperty(limitKey, "0"); m_log.info(limitKey + " = " + System.getProperty(limitKey)); // TODO ???agentHome // ?????????? File file = new File(args[0]); agentHome = file.getParentFile().getParent() + "/"; m_log.info("agentHome=" + agentHome); // long startDate = HinemosTime.currentTimeMillis(); m_log.info("start date = " + new Date(startDate) + "(" + startDate + ")"); agentInfo.setStartupTime(startDate); // Agent?? m_log.info("Agent.properties = " + args[0]); // ? File scriptDir = new File(agentHome + "script/"); if (scriptDir.exists()) { File[] listFiles = scriptDir.listFiles(); if (listFiles != null) { for (File f : listFiles) { boolean ret = f.delete(); if (ret) { m_log.debug("delete script : " + f.getName()); } else { m_log.warn("delete script error : " + f.getName()); } } } else { m_log.warn("listFiles is null"); } } else { //???????? boolean ret = scriptDir.mkdir(); if (!ret) { m_log.warn("mkdir error " + scriptDir.getPath()); } } // queue? m_sendQueue = new SendQueue(); // Agent? Agent agent = new Agent(args[0]); //----------------- //-- //----------------- m_log.debug("exec() : create topic "); m_receiveTopic = new ReceiveTopic(m_sendQueue); m_receiveTopic.setName("ReceiveTopicThread"); m_log.info("receiveTopic start 1"); m_receiveTopic.start(); m_log.info("receiveTopic start 2"); // ? agent.exec(); m_log.info("Hinemos Agent started"); // ? agent.waitAwakeAgent(); } catch (Throwable e) { m_log.error("Agent.java: Runtime Exception Occurred. " + e.getClass().getName() + ", " + e.getMessage(), e); } }
From source file:edu.oregonstate.eecs.mcplan.search.fsss.experiments.FsssJairExperiments.java
public static void main(final String[] args) throws Exception { final String experiment_file = args[0]; final File root_directory; if (args.length > 1) { root_directory = new File(args[1]); } else {//from ww w .j a va 2s . c o m root_directory = new File("."); } final CsvConfigurationParser csv_config = new CsvConfigurationParser(new FileReader(experiment_file)); final String experiment_name = FilenameUtils.getBaseName(experiment_file); final File expr_directory = new File(root_directory, experiment_name); expr_directory.mkdirs(); for (int expr = 0; expr < csv_config.size(); ++expr) { final KeyValueStore expr_config = csv_config.get(expr); final Configuration config = new Configuration(root_directory.getPath(), experiment_name, expr_config); LoggerManager.getLogger("log.domain").setLevel(Level.valueOf(config.get("log.domain"))); LoggerManager.getLogger("log.search").setLevel(Level.valueOf(config.get("log.search"))); final GsonBuilder gson_builder = new GsonBuilder(); if (config.getBoolean("log.history.pretty")) { gson_builder.setPrettyPrinting(); } if ("advising".equals(config.domain)) { final File domain = new File(config.get("rddl.domain") + ".rddl"); final File instance = new File(config.get("rddl.instance") + ".rddl"); final int max_grade = config.getInt("advising.max_grade"); final int passing_grade = config.getInt("advising.passing_grade"); final AdvisingParameters params = AdvisingRddlParser.parse(max_grade, passing_grade, domain, instance); final AdvisingFsssModel model = new AdvisingFsssModel(config.rng_world, params); runGames(config, model, expr); } // else if( "cliffworld".equals( config.domain ) ) { // final CliffWorld.FsssModel model = new CliffWorld.FsssModel( config.rng_world, config ); // runGames( config, model, expr ); // } else if ("crossing".equals(config.domain)) { final File domain = new File(config.get("rddl.domain") + ".rddl"); final File instance = new File(config.get("rddl.instance") + ".rddl"); final IpcCrossingState s0 = IpcCrossingDomains.parse(domain, instance); final IpcCrossingFsssModel model = new IpcCrossingFsssModel(config.rng_world, s0); runGames(config, model, expr); } else if ("elevators".equals(config.domain)) { final File domain = new File(config.get("rddl.domain") + ".rddl"); final File instance = new File(config.get("rddl.instance") + ".rddl"); final IpcElevatorsState s0 = IpcElevatorsDomains.parse(domain, instance); final IpcElevatorsFsssModel model = new IpcElevatorsFsssModel(config.rng_world, s0); runGames(config, model, expr); } // else if( "firegirl".equals( config.domain ) ) { // final int T = config.getInt( "firegirl.T" ); // final double discount = config.getDouble( "discount" ); // final FactoredRepresenter<FireGirlState, ? extends FactoredRepresentation<FireGirlState>> base_repr; // if( "local".equals( config.get( "firegirl.repr" ) ) ) { // base_repr = new FireGirlLocalFeatureRepresenter(); // } // else { // throw new IllegalArgumentException( "firegirl.repr" ); // } // final FireGirlParameters params = new FireGirlParameters( T, discount, base_repr ); // final FireGirlFsssModel model = new FireGirlFsssModel( params, config.rng_world ); // runGames( config, model, expr ); // } // else if( "inventory".equals( config.domain ) ) { // final String problem_name = config.get( "inventory.problem" ); // final InventoryProblem problem; // if( "Dependent".equals( problem_name ) ) { // problem = InventoryProblem.Dependent(); // } // else if( "Geometric".equals( problem_name ) ) { // problem = InventoryProblem.Geometric(); // } // else if( "Geometric2".equals( problem_name ) ) { // problem = InventoryProblem.Geometric2(); // } // else if( "TwoProducts".equals( problem_name ) ) { // problem = InventoryProblem.TwoProducts(); // } // else { // throw new IllegalArgumentException( "inventory.problem" ); // } // final InventoryFsssModel model = new InventoryFsssModel( config.rng_world, problem ); // runGames( config, model, expr ); // } else if ("racegrid".equals(config.domain)) { final String circuit = config.get("racegrid.circuit"); final int scale = config.getInt("racegrid.scale"); final int T = config.getInt("racegrid.T"); final RacegridState ex; if ("bbs_small".equals(circuit)) { ex = RacegridCircuits.barto_bradtke_singh_SmallTrack(config.rng_world, T, scale); } else if ("bbs_large".equals(circuit)) { ex = RacegridCircuits.barto_bradtke_singh_LargeTrack(config.rng_world, T, scale); } else { throw new IllegalArgumentException("racegrid.circuit"); } final double slip = config.getDouble("racegrid.slip"); final RacegridFsssModel model = new RacegridFsssModel(config.rng_world, ex, slip); runGames(config, model, expr); } // else if( "rally".equals( config.domain ) ) { // final RallyWorld.Parameters params = new RallyWorld.Parameters( config.rng_world, config ); // final RallyWorld.FsssModel model = new RallyWorld.FsssModel( params ); // runGames( config, model, expr ); // } else if ("relevant_irrelevant".equals(config.domain)) { final RelevantIrrelevant.Parameters params = new RelevantIrrelevant.Parameters(config); final RelevantIrrelevant.FsssModel model = new RelevantIrrelevant.FsssModel(config.rng_world, params); runGames(config, model, expr); } else if ("sailing".equals(config.domain)) { final String world = config.get("sailing.world"); final int V = config.getInt("sailing.V"); final int T = config.getInt("sailing.T"); final int dim = config.getInt("sailing.dim"); final SailingState.Factory state_factory; if ("empty".equals(world)) { state_factory = new SailingWorlds.EmptyRectangleFactory(V, T, dim, dim); } else if ("island".equals(world)) { state_factory = new SailingWorlds.SquareIslandFactory(V, T, dim, dim / 3); } else if ("random".equals(world)) { final double p = config.getDouble("sailing.p"); state_factory = new SailingWorlds.RandomObstaclesFactory(p, V, T, dim); } else { throw new IllegalArgumentException("sailing.world"); } final SailingFsssModel model = new SailingFsssModel(config.rng_world, state_factory); runGames(config, model, expr); } else if ("saving".equals(config.domain)) { final SavingProblem.Parameters params = new SavingProblem.Parameters(config); final SavingProblem.FsssModel model = new SavingProblem.FsssModel(config.rng_world, params); runGames(config, model, expr); } else if ("spbj".equals(config.domain)) { final SpBjFsssModel model = new SpBjFsssModel(config.rng_world); runGames(config, model, expr); } else if ("tamarisk".equals(config.domain)) { final File domain = new File(config.get("rddl.domain") + ".rddl"); final File instance = new File(config.get("rddl.instance") + ".rddl"); final IpcTamariskState s0 = IpcTamariskDomains.parse(domain, instance); // TODO: Make this a parameter final IpcTamariskReachRepresenter base_repr = new IpcTamariskReachRepresenter(s0.params); final IpcTamariskFsssModel model = new IpcTamariskFsssModel(config.rng_world, s0.params, s0, base_repr); runGames(config, model, expr); } else if ("tetris".equals(config.domain)) { final int T = config.getInt("tetris.T"); final int Nrows = config.getInt("tetris.Nrows"); final TetrisParameters params = new TetrisParameters(T, Nrows); final FactoredRepresenter<TetrisState, ? extends FactoredRepresentation<TetrisState>> base_repr; if ("ground".equals(config.get("tetris.repr"))) { base_repr = new TetrisGroundRepresenter(params); } else if ("bertsekas".equals(config.get("tetris.repr"))) { base_repr = new TetrisBertsekasRepresenter(params); } else { throw new IllegalArgumentException("tetris.repr"); } final TetrisFsssModel model = new TetrisFsssModel(config.rng_world, params, base_repr); gson_builder.registerTypeAdapter(TetrisState.class, new TetrisState.GsonSerializer()); gson_builder.registerTypeAdapter(TetrisAction.class, new TetrisAction.GsonSerializer()); gson = gson_builder.create(); runGames(config, model, expr); } else if ("weinstein_littman".equals(config.domain)) { final WeinsteinLittman.Parameters params = new WeinsteinLittman.Parameters(config); final WeinsteinLittman.FsssModel model = new WeinsteinLittman.FsssModel(config.rng_world, params); runGames(config, model, expr); } else { throw new IllegalArgumentException("domain = " + config.domain); } } System.out.println("Alles gut!"); }
From source file:net.massbank.validator.RecordValidator.java
public static void main(String[] args) { RequestDummy request;/*from w ww . j a v a 2 s .c o m*/ PrintStream out = System.out; Options lvOptions = new Options(); lvOptions.addOption("h", "help", false, "show this help."); lvOptions.addOption("r", "recdata", true, "points to the recdata directory containing massbank records. Reads all *.txt files in there."); CommandLineParser lvParser = new BasicParser(); CommandLine lvCmd = null; try { lvCmd = lvParser.parse(lvOptions, args); if (lvCmd.hasOption('h')) { printHelp(lvOptions); return; } } catch (org.apache.commons.cli.ParseException pvException) { System.out.println(pvException.getMessage()); } String recDataPath = lvCmd.getOptionValue("recdata"); // --------------------------------------------- // ???? // --------------------------------------------- final String baseUrl = MassBankEnv.get(MassBankEnv.KEY_BASE_URL); final String dbRootPath = "./"; final String dbHostName = MassBankEnv.get(MassBankEnv.KEY_DB_HOST_NAME); final String tomcatTmpPath = "."; final String tmpPath = (new File(tomcatTmpPath + sdf.format(new Date()))).getPath() + File.separator; GetConfig conf = new GetConfig(baseUrl); int recVersion = 2; String selDbName = ""; Object up = null; // Was: file Upload boolean isResult = true; String upFileName = ""; boolean upResult = false; DatabaseAccess db = null; try { // ---------------------------------------------------- // ??? // ---------------------------------------------------- // if (FileUpload.isMultipartContent(request)) { // (new File(tmpPath)).mkdir(); // String os = System.getProperty("os.name"); // if (os.indexOf("Windows") == -1) { // isResult = FileUtil.changeMode("777", tmpPath); // if (!isResult) { // out.println(msgErr("[" + tmpPath // + "] chmod failed.")); // return; // } // } // up = new FileUpload(request, tmpPath); // } // ---------------------------------------------------- // ?DB???? // ---------------------------------------------------- List<String> dbNameList = Arrays.asList(conf.getDbName()); ArrayList<String> dbNames = new ArrayList<String>(); dbNames.add(""); File[] dbDirs = (new File(dbRootPath)).listFiles(); if (dbDirs != null) { for (File dbDir : dbDirs) { if (dbDir.isDirectory()) { int pos = dbDir.getName().lastIndexOf("\\"); String dbDirName = dbDir.getName().substring(pos + 1); pos = dbDirName.lastIndexOf("/"); dbDirName = dbDirName.substring(pos + 1); if (dbNameList.contains(dbDirName)) { // DB???massbank.conf???DB???? dbNames.add(dbDirName); } } } } if (dbDirs == null || dbNames.size() == 0) { out.println(msgErr("[" + dbRootPath + "] directory not exist.")); return; } Collections.sort(dbNames); // ---------------------------------------------------- // ? // ---------------------------------------------------- // if (FileUpload.isMultipartContent(request)) { // HashMap<String, String[]> reqParamMap = new HashMap<String, // String[]>(); // reqParamMap = up.getRequestParam(); // if (reqParamMap != null) { // for (Map.Entry<String, String[]> req : reqParamMap // .entrySet()) { // if (req.getKey().equals("ver")) { // try { // recVersion = Integer // .parseInt(req.getValue()[0]); // } catch (NumberFormatException nfe) { // } // } else if (req.getKey().equals("db")) { // selDbName = req.getValue()[0]; // } // } // } // } else { // if (request.getParameter("ver") != null) { // try { // recVersion = Integer.parseInt(request // .getParameter("ver")); // } catch (NumberFormatException nfe) { // } // } // selDbName = request.getParameter("db"); // } // if (selDbName == null || selDbName.equals("") // || !dbNames.contains(selDbName)) { // selDbName = dbNames.get(0); // } // --------------------------------------------- // // --------------------------------------------- out.println("Database: "); for (int i = 0; i < dbNames.size(); i++) { String dbName = dbNames.get(i); out.print("dbName"); if (dbName.equals(selDbName)) { out.print(" selected"); } if (i == 0) { out.println("------------------"); } else { out.println(dbName); } } out.println("Record Version : "); out.println(recVersion); out.println("Record Archive :"); // --------------------------------------------- // // --------------------------------------------- // HashMap<String, Boolean> upFileMap = up.doUpload(); // if (upFileMap != null) { // for (Map.Entry<String, Boolean> e : upFileMap.entrySet()) { // upFileName = e.getKey(); // upResult = e.getValue(); // break; // } // if (upFileName.equals("")) { // out.println(msgErr("please select file.")); // isResult = false; // } else if (!upResult) { // out.println(msgErr("[" + upFileName // + "] upload failed.")); // isResult = false; // } else if (!upFileName.endsWith(ZIP_EXTENSION) // && !upFileName.endsWith(MSBK_EXTENSION)) { // out.println(msgErr("please select [" // + UPLOAD_RECDATA_ZIP // + "] or [" // + UPLOAD_RECDATA_MSBK + "].")); // up.deleteFile(upFileName); // isResult = false; // } // } else { // out.println(msgErr("server error.")); // isResult = false; // } // up.deleteFileItem(); // if (!isResult) { // return; // } // --------------------------------------------- // ??? // --------------------------------------------- // final String upFilePath = (new File(tmpPath + File.separator // + upFileName)).getPath(); // isResult = FileUtil.unZip(upFilePath, tmpPath); // if (!isResult) { // out.println(msgErr("[" // + upFileName // + "] extraction failed. possibility of time-out.")); // return; // } // --------------------------------------------- // ?? // --------------------------------------------- final String recPath = (new File(dbRootPath + File.separator + selDbName)).getPath(); File tmpRecDir = new File(recDataPath); if (!tmpRecDir.isDirectory()) { tmpRecDir.mkdirs(); } // --------------------------------------------- // ??? // --------------------------------------------- // data? // final String recDataPath = (new File(tmpPath + File.separator // + RECDATA_DIR_NAME)).getPath() // + File.separator; // // if (!(new File(recDataPath)).isDirectory()) { // if (upFileName.endsWith(ZIP_EXTENSION)) { // out.println(msgErr("[" // + RECDATA_DIR_NAME // + "] directory is not included in the up-loading file.")); // } else if (upFileName.endsWith(MSBK_EXTENSION)) { // out.println(msgErr("The uploaded file is not record data.")); // } // return; // } // --------------------------------------------- // DB // --------------------------------------------- // db = new DatabaseAccess(dbHostName, selDbName); // isResult = db.open(); // if (!isResult) { // db.close(); // out.println(msgErr("not connect to database.")); // return; // } // --------------------------------------------- // ?? // --------------------------------------------- TreeMap<String, String> resultMap = validationRecord(db, out, recDataPath, recPath, recVersion); if (resultMap.size() == 0) { return; } // --------------------------------------------- // ? // --------------------------------------------- isResult = dispResult(out, resultMap); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (db != null) { db.close(); } File tmpDir = new File(tmpPath); if (tmpDir.exists()) { FileUtil.removeDir(tmpDir.getPath()); } } }
From source file:com.telefonica.iot.cygnus.nodes.CygnusApplication.java
/** * Main application to be run when this CygnusApplication is invoked. The only differences with the original one * are the CygnusApplication is used instead of the Application one, and the Management Interface port option in * the command line./*from www . j av a 2 s. c om*/ * @param args */ public static void main(String[] args) { try { // Print Cygnus starting trace including version LOGGER.info("Starting Cygnus, version " + CommonUtils.getCygnusVersion() + "." + CommonUtils.getLastCommit()); // Define the options to be read Options options = new Options(); Option option = new Option("n", "name", true, "the name of this agent"); option.setRequired(true); options.addOption(option); option = new Option("f", "conf-file", true, "specify a conf file"); option.setRequired(true); options.addOption(option); option = new Option(null, "no-reload-conf", false, "do not reload conf file if changed"); options.addOption(option); option = new Option("h", "help", false, "display help text"); options.addOption(option); option = new Option("p", "mgmt-if-port", true, "the management interface port"); option.setRequired(false); options.addOption(option); option = new Option("g", "gui-port", true, "the GUI port"); option.setRequired(false); options.addOption(option); option = new Option("t", "polling-interval", true, "polling interval"); option.setRequired(false); options.addOption(option); // Read the options CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); File configurationFile = new File(commandLine.getOptionValue('f')); String agentName = commandLine.getOptionValue('n'); boolean reload = !commandLine.hasOption("no-reload-conf"); if (commandLine.hasOption('h')) { new HelpFormatter().printHelp("cygnus-flume-ng agent", options, true); return; } // if int apiPort = DEF_MGMT_IF_PORT; if (commandLine.hasOption('p')) { apiPort = new Integer(commandLine.getOptionValue('p')); } // if int guiPort = DEF_GUI_PORT; if (commandLine.hasOption('g')) { guiPort = new Integer(commandLine.getOptionValue('g')); } else { guiPort = 0; // this disables the GUI for the time being } // if else int pollingInterval = DEF_POLLING_INTERVAL; if (commandLine.hasOption('t')) { pollingInterval = new Integer(commandLine.getOptionValue('t')); } // if // the following is to ensure that by default the agent will fail on startup if the file does not exist if (!configurationFile.exists()) { // if command line invocation, then need to fail fast if (System.getProperty(Constants.SYSPROP_CALLED_FROM_SERVICE) == null) { String path = configurationFile.getPath(); try { path = configurationFile.getCanonicalPath(); } catch (IOException e) { LOGGER.error( "Failed to read canonical path for file: " + path + ". Details=" + e.getMessage()); } // try catch throw new ParseException("The specified configuration file does not exist: " + path); } // if } // if List<LifecycleAware> components = Lists.newArrayList(); CygnusApplication application; if (reload) { LOGGER.debug( "no-reload-conf was not set, thus the configuration file will be polled each 30 seconds"); EventBus eventBus = new EventBus(agentName + "-event-bus"); PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider( agentName, configurationFile, eventBus, pollingInterval); components.add(configurationProvider); application = new CygnusApplication(components); eventBus.register(application); } else { LOGGER.debug("no-reload-conf was set, thus the configuration file will only be read this time"); PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider( agentName, configurationFile); application = new CygnusApplication(); application.handleConfigurationEvent(configurationProvider.getConfiguration()); } // if else // use the agent name as component name in the logs through log4j Mapped Diagnostic Context (MDC) MDC.put(CommonConstants.LOG4J_COMP, commandLine.getOptionValue('n')); // start the Cygnus application application.start(); // wait until the references to Flume components are not null try { while (sourcesRef == null || channelsRef == null || sinksRef == null) { LOGGER.info("Waiting for valid Flume components references..."); Thread.sleep(1000); } // while } catch (InterruptedException e) { LOGGER.error("There was an error while waiting for Flume components references. Details: " + e.getMessage()); } // try catch // start the Management Interface, passing references to Flume components LOGGER.info("Starting a Jetty server listening on port " + apiPort + " (Management Interface)"); mgmtIfServer = new JettyServer(apiPort, guiPort, new ManagementInterface(configurationFile, sourcesRef, channelsRef, sinksRef, apiPort, guiPort)); mgmtIfServer.start(); // create a hook "listening" for shutdown interrupts (runtime.exit(int), crtl+c, etc) Runtime.getRuntime().addShutdownHook(new AgentShutdownHook("agent-shutdown-hook", supervisorRef)); // start YAFS YAFS yafs = new YAFS(); yafs.start(); } catch (IllegalArgumentException e) { LOGGER.error("A fatal error occurred while running. Exception follows. Details=" + e.getMessage()); } catch (ParseException e) { LOGGER.error("A fatal error occurred while running. Exception follows. Details=" + e.getMessage()); } // try catch // try catch }
From source file:com.crushpaper.Main.java
public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption("help", false, "print this message"); options.addOption("properties", true, "file system path to the crushpaper properties file"); // Parse the command line. CommandLineParser parser = new BasicParser(); CommandLine commandLine = null;//w w w. jav a 2 s. c o m try { commandLine = parser.parse(options, args); } catch (ParseException e) { System.err.println("crushpaper: Sorry, could not parse command line because `" + e.getMessage() + "`."); System.exit(1); } if (commandLine == null || commandLine.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("crushpaper", options); return; } // Get the properties path. String properties = null; if (commandLine.hasOption("properties")) { properties = commandLine.getOptionValue("properties"); } if (properties == null || properties.isEmpty()) { System.err.println("crushpaper: Sorry, the `properties` command argument must be specified."); System.exit(1); } Configuration configuration = new Configuration(); if (!configuration.load(new File(properties))) { System.exit(1); } // Get values. File databaseDirectory = configuration.getDatabaseDirectory(); File keyStorePath = configuration.getKeyStoreFile(); Integer httpPort = configuration.getHttpPort(); Integer httpsPort = configuration.getHttpsPort(); Integer httpsProxiedPort = configuration.getHttpsProxiedPort(); String keyStorePassword = configuration.getKeyStorePassword(); String keyManagerPassword = configuration.getKeyManagerPassword(); File temporaryDirectory = configuration.getTemporaryDirectory(); String singleUserName = configuration.getSingleUserName(); Boolean allowSelfSignUp = configuration.getAllowSelfSignUp(); Boolean allowSaveIfNotSignedIn = configuration.getAllowSaveIfNotSignedIn(); File logDirectory = configuration.getLogDirectory(); Boolean loopbackIsAdmin = configuration.getLoopbackIsAdmin(); File sessionStoreDirectory = configuration.getSessionStoreDirectory(); Boolean isOfficialSite = configuration.getIsOfficialSite(); File extraHeaderFile = configuration.getExtraHeaderFile(); // Validate the values. if (httpPort != null && httpsPort != null && httpPort.equals(httpsPort)) { System.err.println("crushpaper: Sorry, `" + configuration.getHttpPortKey() + "` and `" + configuration.getHttpsPortKey() + "` must not be set to the same value."); System.exit(1); } if ((httpsPort == null) != (keyStorePath == null)) { System.err.println("crushpaper: Sorry, `" + configuration.getHttpsPortKey() + "` and `" + configuration.getKeyStoreKey() + "` must either both be set or not set."); System.exit(1); } if (httpsProxiedPort != null && httpsPort == null) { System.err.println("crushpaper: Sorry, `" + configuration.getHttpsProxiedPortKey() + "` can only be set if `" + configuration.getHttpsPortKey() + "` is set."); System.exit(1); } if (databaseDirectory == null) { System.err.println("crushpaper: Sorry, `" + configuration.getDatabaseDirectoryKey() + "` must be set."); System.exit(1); } if (singleUserName != null && !AccountAttributeValidator.isUserNameValid(singleUserName)) { System.err.println( "crushpaper: Sorry, the username in `" + configuration.getSingleUserKey() + "` is not valid."); return; } if (allowSelfSignUp == null || allowSaveIfNotSignedIn == null || loopbackIsAdmin == null) { System.exit(1); } String extraHeader = null; if (extraHeaderFile != null) { extraHeader = readFile(extraHeaderFile); if (extraHeader == null) { System.err.println("crushpaper: Sorry, the file `" + extraHeaderFile.getPath() + "` set in `" + configuration.getExtraHeaderKey() + "` could not be read."); System.exit(1); } } final DbLogic dbLogic = new DbLogic(databaseDirectory); dbLogic.createDb(); final Servlet servlet = new Servlet(dbLogic, singleUserName, allowSelfSignUp, allowSaveIfNotSignedIn, loopbackIsAdmin, httpPort, httpsPort, httpsProxiedPort, keyStorePath, keyStorePassword, keyManagerPassword, temporaryDirectory, logDirectory, sessionStoreDirectory, isOfficialSite, extraHeader); servlet.run(); }
From source file:grnet.validation.XMLValidation.java
public static void main(String[] args) throws IOException { // TODO Auto-generated method ssstub Enviroment enviroment = new Enviroment(args[0]); if (enviroment.envCreation) { String schemaUrl = enviroment.getArguments().getSchemaURL(); Core core = new Core(schemaUrl); XMLSource source = new XMLSource(args[0]); File sourceFile = source.getSource(); if (sourceFile.exists()) { Collection<File> xmls = source.getXMLs(); System.out.println("Validating repository:" + sourceFile.getName()); System.out.println("Number of files to validate:" + xmls.size()); Iterator<File> iterator = xmls.iterator(); System.out.println("Validating against schema:" + schemaUrl + "..."); ValidationReport report = null; if (enviroment.getArguments().createReport().equalsIgnoreCase("true")) { report = new ValidationReport(enviroment.getArguments().getDestFolderLocation(), enviroment.getDataProviderValid().getName()); }//from w w w . ja v a 2 s .c o m ConnectionFactory factory = new ConnectionFactory(); factory.setHost(enviroment.getArguments().getQueueHost()); factory.setUsername(enviroment.getArguments().getQueueUserName()); factory.setPassword(enviroment.getArguments().getQueuePassword()); while (iterator.hasNext()) { StringBuffer logString = new StringBuffer(); logString.append(sourceFile.getName()); logString.append(" " + schemaUrl); File xmlFile = iterator.next(); String name = xmlFile.getName(); name = name.substring(0, name.indexOf(".xml")); logString.append(" " + name); boolean xmlIsValid = core.validateXMLSchema(xmlFile); if (xmlIsValid) { logString.append(" " + "Valid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.raiseValidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { logString.append(" " + "Invalid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { if (enviroment.getArguments().extendedReport().equalsIgnoreCase("true")) report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.invalidData, core.getReason()); report.raiseInvalidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderInValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (report != null) { report.writeErrorBank(core.getErrorBank()); report.appendGeneralInfo(); } System.out.println("Validation is done."); } } }
From source file:com.doculibre.constellio.utils.license.ApplyLicenseUtils.java
/** * @param args/* w ww . j a v a2s .co m*/ */ @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { URL licenceHeaderURL = ApplyLicenseUtils.class.getResource("LICENSE_HEADER"); File binDir = ClasspathUtils.getClassesDir(); File projectDir = binDir.getParentFile(); // File dryrunDir = new File(projectDir, "dryrun"); File licenceFile = new File(licenceHeaderURL.toURI()); List<String> licenceLines = readLines(licenceFile); // for (int i = 0; i < licenceLines.size(); i++) { // String licenceLine = licenceLines.get(i); // licenceLines.set(i, " * " + licenceLine); // } // licenceLines.add(0, "/**"); // licenceLines.add(" */"); List<File> javaFiles = (List<File>) org.apache.commons.io.FileUtils.listFiles(projectDir, new String[] { "java" }, true); for (File javaFile : javaFiles) { if (isValidPackage(javaFile)) { List<String> javaFileLines = readLines(javaFile); if (!javaFileLines.isEmpty()) { boolean modified = false; String firstLineTrim = javaFileLines.get(0).trim(); if (firstLineTrim.startsWith("package")) { modified = true; javaFileLines.addAll(0, licenceLines); } else if (firstLineTrim.startsWith("/**")) { int indexOfEndCommentLine = -1; loop2: for (int i = 0; i < javaFileLines.size(); i++) { String javaFileLine = javaFileLines.get(i); if (javaFileLine.indexOf("*/") != -1) { indexOfEndCommentLine = i; break loop2; } } if (indexOfEndCommentLine != -1) { modified = true; int i = 0; loop3: for (Iterator<String> it = javaFileLines.iterator(); it.hasNext();) { it.next(); if (i <= indexOfEndCommentLine) { it.remove(); } else { break loop3; } i++; } javaFileLines.addAll(0, licenceLines); } else { throw new RuntimeException( "Missing end comment for file " + javaFile.getAbsolutePath()); } } if (modified) { // String outputFilePath = javaFile.getPath().substring(projectDir.getPath().length()); // File outputFile = new File(dryrunDir, outputFilePath); // outputFile.getParentFile().mkdirs(); // System.out.println(outputFile.getPath()); // FileOutputStream fos = new FileOutputStream(outputFile); System.out.println(javaFile.getPath()); FileOutputStream fos = new FileOutputStream(javaFile); IOUtils.writeLines(javaFileLines, "\n", fos); IOUtils.closeQuietly(fos); } } } } }
From source file:net.itransformers.postDiscoverer.core.ReportManager.java
public static void main(String[] args) throws IOException { File projectDir = new File("."); File scriptPath = new File("postDiscoverer/src/main/resources/postDiscoverer/conf/groovy/"); ResourceManagerFactory resourceManagerFactory = new XmlResourceManagerFactory( "iDiscover/resourceManager/xmlResourceManager/src/main/resources/xmlResourceManager/conf/xml/resource.xml"); Map<String, String> resourceManagerParams = new HashMap<>(); resourceManagerParams.put("projectPath", projectDir.getAbsolutePath()); ResourceManager resourceManager = resourceManagerFactory.createResourceManager("xml", resourceManagerParams);/* w ww . j a v a 2s . c o m*/ Map<String, String> params = new HashMap<String, String>(); params.put("protocol", "telnet"); params.put("deviceName", "R1"); params.put("deviceType", "CISCO"); params.put("address", "10.17.1.5"); params.put("port", "23"); ResourceType resource = resourceManager.findFirstResourceBy(params); List connectParameters = resource.getConnectionParams(); for (int i = 0; i < connectParameters.size(); i++) { ConnectionParamsType connParamsType = (ConnectionParamsType) connectParameters.get(i); String connectionType = connParamsType.getConnectionType(); if (connectionType.equalsIgnoreCase(params.get("protocol"))) { for (ParamType param : connParamsType.getParam()) { params.put(param.getName(), param.getValue()); } } } File postDiscoveryConfing = new File( projectDir + "/postDiscoverer/src/main/resources/postDiscoverer/conf/xml/reportGenerator.xml"); if (!postDiscoveryConfing.exists()) { System.out.println("File missing: " + postDiscoveryConfing.getAbsolutePath()); return; } ReportGeneratorType reportGenerator = null; FileInputStream is = new FileInputStream(postDiscoveryConfing); try { reportGenerator = JaxbMarshalar.unmarshal(ReportGeneratorType.class, is); } catch (JAXBException e) { logger.info(e); //To change body of catch statement use File | Settings | File Templates. } finally { is.close(); } ReportManager reportManager = new ReportManager(reportGenerator, scriptPath.getPath(), projectDir, "postDiscoverer/conf/xslt/table_creator.xslt"); StringBuffer report = null; HashMap<String, Object> groovyExecutorParams = new HashMap<String, Object>(); for (String s : params.keySet()) { groovyExecutorParams.put(s, params.get(s)); } try { report = reportManager.reportExecutor( new File("/Users/niau/Projects/Projects/netTransformer10/version1/post-discovery"), groovyExecutorParams); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } if (report != null) { System.out.println(report.toString()); } else { System.out.println("Report generation failed!"); } }