List of usage examples for java.lang Object toString
public String toString()
From source file:org.atomspace.pi2c.runtime.Server.java
public static void main(String[] args) throws Exception { System.err.println("::: ----------------------------------------------------------------------- :::"); System.err.println("::: ------------------------------ STARTING ------------------------------:::"); System.err.println("::: ----------------------------------------------------------------------- :::"); System.err.println("\n::: SYSTEM-Properties: :::"); Set<?> properties = System.getProperties().keySet(); for (Object object : properties) { System.err.println("::: " + object.toString() + " = " + System.getProperty(object.toString())); }//from w ww . j a va 2 s. c o m System.err.println("\n::: ENV-Properties: :::"); properties = System.getenv().keySet(); for (Object object : properties) { System.err.println("::: " + object.toString() + " = " + System.getenv(object.toString())); } windows = System.getProperty("os.name").toLowerCase().startsWith("windows"); linux = System.getProperty("os.name").toLowerCase().startsWith("linux"); sunos = System.getProperty("os.name").toLowerCase().startsWith("sun"); freebsd = System.getProperty("os.name").toLowerCase().startsWith("freebsd"); if (linux || sunos) { //USR2-Signal-Handel lookup internal Server STATUS for Linux or SunOS System.err.println("::: " + new Date() + "::: run unter Linux or SunOS :::"); addUnixSignalStatusHandle(); } else if (freebsd) { System.err.println("::: " + new Date() + "::: run unter FreeBSD :::"); } else if (windows) { //Gracefull Shutdown JFrame for Windows, because can not kill -15 <pid> on Window or in Eclipse Console System.err.println("::: " + new Date() + " ::: run unter windows :::"); addWindowsShutdownHandle(); } else { System.err.println("UNKNOWN OS:" + System.getProperty("os.name")); } status = STATUS_STARTING; Server server = new Server(); Thread serverThread = new Thread(server); serverThread.start(); //Thread can stop by Shutdown-Hook while (true) { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); break; } } }
From source file:gpframework.RunExperiment.java
/** * Application's entry point.// w w w . j a va 2 s .co m * * @param args * @throws ParseException * @throws ParameterException */ public static void main(String[] args) throws ParseException, ParameterException { // Failsafe parameters if (args.length == 0) { args = new String[] { "-f", "LasSortednessFunction", "-n", "5", "-ff", "JoinFactory", "-tf", "SortingElementFactory", "-pf", "SortingProgramFactory", "-s", "SMOGPSelection", "-a", "SMOGP", "-t", "50", "-e", "1000000000", "-mf", "SingleMutationFactory", "-d", "-bn", "other" }; } // Create options Options options = new Options(); setupOptions(options); // Read options from the command line CommandLineParser parser = new PosixParser(); CommandLine cmd; // Print help if parameter requirements are not met try { cmd = parser.parse(options, args); } // If some parameters are missing, print help catch (MissingOptionException e) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar GPFramework \n", options); System.out.println(); System.out.println("Missing parameters: " + e.getMissingOptions()); return; } // Re-initialize PRNG long seed = System.currentTimeMillis(); Utils.random = new Random(seed); // Set the problem size int problemSize = Integer.parseInt(cmd.getOptionValue("n")); // Set debug mode and cluster mode Utils.debug = cmd.hasOption("d"); RunExperiment.cluster = cmd.hasOption("c"); // Initialize fitness function and some factories FitnessFunction fitnessFunction = fromName(cmd.getOptionValue("f"), problemSize); MutationFactory mutationFactory = fromName(cmd.getOptionValue("mf")); Selection selectionCriterion = fromName(cmd.getOptionValue("s")); FunctionFactory functionFactory = fromName(cmd.getOptionValue("ff")); TerminalFactory terminalFactory = fromName(cmd.getOptionValue("tf"), problemSize); ProgramFactory programFactory = fromName(cmd.getOptionValue("pf"), functionFactory, terminalFactory); // Initialize algorithm Algorithm algorithm = fromName(cmd.getOptionValue("a"), mutationFactory, selectionCriterion); algorithm.setParameter("evaluationsBudget", cmd.getOptionValue("e")); algorithm.setParameter("timeBudget", cmd.getOptionValue("t")); // Initialize problem Problem problem = new Problem(programFactory, fitnessFunction); Program solution = algorithm.solve(problem); Utils.debug("Population results: "); Utils.debug(algorithm.getPopulation().toString()); Utils.debug(algorithm.getPopulation().parse()); Map<String, Object> entry = new HashMap<String, Object>(); // Copy algorithm setup for (Object o : options.getRequiredOptions()) { Option option = options.getOption(o.toString()); entry.put(option.getLongOpt(), cmd.getOptionValue(option.getOpt())); } entry.put("seed", seed); // Copy results entry.put("bestProgram", solution.toString()); entry.put("bestSolution", fitnessFunction.normalize(solution)); // Copy all statistics entry.putAll(algorithm.getStatistics()); Utils.debug("Maximum encountered population size: " + algorithm.getStatistics().get("maxPopulationSizeToCompleteFront")); Utils.debug("Maximum encountered tree size: " + algorithm.getStatistics().get("maxProgramComplexityToCompleteFront")); Utils.debug("Solution complexity: " + solution.complexity() + "/" + (2 * problemSize - 1)); }
From source file:eu.annocultor.utils.OntologySubtractor.java
public static void main(String[] args) throws Exception { boolean copy = checkNoCopyOption(args); if (args.length == 2 || args.length == 3) { File sourceDir = new File(args[0]); File destinationDir = new File(args[1]); checkSrcAndDstDirs(sourceDir, destinationDir); Collection<String> filesWithDeletedStatements = listNameStamsForFilesWithDeletedStatements(sourceDir); if (filesWithDeletedStatements.isEmpty()) { System.out.println(/*from ww w . j a v a 2s .c om*/ "Did not found any file *.*.*.deleted.rdf with statements to be deleted. Do nothing and exit."); } else { System.out.println( "Found " + filesWithDeletedStatements.size() + " files with statements to be deleted"); System.out.println( "Copying all RDF files from " + sourceDir.getName() + " to " + destinationDir.getName()); if (copy) { copyRdfFiles(sourceDir, destinationDir); } sutractAll(sourceDir, destinationDir, filesWithDeletedStatements); } } else { for (Object string : IOUtils.readLines(new AutoCloseInputStream( OntologySubtractor.class.getResourceAsStream("/subtractor/readme.txt")))) { System.out.println(string.toString()); } } }
From source file:Main.java
public static void main(String[] args) { Person p = new Person("A"); Animal a = new Animal("B"); Thing t = new Thing("C"); String text = "hello"; Integer number = 1000;/*ww w .j a v a 2 s . c o m*/ List<Object> list = new ArrayList<Object>(); list.add(p); list.add(a); list.add(t); list.add(text); list.add(number); for (int i = 0; i < list.size(); i++) { Object o = list.get(i); if (o instanceof Person) { System.out.println("My name is " + ((Person) o).getName()); } else if (o instanceof Animal) { System.out.println("I live in " + ((Animal) o).getHabitat()); } else if (o instanceof Thing) { System.out.println("My color is " + ((Thing) o).getColor()); } else if (o instanceof String) { System.out.println("My text is " + o.toString()); } else if (o instanceof Integer) { System.out.println("My value is " + ((Integer) o)); } } }
From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java
public static void main(String[] args) { // check & validate cmdline options OptionGroup opt_g = getCMDLineOptionsGroups(); Options opt = getCMDLineOptions();/*from www . j av a 2 s. c om*/ opt.addOptionGroup(opt_g); CommandLineParser cli = new DefaultParser(); try { CommandLine cl = cli.parse(opt, args); if (cl.hasOption("v")) { VerboseOutputFilter.SHOW_VERBOSE = true; } switch (opt_g.getSelected()) { case "V": try { URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation(); String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8"); JarFile jarFile = new JarFile(jarPath); Manifest m = jarFile.getManifest(); StringBuilder versionInfo = new StringBuilder(); for (Object key : m.getMainAttributes().keySet()) { versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString())) .append("\n"); } System.out.println(versionInfo.toString()); } catch (Exception e) { log.error("Version info could not be read."); } break; case "h": HelpFormatter help = new HelpFormatter(); String header = ""; //TODO: missing infotext StringBuilder footer = new StringBuilder("Supported configuration properties :"); help.printHelp("CodeGen -h | -V | -g [...]", header, opt, footer.toString()); break; case "g": // target dir if (cl.hasOption("t")) { File target = new File(cl.getOptionValue("t")); if (target.isDirectory() && target.canExecute() && target.canWrite()) { config.setProperty("target.dir", cl.getOptionValue("t")); } else { log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t")); break; } } else { config.setProperty("target.dir", System.getProperty("java.io.tmpdir")); } // project dir if (cl.hasOption("p")) { File project = new File(cl.getOptionValue("p")); if (!project.exists()) { if (!project.mkdirs()) { log.error("Project dir '{}' can't be created!", cl.getOptionValue("p")); break; } } if (project.isDirectory() && project.canExecute() && project.canWrite()) { config.setProperty("project.dir", cl.getOptionValue("p")); } else { log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p")); break; } } generateAppfromXML(cl.getOptionValue("g")); break; } } catch (ParseException e) { log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage()); } }
From source file:Main.java
public static void main(String[] argv) throws Exception { JTextPane textPane = new JTextPane(); DefaultStyledDocument doc = (DefaultStyledDocument) textPane.getDocument(); Enumeration e1 = doc.getStyleNames(); while (e1.hasMoreElements()) { String styleName = (String) e1.nextElement(); System.out.println(styleName); Style style = doc.getStyle(styleName); int count = style.getAttributeCount(); System.out.println(count); Enumeration e = style.getAttributeNames(); while (e.hasMoreElements()) { Object o = e.nextElement(); if (o instanceof String) { String attrName = (String) o; Object attrValue = style.getAttribute(attrName); System.out.println(attrValue); } else if (o == StyleConstants.NameAttribute) { styleName = (String) style.getAttribute(o); System.out.println(styleName); } else if (o == StyleConstants.ResolveAttribute) { Style parent = (Style) style.getAttribute(o); System.out.println(parent.getName()); } else { String attrName = o.toString(); System.out.println(attrName); Object attrValue = style.getAttribute(o); System.out.println(attrValue); }// w w w . j av a2s . c o m } } }
From source file:com.utdallas.s3lab.smvhunter.monkey.MonkeyMe.java
/** * @param args/* w ww .j a v a 2s .c o m*/ */ public static void main(String[] args) throws Exception { logger.info("start time ==== " + System.currentTimeMillis()); try { //load the adb location from the props file Properties props = new Properties(); props.load(new FileInputStream(new File("adb.props"))); //set the adb location WindowUpdate.adbLocation = props.getProperty("adb_location"); adbLocation = props.getProperty("adb_location"); //set root dir ROOT_DIRECTORY = props.getProperty("root_dir"); //completed txt completedFile = new File(ROOT_DIRECTORY + "tested.txt"); //db location for static analysis dbLocation = props.getProperty("db_location"); //location for smart input generation output smartInputLocation = props.getProperty("smart_input_location"); //udp dump location udpDumpLocation = props.getProperty("udp_dump_location"); //logcat dump location logCatLocation = props.getProperty("log_cat_location"); //strace output location straceOutputLocation = props.getProperty("strace_output_location"); //strace dump location straceDumpLocation = props.getProperty("strace_output_location"); //set x and y coords UIEnumerator.screenX = props.getProperty("x"); UIEnumerator.screenY = props.getProperty("y"); DeviceOfflineMonitor.START_EMULATOR = props.getProperty("restart"); //read output of static analysis readFromStaticAnalysisText(); logger.info("Read static analysis output"); readFromSmartInputText(); logger.info("Read smart input generation output"); //populate the queue with apps which are only present in the static analysis @SuppressWarnings("unchecked") final Set<? extends String> sslApps = new HashSet<String>( CollectionUtils.collect(FileUtils.readLines(new File(dbLocation)), new Transformer() { @Override public Object transform(Object input) { //get app file name String temp = StringUtils.substringBefore(input.toString(), " "); return StringUtils.substringAfterLast(temp, "/"); } })); Collection<File> fileList = FileUtils.listFiles(new File(ROOT_DIRECTORY), new String[] { "apk" }, false); CollectionUtils.filter(fileList, new Predicate() { @Override public boolean evaluate(Object object) { return sslApps.contains(StringUtils.substringAfterLast(object.toString(), "/")); } }); apkQueue = new LinkedBlockingDeque<File>(fileList); logger.info("finished listing files from the root directory"); try { //populate the tested apk list completedApps.addAll(FileUtils.readLines(completedFile)); } catch (Exception e) { //pass except logger.info("No tested.txt file found"); //create new file if (completedFile.createNewFile()) { logger.info("tested.txt created in root directory"); } else { logger.info("tested.txt file could not be created"); } } //get the executors for managing the emulators executors = Executors.newCachedThreadPool(); //set the devicemonitor exec DeviceOfflineMonitor.exec = executors; final List<Future<?>> futureList = new ArrayList<Future<?>>(); //start the offline device monitor (emulator management thread) logger.info("Starting Device Offline Monitor Thread"); executors.submit(new DeviceOfflineMonitor()); //get ADB backend object for device change listener AdbBackend adb = new AdbBackend(); //register for device change and wait for events //once event is received, start the MonkeyMe thread MonkeyDeviceChangeListener deviceChangeListener = new MonkeyDeviceChangeListener(executors, futureList); AndroidDebugBridge.addDeviceChangeListener(deviceChangeListener); logger.info("Listening to changes in devices (emulators)"); //wait for the latch to come down //this means that all the apks have been processed cdl.await(); logger.info("Finished testing all apps waiting for threads to join"); //now wait for every thread to finish for (Future<?> future : futureList) { future.get(); } logger.info("All threads terminated"); //stop listening for device update AndroidDebugBridge.removeDeviceChangeListener(deviceChangeListener); //stop the debug bridge AndroidDebugBridge.terminate(); //stop offline device monitor DeviceOfflineMonitor.stop = true; logger.info("adb and listeners terminated"); } finally { logger.info("Executing this finally"); executors.shutdownNow(); } logger.info("THE END!!"); }
From source file:edu.osu.ling.pep.Pep.java
/** * Invokes Pep from the command line./*from w ww . ja v a2s . c om*/ * <p> * The main work this method does, apart from tokenizing the arguments and * input tokens, is to load and parse the XML grammar file (as specified by * <code>-g</code> or <code>--grammar</code>). If any of the arguments * <code>-g</code>, <code>--grammar</code>, <code>-s</code>, * <code>--seed</code>, <code>-o</code>, <code>--option</code>, occur with * no argument following, this method prints an error notifying the user. * * @param args * The expected arguments are as follows, and can occur in any * particular order: * <ul> * <li><code>-g|--grammar <grammar file></code></li> <li> * <code>-s|--seed <seed category></code></li> <li><code> * -v|--verbose {verbosity level}</code></li> <li><code> * -o|--option <OPTION_NAME=value></code></li> <li><code> * -h|--help (prints usage information)</code></li> <li><code> * <token1 ... token<em>n</em>></code> (or <code>-</code> * for standard input)</li> * </ul> * <code>OPTION_NAME</code> must be the name of one of the * recognized {@link ParserOption options}. If <code>-h</code> or * <code>--help</code> occur anywhere in the arguments, usage * information is printed and no parsing takes place. */ @SuppressWarnings("static-access") public static final void main(final String[] args) { try { final Options opts = new Options(); opts.addOption(OptionBuilder.withLongOpt("grammar").withDescription("the grammar to use").hasArg() .isRequired().withArgName("grammar file").create('g')); opts.addOption(OptionBuilder.withLongOpt("seed").withDescription("the seed category to parse for") .hasArg().isRequired().withArgName("seed category").create('s')); opts.addOption(OptionBuilder.withLongOpt("verbose").withDescription("0-3").hasOptionalArg() .withArgName("verbosity level").create('v')); opts.addOption(OptionBuilder.withLongOpt("option").withDescription("sets parser options") .withArgName("OPTION=value").hasArgs(2).withValueSeparator() .withDescription("use value for given property").create("o")); opts.addOption(OptionBuilder.withLongOpt("help").withDescription("prints this message").create('h')); final CommandLineParser parser = new GnuParser(); try { final CommandLine line = parser.parse(opts, args); if (line.hasOption('h')) { Pep.printHelp(opts); } else { final int v = Integer.parseInt(line.getOptionValue('v', Integer.toString(Pep.V_PARSE))); if (v < 0) { throw new PepException("verbosity < 0: " + v); } Pep.verbosity = v; final Map<ParserOption, Boolean> options = new EnumMap<ParserOption, Boolean>( ParserOption.class); final Properties props = line.getOptionProperties("o"); for (final Object key : props.keySet()) { try { options.put(ParserOption.valueOf(key.toString()), Boolean.valueOf(props.get(key).toString())); } catch (final IllegalArgumentException iae) { Pep.printError("no option named " + key.toString()); Pep.printHelp(opts); return; } } final Pep pep = new Pep(options); // final Grammar grammar = // new GrammarParser(Pep.findGrammar(line // .getOptionValue('g'))).t.parse(); final List<?> ts = line.getArgList(); List<String> tokens = null; if (ts.isEmpty() || ts.get(0).equals("-")) { tokens = Pep.readTokens(new Scanner(System.in)); } else { tokens = new ArrayList<String>(ts.size()); for (final Object t : ts) { tokens.add(t.toString()); } } pep.lastParseStart = System.currentTimeMillis(); // try { // pep.parse(grammar, tokens, // new Category(line.getOptionValue('s'))); // } catch (final PepException ignore) { // // ignore here, we're listening // } } } catch (final ParseException pe) { Pep.printError("command-line syntax problem: " + pe.getMessage()); Pep.printHelp(opts); } } catch (final PepException pe) { final Throwable cause = pe.getCause(); Pep.printError((cause == null) ? pe : cause); } catch (final RuntimeException re) { Pep.printError(re); } }
From source file:br.unicamp.ft.priva.aas.client.RESTUsageExample.java
public static void main(String[] args) { Object policyJSON, dataJSON; //Example Data: String policyFile = "../priva-poc/input/example-mock-data/mock_data.policy.json"; String dataFile = "../priva-poc/input/example-mock-data/mock_data.json"; // Load Example Data: JSONParser parser = new JSONParser(); try {//from ww w . j a va 2s . c o m FileReader policyReader = new FileReader(policyFile); policyJSON = parser.parse(policyReader); FileReader dataReader = new FileReader(dataFile); dataJSON = parser.parse(dataReader); } catch (IOException | ParseException e) { System.out.println("IOException | ParseException = " + e); return; } System.out.println("policyJSON = " + policyJSON.toString().length()); System.out.println("dataJSON = " + dataJSON.toString().length()); JSONArray payload = new JSONArray(); payload.add(policyJSON); payload.add(dataJSON); // POST data to server Client client = ClientBuilder.newClient(); WebTarget statistics = client.target(ENDPOINT); String content = statistics.request(MediaType.APPLICATION_JSON) .post(Entity.entity(payload, MediaType.APPLICATION_JSON), String.class); System.out.println("result = " + content); }
From source file:org.ala.hbase.RepoDataLoader.java
/** * This takes a list of infosource ids... * <p/>/*from www . ja va 2s. co m*/ * Usage: -stats or -reindex or -gList and list of infosourceId * * @param args */ public static void main(String[] args) throws Exception { //RepoDataLoader loader = new RepoDataLoader(); ApplicationContext context = SpringUtils.getContext(); RepoDataLoader loader = (RepoDataLoader) context.getBean(RepoDataLoader.class); long start = System.currentTimeMillis(); loader.loadInfoSources(); String filePath = repositoryDir; if (args.length > 0) { if (args[0].equalsIgnoreCase("-stats")) { loader.statsOnly = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); } if (args[0].equalsIgnoreCase("-reindex")) { loader.reindex = true; loader.indexer = context.getBean(PartialIndex.class); args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -reindex: " + loader.reindex); logger.debug("reindex url: " + loader.reindexUrl); } if (args[0].equalsIgnoreCase("-gList")) { loader.gList = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -gList: " + loader.gList); } if (args[0].equalsIgnoreCase("-biocache")) { Hashtable<String, String> hashTable = new Hashtable<String, String>(); hashTable.put("accept", "application/json"); ObjectMapper mapper = new ObjectMapper(); mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); RestfulClient restfulClient = new RestfulClient(0); String fq = "&fq="; if (args.length > 1) { java.util.Date date = new java.util.Date(); if (args[1].equals("-lastWeek")) { date = DateUtils.addWeeks(date, -1); } else if (args[1].equals("-lastMonth")) { date = DateUtils.addMonths(date, -1); } else if (args[1].equals("-lastYear")) { date = DateUtils.addYears(date, -1); } else date = null; if (date != null) { SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); fq += "last_load_date:%5B" + sfd.format(date) + "%20TO%20*%5D"; } } Object[] resp = restfulClient .restGet("http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0", hashTable); logger.info("The URL: " + "http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0"); if ((Integer) resp[0] == HttpStatus.SC_OK) { String content = resp[1].toString(); logger.debug(resp[1]); if (content != null && content.length() > "[]".length()) { Map map = mapper.readValue(content, Map.class); try { List<java.util.LinkedHashMap<String, String>> list = ((List<java.util.LinkedHashMap<String, String>>) ((java.util.LinkedHashMap) ((java.util.ArrayList) map .get("facetResults")).get(0)).get("fieldResult")); Set<String> arg = new LinkedHashSet<String>(); for (int i = 0; i < list.size(); i++) { java.util.LinkedHashMap<String, String> value = list.get(i); String dataResource = getDataResource(value.get("fq")); Object provider = (loader.getUidInfoSourceMap().get(dataResource)); if (provider != null) { arg.add(provider.toString()); } } logger.info("Set of biocache infosource ids to load: " + arg); args = new String[] {}; args = arg.toArray(args); //handle the situation where biocache-service reports no data resources if (args.length < 1) { logger.error("No biocache data resources found. Unable to load."); System.exit(0); } } catch (Exception e) { logger.error("ERROR: exit process....." + e); e.printStackTrace(); System.exit(0); } } } else { logger.warn("Unable to process url: "); } } } int filesRead = loader.load(filePath, args); //FIX ME - move to config long finish = System.currentTimeMillis(); logger.info(filesRead + " files scanned/loaded in: " + ((finish - start) / 60000) + " minutes " + ((finish - start) / 1000) + " seconds."); System.exit(1); }