List of usage examples for java.util Map put
V put(K key, V value);
From source file:com.linecorp.platform.channel.sample.Main.java
public static void main(String[] args) { BusinessConnect bc = new BusinessConnect(); /**//w ww. ja v a 2 s .c om * Prepare the required channel secret and access token */ String channelSecret = System.getenv("CHANNEL_SECRET"); String channelAccessToken = System.getenv("CHANNEL_ACCESS_TOKEN"); if (channelSecret == null || channelSecret.isEmpty() || channelAccessToken == null || channelAccessToken.isEmpty()) { System.err.println("Error! Environment variable CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN not defined."); return; } port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); /** * Define the callback url path */ post("/events", (request, response) -> { String requestBody = request.body(); /** * Verify whether the channel signature is valid or not */ String channelSignature = request.headers("X-LINE-CHANNELSIGNATURE"); if (channelSignature == null || channelSignature.isEmpty()) { response.status(400); return "Please provide valid channel signature and try again."; } if (!bc.validateBCRequest(requestBody, channelSecret, channelSignature)) { response.status(401); return "Invalid channel signature."; } /** * Parse the http request body */ ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance())); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); EventList events; try { events = objectMapper.readValue(requestBody, EventList.class); } catch (IOException e) { response.status(400); return "Invalid request body."; } ApiHttpClient apiHttpClient = new ApiHttpClient(channelAccessToken); /** * Process the incoming messages/operations one by one */ List<String> toUsers; for (Event event : events.getResult()) { switch (event.getEventType()) { case Constants.EventType.MESSAGE: toUsers = new ArrayList<>(); toUsers.add(event.getContent().getFrom()); // @TODO: We strongly suggest you should modify this to process the incoming message/operation async bc.sendTextMessage(toUsers, "You said: " + event.getContent().getText(), apiHttpClient); break; case Constants.EventType.OPERATION: if (event.getContent().getOpType() == Constants.OperationType.ADDED_AS_FRIEND) { String newFriend = event.getContent().getParams().get(0); Profile profile = bc.getProfile(newFriend, apiHttpClient); String displayName = profile == null ? "Unknown" : profile.getDisplayName(); toUsers = new ArrayList<>(); toUsers.add(newFriend); bc.sendTextMessage(toUsers, displayName + ", welcome to be my friend!", apiHttpClient); Connection connection = null; connection = DatabaseUrl.extract().getConnection(); toUsers = bc.getFriends(newFriend, connection); if (toUsers.size() > 0) { bc.sendTextMessage(toUsers, displayName + " just join us, let's welcome him/her!", apiHttpClient); } bc.addFriend(newFriend, displayName, connection); if (connection != null) { connection.close(); } } break; default: // Unknown type? } } return "Events received successfully."; }); get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Hello World!"); return new ModelAndView(attributes, "index.ftl"); }, new FreeMarkerEngine()); }
From source file:Naive.java
public static void main(String[] args) throws Exception { // Basic access authentication setup String key = "CHANGEME: YOUR_API_KEY"; String secret = "CHANGEME: YOUR_API_SECRET"; String version = "preview1"; // CHANGEME: the API version to use String practiceid = "000000"; // CHANGEME: the practice ID to use // Find the authentication path Map<String, String> auth_prefix = new HashMap<String, String>(); auth_prefix.put("v1", "oauth"); auth_prefix.put("preview1", "oauthpreview"); auth_prefix.put("openpreview1", "oauthopenpreview"); URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token"); HttpURLConnection conn = (HttpURLConnection) authurl.openConnection(); conn.setRequestMethod("POST"); // Set the Authorization request header String auth = Base64.encodeBase64String((key + ':' + secret).getBytes()); conn.setRequestProperty("Authorization", "Basic " + auth); // Since this is a POST, the parameters go in the body conn.setDoOutput(true);// w ww. j a va 2 s.c o m String contents = "grant_type=client_credentials"; DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(contents); wr.flush(); wr.close(); // Read the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); // Decode from JSON and save the token for later String response = sb.toString(); JSONObject authorization = new JSONObject(response); String token = authorization.get("access_token").toString(); // GET /departments HashMap<String, String> params = new HashMap<String, String>(); params.put("limit", "1"); // Set up the URL, method, and Authorization header URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?" + urlencode(params)); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Bearer " + token); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); JSONObject departments = new JSONObject(response); System.out.println(departments.toString()); // POST /appointments/{appointmentid}/notes params = new HashMap<String, String>(); params.put("notetext", "Hello from Java!"); url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + token); // POST parameters go in the body conn.setDoOutput(true); contents = urlencode(params); wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(contents); wr.flush(); wr.close(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); JSONObject note = new JSONObject(response); System.out.println(note.toString()); }
From source file:com.singularity.ee.agent.systemagent.monitors.KeynoteMonitor.java
public static void main(String[] argv) throws Exception { Map<String, String> executeParams = new HashMap<String, String>(); executeParams.put("api_key", "c05f56b6-2ca8-3765-afc6-92745cb9709b"); executeParams.put("exclude_slots", ""); new KeynoteMonitor().execute(executeParams, null); }
From source file:Main.java
public static void main(String[] args) throws Exception { String bubba = "this is a test this is a test"; Map<Integer, Integer> occurrences = new HashMap<Integer, Integer>(); for (String currentWord : bubba.split(" ")) { Integer current = occurrences.get(currentWord.length()); if (current == null) { current = 0;/*from w ww .jav a 2 s. com*/ } occurrences.put(currentWord.length(), current + 1); } for (Integer currentKey : occurrences.keySet()) { System.out.println("There are " + occurrences.get(currentKey) + " " + currentKey + " letter words"); } }
From source file:io.rodeo.chute.ChuteMain.java
public static void main(String[] args) throws SQLException, JsonParseException, JsonMappingException, IOException { InputStream is = new FileInputStream(new File(CONFIG_FILENAME)); ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); ChuteConfiguration config = mapper.readValue(is, ChuteConfiguration.class); Map<String, Importer> importManagers = new HashMap<String, Importer>(config.importerConfigurations.size()); for (Entry<String, ImporterConfiguration> importerConfig : config.importerConfigurations.entrySet()) { importManagers.put(importerConfig.getKey(), importerConfig.getValue().createImporter()); }//from w ww . j a va 2 s . c o m Map<String, Exporter> exportManagers = new HashMap<String, Exporter>(config.exporterConfigurations.size()); for (Entry<String, ExporterConfiguration> exporterConfig : config.exporterConfigurations.entrySet()) { exportManagers.put(exporterConfig.getKey(), exporterConfig.getValue().createExporter()); } for (Entry<String, ConnectionConfiguration> connectionConfig : config.connectionConfigurations.entrySet()) { importManagers.get(connectionConfig.getValue().in) .addProcessor(exportManagers.get(connectionConfig.getValue().out)); } for (Entry<String, Exporter> exportManager : exportManagers.entrySet()) { exportManager.getValue().start(); } for (Entry<String, Importer> importManager : importManagers.entrySet()) { importManager.getValue().start(); } }
From source file:com.blackboard.WebdavBulkDeleterClient.java
public static void main(String[] args) { if (System.getProperty("log4j.configuration") != null) { PropertyConfigurator.configure(System.getProperty("log4j.configuration")); } else {/* w w w .ja va2 s .c o m*/ BasicConfigurator.configure(); } // Perform command line parsing in an as friendly was as possible. // Could be improved CommandLineParser parser = new PosixParser(); Options options = new Options(); // Use a map to store our options and loop over it to check and parse options via // addAllOptions() and verifyOptions() below Map<String, String> optionsAvailable = new HashMap<String, String>(); optionsAvailable.put("deletion-list", "The file containing the list of courses to delete"); optionsAvailable.put("user", "User with deletion privileges, usually bbsupport"); optionsAvailable.put("password", "Password - ensure you escape any shell characters"); optionsAvailable.put("url", "The Learn URL - usually https://example.com/bbcswebdav/courses"); options = addAllOptions(options, optionsAvailable); options.addOption(OptionBuilder.withLongOpt("no-verify-ssl").withDescription("Don't verify SSL") .hasArg(false).create()); CommandLine line = null; try { line = parser.parse(options, args); verifyOptions(line, optionsAvailable); } catch (ParseException e) { // Detailed reason will be printed by verifyOptions above logger.fatal("Incorrect options specified, exiting..."); System.exit(1); } Scanner scanner = null; try { scanner = new Scanner(new File(line.getOptionValue("deletion-list"))); } catch (FileNotFoundException e) { logger.fatal("Cannot open file : " + e.getLocalizedMessage()); System.exit(1); } // By default we verify SSL certs boolean verifyCertStatus = true; if (line.hasOption("no-verify-ssl")) { verifyCertStatus = false; } // Loop through deletion list and delete courses if they exist. LearnServer instance; try { logger.debug("Attempting to open connection"); instance = new LearnServer(line.getOptionValue("user"), line.getOptionValue("password"), line.getOptionValue("url"), verifyCertStatus); String currentCourse = null; logger.debug("Connection open"); while (scanner.hasNextLine()) { currentCourse = scanner.nextLine(); if (instance.exists(currentCourse)) { try { instance.deleteCourse(currentCourse); logger.info("Processing " + currentCourse + " : Result - Deletion Successful"); } catch (IOException ioe) { logger.error("Processing " + currentCourse + " : Result - Could not Delete (" + ioe.getLocalizedMessage() + ")"); } } else { logger.info("Processing " + currentCourse + " : Result - Course does not exist"); } } } catch (IllegalArgumentException e) { logger.fatal(e.getLocalizedMessage()); System.exit(1); } catch (IOException ioe) { logger.debug(ioe); logger.fatal(ioe.getMessage()); } }
From source file:com.mycompany.javaapplicaton3.ExcelWorkSheetHandlerTest.java
/** * @param args//w ww.j a v a 2s . co m * @throws Exception */ public static void main(String[] args) throws Exception { String SAMPLE_PERSON_DATA_FILE_PATH = "C:/Users/lprates/Documents/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); ExcelSheetCallback sheetCallback = new ExcelSheetCallback() { private int sheetNumber = 0; public void startSheet(int sheetNum, String sheetName) { this.sheetNumber = sheetNum; System.out.println("Started processing sheet number=" + sheetNumber + " and Sheet Name is '" + sheetName + "'"); } @Override public void endSheet() { System.out.println("Processing completed for sheet number=" + sheetNumber); } public void startSheet(int sheetNum) { System.out.println("Started processing sheet number=" + sheetNum); } }; System.out.println("Constructor: pkg, workSheetHandler, sheetCallback"); ExcelReader example1 = new ExcelReader(pkg, workSheetHandler, sheetCallback); example1.process("Lot 1 Data"); 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()); } /* System.out.println("\nConstructor: filePath, workSheetHandler, sheetCallback"); ExcelReader example2 = new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, workSheetHandler, sheetCallback); example2.process(); System.out.println("\nConstructor: file, workSheetHandler, sheetCallback"); ExcelReader example3 = new ExcelReader(file, workSheetHandler, null); example3.process(); */ } 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:Counter.java
public static void main(String[] args) { Map hm = new HashMap(); for (int i = 0; i < 10000; i++) { // Produce a number between 0 and 20: Integer r = new Integer(rand.nextInt(20)); if (hm.containsKey(r)) ((Counter) hm.get(r)).i++;/*from w w w . j a v a2 s .c o m*/ else hm.put(r, new Counter()); } System.out.println(hm); }
From source file:com.sxjun.core.generate.Generate.java
public static void main(String[] args) throws Exception { // ========== ?? ==================== // ??????// w w w. j a v a 2 s . c o m // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className} // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4? String packageName = "com.sxjun"; String moduleName = "retrieval"; // ???sys String subModuleName = ""; // ????? String className = "IndexManager"; // ??user String classAuthor = "sxjun"; // ThinkGem String functionName = "?"; // ?? // ??? Boolean isEnable = true; // ========== ?? ==================== if (!isEnable) { logger.error("????isEnable = true"); return; } if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className) || StringUtils.isBlank(functionName)) { logger.error("??????????????"); return; } // ? String separator = File.separator; String classPath = new DefaultResourceLoader().getResource("").getFile().getPath(); String templatePath = classPath.replace( separator + "WebRoot" + separator + "WEB-INF" + separator + "classes", separator + "src" + separator + "com" + separator + "sxjun" + separator + "retrieval"); String javaPath = classPath.replace(separator + "WebRoot" + separator + "WEB-INF" + separator + "classes", separator + "src" + separator + (StringUtils.lowerCase(packageName)).replace(".", separator)); String viewPath = classPath.replace(separator + "classes", separator + "retrieval"); // ??? Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File(templatePath.substring(0, templatePath.lastIndexOf(separator)) + separator + "generate" + separator + "template")); // ??? Map<String, String> model = Maps.newHashMap(); model.put("packageName", StringUtils.lowerCase(packageName)); model.put("moduleName", StringUtils.lowerCase(moduleName)); model.put("subModuleName", StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : ""); model.put("className", StringUtils.uncapitalize(className)); model.put("ClassName", StringUtils.capitalize(className)); model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools"); model.put("classVersion", DateUtils.getDate()); model.put("functionName", functionName); model.put("urlPrefix", (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) + "/" : "") + model.get("className")); model.put("viewPrefix", StringUtils.substringAfterLast(model.get("packageName"), ".") + "/" + model.get("urlPrefix")); // ? Entity Template template = cfg.getTemplate("pojo.ftl"); String content = FreeMarkers.renderTemplate(template, model); String filePath = javaPath + separator + model.get("moduleName") + separator + "pojo" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java"; writeFile(content, filePath); logger.info(filePath); // ? Dao /*template = cfg.getTemplate("dao.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath+separator+model.get("moduleName")+separator+"dao"+separator +StringUtils.lowerCase(subModuleName)+separator+model.get("ClassName")+"Dao.java"; writeFile(content, filePath); logger.info(filePath); // ? Service template = cfg.getTemplate("service.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath+separator+model.get("moduleName")+separator+"service"+separator +StringUtils.lowerCase(subModuleName)+separator+model.get("ClassName")+"Service.java"; writeFile(content, filePath); logger.info(filePath);*/ // ? Controller template = cfg.getTemplate("controller.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "controller" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Controller.java"; writeFile(content, filePath); logger.info(filePath); // ? ViewForm template = cfg.getTemplate("viewForm.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + model.get("className") + separator + model.get("className") + "Form.jsp"; writeFile(content, filePath); logger.info(filePath); // ? ViewList template = cfg.getTemplate("viewList.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + model.get("className") + separator + model.get("className") + "List.jsp"; writeFile(content, filePath); logger.info(filePath); logger.info("????"); }
From source file:SparkStreaming.java
public static void main(String[] args) throws Exception { JSONObject jo = new JSONObject(); SparkConf sparkConf = new SparkConf().setAppName("mytestapp").setMaster("local[2]"); JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, new Duration(2000)); int numThreads = Integer.parseInt("2"); Map<String, Integer> topicMap = new HashMap<>(); String[] topics = "testdemo".split(","); for (String topic : topics) { topicMap.put(topic, numThreads); }//from w w w . j a v a 2 s .com JavaPairReceiverInputDStream<String, String> messages = KafkaUtils.createStream(jssc, "localhost:2181", "testdemo", topicMap); JavaDStream<String> lines = messages.map(new Function<Tuple2<String, String>, String>() { @Override public String call(Tuple2<String, String> tuple2) { return tuple2._2(); } }); JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() { @Override public Iterable<String> call(String x) throws IOException { String temperature = x.substring(x.indexOf(":") + 1); /* System.out.println("Temperature from spark++++++++++ "+temperature); URL url = new URL("http://localhost:8080/apachetest/Test?var1="+temperature); URLConnection conn = url.openConnection(); conn.setDoOutput(true);*/ final ThermometerDemo2 demo = new ThermometerDemo2("Thermometer Demo 2", temperature); demo.pack(); demo.setVisible(true); return Arrays.asList(x.split(" ")); } }); JavaPairDStream<String, Integer> wordCounts = words.mapToPair(new PairFunction<String, String, Integer>() { @Override public Tuple2<String, Integer> call(String s) { return new Tuple2<>(s, 1); } }).reduceByKey(new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer i1, Integer i2) { return i1 + i2; } }); wordCounts.print(); jssc.start(); jssc.awaitTermination(); }