List of usage examples for java.lang String isEmpty
public boolean isEmpty()
From source file:ch.ethz.dcg.jukefox.cli.CliJukefoxApplication.java
public static void main(String[] args) { CommandLineParser parser = new PosixParser(); LogLevel logLevel = LogLevel.ERROR;/*from w w w. java 2 s . c om*/ try { CommandLine line = parser.parse(getCliOptions(), args); if (line.hasOption(VERBOSE_OPTION)) { logLevel = LogLevel.VERBOSE; } } catch (ParseException e1) { Log.e(TAG, "Unexpected exception: " + e1.getMessage()); } printWelcome(); Log.setLogLevel(logLevel); // Send logs async new Thread(new Runnable() { @Override public void run() { playerModel.getLogManager().sendLogs(); } }).start(); CliJukefoxApplication application = new CliJukefoxApplication(); try { scanner = new Scanner(System.in); application.start(); ImportState importState = libraryImportManager.getImportState(); importState.addListener(application); //System.out.println(importState.getProgress().getStatusMessage()); while (running) { String next = scanner.nextLine(); if (next.isEmpty()) { continue; } try { application.getCommandLineInterface().execute(next); } catch (ExecutionException e) { System.out.println("Invalid input, please use following commands: "); application.getCommandLineInterface().execute("help"); } } } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.crawler.app.run.CrawlSiteController.java
public static void main(String[] args) throws Exception { logger.info("Start...: "); /*//from w w w . j ava2s . c o m * if (args.length != 2) { logger.info("Needed parameters: "); * logger.info * ("\t rootFolder (it will contain intermediate crawl data)"); * logger.info("\t numberOfCralwers (number of concurrent threads)"); * return; } */ /* * crawlStorageFolder is a folder where intermediate crawl data is * stored. */ String crawlStorageFolder = "D:\\/Java\\/storage";//"/crawler4j/storage";// args[0]; /* * numberOfCrawlers shows the number of concurrent threads that should * be initiated for crawling. */ // int numberOfCrawlers = Integer.parseInt(args[1]); int numberOfCrawlers = 1; CrawlConfig config = new CrawlConfig(); config.setCrawlStorageFolder(crawlStorageFolder); /* * Be polite: Make sure that we don't send more than 1 request per * second (1000 milliseconds between requests). */ config.setPolitenessDelay(1000); // config.setFollowRedirects(false); /* * You can set the maximum crawl depth here. The default value is -1 for * unlimited depth */ config.setMaxDepthOfCrawling(1);// ( use -1 for unlimited depth ) /* * You can set the maximum number of pages to crawl. The default value * is -1 for unlimited number of pages */ config.setMaxPagesToFetch(-1);// ( use -1 for unlimited pages ) /** * Do you want crawler4j to crawl also binary data ? example: the * contents of pdf, or the metadata of images etc */ config.setIncludeBinaryContentInCrawling(false); /* * Do you need to set a proxy? If so, you can use: * config.setProxyHost("proxyserver.example.com"); * config.setProxyPort(8080); * * If your proxy also needs authentication: * config.setProxyUsername(username); config.getProxyPassword(password); */ /* * This config parameter can be used to set your crawl to be resumable * (meaning that you can resume the crawl from a previously * interrupted/crashed crawl). Note: if you enable resuming feature and * want to start a fresh crawl, you need to delete the contents of * rootFolder manually. */ config.setResumableCrawling(false); /* * Overwrite user ddagent */ config.setUserAgentString("Crawler"); /* * Instantiate the controller for this crawl. */ PageFetcher pageFetcher = new PageFetcher(config); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); // by me robotstxtConfig.setEnabled(false); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); // by me CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); /* * For each crawl, you need to add some seed urls. These are the first * URLs that are fetched and then the crawler starts following links * which are found in these pages */ // controller.addSeed("http://careerbuilder.vn/"); try { String tag_size = "site102"; int sizeIDXML = -1; String provinceYESNO, linkCrawlerBegin, linkCrawlerPage; int pageNumberBegin = -1, pageNumberEnd = -1, pageLoopInit = -1, pageLoop = -1; File fXmlFile = new File(pathXmlFile); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); org.w3c.dom.Document doc = dBuilder.parse(fXmlFile); org.w3c.dom.NodeList nList = doc.getElementsByTagName(tag_size); org.w3c.dom.Node nNode = nList.item(0); if (nNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { org.w3c.dom.Element eElement = (org.w3c.dom.Element) nNode; sizeIDXML = Integer.parseInt(eElement.getAttribute("id")); String pageDefine = eElement.getElementsByTagName("pageDefine").item(0).getTextContent(); // read config ReadConfigPageNumberEnd(eElement); // if define then get define value to using if (!pageDefine.isEmpty() && pageDefine.toUpperCase().equals("YES")) { org.w3c.dom.NodeList nListOnewebsite = eElement.getElementsByTagName("website"); org.w3c.dom.Element eElementOnewebsite = (org.w3c.dom.Element) nListOnewebsite.item(0); linkCrawlerBegin = eElementOnewebsite.getElementsByTagName("linkCrawlerBegin").item(0) .getTextContent(); linkCrawlerPage = eElementOnewebsite.getElementsByTagName("linkCrawlerPage").item(0) .getTextContent(); int pageNumberTotal = Integer.parseInt( eElementOnewebsite.getElementsByTagName("pageNumberTotal").item(0).getTextContent()); pageNumberBegin = Integer.parseInt( eElementOnewebsite.getElementsByTagName("pageNumberBegin").item(0).getTextContent()); pageLoopInit = Integer.parseInt( eElementOnewebsite.getElementsByTagName("pageLoopInit").item(0).getTextContent()); pageLoop = Integer .parseInt(eElementOnewebsite.getElementsByTagName("pageLoop").item(0).getTextContent()); if (!linkCrawlerBegin.isEmpty()) { controller.addSeed(linkCrawlerBegin); //pageNumberEnd = getPageNumberEnd(linkCrawlerBegin); if (pageNumberTotal > 1) { int i = 0; for (; pageNumberTotal >= pageNumberBegin; pageNumberBegin++) { String convertlinkCrawlerPage = linkCrawlerPage.replace("%s", String.valueOf(pageLoopInit)); controller.addSeed(convertlinkCrawlerPage); pageLoopInit += pageLoop; i++; System.out.println(i); } } } } else { provinceYESNO = eElement.getElementsByTagName("provinceYESNO").item(0).getTextContent(); if (!provinceYESNO.isEmpty() && provinceYESNO.toUpperCase().equals("YES")) { // have sevent province org.w3c.dom.NodeList nListProvince = eElement.getElementsByTagName("province"); for (int index = 0; index < nListProvince.getLength(); index++) { org.w3c.dom.Element eElementProvince = (org.w3c.dom.Element) nListProvince.item(index); linkCrawlerBegin = eElementProvince.getElementsByTagName("linkCrawlerBegin").item(0) .getTextContent(); linkCrawlerPage = eElementProvince.getElementsByTagName("linkCrawlerPage").item(0) .getTextContent(); if (!eElementProvince.getElementsByTagName("pageNumberBegin").item(0).getTextContent() .isEmpty()) { pageNumberBegin = Integer.parseInt(eElementProvince .getElementsByTagName("pageNumberBegin").item(0).getTextContent()); } if (!eElementProvince.getElementsByTagName("pageLoopInit").item(0).getTextContent() .isEmpty()) { pageLoopInit = Integer.parseInt(eElementProvince .getElementsByTagName("pageLoopInit").item(0).getTextContent()); } if (!eElementProvince.getElementsByTagName("pageLoop").item(0).getTextContent() .isEmpty()) { pageLoop = Integer.parseInt( eElementProvince.getElementsByTagName("pageLoop").item(0).getTextContent()); } if (!linkCrawlerBegin.isEmpty()) { controller.addSeed(linkCrawlerBegin); pageNumberEnd = getPageNumberEnd(linkCrawlerBegin); if (pageNumberEnd > 1) { for (; pageNumberBegin <= pageNumberEnd; pageNumberBegin++) { String convertlinkCrawlerPage = linkCrawlerPage.replace("%s", String.valueOf(pageLoopInit)); controller.addSeed(convertlinkCrawlerPage); pageLoopInit += pageLoop; } } } } } else if (!provinceYESNO.isEmpty() && provinceYESNO.toUpperCase().equals("NO")) { // don't have sevent province org.w3c.dom.NodeList nListOnewebsite = eElement.getElementsByTagName("website"); org.w3c.dom.Element eElementOnewebsite = (org.w3c.dom.Element) nListOnewebsite.item(0); // read config of pagenumber end linkCrawlerBegin = eElementOnewebsite.getElementsByTagName("linkCrawlerBegin").item(0) .getTextContent(); linkCrawlerPage = eElementOnewebsite.getElementsByTagName("linkCrawlerPage").item(0) .getTextContent(); if (!eElementOnewebsite.getElementsByTagName("pageNumberBegin").item(0).getTextContent() .isEmpty()) { pageNumberBegin = Integer.parseInt(eElementOnewebsite .getElementsByTagName("pageNumberBegin").item(0).getTextContent()); } if (!eElementOnewebsite.getElementsByTagName("pageLoopInit").item(0).getTextContent() .isEmpty()) { pageLoopInit = Integer.parseInt(eElementOnewebsite.getElementsByTagName("pageLoopInit") .item(0).getTextContent()); } if (!eElementOnewebsite.getElementsByTagName("pageLoop").item(0).getTextContent() .isEmpty()) { pageLoop = Integer.parseInt( eElementOnewebsite.getElementsByTagName("pageLoop").item(0).getTextContent()); } if (!linkCrawlerBegin.isEmpty()) { controller.addSeed(linkCrawlerBegin); pageNumberEnd = getPageNumberEnd(linkCrawlerBegin); if (pageNumberEnd > 1) { for (; pageNumberBegin <= pageNumberEnd; pageNumberBegin++) { String convertlinkCrawlerPage = linkCrawlerPage.replace("%s", String.valueOf(pageLoopInit)); controller.addSeed(convertlinkCrawlerPage); pageLoopInit += pageLoop; } } } } } CrawlSite.tag_size = tag_size; CrawlSite.siteIDXML = sizeIDXML; controller.start(CrawlSite.class, numberOfCrawlers); } } catch (Exception ex) { System.out.print("can't read config xml, review xml file !!"); System.out.print(ex.getMessage()); } }
From source file:com.meli.client.controller.AppController.java
public static void main(String[] args) { String query = ""; String fileName = ""; String countryCode = ""; String option = ""; for (int i = 0; i < args.length - 1; i++) { option = args[i];/*from w w w. j a v a2 s . c om*/ if (option.length() >= 2) { String argVal = option.substring(0, 2); if (!args[i + 1].isEmpty() && !args[i + 1].matches("-[qfc]")) { if ("-q".equals(argVal)) { query = args[i + 1]; continue; } if ("-f".equals(argVal)) { fileName = args[i + 1]; continue; } if ("-c".equals(argVal)) countryCode = args[i + 1]; } } } if (!fileName.isEmpty()) processQueryFile(fileName, countryCode); if (!query.isEmpty()) doApiCalls(query, countryCode); }
From source file:bear.core.BearMain.java
/** * -VbearMain.appConfigDir=src/main/groovy/examples -VbearMain.buildDir=.bear/classes -VbearMain.script=dumpSampleGrid -VbearMain.projectClass=SecureSocialDemoProject -VbearMain.propertiesFile=.bear/test.properties *///from w w w. j a v a 2 s . co m public static void main(String[] args) throws Exception { int i = ArrayUtils.indexOf(args, "--log-level"); if (i != -1) { LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.toLevel(args[i + 1])); } i = ArrayUtils.indexOf(args, "-q"); if (i != -1) { LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.WARN); } GlobalContext global = GlobalContext.getInstance(); BearMain bearMain = null; try { bearMain = new BearMain(global, getCompilerManager(), args); } catch (Exception e) { if (e.getClass().getSimpleName().equals("MissingRequiredOptionException")) { System.out.println(e.getMessage()); } else { Throwables.getRootCause(e).printStackTrace(); } System.exit(-1); } if (bearMain.checkHelpAndVersion()) { return; } AppOptions2 options2 = bearMain.options; if (options2.has(AppOptions2.UNPACK_DEMOS)) { String filesAsText = ProjectGenerator.readResource("/demoFiles.txt"); int count = 0; for (String resource : filesAsText.split("::")) { File dest = new File(BEAR_DIR + resource); System.out.printf("copying %s to %s...%n", resource, dest); writeStringToFile(dest, ProjectGenerator.readResource(resource)); count++; } System.out.printf("extracted %d files%n", count); return; } if (options2.has(AppOptions2.CREATE_NEW)) { String dashedTitle = options2.get(AppOptions2.CREATE_NEW); String user = options2.get(AppOptions2.USER); String pass = options2.get(AppOptions2.PASSWORD); List<String> hosts = options2.getList(AppOptions2.HOSTS); List<String> template; if (options2.has(AppOptions2.TEMPLATE)) { template = options2.getList(AppOptions2.TEMPLATE); } else { template = emptyList(); } ProjectGenerator g = new ProjectGenerator(dashedTitle, user, pass, hosts, template); if (options2.has(AppOptions2.ORACLE_USER)) { g.oracleUser = options2.get(AppOptions2.ORACLE_USER); } if (options2.has(AppOptions2.ORACLE_PASSWORD)) { g.oraclePassword = options2.get(AppOptions2.ORACLE_PASSWORD); } File projectFile = new File(BEAR_DIR, g.getProjectTitle() + ".groovy"); File pomFile = new File(BEAR_DIR, "pom.xml"); writeStringToFile(projectFile, g.processTemplate("TemplateProject.template")); writeStringToFile(new File(BEAR_DIR, dashedTitle + ".properties"), g.processTemplate("project-properties.template")); writeStringToFile(new File(BEAR_DIR, "demos.properties"), g.processTemplate("project-properties.template")); writeStringToFile(new File(BEAR_DIR, "bear-fx.properties"), g.processTemplate("bear-fx.properties.template")); writeStringToFile(pomFile, g.generatePom(dashedTitle)); System.out.printf("Created project file: %s%n", projectFile.getPath()); System.out.printf("Created maven pom: %s%n", pomFile.getPath()); System.out.println("\nProject files have been created. You may now: " + "\n a) Run `bear " + g.getShortName() + ".ls` to quick-test your minimal setup" + "\n b) Import the project to IDE or run smoke tests, find more details at the project wiki: https://github.com/chaschev/bear/wiki/."); return; } Bear bear = global.bear; if (options2.has(AppOptions2.QUIET)) { global.put(bear.quiet, true); LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.WARN); } if (options2.has(AppOptions2.USE_UI)) { global.put(bear.useUI, true); } if (options2.has(AppOptions2.NO_UI)) { global.put(bear.useUI, false); } List<?> list = options2.getOptionSet().nonOptionArguments(); if (list.size() > 1) { throw new IllegalArgumentException("too many arguments: " + list + ", " + "please specify an invoke line, project.method(arg1, arg2)"); } if (list.isEmpty()) { throw new UnsupportedOperationException("todo implement running a single project"); } String invokeLine = (String) list.get(0); String projectName; String method; if (invokeLine.contains(".")) { projectName = StringUtils.substringBefore(invokeLine, "."); method = StringUtils.substringAfter(invokeLine, "."); } else { projectName = invokeLine; method = null; } if (method == null || method.isEmpty()) method = "deploy()"; if (!method.contains("(")) method += "()"; Optional<CompiledEntry<? extends BearProject>> optional = bearMain.compileManager.findProject(projectName); if (!optional.isPresent()) { throw new IllegalArgumentException("project was not found: " + projectName + ", loaded classes: \n" + Joiner.on("\n").join(bearMain.compileManager.findProjects()) + ", searched in: " + bearMain.compileManager.getSourceDirs() + ", "); } BearProject project = OpenBean.newInstance(optional.get().aClass).injectMain(bearMain); GroovyShell shell = new GroovyShell(); shell.setVariable("project", project); shell.evaluate("project." + method); }
From source file:de.bruse.c2x.cli.Main.java
public static void main(String[] args) { CommandLineParser parser = new GnuParser(); Options options = new Options(); Option input = new Option("i", INPUT, HAS_ARGS, "CityGML file to be converted."); input.setArgs(ONE);//from w w w.j a v a 2s.c om input.setArgName(INPUT); input.setRequired(Boolean.TRUE); options.addOption(input); Option levelOfDetail = new Option("l", LEVEL_OF_DETAIL, HAS_ARGS, "Level of detail to be converted. Possible values are LOD1 and LOD2."); levelOfDetail.setArgs(ONE); levelOfDetail.setArgName(LEVEL_OF_DETAIL); levelOfDetail.setRequired(Boolean.TRUE); options.addOption(levelOfDetail); Option geometryType = new Option("t", GEOMETRY_TYPE, HAS_ARGS, "Geometry type to be converted. Possible values are SOLID and MULTI_SURFACE."); geometryType.setArgs(ONE); geometryType.setArgName(GEOMETRY_TYPE); geometryType.setRequired(Boolean.TRUE); options.addOption(geometryType); Option output = new Option("o", OUTPUT, HAS_ARGS, "File path of the output file."); output.setArgs(ONE); output.setArgName(OUTPUT); output.setRequired(Boolean.FALSE); options.addOption(output); Option targetFormat = new Option("f", FORMAT, HAS_ARGS, "Format of the output file. Possible values are X3D and COLLADA."); targetFormat.setArgs(ONE); targetFormat.setArgName(FORMAT); targetFormat.setRequired(Boolean.TRUE); options.addOption(targetFormat); Option split = new Option("s", SPLIT, NO_ARGS, "Generate one scene node for each building (X3D only)."); split.setArgName(SPLIT); split.setRequired(Boolean.FALSE); options.addOption(split); Option validate = new Option("v", VALIDATE, NO_ARGS, "Validate the CityGML file."); validate.setArgName(VALIDATE); validate.setRequired(Boolean.FALSE); options.addOption(validate); try { CommandLine line = parser.parse(options, args); if (line.hasOption(INPUT) && line.hasOption(LEVEL_OF_DETAIL) && line.hasOption(GEOMETRY_TYPE) && line.hasOption(FORMAT)) { String inputValue = line.getOptionValue(INPUT); String levelOfDetailValue = line.getOptionValue(LEVEL_OF_DETAIL); String geometryTypeValue = line.getOptionValue(GEOMETRY_TYPE); String targetFormatValue = line.getOptionValue(FORMAT); String outputValue = line.getOptionValue(OUTPUT); LevelOfDetail lod = LevelOfDetail.valueOf(levelOfDetailValue); GeometryType type = GeometryType.valueOf(geometryTypeValue); if (Objects.isNull(lod) || Objects.isNull(type) || (!targetFormatValue.equals(X3D) && !targetFormatValue.equals(COLLADA))) { printHelp(options); } else { if (line.hasOption(VALIDATE)) { triggerValidation(inputValue); } if (targetFormatValue.equals(X3D)) { boolean splitValue = false; if (line.hasOption(SPLIT)) { splitValue = true; } if (Objects.isNull(outputValue) || outputValue.isEmpty()) { outputValue = inputValue + X3D_FILE_EXT; } triggerX3DConversion(inputValue, lod, type, outputValue, splitValue); } else if (targetFormatValue.equals(COLLADA)) { if (Objects.isNull(outputValue) || outputValue.isEmpty()) { outputValue = inputValue + COLLADA_FILE_EXT; } triggerColladaConversion(inputValue, lod, type, outputValue); } System.out.println("Conversion succeeded."); } } else { printHelp(options); } } catch (ParseException | IllegalArgumentException e) { printHelp(options); } catch (ValidationException e) { System.out.println("Input file is invalid. Operation canceled.\n" + e.getMessage()); } catch (ConversionException e) { String message = "Failed to convert CityGML."; if (Objects.nonNull(e.getMessage())) { message += " " + e.getMessage(); } System.out.println(message); } catch (IOException e) { System.out.println("Failed to read from file '" + input + "'."); } }
From source file:net.yacy.yacy.java
/** * Main-method which is started by java. Checks for special arguments or * starts up the application.//from w w w .ja v a2 s. c om * * @param args * Given arguments from the command line. */ public static void main(String args[]) { try { // check assertion status //ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true); boolean assertionenabled = false; assert (assertionenabled = true) == true; // compare to true to remove warning: "Possible accidental assignement" if (assertionenabled) System.out.println("Asserts are enabled"); // check memory amount System.gc(); final long startupMemFree = MemoryControl.free(); final long startupMemTotal = MemoryControl.total(); // maybe go into headless awt mode: we have three cases depending on OS and one exception: // windows : better do not go into headless mode // mac : go into headless mode because an application is shown in gui which may not be wanted // linux : go into headless mode because this does not need any head operation // exception : if the -gui option is used then do not go into headless mode since that uses a gui boolean headless = true; if (OS.isWindows) headless = false; if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui")) headless = false; System.setProperty("java.awt.headless", headless ? "true" : "false"); String s = ""; for (final String a : args) s += a + " "; yacyRelease.startParameter = s.trim(); File applicationRoot = new File(System.getProperty("user.dir").replace('\\', '/')); File dataRoot = applicationRoot; //System.out.println("args.length=" + args.length); //System.out.print("args=["); for (int i = 0; i < args.length; i++) System.out.print(args[i] + ", "); System.out.println("]"); if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-startup") || args[0].equals("-start"))) { // normal start-up of yacy if (args.length > 1) { if (args[1].startsWith(File.separator)) { /* data root folder provided as an absolute path */ dataRoot = new File(args[1]); } else { /* data root folder provided as a path relative to the user home folder */ dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]); } } preReadSavedConfigandInit(dataRoot); startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false); } else if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui")) { // start-up of yacy with gui if (args.length > 1) { if (args[1].startsWith(File.separator)) { /* data root folder provided as an absolute path */ dataRoot = new File(args[1]); } else { /* data root folder provided as a path relative to the user home folder */ dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]); } } preReadSavedConfigandInit(dataRoot); startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, true); } else if ((args.length >= 1) && ((args[0].toLowerCase(Locale.ROOT).equals("-shutdown")) || (args[0].equals("-stop")))) { // normal shutdown of yacy if (args.length == 2) applicationRoot = new File(args[1]); shutdown(applicationRoot); } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-update"))) { // aut-update yacy if (args.length == 2) applicationRoot = new File(args[1]); update(applicationRoot); } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-version"))) { // show yacy version System.out.println(copyright); } else if ((args.length > 1) && (args[0].toLowerCase(Locale.ROOT).equals("-config"))) { // set config parameter. Special handling of adminAccount=user:pwd (generates md5 encoded password) // on Windows parameter should be enclosed in doublequotes to accept = sign (e.g. -config "port=8090" "port.ssl=8043") File f = new File(dataRoot, "DATA/SETTINGS/"); if (!f.exists()) { mkdirsIfNeseccary(f); } else { if (new File(dataRoot, "DATA/yacy.running").exists()) { System.out.println("please restart YaCy"); } } // use serverSwitch to read config properties (including init values from yacy.init serverSwitch ss = new serverSwitch(dataRoot, applicationRoot, "defaults/yacy.init", "DATA/SETTINGS/yacy.conf"); for (int icnt = 1; icnt < args.length; icnt++) { String cfg = args[icnt]; int pos = cfg.indexOf('='); if (pos > 0) { String cmd = cfg.substring(0, pos); String val = cfg.substring(pos + 1); if (!val.isEmpty()) { if (cmd.equalsIgnoreCase(SwitchboardConstants.ADMIN_ACCOUNT)) { // special command to set adminusername and md5-pwd int cpos = val.indexOf(':'); //format adminAccount=adminname:adminpwd if (cpos >= 0) { String username = val.substring(0, cpos); String pwdtxt = val.substring(cpos + 1); if (!username.isEmpty()) { ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME, username); System.out.println("Set property " + SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME + " = " + username); } else { username = ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME, "admin"); } ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "MD5:" + Digest.encodeMD5Hex(username + ":" + ss.getConfig(SwitchboardConstants.ADMIN_REALM, "YaCy") + ":" + pwdtxt)); System.out.println("Set property " + SwitchboardConstants.ADMIN_ACCOUNT_B64MD5 + " = " + ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "")); } } else { ss.setConfig(cmd, val); System.out.println("Set property " + cmd + " = " + val); } } } else { System.out.println( "skip parameter " + cfg + " (equal sign missing, put parameter in doublequotes)"); } System.out.println(); } } else { if (args.length == 1) { applicationRoot = new File(args[0]); } preReadSavedConfigandInit(dataRoot); startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false); } } finally { ConcurrentLog.shutdown(); } }
From source file:com.oltpbenchmark.multitenancy.MuTeBench.java
/** * @param args//from w ww . j a va2 s. c o m * @throws Exception */ public static void main(String[] args) throws Exception { String duration = null; String scenarioFile = null; // ------------------------------------------------------------------- // INITIALIZE LOGGING // ------------------------------------------------------------------- String log4jPath = System.getProperty("log4j.configuration"); if (log4jPath != null) { org.apache.log4j.PropertyConfigurator.configure(log4jPath); } else { throw new RuntimeException("Missing log4j.properties file"); } // ------------------------------------------------------------------- // PARSE COMMAND LINE PARAMETERS // ------------------------------------------------------------------- CommandLineParser parser = new PosixParser(); XMLConfiguration pluginConfig = null; try { pluginConfig = new XMLConfiguration("config/plugin.xml"); } catch (ConfigurationException e1) { LOG.info("Plugin configuration file config/plugin.xml is missing"); e1.printStackTrace(); } pluginConfig.setExpressionEngine(new XPathExpressionEngine()); Options options = new Options(); options.addOption("s", "scenario", true, "[required] Workload scenario file"); options.addOption("a", "analysis-buckets", true, "sampling buckets for result aggregation"); options.addOption("r", "runtime", true, "maximum runtime (no events will be started after finishing runtime)"); options.addOption("v", "verbose", false, "Display Messages"); options.addOption("g", "gui", false, "Show controlling GUI"); options.addOption("h", "help", false, "Print this help"); options.addOption("o", "output", true, "Output file (default System.out)"); options.addOption("b", "baseline", true, "Output files of previous baseline run"); options.addOption(null, "histograms", false, "Print txn histograms"); options.addOption("d", "dialects-export", true, "Export benchmark SQL to a dialects file"); // parse the command line arguments CommandLine argsLine = parser.parse(options, args); if (argsLine.hasOption("h")) { printUsage(options); return; } else if (!argsLine.hasOption("scenario")) { INIT_LOG.fatal("Missing scenario description file"); System.exit(-1); } else scenarioFile = argsLine.getOptionValue("scenario"); if (argsLine.hasOption("r")) duration = argsLine.getOptionValue("r"); if (argsLine.hasOption("runtime")) duration = argsLine.getOptionValue("runtime"); // ------------------------------------------------------------------- // CREATE TENANT SCHEDULE // ------------------------------------------------------------------- INIT_LOG.info("Create schedule"); Schedule schedule = new Schedule(duration, scenarioFile); HashMap<Integer, ScheduleEvents> tenantEvents = schedule.getTenantEvents(); ArrayList<Integer> tenantList = schedule.getTenantList(); List<BenchmarkModule> benchList = new ArrayList<BenchmarkModule>(); for (int tenInd = 0; tenInd < tenantList.size(); tenInd++) { int tenantID = tenantList.get(tenInd); for (int tenEvent = 0; tenEvent < tenantEvents.get(tenantID).size(); tenEvent++) { BenchmarkSettings benchmarkSettings = (BenchmarkSettings) tenantEvents.get(tenantID) .getBenchmarkSettings(tenEvent); // update benchmark Settings benchmarkSettings.setTenantID(tenantID); // ------------------------------------------------------------------- // GET PLUGIN LIST // ------------------------------------------------------------------- String plugins = benchmarkSettings.getBenchmark(); String[] pluginList = plugins.split(","); String configFile = benchmarkSettings.getConfigFile(); XMLConfiguration xmlConfig = new XMLConfiguration(configFile); xmlConfig.setExpressionEngine(new XPathExpressionEngine()); int lastTxnId = 0; for (String plugin : pluginList) { // ---------------------------------------------------------------- // WORKLOAD CONFIGURATION // ---------------------------------------------------------------- String pluginTest = ""; pluginTest = "[@bench='" + plugin + "']"; WorkloadConfiguration wrkld = new WorkloadConfiguration(); wrkld.setTenantId(tenantID); wrkld.setBenchmarkName(setTenantIDinString(plugin, tenantID)); wrkld.setXmlConfig(xmlConfig); wrkld.setDBType(DatabaseType.get(setTenantIDinString(xmlConfig.getString("dbtype"), tenantID))); wrkld.setDBDriver(setTenantIDinString(xmlConfig.getString("driver"), tenantID)); wrkld.setDBConnection(setTenantIDinString(xmlConfig.getString("DBUrl"), tenantID)); wrkld.setDBName(setTenantIDinString(xmlConfig.getString("DBName"), tenantID)); wrkld.setDBUsername(setTenantIDinString(xmlConfig.getString("username"), tenantID)); wrkld.setDBPassword(setTenantIDinString(xmlConfig.getString("password"), tenantID)); String terminalString = setTenantIDinString(xmlConfig.getString("terminals[not(@bench)]", "0"), tenantID); int terminals = Integer.parseInt(xmlConfig.getString("terminals" + pluginTest, terminalString)); wrkld.setTerminals(terminals); int taSize = Integer.parseInt(xmlConfig.getString("taSize", "1")); if (taSize < 0) INIT_LOG.fatal("taSize must not be negative!"); wrkld.setTaSize(taSize); wrkld.setProprietaryTaSyntax(xmlConfig.getBoolean("proprietaryTaSyntax", false)); wrkld.setIsolationMode(setTenantIDinString( xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE"), tenantID)); wrkld.setScaleFactor(Double .parseDouble(setTenantIDinString(xmlConfig.getString("scalefactor", "1.0"), tenantID))); wrkld.setRecordAbortMessages(xmlConfig.getBoolean("recordabortmessages", false)); int size = xmlConfig.configurationsAt("/works/work").size(); for (int i = 1; i < size + 1; i++) { SubnodeConfiguration work = xmlConfig.configurationAt("works/work[" + i + "]"); List<String> weight_strings; // use a workaround if there multiple workloads or // single // attributed workload if (pluginList.length > 1 || work.containsKey("weights[@bench]")) { weight_strings = get_weights(plugin, work); } else { weight_strings = work.getList("weights[not(@bench)]"); } int rate = 1; boolean rateLimited = true; boolean disabled = false; // can be "disabled", "unlimited" or a number String rate_string; rate_string = setTenantIDinString(work.getString("rate[not(@bench)]", ""), tenantID); rate_string = setTenantIDinString(work.getString("rate" + pluginTest, rate_string), tenantID); if (rate_string.equals(RATE_DISABLED)) { disabled = true; } else if (rate_string.equals(RATE_UNLIMITED)) { rateLimited = false; } else if (rate_string.isEmpty()) { LOG.fatal(String.format( "Tenant " + tenantID + ": Please specify the rate for phase %d and workload %s", i, plugin)); System.exit(-1); } else { try { rate = Integer.parseInt(rate_string); if (rate < 1) { LOG.fatal("Tenant " + tenantID + ": Rate limit must be at least 1. Use unlimited or disabled values instead."); System.exit(-1); } } catch (NumberFormatException e) { LOG.fatal(String.format( "Tenant " + tenantID + ": Rate string must be '%s', '%s' or a number", RATE_DISABLED, RATE_UNLIMITED)); System.exit(-1); } } Phase.Arrival arrival = Phase.Arrival.REGULAR; String arrive = setTenantIDinString(work.getString("@arrival", "regular"), tenantID); if (arrive.toUpperCase().equals("POISSON")) arrival = Phase.Arrival.POISSON; int activeTerminals; activeTerminals = Integer.parseInt(setTenantIDinString( work.getString("active_terminals[not(@bench)]", String.valueOf(terminals)), tenantID)); activeTerminals = Integer.parseInt(setTenantIDinString( work.getString("active_terminals" + pluginTest, String.valueOf(activeTerminals)), tenantID)); if (activeTerminals > terminals) { LOG.fatal("Tenant " + tenantID + ": Configuration error in work " + i + ": number of active terminals" + "" + "is bigger than the total number of terminals"); System.exit(-1); } wrkld.addWork(Integer.parseInt(setTenantIDinString(work.getString("/time"), tenantID)), rate, weight_strings, rateLimited, disabled, activeTerminals, arrival); } // FOR int numTxnTypes = xmlConfig .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size(); if (numTxnTypes == 0 && pluginList.length == 1) { // if it is a single workload run, <transactiontypes /> // w/o attribute is used pluginTest = "[not(@bench)]"; numTxnTypes = xmlConfig .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size(); } wrkld.setNumTxnTypes(numTxnTypes); // CHECKING INPUT PHASES int j = 0; for (Phase p : wrkld.getAllPhases()) { j++; if (p.getWeightCount() != wrkld.getNumTxnTypes()) { LOG.fatal(String.format("Tenant " + tenantID + ": Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types", j, p.getWeightCount(), wrkld.getNumTxnTypes())); System.exit(-1); } } // FOR // Generate the dialect map wrkld.init(); assert (wrkld.getNumTxnTypes() >= 0); assert (xmlConfig != null); // ---------------------------------------------------------------- // BENCHMARK MODULE // ---------------------------------------------------------------- String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']"); if (classname == null) { throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml"); } BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[] { wrkld }, new Class<?>[] { WorkloadConfiguration.class }); assert (benchList.get(0) != null); Map<String, Object> initDebug = new ListOrderedMap<String, Object>(); initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname)); initDebug.put("Configuration", configFile); initDebug.put("Type", wrkld.getDBType()); initDebug.put("Driver", wrkld.getDBDriver()); initDebug.put("URL", wrkld.getDBConnection()); initDebug.put("Isolation", setTenantIDinString( xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE [DEFAULT]"), tenantID)); initDebug.put("Scale Factor", wrkld.getScaleFactor()); INIT_LOG.info(SINGLE_LINE + "\n\n" + StringUtil.formatMaps(initDebug)); INIT_LOG.info(SINGLE_LINE); // Load TransactionTypes List<TransactionType> ttypes = new ArrayList<TransactionType>(); // Always add an INVALID type for Carlo ttypes.add(TransactionType.INVALID); int txnIdOffset = lastTxnId; for (int i = 1; i < wrkld.getNumTxnTypes() + 1; i++) { String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]"; String txnName = setTenantIDinString(xmlConfig.getString(key + "/name"), tenantID); int txnId = i + 1; if (xmlConfig.containsKey(key + "/id")) { txnId = Integer .parseInt(setTenantIDinString(xmlConfig.getString(key + "/id"), tenantID)); } ttypes.add(bench.initTransactionType(txnName, txnId + txnIdOffset)); lastTxnId = i; } // FOR TransactionTypes tt = new TransactionTypes(ttypes); wrkld.setTransTypes(tt); if (benchmarkSettings.getBenchmarkSlaFile() != null) wrkld.setSlaFromFile(benchmarkSettings.getBenchmarkSlaFile()); LOG.debug("Tenant " + tenantID + ": Using the following transaction types: " + tt); bench.setTenantOffset(tenantEvents.get(tenantID).getTime(tenEvent)); bench.setTenantID(tenantID); bench.setBenchmarkSettings(benchmarkSettings); benchList.add(bench); } } } // create result collector ResultCollector rCollector = new ResultCollector(tenantList); // execute benchmarks in parallel ArrayList<Thread> benchThreads = new ArrayList<Thread>(); for (BenchmarkModule benchmark : benchList) { BenchmarkExecutor benchThread = new BenchmarkExecutor(benchmark, argsLine); Thread t = new Thread(benchThread); t.start(); benchThreads.add(t); benchmark.getWorkloadConfiguration().setrCollector(rCollector); } // waiting for completion of all benchmarks for (Thread t : benchThreads) { t.join(); } // print statistics int analysisBuckets = -1; if (argsLine.hasOption("analysis-buckets")) analysisBuckets = Integer.parseInt(argsLine.getOptionValue("analysis-buckets")); String output = null; if (argsLine.hasOption("o")) output = argsLine.getOptionValue("o"); String baseline = null; if (argsLine.hasOption("b")) baseline = argsLine.getOptionValue("b"); rCollector.printStatistics(output, analysisBuckets, argsLine.hasOption("histograms"), baseline); // create GUI if (argsLine.hasOption("g") && (!rCollector.getAllResults().isEmpty())) { try { Gui gui = new Gui(Integer.parseInt(argsLine.getOptionValue("analysis-buckets", "10")), rCollector, output); } catch (Exception e) { e.printStackTrace(); } } }
From source file:de.ipbhalle.metfusion.main.SubstructureSearch.java
public static void main(String[] args) { String token = "eeca1d0f-4c03-4d81-aa96-328cdccf171a"; //String token = "a1004d0f-9d37-47e0-acdd-35e58e34f603"; //test();/* w w w .j a v a 2 s . c o m*/ //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/136m0498_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/148m0859_MSMS.mf"); // File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/164m0445a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/192m0757a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/naringenin.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Known_BT_MSMS_ChemSp/1MeBT_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/150m0655a_MSMS.mf"); File file = new File( "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/192m0757b_MSMS.mf"); MetFusionBatchFileHandler mbf = new MetFusionBatchFileHandler(file); try { mbf.readFile(); } catch (IOException e) { //System.out.println(e.getMessage()); System.err.println( "Error reading from MetFusion settings file [" + file.getAbsolutePath() + "]. Aborting!"); System.exit(-1); } MetFusionBatchSettings settings = mbf.getBatchSettings(); List<String> absent = settings.getSubstrucAbsent(); List<String> present = settings.getSubstrucPresent(); for (String s : present) { System.out.println("present -> " + s); } for (String s : absent) { System.out.println("absent -> " + s); } String formula = settings.getMfFormula(); System.out.println("formula -> " + formula); boolean useFormulaAsQuery = true; boolean useSDF = false; String sdfFile = ""; if (useSDF) { sdfFile = "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/results_afterFormulaQuery/192m0757b_MSMS.sdf"; if (sdfFile.isEmpty()) { // TODO alternatively use SDF file from query file? System.err.println("SDF file needs to be specified! Exiting."); System.exit(-1); } } SubstructureSearch ss = new SubstructureSearch(present, absent, token, formula, mbf, useFormulaAsQuery, useSDF, sdfFile); ss.run(); List<ResultSubstructure> remaining = ss.getResultsRemaining(); List<Result> resultsForSDF = new ArrayList<Result>(); StringBuilder sb = new StringBuilder(); String sep = ","; for (ResultSubstructure rs : remaining) { sb.append(rs.getId()).append(sep); Result r = new Result(rs.getPort(), rs.getId(), rs.getName(), rs.getScore()); r.setMol(rs.getMol()); r.setSmiles(rs.getSmiles()); r.setInchi(rs.getInchi()); r.setInchikey(rs.getInchikey()); resultsForSDF.add(r); } String ids = sb.toString(); String fileSep = System.getProperty("file.separator"); if (!ids.isEmpty()) { ids = ids.substring(0, ids.length() - 1); System.out.println("ids -> " + ids); settings.setMfDatabaseIDs(ids); String filename = file.getName(); String prefix = filename.substring(0, filename.lastIndexOf(".")); filename = filename.replace(prefix, prefix + "_ids"); String dir = file.getParent(); System.out.println("dir -> " + dir); if (!dir.endsWith(fileSep)) dir += fileSep; File output = new File(file.getParent(), filename); mbf.writeFile(output, settings); SDFOutputHandler so = new SDFOutputHandler(dir + prefix + ".sdf"); boolean writeOK = so.writeOriginalResults(resultsForSDF, false); if (!writeOK) System.err.println("Error writing SDF [" + so.getFilename()); } }
From source file:AndroidUninstallStock.java
@SuppressWarnings("static-access") public static void main(String[] args) { try {/*from www . jav a 2 s.c om*/ String lang = Locale.getDefault().getLanguage(); GnuParser cmdparser = new GnuParser(); Options cmdopts = new Options(); for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) { // hack for printOptions java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld); fieldopt.setAccessible(true); fieldopt.set(cmdopts, new LinkedHashMap<>()); } cmdopts.addOption("h", "help", false, "Help"); cmdopts.addOption("t", "test", false, "Show only report"); cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg() .withDescription("Path to ADB from Android SDK").create("a")); cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg() .withDescription("Select device (\"adb devices\")").create("d")); cmdopts.addOption(null, "restore", false, "If packages have not yet removed and are disabled, " + "you can activate them again"); cmdopts.addOption(null, "google", false, "Delete packages are in the Google section"); cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex" + System.lineSeparator() + "(It is required to repeat command execution)"); cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]"); //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)"); cmdopts.addOption(null, "scanlibs", false, "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib"); cmdopts.addOptionGroup(new OptionGroup() { { addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired() .withDescription("Create file with list packages").create()); addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create()); } }); cmdopts.getOption("lang").setDescription( "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market"); CommandLine cmd = cmdparser.parse(cmdopts, args); if (args.length == 0 || cmd.hasOption("help")) { PrintWriter console = new PrintWriter(System.out); HelpFormatter cmdhelp = new HelpFormatter(); cmdhelp.setOptionComparator(new Comparator<Option>() { @Override public int compare(Option o1, Option o2) { return 0; } }); console.println("WARNING: Before use make a backup with ClockworkMod Recovery!"); console.println(); console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]"); cmdhelp.printOptions(console, 80, cmdopts, 3, 2); console.flush(); return; } String adb = cmd.getOptionValue("adb", "adb"); try { run(adb, "start-server"); } catch (IOException e) { System.out.println("Error: Not found ADB! Use -a or --adb"); return; } final boolean NotTest = !cmd.hasOption("test"); String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev")); if (!deverror.isEmpty()) { System.out.println(deverror); return; } System.out.println("Getting list packages:"); LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>(); for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) { // "pm list packages" give list sorted by packages ;) String pckg = ln.substring("package:".length()); String pckgname = ln.substring(ln.lastIndexOf('=') + 1); pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1); if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) { apklist.put(pckg, pckgname); } } for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) { String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk"); if (!apklist.containsKey(path)) { apklist.put(path, ""); } } apklist.remove("/system/app/mcRegistry"); for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } String genfile = cmd.getOptionValue("genfile"); if (genfile != null) { Path genpath = Paths.get(genfile); try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8, new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE })) { if (cmd.getOptionValue("lang") != null) { lang = cmd.getOptionValue("lang"); } LinkedHashSet<String> listsystem = new LinkedHashSet<String>() { { add("com.android"); add("com.google.android"); //add("com.sec.android.app"); add("com.monotype.android"); add("eu.chainfire.supersu"); } }; // \r\n for Windows Notepad gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"); gen.write("<!-- & raplace with & or use <![CDATA[ ]]> -->\r\n"); gen.write("<AndroidUninstallStock>\r\n\r\n"); gen.write("<Normal>\r\n"); System.out.println(); System.out.println("\tNormal:"); writeInfo(gen, apklist, lang, listsystem, true); gen.write("\t<apk name=\"Exclude Google and etc\">\r\n"); for (String exc : listsystem) { gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n"); } gen.write("\t</apk>\r\n"); gen.write("</Normal>\r\n\r\n"); gen.write("<Google>\r\n"); System.out.println(); System.out.println("\tGoogle:"); writeInfo(gen, apklist, lang, listsystem, false); gen.write("</Google>\r\n\r\n"); gen.write("</AndroidUninstallStock>\r\n"); System.out.println("File " + genpath.toAbsolutePath() + " created."); } return; } String[] FileName = cmd.getArgs(); if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) { System.out.println("Error: File " + FileName[0] + " not found!"); return; } DocumentBuilderFactory xmlfactory = getXmlDocFactory(); // DocumentBuilder.setErrorHandler() for print errors Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0])); LinkedList<AusInfo> Normal = new LinkedList<AusInfo>(); LinkedList<AusInfo> Google = new LinkedList<AusInfo>(); NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes(); for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) { Node ndnow = ndaus.item(ndausx); NodeList nd = ndnow.getChildNodes(); String ndname = ndnow.getNodeName(); for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) { if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) { continue; } if (ndname.equalsIgnoreCase("Normal")) { Normal.add(getApkInfo(nd.item(ndx))); } else if (ndname.equalsIgnoreCase("Google")) { Google.add(getApkInfo(nd.item(ndx))); } } } // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages. // Now requires a restart. System.out.println(); System.out.println("Include and Exclude packages (Normal):"); LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false); System.out.println(); System.out.println("Global Exclude packages (Normal):"); apkNormal = getApkFromPattern(apkNormal, Normal, true); System.out.println(); System.out.println("Final list packages (Normal):"); for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>(); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Include and Exclude packages (Google):"); apkGoogle = getApkFromPattern(apklist, Google, false); System.out.println(); System.out.println("Global Exclude packages (Google):"); apkGoogle = getApkFromPattern(apkGoogle, Google, true); System.out.println(); System.out.println("Final list packages (Google):"); for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } } if (NotTest) { if (!hasRoot(adb)) { System.out.println("No Root"); System.out.println(); System.out.println("FINISH :)"); return; } } if (cmd.hasOption("restore")) { System.out.println(); System.out.println("Enable (Restore) packages (Normal):"); damage(adb, "pm enable ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Enable (Restore) packages (Google):"); damage(adb, "pm enable ", NotTest, apkGoogle, 2); } System.out.println(); System.out.println("FINISH :)"); return; } else { System.out.println(); System.out.println("Disable packages (Normal):"); damage(adb, "pm disable ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Disable packages (Google):"); damage(adb, "pm disable ", NotTest, apkGoogle, 2); } } if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) { System.out.println(); System.out.println("FINISH :)"); return; } // Reboot now not needed /*if (NotTest) { reboot(adb, "-s", lastdevice, "reboot"); if (!hasRoot(adb)) { System.out.println("No Root"); System.out.println(); System.out.println("FINISH :)"); return; } }*/ if (cmd.hasOption("unlib")) { // "find" not found System.out.println(); System.out.println("Getting list libraries:"); LinkedList<String> liblist = new LinkedList<String>(); liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/")); String dircur = "/system/lib/"; for (int x = 0; x < liblist.size(); x++) { if (liblist.get(x).startsWith("scan:")) { dircur = liblist.get(x).substring("scan:".length()); liblist.remove(x); x--; } else if (liblist.get(x).startsWith("d")) { String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/"; liblist.remove(x); x--; liblist.add("scan:/system/lib/" + dir); liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir)); continue; } liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4)); System.out.println(liblist.get(x)); } final boolean scanlibs = cmd.hasOption("scanlibs"); LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal, "Normal", scanlibs); libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal"); System.out.println(); System.out.println("Final list libraries (Normal):"); for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) { System.out.println(info.getKey() + " = " + info.getValue()); } LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>(); if (cmd.hasOption("google")) { libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs); libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google"); System.out.println(); System.out.println("Final list libraries (Google):"); for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) { System.out.println(info.getKey() + " = " + info.getValue()); } } LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist); for (String key : apkNormal.keySet()) { apkExclude.remove(key); } for (String key : apkGoogle.keySet()) { apkExclude.remove(key); } System.out.println(); System.out.println("Include libraries from Exclude packages:"); LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude); System.out.println(); System.out.println("Enclude libraries from Exclude packages (Normal):"); for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) { if (libExclude.containsKey(info.getKey())) { System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey())); libNormal.remove(info.getKey()); } } System.out.println(); System.out.println("Enclude libraries from Exclude packages (Google):"); for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) { if (libExclude.containsKey(info.getKey())) { System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey())); libGoogle.remove(info.getKey()); } } System.out.println(); System.out.println("Delete libraries (Normal):"); damage(adb, "rm ", NotTest, libNormal, 1); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Delete libraries (Google):"); damage(adb, "rm ", NotTest, libGoogle, 1); } } if (cmd.hasOption("unapk")) { System.out.println(); System.out.println("Cleaning data packages (Normal):"); damage(adb, "pm clear ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Cleaning data packages (Google):"); damage(adb, "pm clear ", NotTest, apkGoogle, 2); } System.out.println(); System.out.println("Uninstall packages (Normal):"); damage(adb, "pm uninstall ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Uninstall packages (Google):"); damage(adb, "pm uninstall ", NotTest, apkGoogle, 2); } } if (cmd.hasOption("unapk")) { System.out.println(); System.out.println("Delete packages (Normal):"); LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>(); for (Map.Entry<String, String> apk : apkNormal.entrySet()) { dexNormal.put(apk.getKey(), apk.getValue()); dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue()); dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue()); } damage(adb, "rm ", NotTest, dexNormal, 1); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Delete packages (Google):"); LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>(); for (Map.Entry<String, String> apk : apkGoogle.entrySet()) { dexGoogle.put(apk.getKey(), apk.getValue()); dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue()); dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue()); } damage(adb, "rm ", NotTest, dexGoogle, 1); } } if (NotTest) { run(adb, "-s", lastdevice, "reboot"); } System.out.println(); System.out.println("FINISH :)"); } catch (SAXException e) { System.out.println("Error parsing list: " + e); } catch (Throwable e) { e.printStackTrace(); } }
From source file:LamportBasicVersion.java
public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException { totalMessageCount = 0;//from w ww .ja v a 2 s.c o m //For parsing the file and storing the information String line; String configurationFile = "configuration.txt"; int lineCountInFile = 0; myProcessId = Integer.parseInt(args[0]); FileReader fileReader = new FileReader(configurationFile); BufferedReader bufferedReader = new BufferedReader(fileReader); while ((line = bufferedReader.readLine()) != null) { if ((!(line.startsWith("#"))) && (!(line.isEmpty()))) { lineCountInFile = lineCountInFile + 1; String[] splitLine = line.split(" "); switch (lineCountInFile) { case 1: numberOfProcesses = Integer.parseInt(splitLine[0]); interRequestDelay = Integer.parseInt(splitLine[1]); csExecutionTime = Integer.parseInt(splitLine[2]); maxNumberOfRequest = Integer.parseInt(splitLine[3]); machineNames = new String[Integer.parseInt(splitLine[0])]; portNumbers = new int[Integer.parseInt(splitLine[0])]; break; default: machineNames[lineCountInFile - 2] = splitLine[1]; portNumbers[lineCountInFile - 2] = Integer.parseInt(splitLine[2]); break; } } } conditionArray = new int[numberOfProcesses]; finishFlagArray = new int[numberOfProcesses]; //Initializing vector class VectorClass.initialize(numberOfProcesses); //Fill the arrays with zero false value for (int o = 0; o < numberOfProcesses; o++) { conditionArray[o] = 0; finishFlagArray[o] = 0; } // Write output to file filename = filename + Integer.toString(myProcessId) + ".out"; file = new File(filename); file.createNewFile(); writer = new FileWriter(file); // Write clocks to file filenameClock = filenameClock + Integer.toString(myProcessId) + ".out"; fileClock = new File(filenameClock); fileClock.createNewFile(); //writerClock = new FileWriter(fileClock); fw = new FileWriter(fileClock); bw = new BufferedWriter(fw); // // Expo mean insert csExecutionExpoDelay = new ExponentialDistribution(csExecutionTime); interRequestExpoDelay = new ExponentialDistribution(interRequestDelay); // System.out.println("********************************************************"); System.out.println("My process id : " + myProcessId); System.out.println("Number of processes : " + numberOfProcesses); System.out.println("Inter-request delay : " + interRequestDelay); System.out.println("Critical section execution time : " + csExecutionTime); System.out.println("Maximum number of request : " + maxNumberOfRequest); System.out.println( "My process name : " + machineNames[myProcessId] + " My port number : " + portNumbers[myProcessId]); for (int i = 0; i < numberOfProcesses; i++) { System.out.println("Process name : " + machineNames[i] + " Port number : " + portNumbers[i]); } System.out.println("********************************************************"); //For hosting server localhost SctpServerChannel sctpServerChannel = SctpServerChannel.open(); InetSocketAddress serverAddr = new InetSocketAddress(portNumbers[myProcessId]); sctpServerChannel.bind(serverAddr); System.out.println("********************************************************"); System.out.println("Local server hosted"); System.out.println("********************************************************"); //For creating neighbor SCTP channels Thread.sleep(30000); socketAddress = new SocketAddress[numberOfProcesses]; sctpChannel = new SctpChannel[numberOfProcesses]; System.out.println("********************************************************"); System.out.println("Neighbor channels created"); System.out.println("********************************************************"); //Thread spanned for generating critical section request new Thread(new LamportBasicVersion()).start(); //while loop to receive all the requests and other messages while (true) { try (SctpChannel sctpChannelFromClient = sctpServerChannel.accept()) { mutex.acquire(); byteBufferFromNeighbor.clear(); String receiveMessage; MessageInfo messageInfoFromNeighbor = sctpChannelFromClient.receive(byteBufferFromNeighbor, null, null); //System.out.println("Raw Message : " + messageInfoFromNeighbor); receiveMessage = byteToString(byteBufferFromNeighbor, messageInfoFromNeighbor); //write to file start writer.write("Received Message : " + receiveMessage); writer.write("\n"); writer.flush(); //write to file end System.out.println("Received Message : " + receiveMessage); if (receiveMessage.contains("Request")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // int requestMade = Integer.parseInt(parseMessage[3] + parseMessage[1]); queue.add(requestMade); //Send reply messages to that process for entering CS lamportClock++; //vector clock construction int[] vector = VectorClass.increment(myProcessId); String vectorClockConstruction = ""; for (int g = 0; g < vector.length; g++) { if (g == 0) { vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]); } else { vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]); } } // for (int k = 0; k < numberOfProcesses; k++) { if (k == Integer.parseInt(parseMessage[1])) { try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[k].connect(socketAddress[k]); String sendMessage = "Reply from Process-" + myProcessId + "-" + Integer.toString(requestMade) + "-" + lamportClock + "-" + vectorClockConstruction; System.out.println("Message sent is : " + sendMessage); //write to file start writer.write("Message sent is : " + sendMessage); writer.write("\n"); writer.flush(); //write to file end MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[k].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[k].close(); } catch (IOException ex) { Logger.getLogger(LamportBasicVersion.class.getName()).log(Level.SEVERE, null, ex); } } } } else if (receiveMessage.contains("Reply")) { conditionArray[myProcessId] = 1; String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // conditionArray[Integer.parseInt(parseMessage[1])] = 1; int count = 0; for (int v = 0; v < numberOfProcesses; v++) { if (conditionArray[v] == 1) { count = count + 1; } } if (count == numberOfProcesses) { L1ConditionFlag = 1; System.out.println("Inside L1"); blockingQueue.put("L1"); //Clearing condition array after receiving all REPLY for (int z = 0; z < numberOfProcesses; z++) { conditionArray[z] = 0; } if (L2ConditionFlag == 0 && outstandingRequest == 1) { Integer[] queueArray = new Integer[queue.size()]; queue.toArray(queueArray); Arrays.sort(queueArray); if (queueArray[0] == currentRequestBeingServed) { System.out.println("Inside L2"); L2ConditionFlag = 1; blockingQueue.put("L2"); } } } } else if (receiveMessage.contains("Release")) { int present = 0; int delete = 0; String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // if (queue.size() != 0) { Integer[] queueArray = new Integer[queue.size()]; queue.toArray(queueArray); Arrays.sort(queueArray); for (int a = 0; a < queueArray.length; a++) { if (queueArray[a] == Integer.parseInt(parseMessage[2])) { present = 1; delete = a; } } if (present == 1) { for (int s = 0; s <= delete; s++) { queue.remove(); } } } if (L2ConditionFlag == 0 && outstandingRequest == 1) { if (queue.size() != 0) { Integer[] queueArray1 = new Integer[queue.size()]; queue.toArray(queueArray1); Arrays.sort(queueArray1); if (currentRequestBeingServed == queueArray1[0]) { L2ConditionFlag = 1; System.out.println("Inside L2"); blockingQueue.put("L2"); } } } } else if (receiveMessage.contains("Finish")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // finishFlagArray[Integer.parseInt(parseMessage[1])] = 1; int count = 0; for (int v = 0; v < numberOfProcesses; v++) { if (finishFlagArray[v] == 1) { count = count + 1; } } if (count == numberOfProcesses) { break; } } //logic for other messages //Print the queue to check System.out.println("********************************************************"); for (Object item : queue) { System.out.print(item); System.out.print("\t"); } System.out.println("********************************************************"); } mutex.release(); } }