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.chaordicsystems.sstableconverter.SSTableConverter.java
public static void main(String[] args) throws Exception { LoaderOptions options = LoaderOptions.parseArgs(args); OutputHandler handler = new OutputHandler.SystemOutput(options.verbose, options.debug); File srcDir = options.sourceDir; File dstDir = options.destDir; IPartitioner srcPart = options.srcPartitioner; IPartitioner dstPart = options.dstPartitioner; String keyspace = options.ks; String cf = options.cf;/* w w w . j a v a 2s . c o m*/ if (keyspace == null) { keyspace = srcDir.getParentFile().getName(); } if (cf == null) { cf = srcDir.getName(); } CFMetaData metadata = new CFMetaData(keyspace, cf, ColumnFamilyType.Standard, BytesType.instance, null); Collection<SSTableReader> originalSstables = readSSTables(srcPart, srcDir, metadata, handler); handler.output( String.format("Converting sstables of ks[%s], cf[%s], from %s to %s. Src dir: %s. Dest dir: %s.", keyspace, cf, srcPart.getClass().getName(), dstPart.getClass().getName(), srcDir.getAbsolutePath(), dstDir.getAbsolutePath())); SSTableSimpleUnsortedWriter destWriter = new SSTableSimpleUnsortedWriter(dstDir, dstPart, keyspace, cf, AsciiType.instance, null, 64); for (SSTableReader reader : originalSstables) { handler.output("Reading: " + reader.getFilename()); SSTableIdentityIterator row; SSTableScanner scanner = reader.getDirectScanner(null); // collecting keys to export while (scanner.hasNext()) { row = (SSTableIdentityIterator) scanner.next(); destWriter.newRow(row.getKey().key); while (row.hasNext()) { IColumn col = (IColumn) row.next(); destWriter.addColumn(col.name(), col.value(), col.timestamp()); } } scanner.close(); } // Don't forget to close! destWriter.close(); System.exit(0); }
From source file:net.itransformers.idiscover.core.DiscoveryManager.java
public static void main(String[] args) throws Exception, IllegalAccessException, JAXBException { Map<String, String> params = CmdLineParser.parseCmdLine(args); if (params == null) { printUsage("mibDir"); return;/*from ww w .jav a2s. c om*/ } final String fileName = params.get("-f"); if (fileName == null) { printUsage("fileName"); return; } File file = new File(fileName); DiscoveryManager manager = createDiscoveryManager(file.getParentFile(), file.getName(), "network", true); String mode = params.get("-d"); if (mode == null) { //Set default snmpDiscovery mode to discover network!!! mode = "network"; } Map<String, String> resourceSelectionParams = new HashMap<String, String>(); resourceSelectionParams.put("protocol", "SNMP"); ResourceType snmp = manager.discoveryResource.returnResourceByParam(resourceSelectionParams); Map<String, String> snmpConnParams = new HashMap<String, String>(); snmpConnParams = manager.discoveryResource.getParamMap(snmp, "snmp"); String host = params.get("-h"); IPv4Address initialIPaddress = new IPv4Address(host, null); snmpConnParams.put("status", "initial"); String mibDir = params.get("-m"); snmpConnParams.put("mibDir", mibDir); snmpConnParams.get("port"); Resource resource = new Resource(initialIPaddress, null, Integer.parseInt(snmpConnParams.get("port")), snmpConnParams); if (resource == null) ; String[] discoveryTypes = new String[] { "PHYSICAL", "NEXT_HOP", "OSPF", "ISIS", "BGP", "RIP", "ADDITIONAL", "IPV6" }; // DiscovererFactory.init(new SimulSnmpWalker(resource, new File("logs.log"))); // DiscovererFactory.init(); // Discoverer discoverer = new SnmpWalker(resource); NetworkType network = manager.discoverNetwork(resource, mode, discoveryTypes); for (DiscoveredDeviceData data : network.getDiscoveredDevice()) { System.out.println(data.getName() + "\n"); for (ObjectType object : data.getObject()) { for (ObjectType innterObject : object.getObject()) { System.out.println(innterObject.getObjectType()); } } } // List<DiscoveredDeviceData> discoveredDeviceDatas = network.getDiscoveredDevice(); // for (DiscoveredDeviceData discoveredDeviceData : discoveredDeviceDatas) { // discoveredDeviceData.getName(); // ParametersType parameters = discoveredDeviceData.getParameters(); // List<ParameterType> paras = parameters.getParameter(); // for (ParameterType para : paras) { // // } // // } }
From source file:apps.quantification.LearnQuantificationSVMPerf.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = LearnQuantificationSVMPerf.class.getName() + " [OPTIONS] <path to svm_perf_learn> <path to svm_perf_classify> <trainingIndexDirectory> <outputDirectory>"; Options options = new Options(); OptionBuilder.withArgName("f"); OptionBuilder.withDescription("Number of folds"); OptionBuilder.withLongOpt("f"); OptionBuilder.isRequired(true);/*from w w w .j ava 2 s. c o m*/ OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("c"); OptionBuilder.withDescription("The c value for svm_perf (default 0.01)"); OptionBuilder.withLongOpt("c"); OptionBuilder.isRequired(false); 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; SvmPerfClassifierCustomizer classificationCustomizer = null; int folds = -1; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]); classificationCustomizer = new SvmPerfClassifierCustomizer(remainingArgs[1]); folds = Integer.parseInt(line.getOptionValue("f")); 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")); classificationCustomizer.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); } assert (classificationLearnerCustomizer != null); if (remainingArgs.length != 4) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String indexFile = remainingArgs[2]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); String outputPath = remainingArgs[3]; SvmPerfLearner classificationLearner = new SvmPerfLearner(); classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer); FileSystemStorageManager fssm = new FileSystemStorageManager(indexPath, false); fssm.open(); IIndex training = TroveReadWriteHelper.readIndex(fssm, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); final TextualProgressBar progressBar = new TextualProgressBar("Learning the quantifiers"); IOperationStatusListener status = new IOperationStatusListener() { @Override public void operationStatus(double percentage) { progressBar.signal((int) percentage); } }; QuantificationLearner quantificationLearner = new QuantificationLearner(folds, classificationLearner, classificationLearnerCustomizer, classificationCustomizer, ClassificationMode.PER_CATEGORY, new LogisticFunction(), status); IQuantifier[] quantifiers = quantificationLearner.learn(training); File executableFile = new File(classificationLearnerCustomizer.getSvmPerfLearnPath()); IDataManager classifierDataManager = 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(); String quantifierPrefix = indexName + "_Quantifier-" + folds + description; FileSystemStorageManager fssmo = new FileSystemStorageManager( outputPath + File.separatorChar + quantifierPrefix, true); fssmo.open(); QuantificationLearner.write(quantifiers, fssmo, classifierDataManager); fssmo.close(); BufferedWriter bfs = new BufferedWriter( new FileWriter(outputPath + File.separatorChar + quantifierPrefix + "_rates.txt")); TShortDoubleHashMap simpleTPRs = quantificationLearner.getSimpleTPRs(); TShortDoubleHashMap simpleFPRs = quantificationLearner.getSimpleFPRs(); TShortDoubleHashMap scaledTPRs = quantificationLearner.getScaledTPRs(); TShortDoubleHashMap scaledFPRs = quantificationLearner.getScaledFPRs(); ContingencyTableSet contingencyTableSet = quantificationLearner.getContingencyTableSet(); short[] cats = simpleTPRs.keys(); for (int i = 0; i < cats.length; ++i) { short cat = cats[i]; String catName = training.getCategoryDB().getCategoryName(cat); ContingencyTable contingencyTable = contingencyTableSet.getCategoryContingencyTable(cat); double simpleTPR = simpleTPRs.get(cat); double simpleFPR = simpleFPRs.get(cat); double scaledTPR = scaledTPRs.get(cat); double scaledFPR = scaledFPRs.get(cat); String line = quantifierPrefix + "\ttrain\tsimple\t" + catName + "\t" + cat + "\t" + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n"; bfs.write(line); line = quantifierPrefix + "\ttrain\tscaled\t" + catName + "\t" + cat + "\t" + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn() + "\t" + scaledTPR + "\t" + scaledFPR + "\n"; bfs.write(line); } bfs.close(); }
From source file:de.prozesskraft.ptest.Compare.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try//from w w w.j a v a 2s . co m // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Compare.class) + "/" + "../etc/ptest-compare.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option oref = OptionBuilder.withArgName("PATH").hasArg() .withDescription("[mandatory] directory or fingerprint, that the --exam will be checked against") // .isRequired() .create("ref"); Option oexam = OptionBuilder.withArgName("PATH").hasArg().withDescription( "[optional; default: parent directory of -ref] directory or fingerprint, that will be checked against --ref") // .isRequired() .create("exam"); Option oresult = OptionBuilder.withArgName("FILE").hasArg().withDescription( "[mandatory; default: result.txt] the result (success|failed) of the comparison will be printed to this file") // .isRequired() .create("result"); Option osummary = OptionBuilder.withArgName("all|error|debug").hasArg().withDescription( "[optional] 'error' prints a summary reduced to failed matches. 'all' prints a full summary. 'debug' is like 'all' plus debug statements") // .isRequired() .create("summary"); Option omd5 = OptionBuilder.withArgName("no|yes").hasArg() .withDescription("[optional; default: yes] to ignore md5 information in comparison use -md5=no") // .isRequired() .create("md5"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(oref); options.addOption(oexam); options.addOption(oresult); options.addOption(osummary); options.addOption(omd5); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("compare", options); System.exit(0); } else if (commandline.hasOption("v")) { System.err.println("web: " + web); System.err.println("author: " + author); System.err.println("version:" + version); System.err.println("date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ boolean error = false; String result = ""; boolean md5 = false; String ref = null; String exam = null; if (!(commandline.hasOption("ref"))) { System.err.println("option -ref is mandatory"); error = true; } else { ref = commandline.getOptionValue("ref"); } if (!(commandline.hasOption("exam"))) { java.io.File refFile = new java.io.File(ref).getCanonicalFile(); java.io.File examFile = refFile.getParentFile(); exam = examFile.getCanonicalPath(); System.err.println("setting default: -exam=" + exam); } else { exam = commandline.getOptionValue("exam"); } if (error) { exiter(); } if (!(commandline.hasOption("result"))) { System.err.println("setting default: -result=result.txt"); result = "result.txt"; } if (!(commandline.hasOption("md5"))) { System.err.println("setting default: -md5=yes"); md5 = true; } else if (commandline.getOptionValue("md5").equals("no")) { md5 = false; } else if (commandline.getOptionValue("md5").equals("yes")) { md5 = true; } else { System.err.println("use only values no|yes for -md5"); System.exit(1); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ // einlesen der referenzdaten java.io.File refPath = new java.io.File(ref); Dir refDir = new Dir(); // wenn es ein directory ist, muss der fingerprint erzeugt werden if (refPath.exists() && refPath.isDirectory()) { refDir.setBasepath(refPath.getCanonicalPath()); refDir.genFingerprint(0f, true, new ArrayList<String>()); refDir.setRespectMd5Recursive(md5); System.err.println("-ref is a directory"); } // wenn es ein fingerprint ist, muss er eingelesen werden else if (refPath.exists()) { refDir.setInfilexml(refPath.getCanonicalPath()); System.err.println("-ref is a fingerprint"); try { refDir.readXml(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } refDir.setRespectMd5Recursive(md5); } else if (!refPath.exists()) { System.err.println("-ref does not exist! " + refPath.getAbsolutePath()); exiter(); } // einlesen der prueflingsdaten java.io.File examPath = new java.io.File(exam); Dir examDir = new Dir(); // wenn es ein directory ist, muss der fingerprint erzeugt werden if (examPath.exists() && examPath.isDirectory()) { examDir.setBasepath(examPath.getCanonicalPath()); examDir.genFingerprint(0f, true, new ArrayList<String>()); examDir.setRespectMd5Recursive(md5); System.err.println("-exam is a directory"); } // wenn es ein fingerprint ist, muss er eingelesen werden else if (examPath.exists()) { examDir.setInfilexml(examPath.getCanonicalPath()); System.err.println("-exam is a fingerprint"); try { examDir.readXml(); } catch (JAXBException e) { System.err.println("error while reading xml"); e.printStackTrace(); } examDir.setRespectMd5Recursive(md5); } else if (!examPath.exists()) { System.err.println("-exam does not exist! " + examPath.getAbsolutePath()); exiter(); } // durchfuehren des vergleichs refDir.runCheck(examDir); // if(examDir.isMatchSuccessfullRecursive() && refDir.isMatchSuccessfullRecursive()) if (refDir.isMatchSuccessfullRecursive()) { System.out.println("SUCCESS"); } else { System.out.println("FAILED"); } // printen der csv-ergebnis-tabelle if (commandline.hasOption("summary")) { if (commandline.getOptionValue("summary").equals("error")) { System.err.println("the results of the reference are crucial for result FAILED|SUCCESS"); System.err.println(refDir.sprintSummaryAsCsv("error")); System.err.println(examDir.sprintSummaryAsCsv("error")); } else if (commandline.getOptionValue("summary").equals("all")) { System.err.println(refDir.sprintSummaryAsCsv("all")); System.err.println(examDir.sprintSummaryAsCsv("all")); } else if (commandline.getOptionValue("summary").equals("debug")) { System.err.println(refDir.sprintSummaryAsCsv("all")); System.err.println(examDir.sprintSummaryAsCsv("all")); // printen des loggings System.err.println("------ logging of reference --------"); System.err.println(refDir.getLogAsStringRecursive()); System.err.println("------ logging of examinee --------"); System.err.println(examDir.getLogAsStringRecursive()); } else { System.err.println("for option -summary you only may use all|error"); exiter(); } } }
From source file:fr.cs.examples.propagation.DSSTPropagation.java
/** Program entry point. * @param args program arguments//www . j av a 2 s.c o m */ public static void main(String[] args) { try { // configure Orekit data acces Utils.setDataRoot("tutorial-orekit-data"); // input/output (in user's home directory) File input = new File(new File(System.getProperty("user.home")), "dsst-propagation.in"); File output = new File(input.getParentFile(), "dsst-propagation.out"); new DSSTPropagation().run(input, output); } 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); } catch (ParseException pe) { System.err.println(pe.getLocalizedMessage()); System.exit(1); } }
From source file:edu.uci.ics.asterix.transaction.management.service.locking.LockManagerRandomUnitTest.java
public static void main(String args[]) throws ACIDException, AsterixException, IOException { int i;// w w w. j a v a2 s. co m //prepare configuration file File cwd = new File(System.getProperty("user.dir")); File asterixdbDir = cwd.getParentFile(); File srcFile = new File(asterixdbDir.getAbsoluteFile(), "asterix-app/src/main/resources/asterix-build-configuration.xml"); File destFile = new File(cwd, "target/classes/asterix-configuration.xml"); FileUtils.copyFile(srcFile, destFile); TransactionSubsystem txnProvider = new TransactionSubsystem("nc1", null, new AsterixTransactionProperties(new AsterixPropertiesAccessor())); rand = new Random(System.currentTimeMillis()); for (i = 0; i < MAX_NUM_OF_ENTITY_LOCK_JOB; i++) { System.out.println("Creating " + i + "th EntityLockJob.."); generateEntityLockThread(txnProvider); } for (i = 0; i < MAX_NUM_OF_DATASET_LOCK_JOB; i++) { System.out.println("Creating " + i + "th DatasetLockJob.."); generateDatasetLockThread(txnProvider); } for (i = 0; i < MAX_NUM_OF_UPGRADE_JOB; i++) { System.out.println("Creating " + i + "th EntityLockUpgradeJob.."); generateEntityLockUpgradeThread(txnProvider); } ((LogManager) txnProvider.getLogManager()).stop(false, null); }
From source file:edu.uci.ics.asterix.transaction.management.service.locking.LockManagerDeterministicUnitTest.java
public static void main(String args[]) throws ACIDException, IOException, AsterixException { //prepare configuration file File cwd = new File(System.getProperty("user.dir")); File asterixdbDir = cwd.getParentFile(); File srcFile = new File(asterixdbDir.getAbsoluteFile(), "asterix-app/src/main/resources/asterix-build-configuration.xml"); File destFile = new File(cwd, "target/classes/asterix-configuration.xml"); FileUtils.copyFile(srcFile, destFile); //initialize controller thread String requestFileName = new String( "src/main/java/edu/uci/ics/asterix/transaction/management/service/locking/LockRequestFile"); Thread t = new Thread(new LockRequestController(requestFileName)); t.start();/*from ww w. j ava 2 s . c o m*/ }
From source file:com.l2jserver.model.template.NPCTemplateConverter.java
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException { controllers.put("L2Teleporter", TeleporterController.class); controllers.put("L2CastleTeleporter", TeleporterController.class); controllers.put("L2Npc", BaseNPCController.class); controllers.put("L2Monster", MonsterController.class); controllers.put("L2FlyMonster", MonsterController.class); Class.forName("com.mysql.jdbc.Driver"); final File target = new File("generated/template/npc"); System.out.println("Scaning legacy HTML files..."); htmlScannedFiles = FileUtils.listFiles(L2J_HTML_FOLDER, new String[] { "html", "htm" }, true); final JAXBContext c = JAXBContext.newInstance(NPCTemplate.class, Teleports.class); final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD); {//from w w w.j av a2s . co m System.out.println("Converting teleport templates..."); teleportation.teleport = CollectionFactory.newList(); final Marshaller m = c.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); final PreparedStatement st = conn.prepareStatement("SELECT * FROM teleport"); st.execute(); final ResultSet rs = st.getResultSet(); while (rs.next()) { final TeleportationTemplate template = new TeleportationTemplate(); template.id = new TeleportationTemplateID(rs.getInt("id"), null); template.name = rs.getString("Description"); TemplateCoordinate coord = new TemplateCoordinate(); coord.x = rs.getInt("loc_x"); coord.y = rs.getInt("loc_y"); coord.z = rs.getInt("loc_z"); template.point = coord; template.price = rs.getInt("price"); template.item = rs.getInt("itemId"); if (rs.getBoolean("fornoble")) { template.restrictions = new Restrictions(); template.restrictions.restriction = Arrays.asList("NOBLE"); } teleportation.teleport.add(template); } m.marshal(teleportation, getXMLSerializer(new FileOutputStream(new File(target, "../teleports.xml")))); // System.exit(0); } System.out.println("Generating template XML files..."); // c.generateSchema(new SchemaOutputResolver() { // @Override // public Result createOutput(String namespaceUri, // String suggestedFileName) throws IOException { // // System.out.println(new File(target, suggestedFileName)); // // return null; // return new StreamResult(new File(target, suggestedFileName)); // } // }); try { final Marshaller m = c.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); final PreparedStatement st = conn.prepareStatement( "SELECT npc.*, npcskills.level AS race " + "FROM npc " + "LEFT JOIN npcskills " + "ON(npc.idTemplate = npcskills.npcid AND npcskills.skillid = ?)"); st.setInt(1, 4416); st.execute(); final ResultSet rs = st.getResultSet(); while (rs.next()) { Object[] result = fillNPC(rs); NPCTemplate t = (NPCTemplate) result[0]; String type = (String) result[1]; String folder = createFolder(type); if (folder.isEmpty()) { m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "npc ../npc.xsd"); } else { m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "npc ../../npc.xsd"); } final File file = new File(target, "npc/" + folder + "/" + t.getID().getID() + (t.getInfo().getName() != null ? "-" + camelCase(t.getInfo().getName().getValue()) : "") + ".xml"); file.getParentFile().mkdirs(); templates.add(t); try { m.marshal(t, getXMLSerializer(new FileOutputStream(file))); } catch (MarshalException e) { System.err.println("Could not generate XML template file for " + t.getInfo().getName().getValue() + " - " + t.getID()); file.delete(); } } System.out.println("Generated " + templates.size() + " templates"); System.gc(); System.out.println("Free: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory())); System.out.println("Total: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory())); System.out.println("Used: " + FileUtils.byteCountToDisplaySize( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); System.out.println("Max: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory())); } finally { conn.close(); } }
From source file:androidimporter.AndroidImporter.java
public static void main(String[] args) throws ParseException { //"/usr/local/apache-ant/bin/ant" String antPath = System.getProperty("ANT_PATH", System.getenv("ANT_PATH")); if (antPath == null || !new File(antPath).exists()) { throw new RuntimeException("Cannot find ant at " + antPath + ". Please specify location to ant via the ANT_PATH environment variable or java system property."); }//from ww w . ja v a 2 s. com Options opts = new Options() .addOption("i", "android-resource-dir", true, "Android project res directory path") .addOption("o", "cn1-project-dir", true, "Path to the CN1 output project directory.") .addOption("r", "cn1-resource-file", false, "Path to CN1 output .res file. Defaults to theme.res in project dir") .addOption("p", "package", true, "Java package to place GUI forms in.") .addOption("h", "help", false, "Usage instructions"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(opts, args); if (line.hasOption("help")) { showHelp(opts); System.exit(0); } args = line.getArgs(); if (args.length < 1) { System.out.println("No command provided."); showHelp(opts); System.exit(0); } switch (args[0]) { case "import-project": { if (!line.hasOption("android-resource-dir") || !line.hasOption("cn1-project-dir") || !line.hasOption("package")) { System.out.println("Please provide android-resource-dir, package, and cn1-project-dir options"); showHelp(opts); System.exit(1); } File resDir = findResDir(new File(line.getOptionValue("android-resource-dir"))); if (resDir == null || !resDir.isDirectory()) { System.out.println("Failed to find android resource directory from provided value"); showHelp(opts); System.exit(1); } File projDir = new File(line.getOptionValue("cn1-project-dir")); File resFile = new File(projDir, "src" + File.separator + "theme.res"); if (line.hasOption("cn1-resource-file")) { resFile = new File(line.getOptionValue("cn1-resource-file")); } JavaSEPort.setShowEDTViolationStacks(false); JavaSEPort.setShowEDTWarnings(false); JFrame frm = new JFrame("Placeholder"); frm.setVisible(false); Display.init(frm.getContentPane()); JavaSEPort.setBaseResourceDir(resFile.getParentFile()); try { System.out.println("About to import project at " + resDir.getAbsolutePath()); System.out.println("Codename One Output Project: " + projDir.getAbsolutePath()); System.out.println("Resource file: " + resFile.getAbsolutePath()); System.out.println("Java Package: " + line.getOptionValue("package")); AndroidProjectImporter.importProject(resDir, projDir, resFile, line.getOptionValue("package")); Runtime.getRuntime().exec(new String[] { antPath, "init" }, new String[] {}, resFile.getParentFile().getParentFile()); //runAnt(new File(resFile.getParentFile().getParentFile(), "build.xml"), "init"); System.exit(0); } catch (Exception ex) { ex.printStackTrace(); } finally { System.exit(0); } break; } default: System.out.println("Unknown command " + args[0]); showHelp(opts); break; } }
From source file:com.clustercontrol.agent.Agent.java
/** * ?/*from ww w .j a v a2 s .c om*/ * * @param args ?? */ public static void main(String[] args) throws Exception { // ? if (args.length != 1) { System.out.println("Usage : java Agent [Agent.properties File Path]"); System.exit(1); } try { // System m_log.info("starting Hinemos Agent..."); m_log.info("java.vm.version = " + System.getProperty("java.vm.version")); m_log.info("java.vm.vendor = " + System.getProperty("java.vm.vendor")); m_log.info("java.home = " + System.getProperty("java.home")); m_log.info("os.name = " + System.getProperty("os.name")); m_log.info("os.arch = " + System.getProperty("os.arch")); m_log.info("os.version = " + System.getProperty("os.version")); m_log.info("user.name = " + System.getProperty("user.name")); m_log.info("user.dir = " + System.getProperty("user.dir")); m_log.info("user.country = " + System.getProperty("user.country")); m_log.info("user.language = " + System.getProperty("user.language")); m_log.info("file.encoding = " + System.getProperty("file.encoding")); // System(SET) String limitKey = "jdk.xml.entityExpansionLimit"; // TODO JRE??????????????????? System.setProperty(limitKey, "0"); m_log.info(limitKey + " = " + System.getProperty(limitKey)); // TODO ???agentHome // ?????????? File file = new File(args[0]); agentHome = file.getParentFile().getParent() + "/"; m_log.info("agentHome=" + agentHome); // long startDate = HinemosTime.currentTimeMillis(); m_log.info("start date = " + new Date(startDate) + "(" + startDate + ")"); agentInfo.setStartupTime(startDate); // Agent?? m_log.info("Agent.properties = " + args[0]); // ? File scriptDir = new File(agentHome + "script/"); if (scriptDir.exists()) { File[] listFiles = scriptDir.listFiles(); if (listFiles != null) { for (File f : listFiles) { boolean ret = f.delete(); if (ret) { m_log.debug("delete script : " + f.getName()); } else { m_log.warn("delete script error : " + f.getName()); } } } else { m_log.warn("listFiles is null"); } } else { //???????? boolean ret = scriptDir.mkdir(); if (!ret) { m_log.warn("mkdir error " + scriptDir.getPath()); } } // queue? m_sendQueue = new SendQueue(); // Agent? Agent agent = new Agent(args[0]); //----------------- //-- //----------------- m_log.debug("exec() : create topic "); m_receiveTopic = new ReceiveTopic(m_sendQueue); m_receiveTopic.setName("ReceiveTopicThread"); m_log.info("receiveTopic start 1"); m_receiveTopic.start(); m_log.info("receiveTopic start 2"); // ? agent.exec(); m_log.info("Hinemos Agent started"); // ? agent.waitAwakeAgent(); } catch (Throwable e) { m_log.error("Agent.java: Runtime Exception Occurred. " + e.getClass().getName() + ", " + e.getMessage(), e); } }