List of usage examples for java.io File getParentFile
public File getParentFile()
null
if this pathname does not name a parent directory. From source file:com.guye.baffle.obfuscate.Main.java
public static void main(String[] args) throws IOException, BaffleException { Options opt = new Options(); opt.addOption("c", "config", true, "config file path,keep or mapping"); opt.addOption("o", "output", true, "output mapping writer file"); opt.addOption("v", "verbose", false, "explain what is being done."); opt.addOption("h", "help", false, "print help for the command."); opt.getOption("c").setArgName("file list"); opt.getOption("o").setArgName("file path"); String formatstr = "baffle [-c/--config filepaths list ][-o/--output filepath][-h/--help] ApkFile TargetApkFile"; HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new PosixParser(); CommandLine cl = null;//w w w. j a v a2 s . co m try { // ?Options? cl = parser.parse(opt, args); } catch (ParseException e) { formatter.printHelp(formatstr, opt); // ??? return; } if (cl == null || cl.getArgs() == null || cl.getArgs().length == 0) { formatter.printHelp(formatstr, opt); return; } // ?-h--help?? if (cl.hasOption("h")) { HelpFormatter hf = new HelpFormatter(); hf.printHelp(formatstr, "", opt, ""); return; } // ???DirectoryName String[] str = cl.getArgs(); if (str == null || str.length != 2) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("not specify apk file or taget apk file", opt); return; } if (str[1].equals(str[0])) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("apk file can not rewrite , please specify new target file", opt); return; } File apkFile = new File(str[0]); if (!apkFile.exists()) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("apk file not exists", opt); return; } File[] configs = null; if (cl.hasOption("c")) { String cfg = cl.getOptionValue("c"); String[] fs = cfg.split(","); int len = fs.length; configs = new File[fs.length]; for (int i = 0; i < len; i++) { configs[i] = new File(fs[i]); if (!configs[i].exists()) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("config file " + fs[i] + " not exists", opt); return; } } } File mappingfile = null; if (cl.hasOption("o")) { String mfile = cl.getOptionValue("o"); mappingfile = new File(mfile); if (mappingfile.getParentFile() != null) { mappingfile.getParentFile().mkdirs(); } } if (cl.hasOption('v')) { Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.CONFIG); } else { Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.OFF); } Logger.getLogger(Obfuscater.LOG_NAME).addHandler(new ConsoleHandler()); Obfuscater obfuscater = new Obfuscater(configs, mappingfile, apkFile, str[1]); obfuscater.obfuscate(); }
From source file:de.pniehus.odal.App.java
public static void main(String[] args) throws IOException { List<Filter> filters = new ArrayList<Filter>(); filters.add(new RegexFilter()); filters.add(new FileTypeFilter()); filters.add(new KeywordFilter()); filters.add(new BlacklistFilter()); Profile p = parseArgs(args, filters); String fileName = "log-" + new Date().toString().replace(":", "-") + ".txt"; fileName = fileName.replace(" ", "-"); File logPath = new File(p.getLogDirectory() + fileName); if (!logPath.getParentFile().isDirectory() && !logPath.getParentFile().mkdirs()) { logPath = new File(fileName); }// w w w . j av a2s. c o m if (logPath.getParentFile().canWrite() || logPath.getParentFile().setWritable(true)) { SimpleLoggingSetup.configureRootLogger(logPath.getAbsolutePath(), p.getLogLevel(), !p.isSilent()); } else { Logger root = Logger.getLogger(""); for (Handler h : root.getHandlers()) { // Removing default console handlers if (h instanceof ConsoleHandler) { root.removeHandler(h); } } ConsolePrintLogHandler cplh = new ConsolePrintLogHandler(); cplh.setFormatter(new ScribblerLogFormat(SimpleLoggingSetup.DEFAULT_DATE_FORMAT)); root.addHandler(cplh); System.out.println("Unable to create log: insufficient permissions!"); } Logger.getLogger("").setLevel(p.getLogLevel()); mainLogger = Logger.getLogger(App.class.getCanonicalName()); untrustedSSLSetup(); mainLogger.info("Successfully intitialized ODAL"); if (!p.isLogging()) mainLogger.setLevel(Level.OFF); if (p.isWindowsConsoleMode() && !p.isLogging()) { Logger root = Logger.getLogger(""); for (Handler h : root.getHandlers()) { if (h instanceof FileHandler) { root.removeHandler(h); // Removes FileHandler to allow console output through logging } } } OdalGui ogui = new OdalGui(p, filters); }
From source file:dk.statsbiblioteket.util.qa.PackageScannerDriver.java
/** * @param args The command line arguments. * @throws IOException If command line arguments can't be passed or there * is an error reading class files. *//*from w w w . j a va2 s.c o m*/ @SuppressWarnings("deprecation") public static void main(final String[] args) throws IOException { Report report; CommandLine cli = null; String reportType, projectName, baseSrcDir, targetPackage; String[] targets = null; // Build command line options CommandLineParser cliParser = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "Print help message and exit"); options.addOption("n", "name", true, "Project name, default 'Unknown'"); options.addOption("o", "output", true, "Type of output, 'plain' or 'html', default is html"); options.addOption("p", "package", true, "Only scan a particular package in input dirs, use dotted " + "package notation to refine selections"); options.addOption("s", "source-dir", true, "Base source dir to use in report, can be a URL. " + "@FILE@ and @MODULE@ will be escaped"); // Parse and validate command line try { cli = cliParser.parse(options, args); targets = cli.getArgs(); if (args.length == 0 || targets.length == 0 || cli.hasOption("help")) { throw new ParseException("Not enough arguments, no input files"); } } catch (ParseException e) { printHelp(options); System.exit(1); } // Extract information from command line reportType = cli.getOptionValue("output") != null ? cli.getOptionValue("output") : "html"; projectName = cli.getOptionValue("name") != null ? cli.getOptionValue("name") : "Unknown"; baseSrcDir = cli.getOptionValue("source-dir") != null ? cli.getOptionValue("source-dir") : System.getProperty("user.dir"); targetPackage = cli.getOptionValue("package") != null ? cli.getOptionValue("package") : ""; targetPackage = targetPackage.replace(".", File.separator); // Set up report type if ("plain".equals(reportType)) { report = new BasicReport(); } else { report = new HTMLReport(projectName, System.out, baseSrcDir); } // Do actual scanning of provided targets for (String target : targets) { PackageScanner scanner; File f = new File(target); if (f.isDirectory()) { scanner = new PackageScanner(report, f, targetPackage); } else { String filename = f.toString(); scanner = new PackageScanner(report, f.getParentFile(), filename.substring(filename.lastIndexOf(File.separator) + 1)); } scanner.scan(); } // Cloce the report before we exit report.end(); }
From source file:com.xiaoxiaomo.flink.batch.distcp.DistCp.java
public static void main(String[] args) throws Exception { // set up the execution environment final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); ParameterTool params = ParameterTool.fromArgs(args); if (!params.has("input") || !params.has("output")) { System.err.println("Usage: --input <path> --output <path> [--parallelism <n>]"); return;//from w ww . j a v a2 s .c om } final Path sourcePath = new Path(params.get("input")); final Path targetPath = new Path(params.get("output")); if (!isLocal(env) && !(isOnDistributedFS(sourcePath) && isOnDistributedFS(targetPath))) { System.out.println("In a distributed mode only HDFS input/output paths are supported"); return; } final int parallelism = params.getInt("parallelism", 10); if (parallelism <= 0) { System.err.println("Parallelism should be greater than 0"); return; } // make parameters available in the web interface env.getConfig().setGlobalJobParameters(params); env.setParallelism(parallelism); long startTime = System.currentTimeMillis(); LOGGER.info("Initializing copy tasks"); List<FileCopyTask> tasks = getCopyTasks(sourcePath); LOGGER.info("Copy task initialization took " + (System.currentTimeMillis() - startTime) + "ms"); DataSet<FileCopyTask> inputTasks = new DataSource<FileCopyTask>(env, new FileCopyTaskInputFormat(tasks), new GenericTypeInfo<FileCopyTask>(FileCopyTask.class), "fileCopyTasks"); FlatMapOperator<FileCopyTask, Object> res = inputTasks .flatMap(new RichFlatMapFunction<FileCopyTask, Object>() { private static final long serialVersionUID = 1109254230243989929L; private LongCounter fileCounter; private LongCounter bytesCounter; @Override public void open(Configuration parameters) throws Exception { bytesCounter = getRuntimeContext().getLongCounter(BYTES_COPIED_CNT_NAME); fileCounter = getRuntimeContext().getLongCounter(FILES_COPIED_CNT_NAME); } @Override public void flatMap(FileCopyTask task, Collector<Object> out) throws Exception { LOGGER.info("Processing task: " + task); Path outPath = new Path(targetPath, task.getRelativePath()); FileSystem targetFs = targetPath.getFileSystem(); // creating parent folders in case of a local FS if (!targetFs.isDistributedFS()) { //dealing with cases like file:///tmp or just /tmp File outFile = outPath.toUri().isAbsolute() ? new File(outPath.toUri()) : new File(outPath.toString()); File parentFile = outFile.getParentFile(); if (!parentFile.mkdirs() && !parentFile.exists()) { throw new RuntimeException( "Cannot create local file system directories: " + parentFile); } } FSDataOutputStream outputStream = null; FSDataInputStream inputStream = null; try { outputStream = targetFs.create(outPath, true); inputStream = task.getPath().getFileSystem().open(task.getPath()); int bytes = IOUtils.copy(inputStream, outputStream); bytesCounter.add(bytes); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } fileCounter.add(1L); } }); // no data sinks are needed, therefore just printing an empty result res.print(); Map<String, Object> accumulators = env.getLastJobExecutionResult().getAllAccumulatorResults(); LOGGER.info("== COUNTERS =="); for (Map.Entry<String, Object> e : accumulators.entrySet()) { LOGGER.info(e.getKey() + ": " + e.getValue()); } }
From source file:ch.admin.hermes.etl.load.HermesETLApplication.java
/** * Hauptprogramm/*from w w w.j av a 2s .co m*/ * @param args Commandline Argumente */ public static void main(String[] args) { JFrame frame = null; try { // Crawler fuer Zugriff auf HERMES 5 Online Loesung initialiseren */ crawler = new HermesOnlineCrawler(); // CommandLine Argumente aufbereiten parseCommandLine(args); // Methoden Export (Variante Zuehlke) extrahieren System.out.println("load library " + model); ModelExtract root = new ModelExtract(); root.extract(model); frame = createProgressDialog(); // wird das XML Model von HERMES Online geholt - URL der Templates korrigieren if (scenario != null) { List<Workproduct> workproducts = (List<Workproduct>) root.getObjects().get("workproducts"); for (Workproduct wp : workproducts) for (Template t : wp.getTemplate()) { // Template beinhaltet kompletten URL - keine Aenderung if (t.getUrl().toLowerCase().startsWith("http") || t.getUrl().toLowerCase().startsWith("file")) continue; // Model wird ab Website geholte if (model.startsWith("http")) t.setUrl(crawler.getTemplateURL(scenario, t.getUrl())); // Model ist lokal - Path aus model und relativem Path Template zusammenstellen else { File m = new File(model); t.setUrl(m.getParentFile() + "/" + t.getUrl()); } } } // JavaScript - fuer Import in Fremdsystem if (script.endsWith(".js")) { final JavaScriptEngine js = new JavaScriptEngine(); js.setObjects(root.getObjects()); js.put("progress", progress); js.eval("function log( x ) { println( x ); progress.setString( x ); }"); progress.setString("call main() in " + script); js.put(ScriptEngine.FILENAME, script); js.call(new InputStreamReader(new FileInputStream(script)), "main", new Object[] { site, user, passwd }); } // FreeMarker - fuer Umwandlungen nach HTML else if (script.endsWith(".ftl")) { FileOutputStream out = new FileOutputStream( new File(script.substring(0, script.length() - 3) + "html ")); int i = script.indexOf("templates"); if (i >= 0) script = script.substring(i + "templates".length()); MethodTransform transform = new MethodTransform(); transform.transform(root.getObjects(), script, out); out.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.toString(), "Fehlerhafte Verarbeitung", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); } if (frame != null) { frame.setVisible(false); frame.dispose(); } System.exit(0); }
From source file:fr.cs.examples.propagation.TrackCorridor.java
/** Program entry point. * @param args program arguments//from ww w . ja v a2s .c o m */ public static void main(String[] args) { try { // configure Orekit Autoconfiguration.configureOrekit(); // input/out File input = new File(TrackCorridor.class.getResource("/track-corridor.in").toURI().getPath()); File output = new File(input.getParentFile(), "track-corridor.csv"); new TrackCorridor().run(input, output, ","); System.out.println("corridor saved as file " + output); } catch (URISyntaxException use) { System.err.println(use.getLocalizedMessage()); System.exit(1); } catch (IOException ioe) { System.err.println(ioe.getLocalizedMessage()); System.exit(1); } catch (IllegalArgumentException iae) { System.err.println(iae.getLocalizedMessage()); System.exit(1); } catch (OrekitException oe) { System.err.println(oe.getLocalizedMessage()); System.exit(1); } }
From source file:com.green.generate.Generate.java
public static void main(String[] args) throws Exception { // ========== ?? ==================== // ??????//from w w w.j ava 2s. c om // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className} // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4? String packageName = "com.thinkgem.jeesite.modules"; String moduleName = "factory"; // ???sys String subModuleName = ""; // ????? String className = "product"; // ??user String classAuthor = "ThinkGem"; // ThinkGem String functionName = "?"; // ?? // ??? Boolean isEnable = false; // ========== ?? ==================== if (!isEnable) { logger.error("????isEnable = true"); return; } if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className) || StringUtils.isBlank(functionName)) { logger.error("??????????????"); return; } // ? String separator = File.separator; // ? File projectPath = new DefaultResourceLoader().getResource("").getFile(); while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) { projectPath = projectPath.getParentFile(); } logger.info("Project Path: {}", projectPath); // ? String tplPath = StringUtils.replace(projectPath + "/src/main/java/com/thinkgem/jeesite/generate/template", "/", separator); logger.info("Template Path: {}", tplPath); // Java String javaPath = StringUtils.replaceEach( projectPath + "/src/main/java/" + StringUtils.lowerCase(packageName), new String[] { "/", "." }, new String[] { separator, separator }); logger.info("Java Path: {}", javaPath); // String viewPath = StringUtils.replace(projectPath + "/src/main/webapp/WEB-INF/views", "/", separator); logger.info("View Path: {}", viewPath); // ??? Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File(tplPath)); // ??? Map<String, String> model = Maps.newHashMap(); model.put("packageName", StringUtils.lowerCase(packageName)); model.put("moduleName", StringUtils.lowerCase(moduleName)); model.put("subModuleName", StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : ""); model.put("className", StringUtils.uncapitalize(className)); model.put("ClassName", StringUtils.capitalize(className)); model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools"); model.put("classVersion", DateUtils.getDate()); model.put("functionName", functionName); model.put("tableName", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "_" + StringUtils.lowerCase(subModuleName) : "") + "_" + model.get("className")); model.put("urlPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) : "") + "/" + model.get("className")); model.put("viewPrefix", //StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+ model.get("urlPrefix")); model.put("permissionPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? ":" + StringUtils.lowerCase(subModuleName) : "") + ":" + model.get("className")); // ? Entity Template template = cfg.getTemplate("entity.ftl"); String content = FreeMarkers.renderTemplate(template, model); String filePath = javaPath + separator + model.get("moduleName") + separator + "entity" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java"; writeFile(content, filePath); logger.info("Entity: {}", filePath); // ? Dao template = cfg.getTemplate("dao.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Dao.java"; writeFile(content, filePath); logger.info("Dao: {}", filePath); // ? Service template = cfg.getTemplate("service.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Service.java"; writeFile(content, filePath); logger.info("Service: {}", filePath); // ? Controller template = cfg.getTemplate("controller.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "web" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Controller.java"; writeFile(content, filePath); logger.info("Controller: {}", filePath); // ? ViewForm template = cfg.getTemplate("viewForm.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "Form.jsp"; writeFile(content, filePath); logger.info("ViewForm: {}", filePath); // ? ViewList template = cfg.getTemplate("viewList.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "List.jsp"; writeFile(content, filePath); logger.info("ViewList: {}", filePath); logger.info("Generate Success."); }
From source file:com.ourlife.dev.generate.Generate.java
public static void main(String[] args) throws Exception { // ========== ?? ==================== // ??????//from ww w . j a v a 2s . co m // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className} // packageName // ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4? String packageName = "com.ourlife.dev.modules"; String moduleName = "biz"; // ???sys String subModuleName = ""; // ????? String className = "orderLog"; // ??user String classAuthor = "ourlife"; // ourlife String functionName = "?"; // ?? // ??? Boolean isEnable = true; // ========== ?? ==================== if (!isEnable) { logger.error("????isEnable = true"); return; } if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className) || StringUtils.isBlank(functionName)) { logger.error("??????????????"); return; } // ? String separator = File.separator; // ? File projectPath = new DefaultResourceLoader().getResource("").getFile(); while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) { projectPath = projectPath.getParentFile(); } logger.info("Project Path: {}", projectPath); // ? String tplPath = StringUtils.replace(projectPath + "/src/main/java/com/ourlife/dev/generate/template", "/", separator); logger.info("Template Path: {}", tplPath); // Java String javaPath = StringUtils.replaceEach( projectPath + "/src/main/java/" + StringUtils.lowerCase(packageName), new String[] { "/", "." }, new String[] { separator, separator }); logger.info("Java Path: {}", javaPath); // String viewPath = StringUtils.replace(projectPath + "/src/main/webapp/WEB-INF/views", "/", separator); logger.info("View Path: {}", viewPath); // ??? Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File(tplPath)); // ??? Map<String, String> model = Maps.newHashMap(); model.put("packageName", StringUtils.lowerCase(packageName)); model.put("moduleName", StringUtils.lowerCase(moduleName)); model.put("subModuleName", StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : ""); model.put("className", StringUtils.uncapitalize(className)); model.put("ClassName", StringUtils.capitalize(className)); model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools"); model.put("classVersion", DateUtils.getDate()); model.put("functionName", functionName); model.put("tableName", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "_" + StringUtils.lowerCase(subModuleName) : "") + "_" + model.get("className")); model.put("urlPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) : "") + "/" + model.get("className")); model.put("viewPrefix", // StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+ model.get("urlPrefix")); model.put("permissionPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? ":" + StringUtils.lowerCase(subModuleName) : "") + ":" + model.get("className")); // ? Entity Template template = cfg.getTemplate("entity.ftl"); String content = FreeMarkers.renderTemplate(template, model); String filePath = javaPath + separator + model.get("moduleName") + separator + "entity" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java"; writeFile(content, filePath); logger.info("Entity: {}", filePath); // ? Dao template = cfg.getTemplate("dao.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Dao.java"; writeFile(content, filePath); logger.info("Dao: {}", filePath); // ? Service template = cfg.getTemplate("service.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Service.java"; writeFile(content, filePath); logger.info("Service: {}", filePath); // ? Controller template = cfg.getTemplate("controller.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "web" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Controller.java"; writeFile(content, filePath); logger.info("Controller: {}", filePath); // ? ViewForm template = cfg.getTemplate("viewForm.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "Form.jsp"; writeFile(content, filePath); logger.info("ViewForm: {}", filePath); // ? ViewList template = cfg.getTemplate("viewList.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "List.jsp"; writeFile(content, filePath); logger.info("ViewList: {}", filePath); logger.info("Generate Success."); }
From source file:apps.classification.LearnSVMPerf.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = LearnSVMPerf.class.getName() + " [OPTIONS] <path to svm_perf> <trainingIndexDirectory>"; Options options = new Options(); OptionBuilder.withArgName("c"); OptionBuilder.withDescription("The c value for svm_perf (default 0.01)"); OptionBuilder.withLongOpt("c"); OptionBuilder.isRequired(false);/*w ww.j av a 2s . c om*/ OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("t"); OptionBuilder.withDescription("Path for temporary files"); OptionBuilder.withLongOpt("t"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("l"); OptionBuilder.withDescription("The loss function to optimize (default 2):\n" + " 0 Zero/one loss: 1 if vector of predictions contains error, 0 otherwise.\n" + " 1 F1: 100 minus the F1-score in percent.\n" + " 2 Errorrate: Percentage of errors in prediction vector.\n" + " 3 Prec/Rec Breakeven: 100 minus PRBEP in percent.\n" + " 4 Prec@p: 100 minus precision at p in percent.\n" + " 5 Rec@p: 100 minus recall at p in percent.\n" + " 10 ROCArea: Percentage of swapped pos/neg pairs (i.e. 100 - ROCArea)."); OptionBuilder.withLongOpt("l"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("w"); OptionBuilder.withDescription("Choice of structural learning algorithm (default 9):\n" + " 0: n-slack algorithm described in [2]\n" + " 1: n-slack algorithm with shrinking heuristic\n" + " 2: 1-slack algorithm (primal) described in [5]\n" + " 3: 1-slack algorithm (dual) described in [5]\n" + " 4: 1-slack algorithm (dual) with constraint cache [5]\n" + " 9: custom algorithm in svm_struct_learn_custom.c"); OptionBuilder.withLongOpt("w"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("p"); OptionBuilder.withDescription("The value of p used by the prec@p and rec@p loss functions (default 0)"); OptionBuilder.withLongOpt("p"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("v"); OptionBuilder.withDescription("Verbose output"); OptionBuilder.withLongOpt("v"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("s"); OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmPerfLearnerCustomizer classificationLearnerCustomizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]); if (line.hasOption("c")) classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c"))); if (line.hasOption("w")) classificationLearnerCustomizer.setW(Integer.parseInt(line.getOptionValue("w"))); if (line.hasOption("p")) classificationLearnerCustomizer.setP(Integer.parseInt(line.getOptionValue("p"))); if (line.hasOption("l")) classificationLearnerCustomizer.setL(Integer.parseInt(line.getOptionValue("l"))); if (line.hasOption("v")) classificationLearnerCustomizer.printSvmPerfOutput(true); if (line.hasOption("s")) classificationLearnerCustomizer.setDeleteTrainingFiles(false); if (line.hasOption("t")) classificationLearnerCustomizer.setTempPath(line.getOptionValue("t")); } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } if (remainingArgs.length != 2) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String indexFile = remainingArgs[1]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); // LEARNING SvmPerfLearner classificationLearner = new SvmPerfLearner(); classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer); FileSystemStorageManager storageManager = new FileSystemStorageManager(indexPath, false); storageManager.open(); IIndex training = TroveReadWriteHelper.readIndex(storageManager, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); storageManager.close(); IClassifier classifier = classificationLearner.build(training); File executableFile = new File(classificationLearnerCustomizer.getSvmPerfLearnPath()); SvmPerfDataManager dataManager = new SvmPerfDataManager(new SvmPerfClassifierCustomizer( executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_perf_classify")); String description = "_SVMPerf_C-" + classificationLearnerCustomizer.getC() + "_W-" + classificationLearnerCustomizer.getW() + "_L-" + classificationLearnerCustomizer.getL(); if (classificationLearnerCustomizer.getL() == 4 || classificationLearnerCustomizer.getL() == 5) description += "_P-" + classificationLearnerCustomizer.getP(); if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0) description += "_" + classificationLearnerCustomizer.getAdditionalParameters(); storageManager = new FileSystemStorageManager(indexPath, false); storageManager.open(); dataManager.write(storageManager, indexName + description, classifier); storageManager.close(); }
From source file:com.joey.Fujikom.generate.Generate.java
public static void main(String[] args) throws Exception { // ========== ?? ==================== // ??????//from w w w.jav a 2s .co m // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className} // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4? String packageName = "com.joey.Fujikom.modules"; String moduleName = "factory"; // ???sys String subModuleName = ""; // ????? String className = "product"; // ??user String classAuthor = "ThinkGem"; // ThinkGem String functionName = "?"; // ?? // ??? //Boolean isEnable = false; Boolean isEnable = true; // ========== ?? ==================== if (!isEnable) { logger.error("????isEnable = true"); return; } if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className) || StringUtils.isBlank(functionName)) { logger.error("??????????????"); return; } // ? String separator = File.separator; // ? File projectPath = new DefaultResourceLoader().getResource("").getFile(); while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) { projectPath = projectPath.getParentFile(); } logger.info("Project Path: {}", projectPath); // ? String tplPath = StringUtils.replace(projectPath + "/src/main/java/com/thinkgem/Fujikom/generate/template", "/", separator); logger.info("Template Path: {}", tplPath); // Java String javaPath = StringUtils.replaceEach( projectPath + "/src/main/java/" + StringUtils.lowerCase(packageName), new String[] { "/", "." }, new String[] { separator, separator }); logger.info("Java Path: {}", javaPath); // String viewPath = StringUtils.replace(projectPath + "/src/main/webapp/WEB-INF/views", "/", separator); logger.info("View Path: {}", viewPath); // ??? Configuration cfg = new Configuration(); cfg.setDefaultEncoding("UTF-8"); cfg.setDirectoryForTemplateLoading(new File(tplPath)); // ??? Map<String, String> model = Maps.newHashMap(); model.put("packageName", StringUtils.lowerCase(packageName)); model.put("moduleName", StringUtils.lowerCase(moduleName)); model.put("subModuleName", StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : ""); model.put("className", StringUtils.uncapitalize(className)); model.put("ClassName", StringUtils.capitalize(className)); model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools"); model.put("classVersion", DateUtils.getDate()); model.put("functionName", functionName); model.put("tableName", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "_" + StringUtils.lowerCase(subModuleName) : "") + "_" + model.get("className")); model.put("urlPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) : "") + "/" + model.get("className")); model.put("viewPrefix", //StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+ model.get("urlPrefix")); model.put("permissionPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? ":" + StringUtils.lowerCase(subModuleName) : "") + ":" + model.get("className")); // ? Entity Template template = cfg.getTemplate("entity.ftl"); String content = FreeMarkers.renderTemplate(template, model); String filePath = javaPath + separator + model.get("moduleName") + separator + "entity" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java"; writeFile(content, filePath); logger.info("Entity: {}", filePath); // ? Dao template = cfg.getTemplate("dao.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Dao.java"; writeFile(content, filePath); logger.info("Dao: {}", filePath); // ? Service template = cfg.getTemplate("service.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Service.java"; writeFile(content, filePath); logger.info("Service: {}", filePath); // ? Controller template = cfg.getTemplate("controller.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "web" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Controller.java"; writeFile(content, filePath); logger.info("Controller: {}", filePath); // ? ViewForm template = cfg.getTemplate("viewForm.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "Form.jsp"; writeFile(content, filePath); logger.info("ViewForm: {}", filePath); // ? ViewList template = cfg.getTemplate("viewList.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "List.jsp"; writeFile(content, filePath); logger.info("ViewList: {}", filePath); logger.info("Generate Success."); }