List of usage examples for java.util Map put
V put(K key, V value);
From source file:com.pureinfo.srm.reports.table.data.weight.WeightStatistic.java
public static void main(String[] args) { try {//from w w w. j ava 2s . c om WeightStatistic s = new WeightStatistic(); Map m = new HashMap(); String[] year = { "2007" }; m.put("year", year); s.setParameters(m); // s.doOutlayQuery(); Object[][] o = s.buildDatas(false, false); for (int i = 0; i < o.length; i++) { for (int j = 0; j < o[i].length; j++) { System.out.print("\t" + "\t" + "\t" + o[i][j]); } System.out.println(); } } catch (Exception ex) { // TODO Auto-generated catch block ex.printStackTrace(System.err); } finally { } }
From source file:org.mitre.mpf.wfm.rest_client.RegisterComponent.java
public static void main(String[] args) { String filePath = "/home/mpf/mpf/trunk/java-hello-world/src/main/resources/HelloWorldComponent.json"; //"/home/mpf/mpf/trunk/extraction/hello/cpp/src/helloComponent.json"; String url = "http://localhost:8080/workflow-manager/rest/component/registerViaFile"; final String credentials = "Basic bXBmOm1wZjEyMw=="; Map<String, String> params = new HashMap<String, String>(); System.out.println("Starting rest-client!"); //not necessary for localhost //System.setProperty("http.proxyHost","gatekeeper.mitre.org"); //System.setProperty("http.proxyPort","80"); RequestInterceptor authorize = new RequestInterceptor() { @Override/*from ww w . ja va 2 s.c o m*/ public void intercept(HttpRequestBase request) { request.addHeader("Authorization", credentials); } }; RestClient client = RestClient.builder().requestInterceptor(authorize).build(); if (args.length > 0) { filePath = args[0]; System.out.println("args[0] = " + args[0]); } params.put("filePath", filePath); Map<String, String> stringVal = null; try { stringVal = client.get(url, params, Map.class); } catch (RestClientException e) { log.error("RestClientException occurred"); e.printStackTrace(); } catch (IOException e) { log.error("IOException occurred"); e.printStackTrace(); } System.out.println(stringVal.get("message")); }
From source file:PodbaseMetadataMigration2.java
public static void main(String[] args) throws Exception { System.out.println("Running data migration"); String projectString = FileUtils.readFileToString(new File("projects.txt")); Map<String, Integer> projectIdMapping = new HashMap<String, Integer>(); for (String line : projectString.split("\n")) { String[] split = line.split(":"); int id = Integer.parseInt(split[0].trim()); String name = split[1].trim(); projectIdMapping.put(name, id); }/* w ww .j a v a 2 s.c o m*/ System.out.println("Reading projects.."); List<ProjectEntry> projects = dataFromFile("./migrate/projects.data", ProjectEntry.class); projectIdMap = parseProjectMap(projects, projectIdMapping); System.out.println("Found " + projects.size() + " projects."); System.out.println("Reading tags.."); List<TagEntry> tags = dataFromFile("./migrate/tags.data", TagEntry.class); System.out.println("Found " + tags.size() + " tags."); System.out.println("Reading templates.."); List<TemplateEntry> templates = dataFromFile("./migrate/templates.data", TemplateEntry.class); System.out.println("Found " + templates.size() + " templates."); System.out.println("Reading template fields.."); List<TemplateFieldEntry> templateFields = dataFromFile("./migrate/template_fields.data", TemplateFieldEntry.class); System.out.println("Found " + templateFields.size() + " templateFields."); int entryCount = tags.size() + templates.size() + templateFields.size(); //System.out.println("Generating Project SQL"); //String projectSql = generateSql((List<AbstractEntry>)(List<?>)projects); System.out.println("Generating Attribute SQL"); String imageAttributes = generateSql((List<AbstractEntry>) (List<?>) tags); System.out.println("Generating Image SQL"); String databaseImages = generateDatabaseImageSql(); //System.out.println("Generating Directory SQL"); //String directorySql = generateDirectorySql(projects); //System.out.println("Generating Template SQL"); //String templateSql = generateSql((List<AbstractEntry>)(List<?>)templates); //System.out.println("Generating Field SQL"); //String fieldsSql = generateSql((List<AbstractEntry>)(List<?>)templateFields); System.out.println("Writing database.sql"); BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./database.sql"))); //bw.append(projectSql); //bw.append("\n\n"); bw.append(databaseImages); bw.append("\n\n"); //bw.append(directorySql); //bw.append("\n\n"); bw.append(imageAttributes); bw.append("\n\n"); // bw.append(templateSql); // bw.append("\n\n"); // bw.append(fieldsSql); // bw.append("\n\n"); bw.close(); System.out.println("Writing missingImages.txt"); bw = new BufferedWriter(new FileWriter(new File("./missingImages.txt"))); for (String img : missingImages) { bw.append(img + "\n"); } bw.close(); System.out.println("Migration completed successfully!"); }
From source file:WordCount.java
public static void main(String args[]) throws Exception { String filename = "WordCount.java"; // Map File from filename to byte buffer FileInputStream input = new FileInputStream(filename); FileChannel channel = input.getChannel(); int fileLength = (int) channel.size(); MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, fileLength); // Convert to character buffer Charset charset = Charset.forName("ISO-8859-1"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(buffer); // Create line pattern Pattern linePattern = Pattern.compile(".*$", Pattern.MULTILINE); // Create word pattern Pattern wordBreakPattern = Pattern.compile("[\\p{Punct}\\s}]"); // Match line pattern to buffer Matcher lineMatcher = linePattern.matcher(charBuffer); Map map = new TreeMap(); Integer ONE = new Integer(1); // For each line while (lineMatcher.find()) { // Get line CharSequence line = lineMatcher.group(); // Get array of words on line String words[] = wordBreakPattern.split(line); // For each word for (int i = 0, n = words.length; i < n; i++) { if (words[i].length() > 0) { Integer frequency = (Integer) map.get(words[i]); if (frequency == null) { frequency = ONE;/*from www . ja v a 2 s. com*/ } else { int value = frequency.intValue(); frequency = new Integer(value + 1); } map.put(words[i], frequency); } } } System.out.println(map); }
From source file:com.px100systems.data.utility.RestoreUtility.java
public static void main(String[] args) { if (args.length < 3) { System.err.println("Usage: java -cp ... com.px100systems.data.utility.RestoreUtility " + "<springXmlConfigFile> <persisterBeanName> <backupDirectory> [compare]"); return;//from w ww . j a va2s .com } FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("file:" + args[0]); try { PersistenceProvider persister = ctx.getBean(args[1], PersistenceProvider.class); File directory = new File(args[2]); if (!directory.isDirectory()) { System.err.println(directory.getName() + " is not a directory"); return; } List<File> files = new ArrayList<File>(); //noinspection ConstantConditions for (File file : directory.listFiles()) if (BackupFile.isBackup(file)) files.add(file); if (files.isEmpty()) { System.err.println(directory.getName() + " directory has no backup files"); return; } if (args.length == 4 && args[3].equalsIgnoreCase("compare")) { final Map<String, Map<Long, RawRecord>> units = new HashMap<String, Map<Long, RawRecord>>(); for (String storage : persister.storage()) { System.out.println("Storage " + storage); persister.loadByStorage(storage, new PersistenceProvider.LoadCallback() { @Override public void process(RawRecord record) { Map<Long, RawRecord> unitList = units.get(record.getUnitName()); if (unitList == null) { unitList = new HashMap<Long, RawRecord>(); units.put(record.getUnitName(), unitList); } unitList.put(record.getId(), record); } }); for (final Map.Entry<String, Map<Long, RawRecord>> unit : units.entrySet()) { BackupFile file = null; for (int i = 0, n = files.size(); i < n; i++) if (BackupFile.isBackup(files.get(i), unit.getKey())) { file = new BackupFile(files.get(i)); files.remove(i); break; } if (file == null) throw new RuntimeException("Could not find backup file for unit " + unit.getKey()); final Long[] count = new Long[] { 0L }; file.read(new PersistenceProvider.LoadCallback() { @Override public void process(RawRecord record) { RawRecord r = unit.getValue().get(record.getId()); if (r == null) throw new RuntimeException("Could not find persisted record " + record.getId() + " for unit " + unit.getKey()); if (!r.equals(record)) throw new RuntimeException( "Record " + record.getId() + " mismatch for unit " + unit.getKey()); count[0] = count[0] + 1; } }); if (count[0] != unit.getValue().size()) throw new RuntimeException("Extra persisted records for unit " + unit.getKey()); System.out.println(" Unit " + unit.getKey() + ": OK"); } units.clear(); } if (!files.isEmpty()) { System.err.println("Extra backups: "); for (File file : files) System.err.println(" " + file.getName()); } } else { persister.init(); for (File file : files) { InMemoryDatabase.readBackupFile(file, persister); System.out.println("Loaded " + file.getName()); } } } catch (Exception e) { throw new RuntimeException(e); } finally { ctx.close(); } }
From source file:org.openspaces.rest.space.ReplicationRESTController.java
public static void main(String[] args) throws Exception { ReplicationRESTController ctl = new ReplicationRESTController(); HashMap body = new HashMap(); Map site1 = new HashMap(); site1.put("rest-api", "ec2-54-221-106-51.compute-1.amazonaws.com:8100"); site1.put("site-id", "EC2"); Map site2 = new HashMap(); site2.put("rest-api", "15.185.186.251:8100"); site2.put("site-id", "HPCS"); List sites = new ArrayList(); sites.add(site1);/*w ww . j a v a 2 s. c o m*/ sites.add(site2); body.put("cloudify-instances", sites); HashMap tspec = new HashMap(); tspec.put("name", "my-topo"); List edges = new ArrayList(); HashMap edge1 = new HashMap(); edge1.put("fromSite", "EC2"); edge1.put("fromSpace", "test"); edge1.put("toSite", "HPCS"); edge1.put("toSpace", "test"); edges.add(edge1); tspec.put("edges", edges); HashMap ports = new HashMap(); HashMap port1 = new HashMap(); port1.put("discovery", DEFAULT_DISCOVERY_PORT); port1.put("data", DEFAULT_DATA_PORT); ports.put("EC2", port1); HashMap port2 = new HashMap(); port2.put("discovery", DEFAULT_DISCOVERY_PORT); port2.put("data", DEFAULT_DATA_PORT); ports.put("HPCS", port2); tspec.put("ports", ports); body.put("topology-spec", tspec); body.put("initial-memory-size", "256m"); body.put("max-memory-size", "512m"); body.put("highly-available", "false"); body.put("max-vm-size", "512"); body.put("batch-size", "1024"); body.put("send-interval", "1000"); ctl.deployTopology("my-topo", body); //deploy service test /* RestClient rc=new RestClient(new URL("http://localhost:8100"),"","",CLOUDIFY_VERSION); rc.connect(); InstallServiceRequest r=new InstallServiceRequest(); File packed=Packager.pack(new File("c:\\gigaspaces\\src\\github\\cloudify-recipes\\services\\tomcat")); final UploadResponse uploadResponse = rc.upload(null, packed); final String uploadKey = uploadResponse.getUploadKey(); r.setServiceFolderUploadKey(uploadKey); r.setAuthGroups(""); r.setServiceFileName("tomcat-service.groovy"); InstallServiceResponse installServiceRespone = rc.installService("test","yomama", r); System.out.println(uploadKey); //r.set //rc.installService("default","test",); */ /* HttpClient client=HttpClientBuilder.create().build(); HttpGet get=new HttpGet("http://ec2-54-197-25-132.compute-1.amazonaws.com:8100/"); HttpResponse response=client.execute(get); InputStream is=response.getEntity().getContent(); BufferedReader rdr=new BufferedReader(new InputStreamReader(is)); String line=""; while((line=rdr.readLine())!=null){ System.out.println(line); } */ /*ObjectMapper om=new ObjectMapper(); JsonNode node=om.readTree(is); System.out.println(node.get("response").get(1));*/ /* ObjectMapper om=new ObjectMapper(); JsonNode node=om.readTree("{\"response\":[\"app1\",\"app2\"]}"); for(Iterator<JsonNode> it=node.get("response").getElements();it.hasNext();){ System.out.println(it.next().getValueAsText()); } */ }
From source file:at.ac.tuwien.inso.subcat.postprocessor.PostProcessor.java
public static void main(String[] args) { Map<String, PostProcessorTask> steps = new HashMap<String, PostProcessorTask>(); PostProcessorTask _step = new ClassificationTask(); steps.put(_step.getName(), _step); CommentAnalyserTask commentAnalysisStep = new CommentAnalyserTask(); steps.put(commentAnalysisStep.getName(), commentAnalysisStep); AccountInterlinkingTask interlinkingTask = new AccountInterlinkingTask(); steps.put(interlinkingTask.getName(), interlinkingTask); _step = new CommitBugInterlinkingTask(); steps.put(_step.getName(), _step);/*from w ww.ja va 2 s . c o m*/ Options options = new Options(); options.addOption("h", "help", false, "Show this options"); options.addOption("d", "db", true, "The database to process (required)"); options.addOption("v", "verbose", false, "Show details"); options.addOption("p", "project", true, "The project ID to process"); options.addOption("P", "list-projects", false, "List all registered projects"); options.addOption("S", "list-processor-steps", false, "List all registered processor steps"); options.addOption("s", "processor-step", true, "A processor step name"); options.addOption("c", "commit-dictionary", true, "Path to a classification dictionary for commit message classification"); options.addOption("b", "bug-dictionary", true, "Path to a classification dictionary for bug classification"); options.addOption("m", "smart-matching", true, "Smart user matching configuration. Syntax: <method>:<distance>"); options.addOption("M", "list-matching-methods", false, "List smart matching methods"); final Reporter reporter = new Reporter(true); reporter.startTimer(); Settings settings = new Settings(); ModelPool pool = null; boolean printTraces = false; CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); printTraces = cmd.hasOption("verbose"); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("postprocessor", options); return; } if (cmd.hasOption("list-processor-steps")) { for (String proj : steps.keySet()) { System.out.println(" " + proj); } return; } if (cmd.hasOption("list-matching-methods")) { for (String method : HashFunc.getHashFuncNames()) { System.out.println(" " + method); } return; } if (cmd.hasOption("db") == false) { reporter.error("post-processor", "Option --db is required"); reporter.printSummary(); return; } File dbf = new File(cmd.getOptionValue("db")); if (dbf.exists() == false || dbf.isFile() == false) { reporter.error("post-processor", "Invalid database file path"); reporter.printSummary(); return; } pool = new ModelPool(cmd.getOptionValue("db"), 2); if (cmd.hasOption("list-projects")) { Model model = pool.getModel(); for (Project proj : model.getProjects()) { System.out.println(" " + proj.getId() + ": " + proj.getDate()); } model.close(); return; } Integer projId = null; if (cmd.hasOption("project") == false) { reporter.error("post-processor", "Option --project is required"); reporter.printSummary(); return; } else { try { projId = Integer.parseInt(cmd.getOptionValue("project")); } catch (NumberFormatException e) { reporter.error("post-processor", "Invalid project ID"); reporter.printSummary(); return; } } Model model = pool.getModel(); Project project = model.getProject(projId); model.close(); if (project == null) { reporter.error("post-processor", "Invalid project ID"); reporter.printSummary(); return; } if (cmd.hasOption("bug-dictionary")) { DictionaryParser dp = new DictionaryParser(); for (String path : cmd.getOptionValues("bug-dictionary")) { try { Dictionary dict = dp.parseFile(path); settings.bugDictionaries.add(dict); } catch (FileNotFoundException e) { reporter.error("post-processor", "File not found: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } catch (XmlReaderException e) { reporter.error("post-processor", "XML Error: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } } } if (cmd.hasOption("commit-dictionary")) { DictionaryParser dp = new DictionaryParser(); for (String path : cmd.getOptionValues("commit-dictionary")) { try { Dictionary dict = dp.parseFile(path); settings.srcDictionaries.add(dict); } catch (FileNotFoundException e) { reporter.error("post-processor", "File not found: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } catch (XmlReaderException e) { reporter.error("post-processor", "XML Error: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } } } if (cmd.hasOption("smart-matching")) { String str = cmd.getOptionValue("smart-matching"); String[] parts = str.split(":"); if (parts.length != 2) { reporter.error("post-processor", "Unexpected smart-matching format"); reporter.printSummary(); return; } HashFunc func = HashFunc.getHashFunc(parts[0]); if (func == null) { reporter.error("post-processor", "Unknown smart matching hash function"); reporter.printSummary(); return; } int dist = -1; try { dist = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { dist = -1; } if (dist < 0) { reporter.error("post-processor", "Invalid smart matching edist distance"); reporter.printSummary(); return; } interlinkingTask.setDistance(dist); interlinkingTask.setHashFunc(func); } PostProcessor processor = new PostProcessor(project, pool, settings); if (cmd.hasOption("processor-step")) { for (String stepName : cmd.getOptionValues("processor-step")) { PostProcessorTask step = steps.get(stepName); if (step == null) { reporter.error("post-processor", "Unknown processor step: '" + stepName + "'"); reporter.printSummary(); return; } processor.register(step); } } else { processor.register(steps.values()); } if (printTraces == true) { model = pool.getModel(); final Stats stats = model.getStats(project); model.close(); processor.addListener(new PostProcessorListener() { private int commitCount = 0; private int bugCount = 0; @Override public void commit(PostProcessor proc) { commitCount++; reporter.note("post-processor", "status: Commit " + commitCount + "/" + stats.commitCount); } @Override public void bug(PostProcessor proc) { bugCount++; reporter.note("post-processor", "status: Bug " + bugCount + "/" + stats.bugCount); } }); } processor.process(); } catch (ParseException e) { reporter.error("post-processor", "Parsing failed: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } catch (ClassNotFoundException e) { reporter.error("post-processor", "Failed to create a database connection: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } catch (SQLException e) { reporter.error("post-processor", "Failed to create a database connection: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } catch (PostProcessorException e) { reporter.error("post-processor", "Post-Processor Error: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } finally { if (pool != null) { pool.close(); } } reporter.printSummary(true); }
From source file:com.buddycloud.channeldirectory.cli.Main.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { JsonElement rootElement = new JsonParser().parse(new FileReader(QUERIES_FILE)); JsonArray rootArray = rootElement.getAsJsonArray(); Map<String, Query> queries = new HashMap<String, Query>(); for (int i = 0; i < rootArray.size(); i++) { JsonObject queryElement = rootArray.get(i).getAsJsonObject(); String queryName = queryElement.get("name").getAsString(); String type = queryElement.get("type").getAsString(); Query query = null;//from w w w . jav a 2 s .c om if (type.equals("solr")) { query = new QueryToSolr(queryElement.get("agg").getAsString(), queryElement.get("core").getAsString(), queryElement.get("q").getAsString()); } else if (type.equals("dbms")) { query = new QueryToDBMS(queryElement.get("q").getAsString()); } queries.put(queryName, query); } LinkedList<String> queriesNames = new LinkedList<String>(queries.keySet()); Collections.sort(queriesNames); Options options = new Options(); options.addOption(OptionBuilder.isRequired(true).withLongOpt("query").hasArg(true) .withDescription("The name of the query. Possible queries are: " + queriesNames).create('q')); options.addOption(OptionBuilder.isRequired(false).withLongOpt("args").hasArg(true) .withDescription("Arguments for the query").create('a')); options.addOption(new Option("?", "help", false, "Print this message")); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { printHelpAndExit(options); } if (cmd.hasOption("help")) { printHelpAndExit(options); } String queryName = cmd.getOptionValue("q"); String argsCmd = cmd.getOptionValue("a"); Properties configuration = ConfigurationUtils.loadConfiguration(); Query query = queries.get(queryName); if (query == null) { printHelpAndExit(options); } System.out.println(query.exec(argsCmd, configuration)); }
From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java
public static void main(String[] args) throws Exception { FogBugzClient client = new FogBugzClient("https://subhash.fogbugz.com", "cs19739@yahoo.com", "cs19739", null);//from w ww . java2 s. c o m Map<String, String> map = new HashMap<String, String>(); map.put("dtDue", "12/8/07 8:00 PM"); client.editCase("6", map, null); }
From source file:com.cjwagner.InfoSecPriv.ExtensionServer.java
public static void main(String[] args) { initializeLogStore();/*www. j a va2 s . c om*/ get("/data", (request, response) -> { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.MINUTE, -5); Date tMinusDelta = cal.getTime(); Map<String, LoggerMessage> filtered = new HashMap<String, LoggerMessage>(); for (Map.Entry<String, LoggerMessage> entry : logStore.entrySet()) { String ip = entry.getKey(); LoggerMessage logmess = entry.getValue(); LoggerMessage logmessFiltered = new LoggerMessage(); logmessFiltered.setFirstLogTime(logmess.getFirstLogTime()); List<LogData> filteredData = new ArrayList<LogData>(); logmessFiltered.setLogs(filteredData); for (LogData data : logmess.getLogs()) { if (data.getDate().after(tMinusDelta)) { filteredData.add(data); } } filtered.put(ip, logmessFiltered); } ObjectMapper objMapper = new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true); String jsonResponse = objMapper.writeValueAsString(filtered); System.out.println("Responded to query for recent data from IP: " + request.ip()); return jsonResponse; }); post("/LicenseRegistry", (request, response) -> { if (storeSize >= MAXSTORESIZE) { response.status(507);//insufficient storage return "Server storage full!"; } String ip = request.ip().replace(':', '_'); String json = request.body(); try { LoggerMessage logMess = LoggerMessage.fromJSON(json); logMess.setFirstLogTime(new Date()); LoggerMessage rec = logStore.get(ip); if (rec == null) { logStore.put(ip, logMess); rec = logMess; } else { rec.getLogs().addAll(logMess.getLogs()); } updateLogFile(ip, rec); storeSize += logMess.getLogs().size(); response.status(200); System.out.println("Recieved log data from IP: " + ip); return "LicenseKey:<c706cfe7-b748-4d75-98b5-c6b32ab789cb>"; } catch (JsonParseException jpe) { response.status(HTTP_BAD_REQUEST); System.out.println("Failed to parse log data from IP: " + ip); return jpe.getMessage(); } }); }