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.zf.util.Post_NetNew.java

public static void main(String[] args) {
    //      String ip = "50.115.163.247";
    //      int port = 80;
    //      System.setProperty("http.proxyHost", "localhost");
    //      System.setProperty("http.proxyPort", "1080");
    //      System.setProperty("http.proxyHost", "207.244.64.132");
    //      System.setProperty("http.proxyPort", "8080");
    System.setProperty("proxyHost", "207.244.64.132");
    System.setProperty("proxyPort", "8080");
    //      System.setProperty("http.proxyHost", "207.244.64.132");
    //      System.setProperty("http.proxyPort", "8080");
    //      System.setProperty("socksProxyHost", "103.30.246.43");
    //      System.setProperty("socksProxyPort", "10800");
    //      System.setProperty("socksProxyHost", "localhost");
    //      System.setProperty("socksProxyPort", "1080");
    //      System.setProperty("socksProxyHost", "207.244.64.132");
    //      System.setProperty("socksProxyPort", "8080");

    Map<String, String> map = new HashMap<String, String>();
    //      map.put("url", "http://www.ip.cn");
    //      map.put("url", "https://www.google.com/");
    map.put("url",
            "http://tracking.crobo.com/aff_c?offer_id=21553&aff_id=1478&aff_sub2=P6P49R4873200591858716615&aff_sub=3181");
    //      map.put("url", "http://www.baidu.com");
    try {/*from w  ww  .  j a va 2s  . com*/
        //         String result = Post_NetNew.pn(map, ip, port);
        String result = Post_NetNew.pn(map);
        System.out.println(result);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.ptm.translater.App.java

public static void main(String... args) {
    GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
    ctx.load("file:src/main/resources/spring/datasource.xml");
    ctx.refresh();//from  ww w.  j a v a 2 s.co  m

    GenericXmlApplicationContext ctx2 = new GenericXmlApplicationContext();
    ctx2.load("file:src/main/resources/spring/datasource2.xml");
    ctx2.refresh();

    ArchiveDao archiveDao = ctx.getBean("archiveDao", ArchiveDao.class);
    List<Archive> archives = archiveDao.findAll();

    UserDao userDao = ctx2.getBean("userDao", UserDao.class);
    TagDao tagDao = ctx2.getBean("tagDao", TagDao.class);
    PhotoDao photoDao = ctx2.getBean("photoDao", PhotoDao.class);

    List<Tag> tagz = tagDao.findAll();
    Map<String, Long> hashTags = new HashMap<String, Long>();
    for (Tag tag : tagz)
        hashTags.put(tag.getName(), tag.getId());

    MongoCache cache = new MongoCache();
    Calendar calendar = Calendar.getInstance();

    Map<String, String> associates = new HashMap<String, String>();

    for (Archive archive : archives) {
        AppUser appUser = new AppUser();
        appUser.setName(archive.getName());
        appUser.setEmail(archive.getUid() + "@mail.th");
        appUser.setPassword("123456");

        Role role = new Role();
        role.setRoleId("ROLE_USER");
        appUser.setRole(role);

        userDao.save(appUser);
        System.out.println("\tCreate user " + appUser);

        for (Photo photo : archive.getPhotos()) {
            // ?  ??? 
            if (cache.contains(photo.getUid()))
                continue;

            System.out.println("\tNew photo");
            org.ptm.translater.ch2.domain.Photo photo2 = new org.ptm.translater.ch2.domain.Photo();
            photo2.setAppUser(appUser);
            photo2.setName(photo.getTitle());
            photo2.setLicense((byte) 7);
            photo2.setDescription(photo.getDescription());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                calendar.setTime(sdf.parse(photo.getTaken()));

                if (calendar.get(Calendar.YEAR) != 0 && calendar.get(Calendar.YEAR) > 1998)
                    continue;
                photo2.setYear(calendar.get(Calendar.YEAR));
                photo2.setMonth(calendar.get(Calendar.MONTH) + 1);
                photo2.setDay(calendar.get(Calendar.DAY_OF_MONTH));
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if (photo.getLongitude() != null && photo.getLongitude().length() > 0) {
                //                    String key = photo.getLongitude()+"#"+photo.getLatitude();
                photo2.setLatitude(photo.getLatitude());
                photo2.setLongitude(photo.getLongitude());
                //                    if (associates.containsKey(key)) {
                //                        photo2.setAddress(associates.get(key));
                //                    } else {
                //                        Geocoder geocoder = new Geocoder();
                //                        GeocoderRequestBuilder geocoderRequest = new GeocoderRequestBuilder();
                //                        GeocoderRequest request =
                //                            geocoderRequest.setLocation(new LatLng(photo.getLongitude(), photo.getLatitude())).getGeocoderRequest();
                //
                //                        GeocodeResponse response = geocoder.geocode(request);
                //                        if (response.getResults().size() > 0) {
                //                            photo2.setAddress(response.getResults().get(0).getFormattedAddress());
                //                        }
                //                        try { Thread.sleep(2000); } catch (InterruptedException ex) { ex.printStackTrace(); }
                //                    }
            }

            System.out.println("\tFind tags");
            Set<Tag> tags = new HashSet<Tag>();
            for (org.ptm.translater.ch1.domain.Tag tag : photo.getTags()) {
                Tag item = new Tag();
                item.setName(tag.getName());
                if (hashTags.containsKey(tag.getName())) {
                    item.setId(hashTags.get(tag.getName()));
                } else {
                    tagDao.save(item);
                    hashTags.put(item.getName(), item.getId());
                }
                System.out.println("\t\tinit tag " + tag.getName());
                tags.add(item);
            }
            photo2.setTags(tags);
            System.out.println("\tFind " + tags.size() + " tags");
            photoDao.save(photo2);
            System.out.println("\tSave photo");

            Imaginator img = new Imaginator();
            img.setFolder(photo2.getId().toString());
            img.setPath();

            for (PhotoSize ps : photo.getSizes()) {
                if (ps.getLabel().equals("Original")) {
                    img.setImage(ps.getSource());
                    break;
                }
            }
            img.generate();
            System.out.println("\tGenerate image of photo");
            img = null;
            cache.create(photo.getUid());
            cache.create(photo2);

            System.out.println("Generate: " + photo2);
        }
    }
}

From source file:io.anserini.index.IndexGov2.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(//from w ww.j  a v a  2  s  . c o  m
            OptionBuilder.withArgName("path").hasArg().withDescription("input data path").create(INPUT_OPTION));
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("output index path")
            .create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of indexer threads")
            .create(THREADS_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("max number of documents to index (-1 to index everything)")
            .create(DOCLIMIT_OPTION));

    options.addOption(POSITIONS_OPTION, false, "index positions");
    options.addOption(OPTIMIZE_OPTION, false, "merge all index segments");

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(THREADS_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(100);
        formatter.printHelp(IndexGov2.class.getCanonicalName(), options);
        System.exit(-1);
    }

    final String dirPath = cmdline.getOptionValue(INDEX_OPTION);
    final String dataDir = cmdline.getOptionValue(INPUT_OPTION);
    final int docCountLimit = cmdline.hasOption(DOCLIMIT_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(DOCLIMIT_OPTION))
            : -1;
    final int numThreads = Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION));

    final boolean doUpdate = cmdline.hasOption(UPDATE_OPTION);
    final boolean positions = cmdline.hasOption(POSITIONS_OPTION);
    final boolean optimize = cmdline.hasOption(OPTIMIZE_OPTION);

    final Analyzer a = new EnglishAnalyzer();
    final TrecContentSource trecSource = createGov2Source(dataDir);
    final Directory dir = FSDirectory.open(Paths.get(dirPath));

    LOG.info("Index path: " + dirPath);
    LOG.info("Doc limit: " + (docCountLimit == -1 ? "all docs" : "" + docCountLimit));
    LOG.info("Threads: " + numThreads);
    LOG.info("Positions: " + positions);
    LOG.info("Optimize (merge segments): " + optimize);

    final IndexWriterConfig config = new IndexWriterConfig(a);

    if (doUpdate) {
        config.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
    } else {
        config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    }

    final IndexWriter writer = new IndexWriter(dir, config);
    Gov2IndexThreads threads = new Gov2IndexThreads(writer, positions, trecSource, numThreads, docCountLimit);
    LOG.info("Indexer: start");

    final long t0 = System.currentTimeMillis();

    threads.start();

    while (!threads.done()) {
        Thread.sleep(100);
    }
    threads.stop();

    final long t1 = System.currentTimeMillis();
    LOG.info("Indexer: indexing done (" + (t1 - t0) / 1000.0 + " sec); total " + writer.maxDoc() + " docs");
    if (!doUpdate && docCountLimit != -1 && writer.maxDoc() != docCountLimit) {
        throw new RuntimeException("w.maxDoc()=" + writer.maxDoc() + " but expected " + docCountLimit);
    }
    if (threads.failed.get()) {
        throw new RuntimeException("exceptions during indexing");
    }

    final long t2;
    t2 = System.currentTimeMillis();

    final Map<String, String> commitData = new HashMap<String, String>();
    commitData.put("userData", "multi");
    writer.setCommitData(commitData);
    writer.commit();
    final long t3 = System.currentTimeMillis();
    LOG.info("Indexer: commit multi (took " + (t3 - t2) / 1000.0 + " sec)");

    if (optimize) {
        LOG.info("Indexer: merging all segments");
        writer.forceMerge(1);
        final long t4 = System.currentTimeMillis();
        LOG.info("Indexer: segments merged (took " + (t4 - t3) / 1000.0 + " sec)");
    }

    LOG.info("Indexer: at close: " + writer.segString());
    final long tCloseStart = System.currentTimeMillis();
    writer.close();
    LOG.info("Indexer: close took " + (System.currentTimeMillis() - tCloseStart) / 1000.0 + " sec");
    dir.close();
    final long tFinal = System.currentTimeMillis();
    LOG.info("Indexer: finished (" + (tFinal - t0) / 1000.0 + " sec)");
    LOG.info("Indexer: net bytes indexed " + threads.getBytesIndexed());
    LOG.info("Indexer: " + (threads.getBytesIndexed() / 1024. / 1024. / 1024. / ((tFinal - t0) / 3600000.))
            + " GB/hour plain text");
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.MorsaCreator.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);//w  ww.  j  a  v a2 s  . c o m
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = URI.createURI("morsa://" + commandLine.getOptionValue(OUT));

        Class<?> inClazz = MorsaCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("morsa",
                new MorsaResourceFactoryImpl(new MongoDBMorsaBackendFactory()));

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        //URI of the MongoDB database (e.g. localhost)
        saveOpts.put(IMorsaResource.OPTION_SERVER_URI, "localhost");
        saveOpts.put(IMorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, 30000);
        saveOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, false);
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        targetResource.unload();

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.glaf.mail.MailSenderImpl.java

public static void main(String[] args) throws Exception {
    Map<String, Object> dataMap = new java.util.HashMap<String, Object>();
    dataMap.put("taskDescription", "?");
    dataMap.put("processStarterName", "?");
    dataMap.put("serviceUrl", "http://127.0.0.1:8080/glaf");
    dataMap.put("callback", "http://127.0.0.1:8080/glaf/task.jsp");

    MailMessage mailMessage = new MailMessage();
    mailMessage.setFrom("joy@127.0.0.1");
    mailMessage.setTo("joy@127.0.0.1");
    mailMessage.setSubject("");
    mailMessage.setDataMap(dataMap);// w w w  .  ja  va 2  s  .com
    mailMessage.setContent("");
    // mailMessage.setTemplateId(args[0]);
    mailMessage.setSupportExpression(false);

    Collection<Object> files = new HashSet<Object>();

    mailMessage.setFiles(files);
    mailMessage.setSaveMessage(false);
    MailSender mailSender = ContextFactory.getBean("mailSender");
    mailSender.send(mailMessage);
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoCreator.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*  www .java  2s  .  c  o  m*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));

        String outputDir = commandLine.getOptionValue(OUT);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        EmbeddedCDOServer server = new EmbeddedCDOServer(outputDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            transaction.getRootResource().getContents().clear();
            LOG.log(Level.INFO, "Start moving elements");
            transaction.getRootResource().getContents().addAll(sourceResource.getContents());
            LOG.log(Level.INFO, "End moving elements");
            LOG.log(Level.INFO, "Commiting");
            transaction.commit();
            LOG.log(Level.INFO, "Commit done");
            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.green.generate.Generate.java

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

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

    // ??????//from ww  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.thinkgem.jeesite.modules";

    String moduleName = "factory"; // ???sys
    String subModuleName = ""; // ????? 
    String className = "product"; // ??user
    String classAuthor = "ThinkGem"; // ThinkGem
    String functionName = "?"; // ??

    // ???
    Boolean isEnable = false;

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

    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/thinkgem/jeesite/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/views", "/", separator);
    logger.info("View Path: {}", viewPath);

    // ???
    Configuration cfg = new Configuration();
    cfg.setDirectoryForTemplateLoading(new File(tplPath));

    // ???
    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("tableName",
            model.get("moduleName")
                    + (StringUtils.isNotBlank(subModuleName) ? "_" + StringUtils.lowerCase(subModuleName) : "")
                    + "_" + model.get("className"));
    model.put("urlPrefix",
            model.get("moduleName")
                    + (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) : "")
                    + "/" + model.get("className"));
    model.put("viewPrefix", //StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+
            model.get("urlPrefix"));
    model.put("permissionPrefix",
            model.get("moduleName")
                    + (StringUtils.isNotBlank(subModuleName) ? ":" + StringUtils.lowerCase(subModuleName) : "")
                    + ":" + model.get("className"));

    // ? Entity
    Template template = cfg.getTemplate("entity.ftl");
    String content = FreeMarkers.renderTemplate(template, model);
    String filePath = javaPath + separator + model.get("moduleName") + separator + "entity" + separator
            + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java";
    writeFile(content, filePath);
    logger.info("Entity: {}", 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("Dao: {}", 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("Service: {}", filePath);

    // ? Controller
    template = cfg.getTemplate("controller.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = javaPath + separator + model.get("moduleName") + separator + "web" + separator
            + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Controller.java";
    writeFile(content, filePath);
    logger.info("Controller: {}", filePath);

    // ? ViewForm
    template = cfg.getTemplate("viewForm.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator
            + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
            + model.get("className") + "Form.jsp";
    writeFile(content, filePath);
    logger.info("ViewForm: {}", filePath);

    // ? ViewList
    template = cfg.getTemplate("viewList.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator
            + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
            + model.get("className") + "List.jsp";
    writeFile(content, filePath);
    logger.info("ViewList: {}", filePath);

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

From source file:com.glaf.core.util.JsonUtils.java

public static void main(String[] args) throws Exception {
    Map<String, Object> dataMap = new java.util.HashMap<String, Object>();
    dataMap.put("key01", "");
    dataMap.put("key02", 12345);
    dataMap.put("key03", 789.85D);
    dataMap.put("date", new Date());
    Collection<Object> actorIds = new HashSet<Object>();
    actorIds.add("sales01");
    actorIds.add("sales02");
    actorIds.add("sales03");
    actorIds.add("sales04");
    actorIds.add("sales05");
    dataMap.put("actorIds", actorIds.toArray());
    dataMap.put("x_sale_actor_actorIds", actorIds);

    Map<String, Object> xxxMap = new java.util.HashMap<String, Object>();
    xxxMap.put("0", "--------");
    xxxMap.put("1", "?");
    xxxMap.put("2", "");
    xxxMap.put("3", "");

    dataMap.put("trans", xxxMap);

    String str = JsonUtils.encode(dataMap);
    System.out.println(str);//from   ww  w .  j ava2  s.co  m
    Map<?, ?> p = JsonUtils.decode(str);
    System.out.println(p);
    System.out.println(p.get("date").getClass().getName());

    String xx = "{name:\"trans\",nodeType:\"select\",children:{\"1\":\"?\",\"3\":\"\",\"2\":\"\",\"0\":\"--------\"}}";
    Map<String, Object> xMap = JsonUtils.decode(xx);
    System.out.println(xMap);
    Set<Entry<String, Object>> entrySet = xMap.entrySet();
    for (Entry<String, Object> entry : entrySet) {
        String key = entry.getKey();
        Object value = entry.getValue();
        System.out.println(key + " = " + value);
        System.out.println(key.getClass().getName() + "  " + value.getClass().getName());
        if (value instanceof JSONObject) {
            JSONObject json = (JSONObject) value;
            Iterator<?> iter = json.keySet().iterator();
            while (iter.hasNext()) {
                String kk = (String) iter.next();
                System.out.println(kk + " = " + json.get(kk));
            }
        }
    }
}

From source file:com.ourlife.dev.generate.Generate.java

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

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

    // ??????//from  w  w w  .  j  a  v a2 s.c  o  m
    // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className}

    // packageName
    // ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4?
    String packageName = "com.ourlife.dev.modules";

    String moduleName = "biz"; // ???sys
    String subModuleName = ""; // ?????
    String className = "orderLog"; // ??user
    String classAuthor = "ourlife"; // ourlife
    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;

    // ?
    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/ourlife/dev/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/views", "/", separator);
    logger.info("View Path: {}", viewPath);

    // ???
    Configuration cfg = new Configuration();
    cfg.setDirectoryForTemplateLoading(new File(tplPath));

    // ???
    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("tableName",
            model.get("moduleName")
                    + (StringUtils.isNotBlank(subModuleName) ? "_" + StringUtils.lowerCase(subModuleName) : "")
                    + "_" + model.get("className"));
    model.put("urlPrefix",
            model.get("moduleName")
                    + (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) : "")
                    + "/" + model.get("className"));
    model.put("viewPrefix", // StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+
            model.get("urlPrefix"));
    model.put("permissionPrefix",
            model.get("moduleName")
                    + (StringUtils.isNotBlank(subModuleName) ? ":" + StringUtils.lowerCase(subModuleName) : "")
                    + ":" + model.get("className"));

    // ? Entity
    Template template = cfg.getTemplate("entity.ftl");
    String content = FreeMarkers.renderTemplate(template, model);
    String filePath = javaPath + separator + model.get("moduleName") + separator + "entity" + separator
            + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java";
    writeFile(content, filePath);
    logger.info("Entity: {}", 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("Dao: {}", 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("Service: {}", filePath);

    // ? Controller
    template = cfg.getTemplate("controller.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = javaPath + separator + model.get("moduleName") + separator + "web" + separator
            + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Controller.java";
    writeFile(content, filePath);
    logger.info("Controller: {}", filePath);

    // ? ViewForm
    template = cfg.getTemplate("viewForm.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator
            + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
            + model.get("className") + "Form.jsp";
    writeFile(content, filePath);
    logger.info("ViewForm: {}", filePath);

    // ? ViewList
    template = cfg.getTemplate("viewList.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".") + separator
            + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
            + model.get("className") + "List.jsp";
    writeFile(content, filePath);
    logger.info("ViewList: {}", filePath);

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

From source file:com.music.tools.InstrumentExtractor.java

public static void main(String[] args) {
    Map<Integer, String> instrumentNames = new HashMap<>();
    Field[] fields = ProgramChanges.class.getDeclaredFields();
    try {/*from   ww  w  .j  ava2  s. c om*/
        for (Field field : fields) {
            Integer value = (Integer) field.get(null);
            if (!instrumentNames.containsKey(value)) {
                instrumentNames.put(value,
                        StringUtils.capitalize(field.getName().toLowerCase()).replace('_', ' '));
            }
        }
    } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }

    Score score = new Score();
    Read.midi(score, "C:\\Users\\bozho\\Downloads\\7938.midi");
    for (Part part : score.getPartArray()) {
        System.out.println(part.getChannel() + " : " + part.getInstrument() + ": "
                + instrumentNames.get(part.getInstrument()));
    }
}