List of usage examples for java.util Map containsKey
boolean containsKey(Object key);
From source file:org.silverpeas.dbbuilder.DBBuilder.java
/** * @param args/*from ww w . ja v a 2 s .co m*/ * @see */ public static void main(String[] args) { ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext( "classpath:/spring-jdbc-datasource.xml"); try { // Ouverture des traces Date startDate = new Date(); System.out.println( MessageFormat.format(messages.getString("dbbuilder.start"), DBBuilderAppVersion, startDate)); console = new Console(DBBuilder.class); console.printMessage("*************************************************************"); console.printMessage( MessageFormat.format(messages.getString("dbbuilder.start"), DBBuilderAppVersion, startDate)); // Lecture des variables d'environnement partir de dbBuilderSettings dbBuilderResources = FileUtil .loadResource("/org/silverpeas/dbBuilder/settings/dbBuilderSettings.properties"); // Lecture des paramtres d'entre params = new CommandLineParameters(console, args); if (params.isSimulate() && DatabaseType.ORACLE == params.getDbType()) { throw new Exception(messages.getString("oracle.simulate.error")); } console.printMessage(messages.getString("jdbc.connection.configuration")); console.printMessage(ConnectionFactory.getConnectionInfo()); console.printMessage("\tAction : " + params.getAction()); console.printMessage("\tVerbose mode : " + params.isVerbose()); console.printMessage("\tSimulate mode : " + params.isSimulate()); if (Action.ACTION_CONNECT == params.getAction()) { // un petit message et puis c'est tout console.printMessage(messages.getString("connection.success")); System.out.println(messages.getString("connection.success")); } else { // Modules en place sur la BD avant install console.printMessage("DB Status before build :"); List<String> packagesIntoDB = checkDBStatus(); // initialisation d'un vecteur des instructions SQL passer en fin d'upgrade // pour mettre niveau les versions de modules en base MetaInstructions sqlMetaInstructions = new MetaInstructions(); File dirXml = new File(params.getDbType().getDBContributionDir()); DBXmlDocument destXml = loadMasterContribution(dirXml); UninstallInformations processesToCacheIntoDB = new UninstallInformations(); File[] listeFileXml = dirXml.listFiles(); Arrays.sort(listeFileXml); List<DBXmlDocument> listeDBXmlDocument = new ArrayList<DBXmlDocument>(listeFileXml.length); int ignoredFiles = 0; // Ouverture de tous les fichiers de configurations console.printMessage(messages.getString("ignored.contribution")); for (File xmlFile : listeFileXml) { if (xmlFile.isFile() && "xml".equals(FileUtil.getExtension(xmlFile)) && !(FIRST_DBCONTRIBUTION_FILE.equalsIgnoreCase(xmlFile.getName())) && !(MASTER_DBCONTRIBUTION_FILE.equalsIgnoreCase(xmlFile.getName()))) { DBXmlDocument fXml = new DBXmlDocument(dirXml, xmlFile.getName()); fXml.load(); // vrification des dpendances et prise en compte uniquement si dependences OK if (hasUnresolvedRequirements(listeFileXml, fXml)) { console.printMessage( '\t' + xmlFile.getName() + " (because of unresolved requirements)."); ignoredFiles++; } else if (ACTION_ENFORCE_UNINSTALL == params.getAction()) { console.printMessage('\t' + xmlFile.getName() + " (because of " + ACTION_ENFORCE_UNINSTALL + " mode)."); ignoredFiles++; } else { listeDBXmlDocument.add(fXml); } } } if (0 == ignoredFiles) { console.printMessage("\t(none)"); } // prpare une HashMap des modules prsents en fichiers de contribution Map packagesIntoFile = new HashMap(); int j = 0; console.printMessage(messages.getString("merged.contribution")); console.printMessage(params.getAction().toString()); if (ACTION_ENFORCE_UNINSTALL != params.getAction()) { console.printMessage('\t' + FIRST_DBCONTRIBUTION_FILE); j++; } for (DBXmlDocument currentDoc : listeDBXmlDocument) { console.printMessage('\t' + currentDoc.getName()); j++; } if (0 == j) { console.printMessage("\t(none)"); } // merge des diffrents fichiers de contribution ligibles : console.printMessage("Build decisions are :"); // d'abord le fichier dbbuilder-contribution ... DBXmlDocument fileXml; if (ACTION_ENFORCE_UNINSTALL != params.getAction()) { try { fileXml = new DBXmlDocument(dirXml, FIRST_DBCONTRIBUTION_FILE); fileXml.load(); } catch (Exception e) { // contribution de dbbuilder non trouve -> on continue, on est certainement en train // de desinstaller la totale fileXml = null; } if (null != fileXml) { DBBuilderFileItem dbbuilderItem = new DBBuilderFileItem(fileXml); packagesIntoFile.put(dbbuilderItem.getModule(), null); mergeActionsToDo(dbbuilderItem, destXml, processesToCacheIntoDB, sqlMetaInstructions); } } // ... puis les autres for (DBXmlDocument currentDoc : listeDBXmlDocument) { DBBuilderFileItem tmpdbbuilderItem = new DBBuilderFileItem(currentDoc); packagesIntoFile.put(tmpdbbuilderItem.getModule(), null); mergeActionsToDo(tmpdbbuilderItem, destXml, processesToCacheIntoDB, sqlMetaInstructions); } // ... et enfin les pices BD dsinstaller // ... attention, l'ordonnancement n'tant pas dispo, on les traite dans // l'ordre inverse pour faire passer busCore a la fin, de nombreuses contraintes // des autres modules referencant les PK de busCore List<String> itemsList = new ArrayList<String>(); boolean foundDBBuilder = false; for (String dbPackage : packagesIntoDB) { if (!packagesIntoFile.containsKey(dbPackage)) { // Package en base et non en contribution -> candidat desinstallation if (DBBUILDER_MODULE.equalsIgnoreCase(dbPackage)) { foundDBBuilder = true; } else if (ACTION_ENFORCE_UNINSTALL == params.getAction()) { if (dbPackage.equals(params.getModuleName())) { itemsList.add(0, dbPackage); } } else { itemsList.add(0, dbPackage); } } } if (foundDBBuilder) { if (ACTION_ENFORCE_UNINSTALL == params.getAction()) { if (DBBUILDER_MODULE.equals(params.getModuleName())) { itemsList.add(itemsList.size(), DBBUILDER_MODULE); } } else { itemsList.add(itemsList.size(), DBBUILDER_MODULE); } } for (String item : itemsList) { console.printMessage("**** Treating " + item + " ****"); DBBuilderDBItem tmpdbbuilderItem = new DBBuilderDBItem(item); mergeActionsToDo(tmpdbbuilderItem, destXml, processesToCacheIntoDB, sqlMetaInstructions); } destXml.setName("res.txt"); destXml.save(); console.printMessage("Build parts are :"); // Traitement des pices slectionnes // remarque : durant cette phase, les erreurs sont traites -> on les catche en // retour sans les retraiter if (ACTION_INSTALL == params.getAction()) { processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_INSTALL); } else if (ACTION_UNINSTALL == params.getAction() || ACTION_ENFORCE_UNINSTALL == params.getAction()) { processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_UNINSTALL); } else if (ACTION_OPTIMIZE == params.getAction()) { processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_OPTIMIZE); } else if (ACTION_ALL == params.getAction()) { processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_ALL); } // Modules en place sur la BD en final console.printMessage("Finally DB Status :"); checkDBStatus(); } Date endDate = new Date(); console.printMessage(MessageFormat.format(messages.getString("dbbuilder.success"), endDate)); System.out.println("*******************************************************************"); System.out.println(MessageFormat.format(messages.getString("dbbuilder.success"), endDate)); } catch (Exception e) { e.printStackTrace(); console.printError(e.getMessage(), e); Date endDate = new Date(); console.printError(MessageFormat.format(messages.getString("dbbuilder.failure"), endDate)); System.out.println("*******************************************************************"); System.out.println(MessageFormat.format(messages.getString("dbbuilder.failure"), endDate)); System.exit(1); } finally { springContext.close(); console.close(); } }
From source file:de.citec.sc.matoll.process.Matoll_CreateMax.java
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException, Exception { String directory;//from w w w . j a v a 2s . c om String gold_standard_lexicon; String output_lexicon; String configFile; Language language; String output; Stopwords stopwords = new Stopwords(); HashMap<String, Double> maxima; maxima = new HashMap<String, Double>(); if (args.length < 3) { System.out.print("Usage: Matoll --mode=train/test <DIRECTORY> <CONFIG>\n"); return; } // Classifier classifier; directory = args[1]; configFile = args[2]; final Config config = new Config(); config.loadFromFile(configFile); gold_standard_lexicon = config.getGoldStandardLexicon(); String model_file = config.getModel(); output_lexicon = config.getOutputLexicon(); output = config.getOutput(); language = config.getLanguage(); LexiconLoader loader = new LexiconLoader(); Lexicon gold = loader.loadFromFile(gold_standard_lexicon); Set<String> uris = new HashSet<>(); // Map<Integer,String> sentence_list = new HashMap<>(); Map<Integer, Set<Integer>> mapping_words_sentences = new HashMap<>(); //consider only properties for (LexicalEntry entry : gold.getEntries()) { try { for (Sense sense : entry.getSenseBehaviours().keySet()) { String tmp_uri = sense.getReference().getURI().replace("http://dbpedia.org/ontology/", ""); if (!Character.isUpperCase(tmp_uri.charAt(0))) { uris.add(sense.getReference().getURI()); } } } catch (Exception e) { } ; } ModelPreprocessor preprocessor = new ModelPreprocessor(language); preprocessor.setCoreferenceResolution(false); Set<String> dep = new HashSet<>(); dep.add("prep"); dep.add("appos"); dep.add("nn"); dep.add("dobj"); dep.add("pobj"); dep.add("num"); preprocessor.setDEP(dep); List<File> list_files = new ArrayList<>(); if (config.getFiles().isEmpty()) { File folder = new File(directory); File[] files = folder.listFiles(); for (File file : files) { if (file.toString().contains(".ttl")) list_files.add(file); } } else { list_files.addAll(config.getFiles()); } System.out.println(list_files.size()); int sentence_counter = 0; Map<String, Set<Integer>> bag_words_uri = new HashMap<>(); Map<String, Integer> mapping_word_id = new HashMap<>(); for (File file : list_files) { Model model = RDFDataMgr.loadModel(file.toString()); for (Model sentence : getSentences(model)) { String reference = getReference(sentence); reference = reference.replace("http://dbpedia/", "http://dbpedia.org/"); if (uris.contains(reference)) { sentence_counter += 1; Set<Integer> words_ids = getBagOfWords(sentence, stopwords, mapping_word_id); //TODO: add sentence preprocessing String obj = getObject(sentence); String subj = getSubject(sentence); preprocessor.preprocess(sentence, subj, obj, language); //TODO: also return marker if object or subject of property (in SPARQL this has to be optional of course) String parsed_sentence = getParsedSentence(sentence); try (FileWriter fw = new FileWriter("mapping_sentences_to_ids_goldstandard.tsv", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println(sentence_counter + "\t" + parsed_sentence); } catch (IOException e) { e.printStackTrace(); } for (Integer word_id : words_ids) { if (mapping_words_sentences.containsKey(word_id)) { Set<Integer> tmp_set = mapping_words_sentences.get(word_id); tmp_set.add(sentence_counter); mapping_words_sentences.put(word_id, tmp_set); } else { Set<Integer> tmp_set = new HashSet<>(); tmp_set.add(sentence_counter); mapping_words_sentences.put(word_id, tmp_set); } } if (bag_words_uri.containsKey(reference)) { Set<Integer> tmp = bag_words_uri.get(reference); for (Integer w : words_ids) { tmp.add(w); } bag_words_uri.put(reference, tmp); } else { Set<Integer> tmp = new HashSet<>(); for (Integer w : words_ids) { tmp.add(w); } bag_words_uri.put(reference, tmp); } } } model.close(); } PrintWriter writer = new PrintWriter("bag_of_words_only_goldstandard.tsv"); StringBuilder string_builder = new StringBuilder(); for (String r : bag_words_uri.keySet()) { string_builder.append(r); for (Integer i : bag_words_uri.get(r)) { string_builder.append("\t"); string_builder.append(i); } string_builder.append("\n"); } writer.write(string_builder.toString()); writer.close(); writer = new PrintWriter("mapping_words_to_sentenceids_goldstandard.tsv"); string_builder = new StringBuilder(); for (Integer w : mapping_words_sentences.keySet()) { string_builder.append(w); for (int i : mapping_words_sentences.get(w)) { string_builder.append("\t"); string_builder.append(i); } string_builder.append("\n"); } writer.write(string_builder.toString()); writer.close(); }
From source file:com.bright.json.PGS.java
public static void main(String[] args) throws FileNotFoundException { String fileBasename = null;//w ww.j av a2s. c o m JFileChooser chooser = new JFileChooser(); try { FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Spreadsheets", "xls", "xlsx"); chooser.setFileFilter(filter); chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home"))); chooser.setDialogTitle("Select the Excel file"); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); // String fileBasename = // chooser.getSelectedFile().toString().substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator)+1,chooser.getSelectedFile().toString().lastIndexOf(".")); fileBasename = chooser.getSelectedFile().toString() .substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator) + 1); System.out.println("Base name: " + fileBasename); } else { System.out.println("No Selection "); } } catch (Exception e) { System.out.println(e.toString()); } String fileName = chooser.getSelectedFile().toString(); InputStream inp = new FileInputStream(fileName); Workbook workbook = null; if (fileName.toLowerCase().endsWith("xlsx")) { try { workbook = new XSSFWorkbook(inp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (fileName.toLowerCase().endsWith("xls")) { try { workbook = new HSSFWorkbook(inp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Sheet nodeSheet = workbook.getSheet("Devices"); Sheet interfaceSheet = workbook.getSheet("Interfaces"); System.out.println("Read nodes sheet."); // Row nodeRow = nodeSheet.getRow(1); // System.out.println(row.getCell(0).toString()); // System.exit(0); JTextField uiHost = new JTextField("demo.brightcomputing.com"); // TextPrompt puiHost = new // TextPrompt("demo.brightcomputing.com",uiHost); JTextField uiUser = new JTextField("root"); // TextPrompt puiUser = new TextPrompt("root", uiUser); JTextField uiPass = new JPasswordField(""); // TextPrompt puiPass = new TextPrompt("x5deix5dei", uiPass); JPanel myPanel = new JPanel(new GridLayout(5, 1)); myPanel.add(new JLabel("Bright HeadNode hostname:")); myPanel.add(uiHost); // myPanel.add(Box.createHorizontalStrut(1)); // a spacer myPanel.add(new JLabel("Username:")); myPanel.add(uiUser); myPanel.add(new JLabel("Password:")); myPanel.add(uiPass); int result = JOptionPane.showConfirmDialog(null, myPanel, "Please fill in all the fields.", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { System.out.println("Input received."); } String rhost = uiHost.getText(); String ruser = uiUser.getText(); String rpass = uiPass.getText(); String cmURL = "https://" + rhost + ":8081/json"; List<Cookie> cookies = doLogin(ruser, rpass, cmURL); chkVersion(cmURL, cookies); Map<String, Long> categories = UniqueKeyMap(cmURL, "cmdevice", "getCategories", cookies); Map<String, Long> networks = UniqueKeyMap(cmURL, "cmnet", "getNetworks", cookies); Map<String, Long> partitions = UniqueKeyMap(cmURL, "cmpart", "getPartitions", cookies); Map<String, Long> racks = UniqueKeyMap(cmURL, "cmpart", "getRacks", cookies); Map<String, Long> switches = UniqueKeyMap(cmURL, "cmdevice", "getEthernetSwitches", cookies); // System.out.println(switches.get("switch01")); // System.out.println("Size of the map: "+ switches.size()); // System.exit(0); cmDevice newnode = new cmDevice(); cmDevice.deviceObject devObj = new cmDevice.deviceObject(); cmDevice.switchObject switchObj = new cmDevice.switchObject(); // cmDevice.netObject netObj = new cmDevice.netObject(); List<String> emptyslist = new ArrayList<String>(); // Row nodeRow = nodeSheet.getRow(1); // Row ifRow = interfaceSheet.getRow(1); // System.out.println(nodeRow.getCell(0).toString()); // nodeRow.getCell(3).getStringCellValue() Map<String, ArrayList<cmDevice.netObject>> ifmap = new HashMap<String, ArrayList<cmDevice.netObject>>(); // Map<String,netObject> helperMap = new HashMap<String,netObject>(); // Iterator<Row> rows = interfaceSheet.rowIterator (); // while (rows. < interfaceSheet.getPhysicalNumberOfRows()) { // List<netObject> netList = new ArrayList<netObject>(); for (int i = 0; i < interfaceSheet.getPhysicalNumberOfRows(); i++) { Row ifRow = interfaceSheet.getRow(i); if (ifRow.getRowNum() == 0) { continue; // just skip the rows if row number is 0 } System.out.println("Row nr: " + ifRow.getRowNum()); cmDevice.netObject netObj = new cmDevice.netObject(); ArrayList<cmDevice.netObject> helperList = new ArrayList<cmDevice.netObject>(); netObj.setBaseType("NetworkInterface"); netObj.setCardType(ifRow.getCell(3).getStringCellValue()); netObj.setChildType(ifRow.getCell(4).getStringCellValue()); netObj.setDhcp((ifRow.getCell(5).getNumericCellValue() > 0.1) ? true : false); netObj.setIp(ifRow.getCell(7).getStringCellValue()); // netObj.setMac(ifRow.getCell(0).toString()); //netObj.setModified(true); netObj.setName(ifRow.getCell(1).getStringCellValue()); netObj.setNetwork(networks.get(ifRow.getCell(6).getStringCellValue())); //netObj.setOldLocalUniqueKey(0L); netObj.setRevision(""); netObj.setSpeed(ifRow.getCell(8, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setStartIf("ALWAYS"); netObj.setToBeRemoved(false); netObj.setUniqueKey((long) ifRow.getCell(2).getNumericCellValue()); //netObj.setAdditionalHostnames(new ArrayList<String>(Arrays.asList(ifRow.getCell(9, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*")))); //netObj.setMac(ifRow.getCell(10, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setMode((int) ifRow.getCell(11, Row.CREATE_NULL_AS_BLANK).getNumericCellValue()); netObj.setOptions(ifRow.getCell(12, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setMembers(new ArrayList<String>(Arrays .asList(ifRow.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*")))); // ifmap.put(ifRow.getCell(0).getStringCellValue(), new // HashMap<String, cmDevice.netObject>()); // helperMap.put(ifRow.getCell(1).getStringCellValue(), netObj) ; // ifmap.get(ifRow.getCell(0).getStringCellValue()).putIfAbsent(ifRow.getCell(1).getStringCellValue(), // netObj); // ifmap.put(ifRow.getCell(0).getStringCellValue(), helperMap); if (!ifmap.containsKey(ifRow.getCell(0).getStringCellValue())) { ifmap.put(ifRow.getCell(0).getStringCellValue(), new ArrayList<cmDevice.netObject>()); } helperList = ifmap.get(ifRow.getCell(0).getStringCellValue()); helperList.add(netObj); ifmap.put(ifRow.getCell(0).getStringCellValue(), helperList); continue; } for (int i = 0; i < nodeSheet.getPhysicalNumberOfRows(); i++) { Row nodeRow = nodeSheet.getRow(i); if (nodeRow.getRowNum() == 0) { continue; // just skip the rows if row number is 0 } newnode.setService("cmdevice"); newnode.setCall("addDevice"); Map<String, Long> ifmap2 = new HashMap<String, Long>(); for (cmDevice.netObject j : ifmap.get(nodeRow.getCell(0).getStringCellValue())) ifmap2.put(j.getName(), j.getUniqueKey()); switchObj.setEthernetSwitch(switches.get(nodeRow.getCell(8).getStringCellValue())); System.out.println(nodeRow.getCell(8).getStringCellValue()); System.out.println(switches.get(nodeRow.getCell(8).getStringCellValue())); switchObj.setPrt((int) nodeRow.getCell(9).getNumericCellValue()); switchObj.setBaseType("SwitchPort"); devObj.setBaseType("Device"); // devObj.setCreationTime(0L); devObj.setCustomPingScript(""); devObj.setCustomPingScriptArgument(""); devObj.setCustomPowerScript(""); devObj.setCustomPowerScriptArgument(""); devObj.setCustomRemoteConsoleScript(""); devObj.setCustomRemoteConsoleScriptArgument(""); devObj.setDisksetup(""); devObj.setBmcPowerResetDelay(0L); devObj.setBurning(false); devObj.setEthernetSwitch(switchObj); devObj.setExcludeListFull(""); devObj.setExcludeListGrab(""); devObj.setExcludeListGrabnew(""); devObj.setExcludeListManipulateScript(""); devObj.setExcludeListSync(""); devObj.setExcludeListUpdate(""); devObj.setFinalize(""); devObj.setRack(racks.get(nodeRow.getCell(10).getStringCellValue())); devObj.setRackHeight((long) nodeRow.getCell(11).getNumericCellValue()); devObj.setRackPosition((long) nodeRow.getCell(12).getNumericCellValue()); devObj.setIndexInsideContainer(0L); devObj.setInitialize(""); devObj.setInstallBootRecord(false); devObj.setInstallMode(""); devObj.setIoScheduler(""); devObj.setLastProvisioningNode(0L); devObj.setMac(nodeRow.getCell(6).getStringCellValue()); devObj.setModified(true); devObj.setCategory(categories.get(nodeRow.getCell(1).getStringCellValue())); devObj.setChildType("PhysicalNode"); //devObj.setDatanode((nodeRow.getCell(5).getNumericCellValue() > 0.1) ? true // : false); devObj.setHostname(nodeRow.getCell(0).getStringCellValue()); devObj.setModified(true); devObj.setPartition(partitions.get(nodeRow.getCell(2).getStringCellValue())); devObj.setUseExclusivelyFor("Category"); devObj.setNextBootInstallMode(""); devObj.setNotes(""); devObj.setOldLocalUniqueKey(0L); devObj.setPowerControl(nodeRow.getCell(7).getStringCellValue()); // System.out.println(ifmap.get("excelnode001").size()); // System.out.println(ifmap.get(nodeRow.getCell(0).getStringCellValue()).get(nodeRow.getCell(3).getStringCellValue()).getUniqueKey()); devObj.setManagementNetwork(networks.get(nodeRow.getCell(3).getStringCellValue())); devObj.setProvisioningNetwork(ifmap2.get(nodeRow.getCell(4).getStringCellValue())); devObj.setProvisioningTransport("RSYNCDAEMON"); devObj.setPxelabel(""); // "rack": 90194313218, // "rackHeight": 1, // "rackPosition": 4, devObj.setRaidconf(""); devObj.setRevision(""); devObj.setSoftwareImageProxy(null); devObj.setStartNewBurn(false); devObj.setTag("00000000a000"); devObj.setToBeRemoved(false); // devObj.setUcsInfoConfigured(null); // devObj.setUniqueKey(12345L); devObj.setUserdefined1(""); devObj.setUserdefined2(""); ArrayList<Object> mylist = new ArrayList<Object>(); ArrayList<cmDevice.netObject> mylist2 = new ArrayList<cmDevice.netObject>(); ArrayList<Object> emptylist = new ArrayList<Object>(); devObj.setFsexports(emptylist); devObj.setFsmounts(emptylist); devObj.setGpuSettings(emptylist); devObj.setFspartAssociations(emptylist); devObj.setPowerDistributionUnits(emptyslist); devObj.setRoles(emptylist); devObj.setServices(emptylist); devObj.setStaticRoutes(emptylist); mylist2 = ifmap.get(nodeRow.getCell(0).getStringCellValue()); devObj.setNetworks(mylist2); mylist.add(devObj); mylist.add(1); newnode.setArgs(mylist); GsonBuilder builder = new GsonBuilder(); builder.enableComplexMapKeySerialization(); // Gson g = new Gson(); Gson g = builder.create(); String json2 = g.toJson(newnode); // To be used from a real console and not Eclipse String message = JSonRequestor.doRequest(json2, cmURL, cookies); continue; } JOptionPane optionPaneF = new JOptionPane("The nodes have been added!"); JDialog myDialogF = optionPaneF.createDialog(null, "Complete: "); myDialogF.setModal(false); myDialogF.setVisible(true); doLogout(cmURL, cookies); // System.exit(0); }
From source file:edu.msu.cme.rdp.alignment.errorcheck.CompareErrorType.java
public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption("s", "stem", true, "Output stem (default <query_nucl.fasta>)"); final SeqReader queryReader; final List<Sequence> refSeqList; final PrintStream alignOutStream; final CompareErrorType errorProcessor; Sequence seq;//from w w w .j a va 2 s .c o m Map<String, PAObject> matchMap = new HashMap(); try { CommandLine line = new PosixParser().parse(options, args); String stem; args = line.getArgs(); if (args.length != 2 && args.length != 3) { throw new Exception("Unexpected number of arguments"); } File refFile = new File(args[0]); File queryFile = new File(args[1]); if (line.hasOption("stem")) { stem = line.getOptionValue("stem"); } else { stem = queryFile.getName(); } File alignOutFile = new File(stem + "_alignments.txt"); File mismatchOutFile = new File(stem + "_mismatches.txt"); File indelOutFile = new File(stem + "_indels.txt"); File qualOutFile = null; refSeqList = SequenceReader.readFully(refFile); if (args.length == 3) { queryReader = new QSeqReader(queryFile, new File(args[2])); } else { queryReader = new SequenceReader(queryFile); } seq = queryReader.readNextSequence(); if (seq instanceof QSequence) { qualOutFile = new File(stem + "_qual.txt"); } errorProcessor = new CompareErrorType(mismatchOutFile, indelOutFile, qualOutFile); alignOutStream = new PrintStream(alignOutFile); System.err.println("Starting CompareErrorType"); System.err.println("* Time: " + new Date()); System.err.println("* Reference File: " + refFile); System.err.println("* Query File: " + queryFile); if (args.length == 3) { System.err.println("* Qual File: " + args[2]); } System.err.println("* Query format: " + queryReader.getFormat()); System.err.println("* Alignment Output: " + alignOutFile); System.err.println("* Mismatches Output: " + mismatchOutFile); System.err.println("* Alignment Output: " + indelOutFile); if (qualOutFile != null) { System.err.println("* Quality Output: " + qualOutFile); } } catch (Exception e) { new HelpFormatter().printHelp( "CompareErrorType [options] <ref_nucl> (<query_nucl> | <query_nucl.fasta> <query_nucl.qual>)", options); System.err.println("ERROR: " + e.getMessage()); throw new RuntimeException(e); //System.exit(1); //return; } //ScoringMatrix scoringMatrix = ScoringMatrix.getDefaultNuclMatrix(); // use a simple scoring function, match score 0, mismatch -1, gap opening -1, gap extension -1. ScoringMatrix scoringMatrix = new ScoringMatrix( ScoringMatrix.class.getResourceAsStream("/data/simple_scoringmatrix.txt"), -1, -1); do { try { PairwiseAlignment bestResult = null; Sequence bestSeq = null; boolean bestReversed = false; String querySeqStr = seq.getSeqString().toLowerCase(); String reversedQuery = IUBUtilities.reverseComplement(querySeqStr); PAObject bestMatch = null; //checking if sequence has been seen before if (matchMap.containsKey(seq.getSeqString())) { bestMatch = matchMap.get(seq.getSeqString()); } else { for (Sequence refSeq : refSeqList) { String refSeqStr = refSeq.getSeqString().toLowerCase(); PairwiseAlignment result = PairwiseAligner.align(refSeqStr, querySeqStr, scoringMatrix, AlignmentMode.global); PairwiseAlignment reversedResult = PairwiseAligner.align(refSeqStr, IUBUtilities.reverseComplement(querySeqStr), scoringMatrix, AlignmentMode.global); PairwiseAlignment currBest = (result.getScore() > reversedResult.getScore()) ? result : reversedResult; if (bestResult == null || currBest.getScore() > bestResult.getScore()) { bestResult = currBest; bestSeq = refSeq; if (currBest == reversedResult) { bestReversed = true; } else { bestReversed = false; } } //Since this is a new sequence, make a new PAObject to put into the map to compare against later bestMatch = new PAObject(bestResult, bestReversed, bestSeq); matchMap.put(seq.getSeqString(), bestMatch); } } int refStart = bestMatch.getPA().getStarti(); int refEnd = bestMatch.getPA().getEndi(); bestSeq = bestMatch.getRefSeq(); bestReversed = bestMatch.getReversed(); bestResult = bestMatch.getPA(); //output information alignOutStream.println(">\t" + seq.getSeqName() + "\t" + bestSeq.getSeqName() + "\t" + seq.getSeqString().length() + "\t" + refStart + "\t" + refEnd + "\t" + bestResult.getScore() + "\t" + ((bestReversed) ? "\treversed" : "")); alignOutStream.println(bestResult.getAlignedSeqj() + "\n"); alignOutStream.println(bestResult.getAlignedSeqi() + "\n"); //seqi is reference seq, seqj is the refseq errorProcessor.processSequence(seq, bestResult.getAlignedSeqj(), bestSeq.getSeqName(), bestResult.getAlignedSeqi(), refStart, bestReversed); } catch (Exception e) { throw new RuntimeException("Failed while processing seq " + seq.getSeqName(), e); } } while ((seq = queryReader.readNextSequence()) != null); queryReader.close(); alignOutStream.close(); errorProcessor.close(); }
From source file:io.compgen.cgpipe.CGPipe.java
public static void main(String[] args) { String fname = null;//from ww w.j a va 2 s. c o m String logFilename = null; String outputFilename = null; PrintStream outputStream = null; int verbosity = 0; boolean silent = false; boolean dryrun = false; boolean silenceStdErr = false; boolean showHelp = false; List<String> targets = new ArrayList<String>(); Map<String, VarValue> confVals = new HashMap<String, VarValue>(); String k = null; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (i == 0) { if (new File(arg).exists()) { fname = arg; silenceStdErr = true; continue; } } else if (args[i - 1].equals("-f")) { fname = arg; continue; } else if (args[i - 1].equals("-l")) { logFilename = arg; continue; } else if (args[i - 1].equals("-o")) { outputFilename = arg; continue; } if (arg.equals("-h") || arg.equals("-help") || arg.equals("--help")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } showHelp = true; } else if (arg.equals("-license")) { license(); System.exit(1); } else if (arg.equals("-s")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } silent = true; } else if (arg.equals("-nolog")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } silenceStdErr = true; } else if (arg.equals("-v")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } verbosity++; } else if (arg.equals("-vv")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } verbosity += 2; } else if (arg.equals("-vvv")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } verbosity += 3; } else if (arg.equals("-dr")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } dryrun = true; } else if (arg.startsWith("--")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } k = arg.substring(2); } else if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } if (confVals.containsKey(k)) { try { VarValue val = confVals.get(k); if (val.getClass().equals(VarList.class)) { ((VarList) val).add(VarValue.parseStringRaw(arg)); } else { VarList list = new VarList(); list.add(val); list.add(VarValue.parseStringRaw(arg)); confVals.put(k, list); } } catch (VarTypeException e) { System.err.println("Error setting variable: " + k + " => " + arg); System.exit(1); ; } } else { confVals.put(k, VarValue.parseStringRaw(arg)); } k = null; } else if (arg.charAt(0) != '-') { targets.add(arg); } } if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } confVals.put("cgpipe.loglevel", new VarInt(verbosity)); if (fname == null) { usage(); System.exit(1); } if (!showHelp) { switch (verbosity) { case 0: SimpleFileLoggerImpl.setLevel(Level.INFO); break; case 1: SimpleFileLoggerImpl.setLevel(Level.DEBUG); break; case 2: SimpleFileLoggerImpl.setLevel(Level.TRACE); break; case 3: default: SimpleFileLoggerImpl.setLevel(Level.ALL); break; } } else { SimpleFileLoggerImpl.setLevel(Level.FATAL); } SimpleFileLoggerImpl.setSilent(silenceStdErr || showHelp); Log log = LogFactory.getLog(CGPipe.class); log.info("Starting new run: " + fname); if (logFilename != null) { confVals.put("cgpipe.log", new VarString(logFilename)); } if (System.getenv("CGPIPE_DRYRUN") != null && !System.getenv("CGPIPE_DRYRUN").equals("")) { dryrun = true; } JobRunner runner = null; try { // Load config values from global config. RootContext root = new RootContext(); loadInitFiles(root); // Load settings from environment variables. root.loadEnvironment(); // Set cmd-line arguments if (silent) { root.setOutputStream(null); } if (outputFilename != null) { outputStream = new PrintStream(new FileOutputStream(outputFilename)); root.setOutputStream(outputStream); } for (String k1 : confVals.keySet()) { log.info("config: " + k1 + " => " + confVals.get(k1).toString()); } root.update(confVals); root.set("cgpipe.procs", new VarInt(Runtime.getRuntime().availableProcessors())); // update the URL Source loader configs SourceLoader.updateRemoteHandlers(root.cloneString("cgpipe.remote")); // Now check for help, only after we've setup the remote handlers... if (showHelp) { try { Parser.showHelp(fname); System.exit(0); } catch (IOException e) { System.err.println("Unable to find pipeline: " + fname); System.exit(1); } } // Set the global config values // globalConfig.putAll(root.cloneValues()); // Parse the AST and run it Parser.exec(fname, root); // Load the job runner *after* we execute the script to capture any config changes runner = JobRunner.load(root, dryrun); // find a build-target, and submit the job(s) to a runner if (targets.size() > 0) { for (String target : targets) { log.debug("building: " + target); BuildTarget initTarget = root.build(target); if (initTarget != null) { runner.submitAll(initTarget, root); } else { System.out.println("CGPIPE ERROR: Unable to find target: " + target); } } } else { BuildTarget initTarget = root.build(); if (initTarget != null) { runner.submitAll(initTarget, root); // Leave this commented out - it should be allowed to run cgpipe scripts w/o a target defined (testing) // } else { // System.out.println("CGPIPE ERROR: Unable to find default target"); } } runner.done(); if (outputStream != null) { outputStream.close(); } } catch (ASTParseException | ASTExecException | RunnerException | FileNotFoundException e) { if (outputStream != null) { outputStream.close(); } if (runner != null) { runner.abort(); } if (e.getClass().equals(ExitException.class)) { System.exit(((ExitException) e).getReturnCode()); } System.out.println("CGPIPE ERROR " + e.getMessage()); if (verbosity > 0) { e.printStackTrace(); } System.exit(1); } }
From source file:org.ptm.translater.App.java
public static void main(String... args) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load("file:src/main/resources/spring/datasource.xml"); ctx.refresh();/*from ww w. j a v a 2 s . c om*/ GenericXmlApplicationContext ctx2 = new GenericXmlApplicationContext(); ctx2.load("file:src/main/resources/spring/datasource2.xml"); ctx2.refresh(); ArchiveDao archiveDao = ctx.getBean("archiveDao", ArchiveDao.class); List<Archive> archives = archiveDao.findAll(); UserDao userDao = ctx2.getBean("userDao", UserDao.class); TagDao tagDao = ctx2.getBean("tagDao", TagDao.class); PhotoDao photoDao = ctx2.getBean("photoDao", PhotoDao.class); List<Tag> tagz = tagDao.findAll(); Map<String, Long> hashTags = new HashMap<String, Long>(); for (Tag tag : tagz) hashTags.put(tag.getName(), tag.getId()); MongoCache cache = new MongoCache(); Calendar calendar = Calendar.getInstance(); Map<String, String> associates = new HashMap<String, String>(); for (Archive archive : archives) { AppUser appUser = new AppUser(); appUser.setName(archive.getName()); appUser.setEmail(archive.getUid() + "@mail.th"); appUser.setPassword("123456"); Role role = new Role(); role.setRoleId("ROLE_USER"); appUser.setRole(role); userDao.save(appUser); System.out.println("\tCreate user " + appUser); for (Photo photo : archive.getPhotos()) { // ? ??? if (cache.contains(photo.getUid())) continue; System.out.println("\tNew photo"); org.ptm.translater.ch2.domain.Photo photo2 = new org.ptm.translater.ch2.domain.Photo(); photo2.setAppUser(appUser); photo2.setName(photo.getTitle()); photo2.setLicense((byte) 7); photo2.setDescription(photo.getDescription()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { calendar.setTime(sdf.parse(photo.getTaken())); if (calendar.get(Calendar.YEAR) != 0 && calendar.get(Calendar.YEAR) > 1998) continue; photo2.setYear(calendar.get(Calendar.YEAR)); photo2.setMonth(calendar.get(Calendar.MONTH) + 1); photo2.setDay(calendar.get(Calendar.DAY_OF_MONTH)); } catch (Exception ex) { ex.printStackTrace(); } if (photo.getLongitude() != null && photo.getLongitude().length() > 0) { // String key = photo.getLongitude()+"#"+photo.getLatitude(); photo2.setLatitude(photo.getLatitude()); photo2.setLongitude(photo.getLongitude()); // if (associates.containsKey(key)) { // photo2.setAddress(associates.get(key)); // } else { // Geocoder geocoder = new Geocoder(); // GeocoderRequestBuilder geocoderRequest = new GeocoderRequestBuilder(); // GeocoderRequest request = // geocoderRequest.setLocation(new LatLng(photo.getLongitude(), photo.getLatitude())).getGeocoderRequest(); // // GeocodeResponse response = geocoder.geocode(request); // if (response.getResults().size() > 0) { // photo2.setAddress(response.getResults().get(0).getFormattedAddress()); // } // try { Thread.sleep(2000); } catch (InterruptedException ex) { ex.printStackTrace(); } // } } System.out.println("\tFind tags"); Set<Tag> tags = new HashSet<Tag>(); for (org.ptm.translater.ch1.domain.Tag tag : photo.getTags()) { Tag item = new Tag(); item.setName(tag.getName()); if (hashTags.containsKey(tag.getName())) { item.setId(hashTags.get(tag.getName())); } else { tagDao.save(item); hashTags.put(item.getName(), item.getId()); } System.out.println("\t\tinit tag " + tag.getName()); tags.add(item); } photo2.setTags(tags); System.out.println("\tFind " + tags.size() + " tags"); photoDao.save(photo2); System.out.println("\tSave photo"); Imaginator img = new Imaginator(); img.setFolder(photo2.getId().toString()); img.setPath(); for (PhotoSize ps : photo.getSizes()) { if (ps.getLabel().equals("Original")) { img.setImage(ps.getSource()); break; } } img.generate(); System.out.println("\tGenerate image of photo"); img = null; cache.create(photo.getUid()); cache.create(photo2); System.out.println("Generate: " + photo2); } } }
From source file:com.mycompany.sparkrentals.Main.java
public static void main(String[] args) { initializeSolrCqlHostsFromArgs(args); // Configure Solr connection RentalSolrClient solrClient = new RentalSolrClient(); solrClient.connect(solrUrl);//from w ww. j ava 2s . c o m // Configure Cassandra connection CqlClient cqlClient = new CqlClient(); cqlClient.connect(cqlHost); cqlClient.setCqlKeyspace(cqlKeyspace); // Configure the view directory Configuration viewConfig = new Configuration(); viewConfig.setClassForTemplateLoading(Main.class, "/views"); FreeMarkerEngine freeMarkerEngine = new FreeMarkerEngine(viewConfig); // Configure the static files directory staticFileLocation("/public"); //exception handling exception(DriverException.class, (exception, request, response) -> { //handle exception for cassandra serve exception response.body("Something wrong for cassandra server " + exception.getMessage()); }); exception(Exception.class, (exception, request, response) -> { //handle exception response.body("Sorry something went wrong. Please try again later."); }); //start setting up routes here get("/add", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("data", new HashMap<>()); fillFormSelectionOption(attributes); return new ModelAndView(attributes, "add.ftl"); }, freeMarkerEngine); post("/add", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); AddRentalForm form = new AddRentalForm(); form.setQueryMap(request.queryMap()); if (form.validate()) { //valid rental data, so will insert into database and solr // or it'll update if one recrod already exists with the same key Rental rental = new Rental(); rental.SetValuesFromMap(form.getCleanedData()); //Assuming for now there's only one currency $ //so we don't need to ask the user to select, we preset it here rental.setCurrency("$"); rental.setUpdated(new Date()); //insert into cql db cqlClient.insertOrUpdateRental(rental); //add index to solr at the same time try { solrClient.addRental(rental); } catch (IOException e) { attributes.put("message", "exception connecting to solr server"); return new ModelAndView(attributes, "exception.ftl"); } catch (SolrServerException e) { attributes.put("message", "solr server exception"); return new ModelAndView(attributes, "exception.ftl"); } return new ModelAndView(attributes, "add_done.ftl"); } // form contains errors attributes.put("errorMessages", form.getErrorMessages()); attributes.put("data", form.getDataToDisplay()); fillFormSelectionOption(attributes); return new ModelAndView(attributes, "add.ftl"); }, freeMarkerEngine); //index is the search page get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); SearchRentalForm form = new SearchRentalForm(); form.setQueryMap(request.queryMap()); int perPage = 20; //number of results per page if (form.validate()) { Map<String, Object> cleanedData = form.getCleanedData(); //get the search results from SOLR try { QueryResponse queryResponse = solrClient.searchRentals(cleanedData, perPage); List<Rental> rentalList = queryResponse.getBeans(Rental.class); //these are for pagination purpose long resultsTotal = queryResponse.getResults().getNumFound(); attributes.put("resultsTotal", resultsTotal); int currentPage = (int) cleanedData.getOrDefault("page", 1); attributes.put("currentPage", currentPage); long maxPage = (resultsTotal % perPage > 0 ? 1 : 0) + resultsTotal / perPage; attributes.put("maxPage", maxPage); attributes.put("rentalList", rentalList); attributes.put("errorMessages", new ArrayList<>()); } catch (IOException e) { attributes.put("errorMessages", Arrays.asList("Exception when connecting to Solr!" + e.getMessage())); } catch (SolrException e) { //there is an error for querying attributes.put("errorMessages", Arrays.asList("Solr query error!")); } } else { //search form not valid attributes.put("rentalList", new ArrayList<>()); attributes.put("errorMessages", form.getErrorMessages()); } if (!attributes.containsKey("rentalList")) { attributes.put("rentalList", new ArrayList<>()); } //for disply back to user entered data attributes.put("data", form.getDataToDisplay()); fillFormSelectionOption(attributes); return new ModelAndView(attributes, "index.ftl"); }, freeMarkerEngine); }
From source file:com.moviejukebox.MovieJukebox.java
public static void main(String[] args) throws Throwable { JukeboxStatistics.setTimeStart(System.currentTimeMillis()); // Create the log file name here, so we can change it later (because it's locked System.setProperty("file.name", LOG_FILENAME); PropertyConfigurator.configure("properties/log4j.properties"); LOG.info("Yet Another Movie Jukebox {}", GitRepositoryState.getVersion()); LOG.info("~~~ ~~~~~~~ ~~~~~ ~~~~~~~ {}", StringUtils.repeat("~", GitRepositoryState.getVersion().length())); LOG.info("https://github.com/YAMJ/yamj-v2"); LOG.info("Copyright (c) 2004-2016 YAMJ Members"); LOG.info(""); LOG.info("This software is licensed under the GNU General Public License v3+"); LOG.info("See this page: https://github.com/YAMJ/yamj-v2/wiki/License"); LOG.info(""); LOG.info(" Revision SHA: {} {}", GIT.getCommitId(), GIT.getDirty() ? "(Custom Build)" : ""); LOG.info(" Commit Date: {}", GIT.getCommitTime()); LOG.info(" Build Date: {}", GIT.getBuildTime()); LOG.info(""); LOG.info(" Java Version: {}", GitRepositoryState.getJavaVersion()); LOG.info(""); if (!SystemTools.validateInstallation()) { LOG.info("ABORTING."); return;//from w w w. j ava2 s . c o m } String movieLibraryRoot = null; String jukeboxRoot = null; Map<String, String> cmdLineProps = new LinkedHashMap<>(); try { for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-v".equalsIgnoreCase(arg)) { // We've printed the version, so quit now return; } else if ("-t".equalsIgnoreCase(arg)) { String pin = args[++i]; // load the apikeys.properties file if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) { return; } // authorize to Trakt.TV TraktTV.getInstance().initialize().authorizeWithPin(pin); // We've authorized access to Trakt.TV, so quit now return; } else if ("-o".equalsIgnoreCase(arg)) { jukeboxRoot = args[++i]; PropertiesUtil.setProperty("mjb.jukeboxRoot", jukeboxRoot); } else if ("-c".equalsIgnoreCase(arg)) { jukeboxClean = Boolean.TRUE; PropertiesUtil.setProperty("mjb.jukeboxClean", TRUE); } else if ("-k".equalsIgnoreCase(arg)) { setJukeboxPreserve(Boolean.TRUE); } else if ("-p".equalsIgnoreCase(arg)) { userPropertiesName = args[++i]; } else if ("-i".equalsIgnoreCase(arg)) { skipIndexGeneration = Boolean.TRUE; PropertiesUtil.setProperty("mjb.skipIndexGeneration", TRUE); } else if ("-h".equalsIgnoreCase(arg)) { skipHtmlGeneration = Boolean.TRUE; PropertiesUtil.setProperty("mjb.skipHtmlGeneration", Boolean.TRUE); } else if ("-dump".equalsIgnoreCase(arg)) { dumpLibraryStructure = Boolean.TRUE; } else if ("-memory".equalsIgnoreCase(arg)) { showMemory = Boolean.TRUE; PropertiesUtil.setProperty("mjb.showMemory", Boolean.TRUE); } else if (arg.startsWith("-D")) { String propLine = arg.length() > 2 ? arg.substring(2) : args[++i]; int propDiv = propLine.indexOf('='); if (-1 != propDiv) { cmdLineProps.put(propLine.substring(0, propDiv), propLine.substring(propDiv + 1)); } } else if (arg.startsWith("-")) { help(); return; } else { movieLibraryRoot = args[i]; } } } catch (Exception error) { LOG.error("Wrong arguments specified"); help(); return; } // Save the name of the properties file for use later setProperty("userPropertiesName", userPropertiesName); LOG.info("Processing started at {}", new Date()); LOG.info(""); // Load the moviejukebox-default.properties file if (!setPropertiesStreamName("./properties/moviejukebox-default.properties", Boolean.TRUE)) { return; } // Load the user properties file "moviejukebox.properties" // No need to abort if we don't find this file // Must be read before the skin, because this may contain an override skin setPropertiesStreamName(userPropertiesName, Boolean.FALSE); // Grab the skin from the command-line properties if (cmdLineProps.containsKey(SKIN_DIR)) { setProperty(SKIN_DIR, cmdLineProps.get(SKIN_DIR)); } // Load the skin.properties file if (!setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin.properties", Boolean.TRUE)) { return; } // Load the skin-user.properties file (ignore the error) setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin-user.properties", Boolean.FALSE); // Load the overlay.properties file (ignore the error) String overlayRoot = getProperty("mjb.overlay.dir", Movie.UNKNOWN); overlayRoot = (PropertiesUtil.getBooleanProperty("mjb.overlay.skinroot", Boolean.TRUE) ? (getProperty(SKIN_DIR, SKIN_DEFAULT) + File.separator) : "") + (StringTools.isValidString(overlayRoot) ? (overlayRoot + File.separator) : ""); setPropertiesStreamName(overlayRoot + "overlay.properties", Boolean.FALSE); // Load the apikeys.properties file if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) { return; } // This is needed to update the static reference for the API Keys in the pattern formatter // because the formatter is initialised before the properties files are read FilteringLayout.addApiKeys(); // Load the rest of the command-line properties for (Map.Entry<String, String> propEntry : cmdLineProps.entrySet()) { setProperty(propEntry.getKey(), propEntry.getValue()); } // Read the information about the skin SkinProperties.readSkinVersion(); // Display the information about the skin SkinProperties.printSkinVersion(); StringBuilder properties = new StringBuilder("{"); for (Map.Entry<Object, Object> propEntry : PropertiesUtil.getEntrySet()) { properties.append(propEntry.getKey()); properties.append("="); properties.append(propEntry.getValue()); properties.append(","); } properties.replace(properties.length() - 1, properties.length(), "}"); // Print out the properties to the log file. LOG.debug("Properties: {}", properties.toString()); // Check for mjb.skipIndexGeneration and set as necessary // This duplicates the "-i" functionality, but allows you to have it in the property file skipIndexGeneration = PropertiesUtil.getBooleanProperty("mjb.skipIndexGeneration", Boolean.FALSE); if (PropertiesUtil.getBooleanProperty("mjb.people", Boolean.FALSE)) { peopleScan = Boolean.TRUE; peopleScrape = PropertiesUtil.getBooleanProperty("mjb.people.scrape", Boolean.TRUE); peopleMax = PropertiesUtil.getIntProperty("mjb.people.maxCount", 10); popularity = PropertiesUtil.getIntProperty("mjb.people.popularity", 5); // Issue 1947: Cast enhancement - option to save all related files to a specific folder peopleFolder = PropertiesUtil.getProperty("mjb.people.folder", ""); if (isNotValidString(peopleFolder)) { peopleFolder = ""; } else if (!peopleFolder.endsWith(File.separator)) { peopleFolder += File.separator; } StringTokenizer st = new StringTokenizer( PropertiesUtil.getProperty("photo.scanner.photoExtensions", "jpg,jpeg,gif,bmp,png"), ",;| "); while (st.hasMoreTokens()) { PHOTO_EXTENSIONS.add(st.nextToken()); } } // Check for mjb.skipHtmlGeneration and set as necessary // This duplicates the "-h" functionality, but allows you to have it in the property file skipHtmlGeneration = PropertiesUtil.getBooleanProperty("mjb.skipHtmlGeneration", Boolean.FALSE); // Look for the parameter in the properties file if it's not been set on the command line // This way we don't overwrite the setting if it's not found and defaults to FALSE showMemory = PropertiesUtil.getBooleanProperty("mjb.showMemory", Boolean.FALSE); // This duplicates the "-c" functionality, but allows you to have it in the property file jukeboxClean = PropertiesUtil.getBooleanProperty("mjb.jukeboxClean", Boolean.FALSE); MovieFilenameScanner.setSkipKeywords( tokenizeToArray(getProperty("filename.scanner.skip.keywords", ""), ",;| "), PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive", Boolean.TRUE)); MovieFilenameScanner.setSkipRegexKeywords( tokenizeToArray(getProperty("filename.scanner.skip.keywords.regex", ""), ","), PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive.regex", Boolean.TRUE)); MovieFilenameScanner.setExtrasKeywords( tokenizeToArray(getProperty("filename.extras.keywords", "trailer,extra,bonus"), ",;| ")); MovieFilenameScanner.setMovieVersionKeywords(tokenizeToArray( getProperty("filename.movie.versions.keywords", "remastered,directors cut,extended cut,final cut"), ",;|")); MovieFilenameScanner.setLanguageDetection( PropertiesUtil.getBooleanProperty("filename.scanner.language.detection", Boolean.TRUE)); final KeywordMap languages = PropertiesUtil.getKeywordMap("filename.scanner.language.keywords", null); if (!languages.isEmpty()) { MovieFilenameScanner.clearLanguages(); for (String lang : languages.getKeywords()) { String values = languages.get(lang); if (values != null) { MovieFilenameScanner.addLanguage(lang, values, values); } else { LOG.info("No values found for language code '{}'", lang); } } } final KeywordMap sourceKeywords = PropertiesUtil.getKeywordMap("filename.scanner.source.keywords", "HDTV,PDTV,DVDRip,DVDSCR,DSRip,CAM,R5,LINE,HD2DVD,DVD,DVD5,DVD9,HRHDTV,MVCD,VCD,TS,VHSRip,BluRay,HDDVD,D-THEATER,SDTV"); MovieFilenameScanner.setSourceKeywords(sourceKeywords.getKeywords(), sourceKeywords); String temp = getProperty("sorting.strip.prefixes"); if (temp != null) { StringTokenizer st = new StringTokenizer(temp, ","); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.startsWith("\"") && token.endsWith("\"")) { token = token.substring(1, token.length() - 1); } Movie.addSortIgnorePrefixes(token.toLowerCase()); } } enableWatchScanner = PropertiesUtil.getBooleanProperty("watched.scanner.enable", Boolean.TRUE); enableWatchTraktTv = PropertiesUtil.getBooleanProperty("watched.trakttv.enable", Boolean.FALSE); enableCompleteMovies = PropertiesUtil.getBooleanProperty("complete.movies.enable", Boolean.TRUE); // Check to see if don't have a root, check the property file if (StringTools.isNotValidString(movieLibraryRoot)) { movieLibraryRoot = getProperty("mjb.libraryRoot"); if (StringTools.isValidString(movieLibraryRoot)) { LOG.info("Got libraryRoot from properties file: {}", movieLibraryRoot); } else { LOG.error("No library root found!"); help(); return; } } if (jukeboxRoot == null) { jukeboxRoot = getProperty("mjb.jukeboxRoot"); if (jukeboxRoot == null) { LOG.info("jukeboxRoot is null in properties file. Please fix this as it may cause errors."); } else { LOG.info("Got jukeboxRoot from properties file: {}", jukeboxRoot); } } File f = new File(movieLibraryRoot); if (f.exists() && f.isDirectory() && jukeboxRoot == null) { jukeboxRoot = movieLibraryRoot; } if (movieLibraryRoot == null) { help(); return; } if (jukeboxRoot == null) { LOG.info("Wrong arguments specified: you must define the jukeboxRoot property (-o) !"); help(); return; } if (!f.exists()) { LOG.error("Directory or library configuration file '{}', not found.", movieLibraryRoot); return; } FileTools.initUnsafeChars(); FileTools.initSubtitleExtensions(); // make canonical names jukeboxRoot = FileTools.getCanonicalPath(jukeboxRoot); movieLibraryRoot = FileTools.getCanonicalPath(movieLibraryRoot); MovieJukebox ml = new MovieJukebox(movieLibraryRoot, jukeboxRoot); if (dumpLibraryStructure) { LOG.warn( "WARNING !!! A dump of your library directory structure will be generated for debug purpose. !!! Library won't be built or updated"); ml.makeDumpStructure(); } else { ml.generateLibrary(); } // Now rename the log files renameLogFile(); if (ScanningLimit.isLimitReached()) { LOG.warn("Scanning limit of {} was reached, please re-run to complete processing.", ScanningLimit.getLimit()); System.exit(EXIT_SCAN_LIMIT); } else { System.exit(EXIT_NORMAL); } }
From source file:Main.java
/** * Return the mapped value of the specified key k. * If no such key k, return the specified value v. * @param <K>//from ww w.ja v a 2s. com * @param <V> * @param map * @param k * @param v the default value if no key exist. * @return */ public static <K, V> V get(Map<K, V> map, K k, V v) { if (map.containsKey(k)) return map.get(k); return v; }
From source file:Main.java
public static <K, V> void putMapList(Map<K, List<V>> map, K key, V val) { if (!map.containsKey(key)) { map.put(key, new ArrayList<V>()); }// w w w . java 2 s. c o m List<V> list = map.get(key); list.add(val); }