Example usage for java.util Map put

List of usage examples for java.util Map put

Introduction

In this page you can find the example usage for java.util Map put.

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

From source file:com.fiveclouds.jasper.JasperRunner.java

public static void main(String[] args) {

    // Set-up the options for the utility
    Options options = new Options();
    Option report = new Option("report", true, "jasper report to run (i.e. /path/to/report.jrxml)");
    options.addOption(report);//from  w ww  .  jav a2s.  c  om

    Option driver = new Option("driver", true, "the jdbc driver class (i.e. com.mysql.jdbc.Driver)");
    driver.setRequired(true);
    options.addOption(driver);

    options.addOption("jdbcurl", true, "database jdbc url (i.e. jdbc:mysql://localhost:3306/database)");
    options.addOption("excel", true, "Will override the PDF default and export to Microsoft Excel");
    options.addOption("username", true, "database username");
    options.addOption("password", true, "database password");
    options.addOption("output", true, "the output filename (i.e. path/to/report.pdf");
    options.addOption("help", false, "print this message");

    Option propertyOption = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value as report property").create("D");

    options.addOption(propertyOption);

    // Parse the options and build the report
    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jasper-runner", options);
        } else {

            System.out.println("Building report " + cmd.getOptionValue("report"));
            try {
                Class.forName(cmd.getOptionValue("driver"));
                Connection connection = DriverManager.getConnection(cmd.getOptionValue("jdbcurl"),
                        cmd.getOptionValue("username"), cmd.getOptionValue("password"));
                System.out.println("Connected to " + cmd.getOptionValue("jdbcurl"));
                JasperReport jasperReport = JasperCompileManager.compileReport(cmd.getOptionValue("report"));

                JRPdfExporter pdfExporter = new JRPdfExporter();

                Properties properties = cmd.getOptionProperties("D");
                Map<String, Object> parameters = new HashMap<String, Object>();

                Map<String, JRParameter> reportParameters = new HashMap<String, JRParameter>();

                for (JRParameter param : jasperReport.getParameters()) {
                    reportParameters.put(param.getName(), param);
                }

                for (Object propertyKey : properties.keySet()) {
                    String parameterName = String.valueOf(propertyKey);
                    String parameterValue = String.valueOf(properties.get(propertyKey));
                    JRParameter reportParam = reportParameters.get(parameterName);

                    if (reportParam != null) {
                        if (reportParam.getValueClass().equals(String.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to String = " + parameterValue);
                            parameters.put(parameterName, parameterValue);
                        } else if (reportParam.getValueClass().equals(Integer.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to Integer = " + parameterValue);
                            parameters.put(parameterName, Integer.parseInt(parameterValue));
                        } else {
                            System.err.print("Unsupported type for property " + parameterName);
                            System.exit(1);

                        }
                    } else {
                        System.out.println("Property " + parameterName + " not found in the report! IGNORING");

                    }
                }

                JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, connection);

                pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
                pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, cmd.getOptionValue("output"));
                System.out.println("Exporting report to " + cmd.getOptionValue("output"));
                pdfExporter.exportReport();
            } catch (JRException e) {
                System.err.print("Unable to parse report file (" + cmd.getOptionValue("r") + ")");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e) {
                System.err.print("Unable to find the database driver,  is it on the classpath?");
                e.printStackTrace();
                System.exit(1);
            } catch (SQLException e) {
                System.err.print("An SQL exception has occurred (" + e.getMessage() + ")");
                e.printStackTrace();
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.print("Unable to parse command line options (" + e.getMessage() + ")");
        System.exit(1);
    }
}

From source file:com.lightboxtechnologies.nsrl.OCSVTest.java

public static void main(String[] args) throws IOException {
    final String mfg_filename = args[0];
    final String os_filename = args[1];
    final String prod_filename = args[2];
    final String hash_filename = args[3];

    final LineTokenizer tok = new OpenCSVLineTokenizer();
    final RecordLoader loader = new RecordLoader();

    final ErrorConsumer err = new ErrorConsumer() {
        public void consume(BadDataException e, long linenum) {
            System.err.println("malformed record, line " + linenum);
            e.printStackTrace();/*from   ww  w  .  java  2 s.c o m*/
        }
    };

    // read manufacturer, OS, product data
    final Map<String, MfgData> mfg = new HashMap<String, MfgData>();
    final Map<String, OSData> os = new HashMap<String, OSData>();
    final Map<Integer, List<ProdData>> prod = new HashMap<Integer, List<ProdData>>();

    SmallTableLoader.load(mfg_filename, mfg, os_filename, os, prod_filename, prod, tok, err);

    // read hash data
    final RecordConsumer<HashData> hcon = new RecordConsumer<HashData>() {
        public void consume(HashData hd) {
            /*
                    System.out.print(hd);
                    
                    for (ProdData pd : prod.get(hd.prod_code)) {
                      System.out.print(pd);
                      final MfgData pmd = mfg.get(pd.mfg_code);
                      System.out.print(pmd);
                    }
                    
                    final OSData osd = os.get(hd.os_code);
                    System.out.print(osd);
                    
                    final MfgData osmd = mfg.get(osd.mfg_code);
                    System.out.print(osmd);
                    
                    System.out.println("");
            */

            /*
                    final Hex hex = new Hex();
                    
                    String sha1 = null;
                    String md5 = null;
                    String crc32 = null;
                    
                    try {
                      sha1 = (String) hex.encode((Object) hd.sha1);
                      md5 = (String) hex.encode((Object) hd.md5);
                      crc32 = (String) hex.encode((Object) hd.crc32);
                    }
                    catch (EncoderException e) {
                      throw new RuntimeException(e);
                    }
            */

            final ObjectMapper mapper = new ObjectMapper();

            final String sha1 = Hex.encodeHexString(hd.sha1);
            final String md5 = Hex.encodeHexString(hd.md5);
            final String crc32 = Hex.encodeHexString(hd.crc32);

            final Map<String, Object> hd_m = new HashMap<String, Object>();

            hd_m.put("sha1", sha1);
            hd_m.put("md5", md5);
            hd_m.put("crc32", crc32);
            hd_m.put("name", hd.name);
            hd_m.put("size", hd.size);
            hd_m.put("special_code", hd.special_code);

            final OSData osd = os.get(hd.os_code);
            final MfgData osmfgd = mfg.get(osd.mfg_code);

            final Map<String, Object> os_m = new HashMap<String, Object>();
            os_m.put("name", osd.name);
            os_m.put("version", osd.version);
            os_m.put("manufacturer", osmfgd.name);
            hd_m.put("os", os_m);

            final List<Map<String, Object>> pl_l = new ArrayList<Map<String, Object>>();
            for (ProdData pd : prod.get(hd.prod_code)) {

                if (!osd.code.equals(pd.os_code)) {
                    // os code mismatch
                    /*
                                System.err.println(
                                  "Hash record OS code == " + osd.code + " != " + pd.os_code + " == product record OS code"
                                );
                    */
                    continue;
                }

                final Map<String, Object> prod_m = new HashMap<String, Object>();

                prod_m.put("name", pd.name);
                prod_m.put("version", pd.version);
                prod_m.put("language", pd.language);
                prod_m.put("app_type", pd.app_type);
                prod_m.put("os_code", pd.os_code);

                final MfgData md = mfg.get(pd.mfg_code);
                prod_m.put("manufacturer", md.name);

                pl_l.add(prod_m);
            }

            if (pl_l.size() > 1) {
                System.err.println(hd.prod_code);
            }

            hd_m.put("products", pl_l);

            try {
                mapper.writeValue(System.out, hd_m);
            } catch (IOException e) {
                // should be impossible
                throw new IllegalStateException(e);
            }
        }
    };

    final RecordProcessor<HashData> hproc = new HashRecordProcessor();
    final LineHandler hlh = new DefaultLineHandler<HashData>(tok, hproc, hcon, err);

    InputStream zin = null;
    try {
        //      zin = new GZIPInputStream(new FileInputStream(hash_filename));
        zin = new FileInputStream(hash_filename);
        loader.load(zin, hlh);
        zin.close();
    } finally {
        IOUtils.closeQuietly(zin);
    }

    System.out.println();

    /*
        for (Map.Entry<String,String> e : mfg.entrySet()) {
          System.out.println(e.getKey() + " = " + e.getValue());
        }
            
        for (Map.Entry<String,OSData> e : os.entrySet()) {
          System.out.println(e.getKey() + " = " + e.getValue());
        }
            
        for (Map.Entry<Integer,List<ProdData>> e : prod.entrySet()) {
          System.out.println(e.getKey() + " = " + e.getValue());
        }
    */
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    InputSource source = new InputSource(new StringReader("<root>\n" + "<field name='firstname'>\n"
            + "    <value>John</value>\n" + "</field>\n" + "<field name='lastname'>\n"
            + "    <value>Citizen</value>\n" + "</field>\n" + "<field name='DoB'>\n"
            + "    <value>01/01/1980</value>\n" + "</field>\n" + "<field name='Profession'>\n"
            + "    <value>Manager</value>\n" + "</field>\n" + "</root>"));

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
    Document document = documentBuilder.parse(source);

    NodeList allFields = (NodeList) document.getElementsByTagName("field");

    Map<String, String> data = new HashMap<>();
    for (int i = 0; i < allFields.getLength(); i++) {
        Element field = (Element) allFields.item(i);
        String nameAttribute = field.getAttribute("name");
        Element child = (Element) field.getElementsByTagName("value").item(0);
        String value = child.getTextContent();
        data.put(nameAttribute, value);
    }/*from w  ww .j a va 2 s  .  c o m*/

    for (Map.Entry field : data.entrySet()) {
        System.out.println(field.getKey() + ": " + field.getValue());
    }
}

From source file:ai.susi.tools.JsonSignature.java

public static void main(String[] args) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);// www . ja  v  a2s  .c  om
    KeyPair keyPair = keyGen.genKeyPair();

    String jsonString = "{\n" + "        \"_id\": \"57b44e738d9af9fa2df13b27\",\n" + "        \"index\": 0,\n"
            + "        \"guid\": \"13af6838-08c8-4709-8dff-5ecb20bbaaa7\",\n" + "        \"isActive\": false,\n"
            + "        \"balance\": \"$2,092.08\",\n" + "        \"picture\": \"http://placehold.it/32x32\",\n"
            + "        \"age\": 22,\n" + "        \"eyeColor\": \"blue\",\n"
            + "        \"name\": \"Wyatt Jefferson\",\n" + "        \"gender\": \"male\",\n"
            + "        \"company\": \"GEEKFARM\",\n" + "        \"email\": \"wyattjefferson@geekfarm.com\",\n"
            + "        \"phone\": \"+1 (855) 405-2375\",\n"
            + "        \"address\": \"506 Court Street, Gambrills, Minnesota, 8953\",\n"
            + "        \"about\": \"Ea sunt quis non occaecat aliquip sint eiusmod. Aliquip id non ut sunt est laboris proident reprehenderit incididunt velit. Quis deserunt dolore aliqua voluptate magna laborum minim. Pariatur voluptate ad consequat culpa sit veniam eiusmod et ex ipsum.\\r\\n\",\n"
            + "        \"registered\": \"2015-08-08T03:21:53 -02:00\",\n"
            + "        \"latitude\": -39.880621,\n" + "        \"longitude\": 44.053688,\n"
            + "        \"tags\": [\n" + "            \"non\",\n" + "            \"cupidatat\",\n"
            + "            \"in\",\n" + "            \"Lorem\",\n" + "            \"tempor\",\n"
            + "            \"fugiat\",\n" + "            \"aliqua\"\n" + "        ],\n"
            + "        \"friends\": [\n" + "            {\n" + "                \"id\": 0,\n"
            + "                \"name\": \"Gail Blevins\"\n" + "            },\n" + "            {\n"
            + "                \"id\": 1,\n" + "                \"name\": \"Tricia Francis\"\n"
            + "            },\n" + "            {\n" + "                \"id\": 2,\n"
            + "                \"name\": \"Letitia Winters\"\n" + "            }\n" + "        ],\n"
            + "        \"greeting\": \"Hello, Wyatt Jefferson! You have 1 unread messages.\",\n"
            + "        \"favoriteFruit\": \"strawberry\"\n" + "    }";

    String jsonStringSimple = "{\n" + "        \"_id\": \"57b44e738d9af9fa2df13b27\",\n"
            + "        \"index\": 0,\n" + "        \"guid\": \"13af6838-08c8-4709-8dff-5ecb20bbaaa7\",\n"
            + "        \"isActive\": false,\n" + "        \"balance\": \"$2,092.08\",\n"
            + "        \"picture\": \"http://placehold.it/32x32\",\n" + "        \"age\": 22,\n"
            + "        \"eyeColor\": \"blue\",\n" + "        \"name\": \"Wyatt Jefferson\",\n"
            + "        \"gender\": \"male\",\n" + "        \"company\": \"GEEKFARM\",\n"
            + "        \"email\": \"wyattjefferson@geekfarm.com\",\n"
            + "        \"phone\": \"+1 (855) 405-2375\",\n"
            + "        \"address\": \"506 Court Street, Gambrills, Minnesota, 8953\",\n"
            + "        \"about\": \"Ea sunt quis non occaecat aliquip sint eiusmod. Aliquip id non ut sunt est laboris proident reprehenderit incididunt velit. Quis deserunt dolore aliqua voluptate magna laborum minim. Pariatur voluptate ad consequat culpa sit veniam eiusmod et ex ipsum.\\r\\n\",\n"
            + "        \"registered\": \"2015-08-08T03:21:53 -02:00\",\n"
            + "        \"latitude\": -39.880621,\n" + "        \"longitude\": 44.053688,\n" + "    }";

    JSONObject randomObj = new JSONObject(jsonString);
    JSONObject tmp = new JSONObject(jsonStringSimple);
    Map<String, byte[]> randomObj2 = new HashMap<String, byte[]>();
    for (String key : tmp.keySet()) {
        Object value = tmp.get(key);
        randomObj2.put(key, value.toString().getBytes());
    }

    addSignature(randomObj, keyPair.getPrivate());
    addSignature(randomObj2, keyPair.getPrivate());
    if (hasSignature(randomObj))
        System.out.println("Verify 1: " + verify(randomObj, keyPair.getPublic()));
    if (hasSignature(randomObj2))
        System.out.println("Verify 2: " + verify(randomObj, keyPair.getPublic()));
    removeSignature(randomObj);
    removeSignature(randomObj2);
}

From source file:com.joliciel.lefff.Lefff.java

/**
 * @param args//from   w w  w .j a  v  a 2 s . c o m
 */
public static void main(String[] args) throws Exception {
    long startTime = (new Date()).getTime();
    String command = args[0];

    String memoryBaseFilePath = "";
    String lefffFilePath = "";
    String posTagSetPath = "";
    String posTagMapPath = "";
    String word = null;
    List<String> categories = null;
    int startLine = -1;
    int stopLine = -1;

    boolean firstArg = true;
    for (String arg : args) {
        if (firstArg) {
            firstArg = false;
            continue;
        }
        int equalsPos = arg.indexOf('=');
        String argName = arg.substring(0, equalsPos);
        String argValue = arg.substring(equalsPos + 1);
        if (argName.equals("memoryBase"))
            memoryBaseFilePath = argValue;
        else if (argName.equals("lefffFile"))
            lefffFilePath = argValue;
        else if (argName.equals("startLine"))
            startLine = Integer.parseInt(argValue);
        else if (argName.equals("stopLine"))
            stopLine = Integer.parseInt(argValue);
        else if (argName.equals("posTagSet"))
            posTagSetPath = argValue;
        else if (argName.equals("posTagMap"))
            posTagMapPath = argValue;
        else if (argName.equals("word"))
            word = argValue;
        else if (argName.equals("categories")) {
            String[] parts = argValue.split(",");
            categories = new ArrayList<String>();
            for (String part : parts) {
                categories.add(part);
            }
        } else
            throw new RuntimeException("Unknown argument: " + argName);
    }

    final LefffServiceLocator locator = new LefffServiceLocator();
    locator.setDataSourcePropertiesFile("jdbc-live.properties");

    TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance();

    final LefffService lefffService = locator.getLefffService();
    if (command.equals("load")) {
        if (lefffFilePath.length() == 0)
            throw new RuntimeException("Required argument: lefffFile");
        final LefffLoader loader = lefffService.getLefffLoader();
        File file = new File(lefffFilePath);
        if (startLine > 0)
            loader.setStartLine(startLine);
        if (stopLine > 0)
            loader.setStopLine(stopLine);

        loader.LoadFile(file);
    } else if (command.equals("serialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");
        if (posTagSetPath.length() == 0)
            throw new RuntimeException("Required argument: posTagSet");
        if (posTagMapPath.length() == 0)
            throw new RuntimeException("Required argument: posTagMap");

        PosTaggerServiceLocator posTaggerServiceLocator = talismaneServiceLocator.getPosTaggerServiceLocator();
        PosTaggerService posTaggerService = posTaggerServiceLocator.getPosTaggerService();
        File posTagSetFile = new File(posTagSetPath);
        PosTagSet posTagSet = posTaggerService.getPosTagSet(posTagSetFile);

        File posTagMapFile = new File(posTagMapPath);
        LefffPosTagMapper posTagMapper = lefffService.getPosTagMapper(posTagMapFile, posTagSet);

        Map<PosTagSet, LefffPosTagMapper> posTagMappers = new HashMap<PosTagSet, LefffPosTagMapper>();
        posTagMappers.put(posTagSet, posTagMapper);

        LefffMemoryLoader loader = new LefffMemoryLoader();
        LefffMemoryBase memoryBase = loader.loadMemoryBaseFromDatabase(lefffService, posTagMappers, categories);
        File memoryBaseFile = new File(memoryBaseFilePath);
        memoryBaseFile.delete();
        loader.serializeMemoryBase(memoryBase, memoryBaseFile);
    } else if (command.equals("deserialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");

        LefffMemoryLoader loader = new LefffMemoryLoader();
        File memoryBaseFile = new File(memoryBaseFilePath);
        LefffMemoryBase memoryBase = loader.deserializeMemoryBase(memoryBaseFile);

        String[] testWords = new String[] { "avoir" };
        if (word != null) {
            testWords = word.split(",");
        }

        for (String testWord : testWords) {
            Set<PosTag> possiblePosTags = memoryBase.findPossiblePosTags(testWord);
            LOG.debug("##### PosTags for '" + testWord + "': " + possiblePosTags.size());
            int i = 1;
            for (PosTag posTag : possiblePosTags) {
                LOG.debug("### PosTag " + (i++) + ":" + posTag);
            }

            List<? extends LexicalEntry> entriesForWord = memoryBase.getEntries(testWord);
            LOG.debug("##### Entries for '" + testWord + "': " + entriesForWord.size());
            i = 1;
            for (LexicalEntry entry : entriesForWord) {
                LOG.debug("### Entry " + (i++) + ":" + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
            }

            List<? extends LexicalEntry> entriesForLemma = memoryBase.getEntriesForLemma(testWord, "");
            LOG.debug("##### Entries for '" + testWord + "' lemma: " + entriesForLemma.size());
            for (LexicalEntry entry : entriesForLemma) {
                LOG.debug("### Entry " + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
                for (PredicateArgument argument : entry.getPredicateArguments()) {
                    LOG.debug("Argument: " + argument.getFunction() + ",Optional? " + argument.isOptional());
                    for (String realisation : argument.getRealisations()) {
                        LOG.debug("Realisation: " + realisation);
                    }
                }
            }
        }

    } else {
        System.out.println("Usage : Lefff load filepath");
    }
    long endTime = (new Date()).getTime() - startTime;
    LOG.debug("Total runtime: " + ((double) endTime / 1000) + " seconds");
}

From source file:MyMap.java

public static void main(String[] argv) {

    // Construct and load the hash. This simulates loading a
    // database or reading from a file, or wherever the data is.

    Map map = new MyMap();

    // The hash maps from company name to address.
    // In real life this might map to an Address object...
    map.put("Adobe", "Mountain View, CA");
    map.put("Learning Tree", "Los Angeles, CA");
    map.put("IBM", "White Plains, NY");
    map.put("Netscape", "Mountain View, CA");
    map.put("Microsoft", "Redmond, WA");
    map.put("Sun", "Mountain View, CA");
    map.put("O'Reilly", "Sebastopol, CA");

    // Two versions of the "retrieval" phase.
    // Version 1: get one pair's value given its key
    // (presumably the key would really come from user input):
    String queryString = "O'Reilly";
    System.out.println("You asked about " + queryString + ".");
    String resultString = (String) map.get(queryString);
    System.out.println("They are located in: " + resultString);
    System.out.println();/*from  w w w .ja  va  2  s .  co  m*/

    // Version 2: get ALL the keys and pairs 
    // (maybe to print a report, or to save to disk)
    Iterator k = map.keySet().iterator();
    while (k.hasNext()) {
        String key = (String) k.next();
        System.out.println("Key " + key + "; Value " + (String) map.get(key));
    }

    // Step 3 - try out the entrySet() method.
    Set es = map.entrySet();
    System.out.println("entrySet() returns " + es.size() + " Map.Entry's");
}

From source file:Applicant.java

public static void main(String[] args) throws ClassNotFoundException, SQLException, UnknownHostException,
        ExecutionException, InterruptedException {
    //        Class.forName("com.mysql.jdbc.Driver");
    //        Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/customer","root","sachin123@");
    //        Statement stmt=con.createStatement();
    //        int Size=0,i=1;
    //        ResultSet rs=stmt.executeQuery("select count(*) from personal limit 100");
    //        while(rs.next())
    //        {//from   www.j av a 2s.c om
    //            Size=rs.getInt(1);
    //            System.out.println(Size);
    //        }
    //
    //
    //        con.close();

    Applicant input = new Applicant();
    input.setCust_No("CU00008333343056");
    input.setFirst_Name("mer");
    input.setLast_Name("Braun");
    input.setStreet("Fangdieckstrae 14");
    input.setTown("Koblenz");
    input.setZipcode("57474  ");
    input.setId("AVtcqDtr-hedAcx8Wh2Y");

    Settings settings = Settings.builder().put("cluster.name", "jvmti-cluster")
            .put("client.transport.sniff", true).build();
    PreBuiltTransportClient client = new PreBuiltTransportClient(settings);

    client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

    Map<String, Object> f = new HashMap<String, Object>();
    f.put("data", "hello");
    UpdateRequest updateRequest = new UpdateRequest("a", "b", "1")
            .script(new Script(ScriptType.INLINE, "painless", "ctx._source.doc=params.data", f));
    client.update(updateRequest).get();

    SearchResponse sr = client.prepareSearch("customer").setTypes("personal_info")
            .setQuery(QueryBuilders.matchQuery("FirstName", input.getFirst_Name())).execute().get();
    Match_Record.updataInput(sr, input, client, "first_name_rel");
    sr = client.prepareSearch("customer").setTypes("personal_info")
            .setQuery(QueryBuilders.matchQuery("LastName", input.getLast_Name())).execute().get();
    Match_Record.updataInput(sr, input, client, "last_name_rel");
    sr = client.prepareSearch("customer").setTypes("personal_info")
            .setQuery(QueryBuilders.matchQuery("Street", input.getStreet())).execute().get();
    Match_Record.updataInput(sr, input, client, "street_rel");
    sr = client.prepareSearch("customer").setTypes("personal_info")
            .setQuery(QueryBuilders.matchQuery("Zip", input.getZipcode())).execute().get();
    Match_Record.updataInput(sr, input, client, "zip_rel");
    sr = client.prepareSearch("customer").setTypes("personal_info")
            .setQuery(QueryBuilders.matchQuery("Place_of_Residence", input.getTown())).execute().get();
    Match_Record.updataInput(sr, input, client, "place_of_residence_rel");

    UpdateByQueryRequestBuilder updateByQuery = UpdateByQueryAction.INSTANCE.newRequestBuilder(client);

    f.put("data", input.getCust_No());

    BulkIndexByScrollResponse response = updateByQuery.source("customer")
            .filter(termQuery("FirstName", input.getFirst_Name()))
            .script(new Script(ScriptType.INLINE, "painless", "ctx._source.FirstName_Rel.add(params.data)", f))
            .get();
    response = updateByQuery.source("customer").filter(termQuery("LastName", input.getLast_Name()))
            .script(new Script(ScriptType.INLINE, "painless", "ctx._source.LastName_Rel.add(params.data)", f))
            .get();
    response = updateByQuery.source("customer").filter(termQuery("Zip", input.getZipcode()))
            .script(new Script(ScriptType.INLINE, "painless", "ctx._source.Zipcode_Rel.add(params.data)", f))
            .get();
    response = updateByQuery.source("customer").filter(termQuery("Place_of_Residence", input.getTown()))
            .script(new Script(ScriptType.INLINE, "painless", "ctx._source.Town_Rel.add(params.data)", f))
            .get();
    response = updateByQuery.source("customer").filter(termQuery("Street", input.getStreet()))
            .script(new Script(ScriptType.INLINE, "painless", "ctx._source.Street_Rel.add(params.data)", f))
            .get();

    //        UpdateRequest updateRequest = new UpdateRequest("a", "b", "1")
    //                .script(new Script(ScriptType.INLINE,"painless","ctx._source.check.add(params.data)",f));
    //        client.update(updateRequest).get();

    client.close();
}

From source file:com.sishuok.es.generate.Generate.java

public static void main(String[] args) throws Exception {

    // ==========  ?? ====================

    // ??????/* w w  w  .  j  a  va 2 s.com*/
    // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className}

    // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4?
    String packageName = "com.sishuok.es";

    String sysName = "sys"; // ??sys?showcase?maintain?personal?shop
    String moduleName = "xxs"; // ???? 
    String tableName = "sys_xxs_attribute"; // user
    String className = "XxsAttribute"; // ??User
    String permissionName = "sys:xxsAttribute";//??????????
    String folderName = "xxs";//??
    String classAuthor = "xxs"; // ThinkGem
    String functionName = "??????"; // ??

    // ???
    //Boolean isEnable = false;
    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;

    // ?
    File projectPath = new DefaultResourceLoader().getResource("").getFile();
    while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) {
        projectPath = projectPath.getParentFile();
    }
    logger.info("Project Path: {}", projectPath);

    // ?
    String tplPath = StringUtils.replace(projectPath + "/src/main/java/com/sishuok/es/generate/template", "/",
            separator);
    logger.info("Template Path: {}", tplPath);

    // Java
    String javaPath = StringUtils.replaceEach(
            projectPath + "/src/main/java/" + StringUtils.lowerCase(packageName), new String[] { "/", "." },
            new String[] { separator, separator });
    logger.info("Java Path: {}", javaPath);

    // 
    String viewPath = StringUtils.replace(projectPath + "/src/main/webapp/WEB-INF/jsp/admin", "/", separator);
    logger.info("View Path: {}", viewPath);

    // ???
    Configuration cfg = new Configuration();
    cfg.setDefaultEncoding("UTF-8");
    cfg.setDirectoryForTemplateLoading(new File(tplPath));

    // ???
    Map<String, String> model = Maps.newHashMap();
    model.put("packageName", StringUtils.lowerCase(packageName)); //
    model.put("sysName", StringUtils.lowerCase(sysName)); //???
    model.put("moduleName", StringUtils.lowerCase(moduleName)); //???
    model.put("tableName", StringUtils.lowerCase(tableName)); //
    model.put("className", StringUtils.uncapitalize(className)); //???
    model.put("permissionName", permissionName); //????
    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("folderName", folderName); //??
    model.put("urlPrefix", model.get("moduleName") + "_" + model.get("className")); //jsp??
    model.put("viewPrefix", //StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+
            model.get("urlPrefix"));
    model.put("permissionPrefix", model.get("sysName") + ":" + model.get("moduleName")); //??

    // ? Entity
    Template template = cfg.getTemplate("entity.ftl");
    String content = FreeMarkers.renderTemplate(template, model);
    String filePath = javaPath + separator + model.get("sysName") + separator + model.get("moduleName")
            + separator + "entity" + separator + model.get("ClassName") + ".java";
    System.out.println("Entity   filePath" + filePath);
    writeFile(content, filePath);
    logger.info("Entity: {}", filePath);

    // ? Repository
    template = cfg.getTemplate("repository.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = javaPath + separator + model.get("sysName") + separator + model.get("moduleName") + separator
            + "repository" + separator + separator + model.get("ClassName") + "Repository.java";
    System.out.println("repository   filePath" + filePath);
    writeFile(content, filePath);
    logger.info("Dao: {}", filePath);

    // ? Service
    template = cfg.getTemplate("service.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = javaPath + separator + model.get("sysName") + separator + model.get("moduleName") + separator
            + "service" + separator + separator + model.get("ClassName") + "Service.java";
    System.out.println("Service   filePath" + filePath);
    writeFile(content, filePath);
    logger.info("Service: {}", filePath);

    // ? ??Controller
    template = cfg.getTemplate("frontController.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = javaPath + separator + model.get("sysName") + separator + model.get("moduleName") + separator
            + "web" + separator + "controller" + separator + "front" + separator + model.get("ClassName")
            + "Controller.java";
    System.out.println("Controller   filePath" + filePath);
    writeFile(content, filePath);
    logger.info("Controller: {}", filePath);

    // ? ??Controller
    template = cfg.getTemplate("adminController.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = javaPath + separator + model.get("sysName") + separator + model.get("moduleName") + separator
            + "web" + separator + "controller" + separator + "admin" + separator + model.get("ClassName")
            + "Controller.java";
    System.out.println("Controller   filePath" + filePath);
    writeFile(content, filePath);
    logger.info("Controller: {}", filePath);

    // ? editForm
    template = cfg.getTemplate("editForm.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = viewPath + separator + model.get("sysName") + separator + model.get("folderName") + separator
            + "editForm.jsp";
    System.out.println("---------------------------------------------------");
    System.out.println("ViewForm   filePath" + filePath);
    writeFile(content, filePath);
    logger.info("ViewForm: {}", filePath);

    // ? list
    template = cfg.getTemplate("list.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = viewPath + separator + model.get("sysName") + separator + model.get("folderName") + separator
            + "list.jsp";
    writeFile(content, filePath);
    System.out.println("ViewListfilePath" + filePath);
    logger.info("ViewList: {}", filePath);

    // ? searcheForm
    template = cfg.getTemplate("searchForm.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = viewPath + separator + model.get("sysName") + separator + model.get("folderName") + separator
            + "searchForm.jsp";
    writeFile(content, filePath);
    System.out.println("searcheForm filePath" + filePath);
    logger.info("ViewList: {}", filePath);

    // ? listTable
    template = cfg.getTemplate("listTable.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = viewPath + separator + model.get("sysName") + separator + model.get("folderName") + separator
            + "listTable.jsp";
    writeFile(content, filePath);
    System.out.println("listTable filePath" + filePath);
    logger.info("ViewList: {}", filePath);

    logger.info("Generate Success.");
}

From source file:com.example.geomesa.kafka08.KafkaQuickStart.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);

    // create the producer and consumer KafkaDataStore objects
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    dsConf.put("isProducer", "true");
    DataStore producerDS = DataStoreFinder.getDataStore(dsConf);
    dsConf.put("isProducer", "false");
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore objects properly
    if (producerDS == null) {
        throw new Exception("Null producer KafkaDataStore");
    }// ww w .j a va  2 s.com
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }

    // create the schema which creates a topic in Kafka
    // (only needs to be done once)
    final String sftName = "KafkaQuickStart08";
    final String sftSchema = "name:String,age:Int,dtg:Date,*geom:Point:srid=4326";
    SimpleFeatureType sft = SimpleFeatureTypes.createType(sftName, sftSchema);
    // set zkPath to default if not specified
    String zkPath = (dsConf.get(ZK_PATH) == null) ? "/geomesa/ds/kafka" : dsConf.get(ZK_PATH);
    SimpleFeatureType preppedOutputSft = KafkaDataStoreHelper.createStreamingSFT(sft, zkPath);
    // only create the schema if it hasn't been created already
    if (!Arrays.asList(producerDS.getTypeNames()).contains(sftName))
        producerDS.createSchema(preppedOutputSft);
    if (!cmd.hasOption("automated")) {
        System.out.println("Register KafkaDataStore in GeoServer (Press enter to continue)");
        System.in.read();
    }

    // the live consumer must be created before the producer writes features
    // in order to read streaming data.
    // i.e. the live consumer will only read data written after its instantiation
    SimpleFeatureSource consumerFS = consumerDS.getFeatureSource(sftName);
    SimpleFeatureStore producerFS = (SimpleFeatureStore) producerDS.getFeatureSource(sftName);

    // creates and adds SimpleFeatures to the producer every 1/5th of a second
    System.out.println("Writing features to Kafka... refresh GeoServer layer preview to see changes");
    Instant replayStart = new Instant();

    String vis = cmd.getOptionValue(VISIBILITY);
    if (vis != null)
        System.out.println("Writing features with " + vis);
    addSimpleFeatures(sft, producerFS, vis);
    Instant replayEnd = new Instant();

    // read from Kafka after writing all the features.
    // LIVE CONSUMER - will obtain the current state of SimpleFeatures
    System.out.println("\nConsuming with the live consumer...");
    SimpleFeatureCollection featureCollection = consumerFS.getFeatures();
    System.out.println(featureCollection.size() + " features were written to Kafka");

    addDeleteNewFeature(sft, producerFS);

    // read from Kafka after writing all the features.
    // LIVE CONSUMER - will obtain the current state of SimpleFeatures
    System.out.println("\nConsuming with the live consumer...");
    featureCollection = consumerFS.getFeatures();
    System.out.println(featureCollection.size() + " features were written to Kafka");

    // the state of the two SimpleFeatures is real time here
    System.out.println("Here are the two SimpleFeatures that were obtained with the live consumer:");
    SimpleFeatureIterator featureIterator = featureCollection.features();
    SimpleFeature feature1 = featureIterator.next();
    SimpleFeature feature2 = featureIterator.next();
    featureIterator.close();
    printFeature(feature1);
    printFeature(feature2);

    // REPLAY CONSUMER - will obtain the state of SimpleFeatures at any specified time
    // Replay consumer requires a ReplayConfig which takes a time range and a
    // duration of time to process
    System.out.println("\nConsuming with the replay consumer...");
    Duration readBehind = new Duration(1000); // 1 second readBehind
    ReplayConfig rc = new ReplayConfig(replayStart, replayEnd, readBehind);
    SimpleFeatureType replaySFT = KafkaDataStoreHelper.createReplaySFT(preppedOutputSft, rc);
    producerDS.createSchema(replaySFT);
    SimpleFeatureSource replayConsumerFS = consumerDS.getFeatureSource(replaySFT.getName());

    // querying for the state of SimpleFeatures approximately 5 seconds before the replayEnd.
    // the ReplayKafkaConsumerFeatureSource will build the state of SimpleFeatures
    // by processing all of the messages that were sent in between queryTime-readBehind and queryTime.
    // only the messages in between replayStart and replayEnd are cached.
    Instant queryTime = replayEnd.minus(5000);
    featureCollection = replayConsumerFS.getFeatures(ReplayTimeHelper.toFilter(queryTime));
    System.out.println(featureCollection.size() + " features were written to Kafka");

    System.out.println("Here are the two SimpleFeatures that were obtained with the replay consumer:");
    featureIterator = featureCollection.features();
    feature1 = featureIterator.next();
    feature2 = featureIterator.next();
    featureIterator.close();
    printFeature(feature1);
    printFeature(feature2);

    if (System.getProperty("clear") != null) {
        // Run Java command with -Dclear=true
        // This will cause a 'clear'
        producerFS.removeFeatures(Filter.INCLUDE);
    }

    System.exit(0);
}

From source file:com.example.geomesa.kafka09.KafkaQuickStart.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);

    // create the producer and consumer KafkaDataStore objects
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    dsConf.put("isProducer", "true");
    DataStore producerDS = DataStoreFinder.getDataStore(dsConf);
    dsConf.put("isProducer", "false");
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore objects properly
    if (producerDS == null) {
        throw new Exception("Null producer KafkaDataStore");
    }//from   ww w  .  j a  v a  2 s  . co  m
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }

    // create the schema which creates a topic in Kafka
    // (only needs to be done once)
    final String sftName = "KafkaQuickStart09";
    final String sftSchema = "name:String,age:Int,dtg:Date,*geom:Point:srid=4326";
    SimpleFeatureType sft = SimpleFeatureTypes.createType(sftName, sftSchema);
    // set zkPath to default if not specified
    String zkPath = (dsConf.get(ZK_PATH) == null) ? "/geomesa/ds/kafka" : dsConf.get(ZK_PATH);
    SimpleFeatureType preppedOutputSft = KafkaDataStoreHelper.createStreamingSFT(sft, zkPath);
    // only create the schema if it hasn't been created already
    if (!Arrays.asList(producerDS.getTypeNames()).contains(sftName))
        producerDS.createSchema(preppedOutputSft);
    if (!cmd.hasOption("automated")) {
        System.out.println("Register KafkaDataStore in GeoServer (Press enter to continue)");
        System.in.read();
    }

    // the live consumer must be created before the producer writes features
    // in order to read streaming data.
    // i.e. the live consumer will only read data written after its instantiation
    SimpleFeatureSource consumerFS = consumerDS.getFeatureSource(sftName);
    SimpleFeatureStore producerFS = (SimpleFeatureStore) producerDS.getFeatureSource(sftName);

    // creates and adds SimpleFeatures to the producer every 1/5th of a second
    System.out.println("Writing features to Kafka... refresh GeoServer layer preview to see changes");
    Instant replayStart = new Instant();

    String vis = cmd.getOptionValue(VISIBILITY);
    if (vis != null)
        System.out.println("Writing features with " + vis);
    addSimpleFeatures(sft, producerFS, vis);
    Instant replayEnd = new Instant();

    // read from Kafka after writing all the features.
    // LIVE CONSUMER - will obtain the current state of SimpleFeatures
    System.out.println("\nConsuming with the live consumer...");
    SimpleFeatureCollection featureCollection = consumerFS.getFeatures();
    System.out.println(featureCollection.size() + " features were written to Kafka");

    addDeleteNewFeature(sft, producerFS);

    // read from Kafka after writing all the features.
    // LIVE CONSUMER - will obtain the current state of SimpleFeatures
    System.out.println("\nConsuming with the live consumer...");
    featureCollection = consumerFS.getFeatures();
    System.out.println(featureCollection.size() + " features were written to Kafka");

    // the state of the two SimpleFeatures is real time here
    System.out.println("Here are the two SimpleFeatures that were obtained with the live consumer:");
    SimpleFeatureIterator featureIterator = featureCollection.features();
    SimpleFeature feature1 = featureIterator.next();
    SimpleFeature feature2 = featureIterator.next();
    featureIterator.close();
    printFeature(feature1);
    printFeature(feature2);

    // REPLAY CONSUMER - will obtain the state of SimpleFeatures at any specified time
    // Replay consumer requires a ReplayConfig which takes a time range and a
    // duration of time to process
    System.out.println("\nConsuming with the replay consumer...");
    Duration readBehind = new Duration(1000); // 1 second readBehind
    ReplayConfig rc = new ReplayConfig(replayStart, replayEnd, readBehind);
    SimpleFeatureType replaySFT = KafkaDataStoreHelper.createReplaySFT(preppedOutputSft, rc);
    producerDS.createSchema(replaySFT);
    SimpleFeatureSource replayConsumerFS = consumerDS.getFeatureSource(replaySFT.getName());

    // querying for the state of SimpleFeatures approximately 5 seconds before the replayEnd.
    // the ReplayKafkaConsumerFeatureSource will build the state of SimpleFeatures
    // by processing all of the messages that were sent in between queryTime-readBehind and queryTime.
    // only the messages in between replayStart and replayEnd are cached.
    Instant queryTime = replayEnd.minus(5000);
    featureCollection = replayConsumerFS.getFeatures(ReplayTimeHelper.toFilter(queryTime));
    System.out.println(featureCollection.size() + " features were written to Kafka");

    System.out.println("Here are the two SimpleFeatures that were obtained with the replay consumer:");
    featureIterator = featureCollection.features();
    feature1 = featureIterator.next();
    feature2 = featureIterator.next();
    featureIterator.close();
    printFeature(feature1);
    printFeature(feature2);

    if (System.getProperty("clear") != null) {
        // Run Java command with -Dclear=true
        // This will cause a 'clear'
        producerFS.removeFeatures(Filter.INCLUDE);
    }

    System.exit(0);
}