List of usage examples for java.util HashMap HashMap
public HashMap()
From source file:pt.souplesse.spark.Server.java
public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("guestbook"); EntityManager manager = factory.createEntityManager(); JinqJPAStreamProvider streams = new JinqJPAStreamProvider(factory); get("/messages", (req, rsp) -> { rsp.type("application/json"); return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList())); });// ww w. jav a 2s . c o m post("/messages", (req, rsp) -> { try { Message msg = gson.fromJson(req.body(), Message.class); if (StringUtils.isBlank(msg.getMessage()) || StringUtils.isBlank(msg.getName())) { halt(400); } manager.getTransaction().begin(); manager.persist(msg); manager.getTransaction().commit(); } catch (JsonSyntaxException e) { halt(400); } rsp.type("application/json"); return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList())); }); get("/comments", (req, rsp) -> { rsp.type("application/json"); Map<String, List<Body>> body = new HashMap<>(); try (CloseableHttpClient client = create().build()) { String url = String.format("https://api.github.com/repos/%s/events", req.queryMap("repo").value()); log.info(url); body = client.execute(new HttpGet(url), r -> { List<Map<String, Object>> list = gson.fromJson(EntityUtils.toString(r.getEntity()), List.class); Map<String, List<Body>> result = new HashMap<>(); list.stream().filter(m -> m.getOrDefault("type", "").equals("IssueCommentEvent")) .map(m -> new Body(((Map<String, String>) m.get("actor")).get("login"), ((Map<String, Map<String, String>>) m.get("payload")).get("comment") .get("body"))) .forEach(b -> result.compute(b.getLogin(), (k, v) -> v == null ? new ArrayList<>() : Lists.asList(b, v.toArray(new Body[v.size()])))); return result; }); } catch (IOException e) { log.error(null, e); halt(400, e.getMessage()); } return gson.toJson(body); }); }
From source file:instamo.AccumuloApp.java
public static void main(String[] args) throws Exception { File tmpDir = new File(FileUtils.getTempDirectory(), "macc-" + UUID.randomUUID().toString()); try {/* w w w .j ava 2 s. c om*/ MiniAccumuloCluster la = new MiniAccumuloCluster(tmpDir, "pass1234", new HashMap<String, String>()); la.start(); System.out.println("\n ---- Running Accumulo App against accumulo-" + la.getAccumuloVersion() + "\n"); run(la.getInstanceName(), la.getZookeepers(), "pass1234", args); System.out.println("\n ---- Ran Accumulo App\n"); la.stop(); } finally { FileUtils.deleteQuietly(tmpDir); } }
From source file:com.sm.replica.DefaultReplicaServer.java
public static void main(String[] args) { String[] opts = new String[] { "-store", "-path", "-port", "-mode", "index" }; String[] defaults = new String[] { "replica", "./data", "7120", "0", "0" }; String[] paras = getOpts(args, opts, defaults); String store = paras[0];//w w w .ja v a 2s .co m int port = Integer.valueOf(paras[2]); String path = paras[1]; int mode = Integer.valueOf(paras[3]); int index = Integer.valueOf(paras[4]); CacheStore cacheStore = new CacheStore(path, null, mode); LogChannel logChannel = new LogChannel(store, 0, path); DefaultReplicaServer defaultReplicaServer = new DefaultReplicaServer(logChannel, index, store, path); HashMap<String, CacheStore> storesMap = new HashMap<String, CacheStore>(); storesMap.put(store, cacheStore); UnisonServerHandler unisonServerHandler = new UnisonServerHandler(defaultReplicaServer); logger.info("start server at " + port); ReplicaServer server = new ReplicaServer(port, storesMap, unisonServerHandler); defaultReplicaServer.hookShutdown(); }
From source file:ch.devmine.javaparser.Main.java
/** * Main function// ww w . ja v a2 s .co m * @param args * the path of the repository to parse */ public static void main(String[] args) { // parse one repository if (args.length != 1) { System.err.println( "usage : javaparser <path>\n" + "path : the path to the folder or the tar archive to parse"); return; } Project project = new Project(); Language language = defineJavaLang(); List<Language> languages = new ArrayList<>(); languages.add(language); project.setLanguages(languages); HashMap<String, Package> packs = new HashMap<>(); if (new File(args[0]).isDirectory()) { parseAsDirectory(project, packs, languages, language, args[0]); } else { parseAsTarArchive(project, packs, languages, language, args[0]); } List<Package> packages = new ArrayList<>(packs.values()); int projLoc = 0; for (Package pack : packages) { int packLoc = 0; for (SourceFile file : pack.getSourceFiles()) { packLoc += file.getLoc(); } pack.setLoc(packLoc); projLoc += packLoc; } project.setPackages(packages); project.setLoc(projLoc); Gson gson = GsonFactory.build(); String jsonProject = gson.toJson(project); // the result is written in the system output in order to be // used in chain with the source analyzer // see https://github.com/devmine/scranlzr System.out.println(jsonProject); }
From source file:br.com.recursive.biblioteca.servicos.EmailService.java
public static void main(String[] args) throws EmailException { // Pessoa p = new Pessoa(); // p.setNome("sdsfsdf"); // /*from www .j av a 2 s . c o m*/ // Contato c = new Contato(); // c.setEmail("oelisiany@gmail.com"); // // p.setContato(c); // p.setUsuario(new Usuario()); // // EmailService es = new EmailService(); // es.sendHtmlEmail(p); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("cpf", "312313123"); map1.put("id", 1); for (String chave : map1.keySet()) { System.out.println(chave); } }
From source file:es.uam.eps.ir.ranksys.examples.RerankerExample.java
public static void main(String[] args) throws Exception { String trainDataPath = args[0]; String featurePath = args[1]; String recIn = args[2];/*from w w w. j a v a 2 s . c o m*/ int cutoff = 100; PreferenceData<Long, Long> trainData = SimplePreferenceData .load(SimpleRatingPreferencesReader.get().read(trainDataPath, lp, lp)); FeatureData<Long, String, Double> featureData = SimpleFeatureData .load(SimpleFeaturesReader.get().read(featurePath, lp, sp)); Map<String, Supplier<Reranker<Long, Long>>> rerankersMap = new HashMap<>(); rerankersMap.put("MMR", () -> { double lambda = 0.5; ItemDistanceModel<Long> dist = new JaccardFeatureItemDistanceModel<>(featureData); return new MMR<>(lambda, cutoff, dist); }); rerankersMap.put("xQuAD", () -> { double lambda = 0.5; IntentModel<Long, Long, String> intentModel = new FeatureIntentModel<>(trainData, featureData); AspectModel<Long, Long, String> aspectModel = new ScoresAspectModel<>(intentModel); return new XQuAD<>(aspectModel, lambda, cutoff, true); }); rerankersMap.put("RxQuAD", () -> { double alpha = 0.5; double lambda = 0.5; IntentModel<Long, Long, String> intentModel = new FeatureIntentModel<>(trainData, featureData); AspectModel<Long, Long, String> aspectModel = new ScoresRelevanceAspectModel<>(intentModel); return new AlphaXQuAD<>(aspectModel, alpha, lambda, cutoff, true); }); rerankersMap.put("PM", () -> { double alpha = 0.5; double lambda = 0.9; BinomialModel<Long, Long, String> binomialModel = new BinomialModel<>(false, Stream.empty(), trainData, featureData, alpha); return new PM<>(featureData, binomialModel, lambda, cutoff); }); RecommendationFormat<Long, Long> format = new SimpleRecommendationFormat<>(lp, lp); rerankersMap.forEach(Unchecked.biConsumer((name, rerankerSupplier) -> { String recOut = Paths.get(Paths.get(recIn).getParent().toString(), String.format("%s-%s", name, FilenameUtils.getName(recIn))).toString(); System.out.printf("running %s, output to %s\n", name, recOut); Reranker<Long, Long> reranker = rerankerSupplier.get(); try (RecommendationFormat.Writer<Long, Long> writer = format.getWriter(recOut)) { format.getReader(recIn).readAll().map(rec -> reranker.rerankRecommendation(rec, cutoff)) .forEach(Unchecked.consumer(writer::write)); } })); }
From source file:cn.dehui.zbj1984105.GetAccountHierarchy.java
public static void main(String[] args) { try {/*from w w w. ja v a 2 s.co m*/ // Log SOAP XML request and response. AdWordsServiceLogger.log(); // Get AdWordsUser from "~/adwords.properties". AdWordsUser user = new AdWordsUser("adwords.properties").generateClientAdWordsUser(null); // Get the ServicedAccountService. ManagedCustomerServiceInterface managedCustomerService = user .getService(AdWordsService.V201209.MANAGED_CUSTOMER_SERVICE); // Create selector. Selector selector = new Selector(); selector.setFields(new String[] { "Login", "CustomerId" }); // Get results. ManagedCustomerPage page = managedCustomerService.get(selector); if (page.getEntries() != null) { // Create map from customerId to customer node. Map<Long, ManagedCustomerTreeNode> customerIdToCustomerNode = new HashMap<Long, ManagedCustomerTreeNode>(); // Create account tree nodes for each customer. for (ManagedCustomer customer : page.getEntries()) { ManagedCustomerTreeNode node = new ManagedCustomerTreeNode(); node.managedCustomer = customer; customerIdToCustomerNode.put(customer.getCustomerId(), node); } // For each link, connect nodes in tree. if (page.getLinks() != null) { for (ManagedCustomerLink link : page.getLinks()) { ManagedCustomerTreeNode managerNode = customerIdToCustomerNode .get(link.getManagerCustomerId()); ManagedCustomerTreeNode childNode = customerIdToCustomerNode .get(link.getClientCustomerId()); childNode.parentNode = managerNode; if (managerNode != null) { managerNode.childAccounts.add(childNode); } } } // Find the root account node in the tree. ManagedCustomerTreeNode rootNode = null; for (ManagedCustomer account : page.getEntries()) { if (customerIdToCustomerNode.get(account.getCustomerId()).parentNode == null) { rootNode = customerIdToCustomerNode.get(account.getCustomerId()); break; } } // Display account tree. System.out.println("Login, CustomerId (Status)"); System.out.println(rootNode.toTreeString(0, new StringBuffer())); } else { System.out.println("No serviced accounts were found."); } } catch (Exception e) { e.printStackTrace(); } }
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 w w . j av 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:com.myjeeva.poi.demo.Excel2JavaDemo.java
/** * @param args/*from w w w . j a va 2s.c o m*/ * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { String SAMPLE_PERSON_DATA_FILE_PATH = "src/main/resources/Sample-Person-Data.xlsx"; // Input File initialize File file = new File(SAMPLE_PERSON_DATA_FILE_PATH); InputStream inputStream = new FileInputStream(file); // Excel Cell Mapping Map<String, String> cellMapping = new HashMap<String, String>(); cellMapping.put("HEADER", "Person Id,Name,Height,Email Address,DOB,Salary"); cellMapping.put("A", "personId"); cellMapping.put("B", "name"); cellMapping.put("C", "height"); cellMapping.put("D", "emailId"); cellMapping.put("E", "dob"); cellMapping.put("F", "salary"); // The package open is instantaneous, as it should be. OPCPackage pkg = null; try { ExcelWorkSheetHandler<PersonVO> workSheetHandler = new ExcelWorkSheetHandler<PersonVO>(PersonVO.class, cellMapping); pkg = OPCPackage.open(inputStream); ExcelReader excelReader = new ExcelReader(pkg, workSheetHandler); excelReader.process(); if (workSheetHandler.getValueList().isEmpty()) { // No data present LOG.error("sHandler.getValueList() is empty"); } else { LOG.info(workSheetHandler.getValueList().size() + " no. of records read from given excel worksheet successfully."); // Displaying data ead from Excel file displayPersonList(workSheetHandler.getValueList()); } } catch (RuntimeException are) { LOG.error(are.getMessage(), are.getCause()); } catch (InvalidFormatException ife) { LOG.error(ife.getMessage(), ife.getCause()); } catch (IOException ioe) { LOG.error(ioe.getMessage(), ioe.getCause()); } finally { IOUtils.closeQuietly(inputStream); try { if (null != pkg) { pkg.close(); } } catch (IOException e) { // just ignore IO exception } } }
From source file:com.sm.store.TestHessianPhp.java
public static void main(String[] args) throws Exception { HessianSerializer hs = new HessianSerializer(); // Map<String, String> map = new HashMap<String, String>(); // map.put("Header", "com.sm.message.Header"); // map.put("StoreParas", "com.sm.store.StoreParas"); // map.put("Value","com.sm.store.Value"); // map.put("array", "java.util.HashMap"); HessianPhp hessianPhp = new HessianPhp(getNameMap()); Map<String, Header> mapH = new HashMap<String, Header>(); mapH.put("key-1", new Header("test-1", 1, (byte) 2, 3)); mapH.put("key-2", new Header("test-2", 2, (byte) 3, 4)); // byte[] m1 = hs.toBytes( mapH); // System.out.println("m1 "+m1.length); // Header hd = new Header("test-1", 2, (byte)1, 3); // byte[] d2 = hs.toBytes( hd); // HessianReader reader = new HessianReader( m1); // reader.readObject(); // System.out.println(new String( reader.getBytes())); List list = new ArrayList(); list.add(new Header("test-1", 1, (byte) 2, 3)); list.add(new Header("test-2", 2, (byte) 3, 4)); byte[] d3 = hs.toBytes(list); HessianReader reader = new HessianReader(d3); reader.readObject();/*from w w w .j av a2s . co m*/ System.out.println(new String(reader.getBytes())); // byte[] data = hessianPhp.php2Hessian( header.getBytes()); // Header header = new Header("test-1",10, (byte) 3,1 ); // byte[] d1 = hs.toBytes( header); //logger.info("len "+data.length+" "+d1.length); //Object obj = hs.toObject(data); //logger.info(obj.getClass().getName()+" obj "+obj.toString()); // byte[] s1 = hessianPhp.php2Hessian( storePara.getBytes()); // Object obj = hs.toObject( s1); // logger.info(obj.toString()); }