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:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5GoldLabelEstimator.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    String inputDir = args[0];/*  www  . j a v  a 2s.c o  m*/
    File outputDir = new File(args[1]);

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    // we will process only a subset first
    List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>();

    Collection<File> files = IOHelper.listXmlFiles(new File(inputDir));

    for (File file : files) {
        allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file));
    }

    // collect turkers and csv
    List<String> turkerIDs = extractAndSortTurkerIDs(allArgumentPairs);
    String preparedCSV = prepareCSV(allArgumentPairs, turkerIDs);

    // save CSV and run MACE
    Path tmpDir = Files.createTempDirectory("mace");
    File maceInputFile = new File(tmpDir.toFile(), "input.csv");
    FileUtils.writeStringToFile(maceInputFile, preparedCSV, "utf-8");

    File outputPredictions = new File(tmpDir.toFile(), "predictions.txt");
    File outputCompetence = new File(tmpDir.toFile(), "competence.txt");

    // run MACE
    MACE.main(new String[] { "--iterations", "500", "--threshold", String.valueOf(MACE_THRESHOLD), "--restarts",
            "50", "--outputPredictions", outputPredictions.getAbsolutePath(), "--outputCompetence",
            outputCompetence.getAbsolutePath(), maceInputFile.getAbsolutePath() });

    // read back the predictions and competence
    List<String> predictions = FileUtils.readLines(outputPredictions, "utf-8");

    // check the output
    if (predictions.size() != allArgumentPairs.size()) {
        throw new IllegalStateException("Wrong size of the predicted file; expected " + allArgumentPairs.size()
                + " lines but was " + predictions.size());
    }

    String competenceRaw = FileUtils.readFileToString(outputCompetence, "utf-8");
    String[] competence = competenceRaw.split("\t");
    if (competence.length != turkerIDs.size()) {
        throw new IllegalStateException(
                "Expected " + turkerIDs.size() + " competence number, got " + competence.length);
    }

    // rank turkers by competence
    Map<String, Double> turkerIDCompetenceMap = new TreeMap<>();
    for (int i = 0; i < turkerIDs.size(); i++) {
        turkerIDCompetenceMap.put(turkerIDs.get(i), Double.valueOf(competence[i]));
    }

    // sort by value descending
    Map<String, Double> sortedCompetences = IOHelper.sortByValue(turkerIDCompetenceMap, false);
    System.out.println("Sorted turker competences: " + sortedCompetences);

    // assign the gold label and competence

    for (int i = 0; i < allArgumentPairs.size(); i++) {
        AnnotatedArgumentPair annotatedArgumentPair = allArgumentPairs.get(i);
        String goldLabel = predictions.get(i).trim();

        // might be empty
        if (!goldLabel.isEmpty()) {
            // so far the gold label has format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal
            // strip now only the gold label
            annotatedArgumentPair.setGoldLabel(goldLabel);
        }

        // update turker competence
        for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) {
            String turkID = assignment.getTurkID();

            int turkRank = getTurkerRank(turkID, sortedCompetences);
            assignment.setTurkRank(turkRank);

            double turkCompetence = turkerIDCompetenceMap.get(turkID);
            assignment.setTurkCompetence(turkCompetence);
        }
    }

    // now sort the data back according to their original file name
    Map<String, List<AnnotatedArgumentPair>> fileNameAnnotatedPairsMap = new HashMap<>();
    for (AnnotatedArgumentPair argumentPair : allArgumentPairs) {
        String fileName = IOHelper.createFileName(argumentPair.getDebateMetaData(),
                argumentPair.getArg1().getStance());

        if (!fileNameAnnotatedPairsMap.containsKey(fileName)) {
            fileNameAnnotatedPairsMap.put(fileName, new ArrayList<AnnotatedArgumentPair>());
        }

        fileNameAnnotatedPairsMap.get(fileName).add(argumentPair);
    }

    // and save them to the output file
    for (Map.Entry<String, List<AnnotatedArgumentPair>> entry : fileNameAnnotatedPairsMap.entrySet()) {
        String fileName = entry.getKey();
        List<AnnotatedArgumentPair> argumentPairs = entry.getValue();

        File outputFile = new File(outputDir, fileName);

        // and save all sampled pairs into a XML file
        XStreamTools.toXML(argumentPairs, outputFile);

        System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile);
    }

}

From source file:org.bigtextml.drivers.BigMapTest.java

public static void main(String[] args) {
    /*/*from  w w  w  . ja v a  2  s . c  o  m*/
    ApplicationContext context = 
    new ClassPathXmlApplicationContext(new String[] {"InMemoryDataMining.xml"});
    */
    System.out.println(System.getProperty("InvokedFromSpring"));
    //Map<String,List<Integer>> bm = context.getBean("bigMapTest",BigMap.class);
    Map<String, List<Integer>> bm = ManagementServices.getBigMap("tmCache");
    System.out.println(((BigMap) bm).getCacheName());
    int max = 1000000;

    //bm.setMaxCapacity(1000);

    for (int i = 0; i < max; i++) {
        List<Integer> x = new ArrayList<Integer>();
        for (int j = 0; j < 5; j++) {
            x.add(j);
        }
        x.add(i);
        bm.put(Integer.toString(i), x);
    }
    String key = Integer.toString(max - 1);
    //bm.remove(key);
    for (int i = 0; i < 3; i++) {
        long millis = System.currentTimeMillis();
        System.out.println(bm.get(Integer.toString(500000)));
        System.out.println(System.currentTimeMillis() - millis);
    }
    bm.clear();
}

From source file:gobblin.restli.throttling.LocalStressTest.java

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

    CommandLine cli = StressTestUtils.parseCommandLine(OPTIONS, args);

    int stressorThreads = Integer.parseInt(
            cli.getOptionValue(STRESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_STRESSOR_THREADS)));
    int processorThreads = Integer.parseInt(
            cli.getOptionValue(PROCESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_PROCESSOR_THREADS)));
    int artificialLatency = Integer.parseInt(
            cli.getOptionValue(ARTIFICIAL_LATENCY.getOpt(), Integer.toString(DEFAULT_ARTIFICIAL_LATENCY)));
    long targetQps = Integer.parseInt(cli.getOptionValue(QPS.getOpt(), Integer.toString(DEFAULT_TARGET_QPS)));

    Configuration configuration = new Configuration();
    StressTestUtils.populateConfigFromCli(configuration, cli);

    String resourceLimited = LocalStressTest.class.getSimpleName();

    Map<String, String> configMap = Maps.newHashMap();

    ThrottlingPolicyFactory factory = new ThrottlingPolicyFactory();
    SharedLimiterKey res1key = new SharedLimiterKey(resourceLimited);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null,
            ThrottlingPolicyFactory.POLICY_KEY), QPSPolicy.FACTORY_ALIAS);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, QPSPolicy.QPS),
            Long.toString(targetQps));

    ThrottlingGuiceServletConfig guiceServletConfig = new ThrottlingGuiceServletConfig();
    guiceServletConfig.initialize(ConfigFactory.parseMap(configMap));
    LimiterServerResource limiterServer = guiceServletConfig.getInjector()
            .getInstance(LimiterServerResource.class);

    RateComputingLimiterContainer limiterContainer = new RateComputingLimiterContainer();

    Class<? extends Stressor> stressorClass = configuration.getClass(StressTestUtils.STRESSOR_CLASS,
            StressTestUtils.DEFAULT_STRESSOR_CLASS, Stressor.class);

    ExecutorService executorService = Executors.newFixedThreadPool(stressorThreads);

    SharedResourcesBroker broker = guiceServletConfig.getInjector().getInstance(
            Key.get(SharedResourcesBroker.class, Names.named(LimiterServerResource.BROKER_INJECT_NAME)));
    ThrottlingPolicy policy = (ThrottlingPolicy) broker.getSharedResource(new ThrottlingPolicyFactory(),
            new SharedLimiterKey(resourceLimited));
    ScheduledExecutorService reportingThread = Executors.newSingleThreadScheduledExecutor();
    reportingThread.scheduleAtFixedRate(new Reporter(limiterContainer, policy), 0, 15, TimeUnit.SECONDS);

    Queue<Future<?>> futures = new LinkedList<>();
    MockRequester requester = new MockRequester(limiterServer, artificialLatency, processorThreads);

    requester.start();//  w w  w  . j a  v  a 2 s.  c om
    for (int i = 0; i < stressorThreads; i++) {
        RestliServiceBasedLimiter restliLimiter = RestliServiceBasedLimiter.builder()
                .resourceLimited(resourceLimited).requestSender(requester).serviceIdentifier("stressor" + i)
                .build();

        Stressor stressor = stressorClass.newInstance();
        stressor.configure(configuration);
        futures.add(executorService
                .submit(new StressorRunner(limiterContainer.decorateLimiter(restliLimiter), stressor)));
    }
    int stressorFailures = 0;
    for (Future<?> future : futures) {
        try {
            future.get();
        } catch (ExecutionException ee) {
            stressorFailures++;
        }
    }
    requester.stop();

    executorService.shutdownNow();

    if (stressorFailures > 0) {
        log.error("There were " + stressorFailures + " failed stressor threads.");
    }
    System.exit(stressorFailures);
}

From source file:com.wealdtech.gcm.GCMClient.java

public static void main(String[] args) {
    final String userName = "your_sender_id" + "@gcm.googleapis.com";
    final String password = "your_api_key";

    final GCMClient ccsClient = new GCMClient();

    try {/*  ww w.ja  va  2 s.c o m*/
        ccsClient.connect(userName, password);
    } catch (XMPPException e) {
        e.printStackTrace();
    }

    // Send a sample hello downstream message to a device.
    final String toRegId = "RegistrationIdOfTheTargetDevice";
    final String messageId = ccsClient.getRandomMessageId();
    final Map<String, String> payload = new HashMap<>();
    payload.put("Hello", "World");
    payload.put("CCS", "Dummy Message");
    payload.put("EmbeddedMessageId", messageId);
    final String collapseKey = "sample";
    final Long timeToLive = 10000L;
    final Boolean delayWhileIdle = true;
    ccsClient.send(createJsonMessage(toRegId, messageId, payload, collapseKey, timeToLive, delayWhileIdle));
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step2FillWithRetrievedResults.java

public static void main(String[] args) throws IOException {
    // input dir - list of xml query containers
    File inputDir = new File(args[0]);

    // retrieved results from Technion
    // ltr-50queries-100docs.txt
    File ltr = new File(args[1]);

    // output dir
    File outputDir = new File(args[2]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();/*from w  ww . ja  va 2s.  c o m*/
    }

    // load the query containers first (into map: id + container)
    Map<String, QueryResultContainer> queryResults = new HashMap<>();
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        System.out.println(f);
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        queryResults.put(queryResultContainer.qID, queryResultContainer);
    }

    // iterate over IR results
    for (String line : FileUtils.readLines(ltr)) {
        String[] split = line.split("\\s+");
        Integer origQueryId = Integer.valueOf(split[0]);
        String clueWebID = split[2];
        Integer rank = Integer.valueOf(split[3]);
        double score = Double.valueOf(split[4]);
        String additionalInfo = split[5];

        // get the container for this result
        QueryResultContainer container = queryResults.get(origQueryId.toString());

        if (container != null) {
            // add new result
            QueryResultContainer.SingleRankedResult result = new QueryResultContainer.SingleRankedResult();
            result.clueWebID = clueWebID;
            result.rank = rank;
            result.score = score;
            result.additionalInfo = additionalInfo;

            if (container.rankedResults == null) {
                container.rankedResults = new ArrayList<>();
            }
            container.rankedResults.add(result);
        }
    }

    // save all containers to the output dir
    for (QueryResultContainer queryResultContainer : queryResults.values()) {
        File outputFile = new File(outputDir, queryResultContainer.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }
}

From source file:org.alex73.osm.validators.vioski.Export.java

public static void main(String[] args) throws Exception {
    RehijonyLoad.load(Env.readProperty("dav") + "/Rehijony.xml");

    osm = new Belarus();

    String dav = Env.readProperty("dav") + "/Nazvy_nasielenych_punktau.csv";
    List<Miesta> daviednik = new CSV('\t').readCSV(dav, Miesta.class);

    Map<String, List<Mdav>> rajony = new TreeMap<>();
    for (Miesta m : daviednik) {
        String r = m.rajon.startsWith("<") ? m.rajon : m.rajon + " ";
        List<Mdav> list = rajony.get(r);
        if (list == null) {
            list = new ArrayList<>();
            rajony.put(r, list);
        }/*from   www .java2  s .c  om*/
        Mdav mm = new Mdav();
        mm.osmID = m.osmID;
        mm.ss = m.sielsaviet;
        mm.why = m.osmComment;
        mm.nameBe = m.nazvaNoStress;
        mm.nameRu = m.ras;
        mm.varyjantBe = m.varyjantyBel;
        mm.varyjantRu = m.rasUsedAsOld;
        list.add(mm);
    }

    placeTag = osm.getTagsPack().getTagCode("place");

    osm.byTag("place",
            o -> o.isNode() && !o.getTag(placeTag).equals("island") && !o.getTag(placeTag).equals("islet"),
            o -> processNode((IOsmNode) o));

    String outDir = Env.readProperty("out.dir");
    File foutDir = new File(outDir + "/vioski");
    foutDir.mkdirs();

    Map<String, String> padzielo = new TreeMap<>();
    for (Voblasc v : RehijonyLoad.kraina.getVoblasc()) {
        for (Rajon r : v.getRajon()) {
            padzielo.put(r.getNameBe(), osm.getObject(r.getOsmID()).getTag("name", osm));
        }
    }

    ObjectMapper om = new ObjectMapper();
    String o = "var data={};\n";
    o += "data.dav=" + om.writeValueAsString(rajony) + "\n";
    o += "data.map=" + om.writeValueAsString(map) + "\n";
    o += "data.padziel=" + om.writeValueAsString(padzielo) + "\n";
    FileUtils.writeStringToFile(new File(outDir + "/vioski/data.js"), o);
    FileUtils.copyFileToDirectory(new File("vioski/control.js"), foutDir);
    FileUtils.copyFileToDirectory(new File("vioski/vioski.html"), foutDir);
}

From source file:cz.hobrasoft.pdfmu.Main.java

/**
 * The main entry point of PDFMU/*from  w  w w. j a  va 2s  . co  m*/
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int exitStatus = 0; // Default: 0 (normal termination)

    // Create a map of operations
    Map<String, Operation> operations = new LinkedHashMap<>();
    operations.put("inspect", OperationInspect.getInstance());
    operations.put("update-version", OperationVersionSet.getInstance());
    operations.put("update-properties", OperationMetadataSet.getInstance());
    operations.put("attach", OperationAttach.getInstance());
    operations.put("sign", OperationSignatureAdd.getInstance());

    // Create a command line argument parser
    ArgumentParser parser = createFullParser(operations);

    // Parse command line arguments
    Namespace namespace = null;
    try {
        // If help is requested,
        // `parseArgs` prints help message and throws `ArgumentParserException`
        // (so `namespace` stays null).
        // If insufficient or invalid `args` are given,
        // `parseArgs` throws `ArgumentParserException`.
        namespace = parser.parseArgs(args);
    } catch (HelpScreenException e) {
        parser.handleError(e); // Do nothing
    } catch (UnrecognizedCommandException e) {
        exitStatus = PARSER_UNRECOGNIZED_COMMAND.getCode();
        parser.handleError(e); // Print the error in human-readable format
    } catch (UnrecognizedArgumentException e) {
        exitStatus = PARSER_UNRECOGNIZED_ARGUMENT.getCode();
        parser.handleError(e); // Print the error in human-readable format
    } catch (ArgumentParserException ape) {
        OperationException oe = apeToOe(ape);
        exitStatus = oe.getCode();
        // We could also write `oe` as a JSON document,
        // but we do not know whether JSON output was requested,
        // so we use the text output (default).

        parser.handleError(ape); // Print the error in human-readable format
    }

    if (namespace == null) {
        System.exit(exitStatus);
    }

    assert exitStatus == 0;

    // Handle command line arguments
    WritingMapper wm = null;

    // Extract operation name
    String operationName = namespace.getString("operation");
    assert operationName != null; // The argument "operation" is a sub-command, thus it is required

    // Select the operation from `operations`
    assert operations.containsKey(operationName); // Only supported operation names are allowed
    Operation operation = operations.get(operationName);
    assert operation != null;

    // Choose the output format
    String outputFormat = namespace.getString("output_format");
    switch (outputFormat) {
    case "json":
        // Disable loggers
        disableLoggers();
        // Initialize the JSON serializer
        wm = new WritingMapper();
        operation.setWritingMapper(wm); // Configure the operation
        break;
    case "text":
        // Initialize the text output
        TextOutput to = new TextOutput(System.err); // Bind to `System.err`
        operation.setTextOutput(to); // Configure the operation
        break;
    default:
        assert false; // The option has limited choices
    }

    // Execute the operation
    try {
        operation.execute(namespace);
    } catch (OperationException ex) {
        exitStatus = ex.getCode();

        // Log the exception
        logger.severe(ex.getLocalizedMessage());
        Throwable cause = ex.getCause();
        if (cause != null && cause.getMessage() != null) {
            logger.severe(cause.getLocalizedMessage());
        }

        if (wm != null) {
            // JSON output is enabled
            ex.writeInWritingMapper(wm);
        }
    }
    System.exit(exitStatus);
}

From source file:com.sccl.attech.generate.Generate.java

/**
 * The main method./*from w w w  . j a v a  2s.co  m*/
 * 
 * @param args the arguments
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {

    // ==========  ?? ====================1412914

    // ??????
    // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className}

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

    String moduleName = "mobil"; // ???sys
    String subModuleName = ""; // ????? 
    String className = "updateApp"; // ??user
    List<GenerateField> fields = Lists.newArrayList();
    fields.add(new GenerateField("name", "??"));
    fields.add(new GenerateField("type", ""));
    fields.add(new GenerateField("version", ""));
    fields.add(new GenerateField("path", ""));

    String classAuthor = "zzz"; // zhaozz
    String functionName = "App?"; // ??

    // ???
    //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/sccl/attech/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 + "/WebRoot/pages", "/", separator);
    logger.info("View Path: {}", viewPath);
    String resPath = StringUtils.replace(projectPath + "/WebRoot/assets/js", "/", separator);
    logger.info("Res Path: {}", resPath);

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

    // ???
    Map<String, Object> model = Maps.newHashMap();
    model.put("packageName", StringUtils.lowerCase(packageName));
    model.put("moduleName", StringUtils.lowerCase(moduleName));
    model.put("fields", fields);
    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
    createJavaFile(subModuleName, separator, javaPath, cfg, model);

    // ? 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.html";
    writeFile(content, filePath);
    logger.info("ViewForm: {}", filePath);

    // ? ViewFormJs
    template = cfg.getTemplate("viewFormJs.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = resPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".")
            + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
            + model.get("className") + "FormCtrl.js";
    writeFile(content, filePath);
    logger.info("ViewFormJs: {}", 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.html";
    writeFile(content, filePath);
    logger.info("ViewList: {}", filePath);

    // ? ViewListJs
    template = cfg.getTemplate("viewListJs.ftl");
    content = FreeMarkers.renderTemplate(template, model);
    filePath = resPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".")
            + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
            + model.get("className") + "ListCtrl.js";
    writeFile(content, filePath);
    logger.info("ViewList: {}", filePath);

    // ? ??sql
    template = cfg.getTemplate("sql.ftl");
    model.put("uid", IdGen.uuid());
    model.put("uid1", IdGen.uuid());
    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") + ".sql";
    writeFile(content, filePath);
    logger.info("ViewList: {}", filePath);

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

From source file:Tester.java

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

    final String filename = "fcl/generated.fcl";
    final String[] linguisticTermNames = { "muuuuuuypeque", "muypeque", "peque", "normal", "grande",
            "muygrande", "muuuuygrande" };
    final RegionDistributionInfo[] linguisticTerms = new RegionDistributionInfo[linguisticTermNames.length];
    for (int i = 0; i < linguisticTermNames.length; ++i)
        linguisticTerms[i] = new RegionDistributionInfo(linguisticTermNames[i],
                1.0 / (linguisticTerms.length - 1));

    final boolean database = true;

    System.out.println("Creating dataset " + System.currentTimeMillis());

    final MobileDevices mobileDevices = createDataset(database);
    System.out.println(mobileDevices.getMobileDevices().size());

    final Map<DeviceCapability, Variable> inputVariables = new HashMap<DeviceCapability, Variable>();

    final Variable realSizeVar = new Variable("real_size", Arrays.asList(linguisticTerms));
    final Variable resoSizeVar = new Variable("reso_size", Arrays.asList(linguisticTerms));

    inputVariables.put(DeviceCapability.real_size, realSizeVar);
    inputVariables.put(DeviceCapability.reso_size, resoSizeVar);

    final Map<String, Variable> outputVariables = new HashMap<String, Variable>();
    outputVariables.put("hey", new Variable("hey", Arrays.asList(new RegionDistributionInfo("ho", 1.0 / 2),
            new RegionDistributionInfo("lets", 1.0 / 2), new RegionDistributionInfo("go", 1.0 / 2))));
    final String rules = "// the rules \n";

    final FclCreator creator = new FclCreator();
    System.out.println("Creating rule file " + System.currentTimeMillis());

    final WarningStore warningStore = new WarningStore();
    final String fileContent = creator.createRuleFile("prueba", inputVariables,
            new HashMap<UserCapability, Variable>(), outputVariables, mobileDevices, rules, warningStore);
    warningStore.print();/*w w  w.j  a  v a2s . c  om*/
    final File file = new File(filename);
    file.createNewFile();
    System.out.println("Dumping the rule file " + System.currentTimeMillis());
    FileUtils.writeStringToFile(file, fileContent);

    System.out.println("Processing the file " + System.currentTimeMillis());
    final FIS fis = FIS.load(filename, true);
    net.sourceforge.jFuzzyLogic.rule.Variable realSize = fis.getVariable("real_size");

    JFreeChart theChart = realSize.chart(false);
    @SuppressWarnings("unused")
    BufferedImage img = theChart.createBufferedImage(1000, 1000);

    /*
    FileOutputStream fos = new FileOutputStream("imagen.png");
    ImageEncoder myEncoder = ImageEncoderFactory.newInstance("png");
    myEncoder.encode(img, fos);
    fos.flush();
    fos.close();
    */

    fis.chart();

}

From source file:com.akana.demo.freemarker.templatetester.App.java

public static void main(String[] args) {

    final Options options = new Options();

    @SuppressWarnings("static-access")
    Option optionContentType = OptionBuilder.withArgName("content-type").hasArg()
            .withDescription("content type of model").create("content");
    @SuppressWarnings("static-access")
    Option optionUrlPath = OptionBuilder.withArgName("httpRequestLine").hasArg()
            .withDescription("url path and parameters in HTTP Request Line format").create("url");
    @SuppressWarnings("static-access")
    Option optionRootMessageName = OptionBuilder.withArgName("messageName").hasArg()
            .withDescription("root data object name, defaults to 'message'").create("root");
    @SuppressWarnings("static-access")
    Option optionAdditionalMessages = OptionBuilder.withArgName("dataModelPaths")
            .hasArgs(Option.UNLIMITED_VALUES).withDescription("additional message object data sources")
            .create("messages");
    @SuppressWarnings("static-access")
    Option optionDebugMessages = OptionBuilder.hasArg(false)
            .withDescription("Shows debug information about template processing").create("debug");

    Option optionHelp = new Option("help", "print this message");

    options.addOption(optionHelp);//from w ww .  j a  va 2  s  .c o m
    options.addOption(optionContentType);
    options.addOption(optionUrlPath);
    options.addOption(optionRootMessageName);
    options.addOption(optionAdditionalMessages);
    options.addOption(optionDebugMessages);

    CommandLineParser parser = new DefaultParser();

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

        // Check for help flag
        if (cmd.hasOption("help")) {
            showHelp(options);
            return;
        }

        String[] remainingArguments = cmd.getArgs();
        if (remainingArguments.length < 2) {
            showHelp(options);
            return;
        }
        String ftlPath, dataPath = "none";

        ftlPath = remainingArguments[0];
        dataPath = remainingArguments[1];

        String contentType = "text/xml";
        // Discover content type from file extension
        String ext = FilenameUtils.getExtension(dataPath);
        if (ext.equals("json")) {
            contentType = "json";
        } else if (ext.equals("txt")) {
            contentType = "txt";
        }
        // Override discovered content type
        if (cmd.hasOption("content")) {
            contentType = cmd.getOptionValue("content");
        }
        // Root data model name
        String rootMessageName = "message";
        if (cmd.hasOption("root")) {
            rootMessageName = cmd.getOptionValue("root");
        }
        // Additional data models
        String[] additionalModels = new String[0];
        if (cmd.hasOption("messages")) {
            additionalModels = cmd.getOptionValues("messages");
        }
        // Debug Info
        if (cmd.hasOption("debug")) {
            System.out.println(" Processing ftl   : " + ftlPath);
            System.out.println("   with data model: " + dataPath);
            System.out.println(" with content-type: " + contentType);
            System.out.println(" data model object: " + rootMessageName);
            if (cmd.hasOption("messages")) {
                System.out.println("additional models: " + additionalModels.length);
            }
        }

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setDirectoryForTemplateLoading(new File("."));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        /* Create the primary data-model */
        Map<String, Object> message = new HashMap<String, Object>();
        if (contentType.contains("json") || contentType.contains("txt")) {
            message.put("contentAsString",
                    FileUtils.readFileToString(new File(dataPath), StandardCharsets.UTF_8));
        } else {
            message.put("contentAsXml", freemarker.ext.dom.NodeModel.parse(new File(dataPath)));
        }

        if (cmd.hasOption("url")) {
            message.put("getProperty", new AkanaGetProperty(cmd.getOptionValue("url")));
        }

        Map<String, Object> root = new HashMap<String, Object>();
        root.put(rootMessageName, message);
        if (additionalModels.length > 0) {
            for (int i = 0; i < additionalModels.length; i++) {
                Map<String, Object> m = createMessageFromFile(additionalModels[i], contentType);
                root.put("message" + i, m);
            }
        }

        /* Get the template (uses cache internally) */
        Template temp = cfg.getTemplate(ftlPath);

        /* Merge data-model with template */
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);

    } catch (ParseException e) {
        showHelp(options);
        System.exit(1);
    } catch (IOException e) {
        System.out.println("Unable to parse ftl.");
        e.printStackTrace();
    } catch (SAXException e) {
        System.out.println("XML parsing issue.");
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        System.out.println("Unable to configure parser.");
        e.printStackTrace();
    } catch (TemplateException e) {
        System.out.println("Unable to parse template.");
        e.printStackTrace();
    }

}