Example usage for java.util HashMap HashMap

List of usage examples for java.util HashMap HashMap

Introduction

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

Prototype

public HashMap() 

Source Link

Document

Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).

Usage

From source file:net.kolola.msgparsercli.MsgParseCLI.java

public static void main(String[] args) {

    // Parse options

    OptionParser parser = new OptionParser("f:a:bi?*");
    OptionSet options = parser.parse(args);

    // Get the filename
    if (!options.has("f")) {
        System.err.print("Specify a msg file with the -f option");
        System.exit(0);/*  ww w.  ja  va  2  s . c om*/
    }

    File file = new File((String) options.valueOf("f"));

    MsgParser msgp = new MsgParser();
    Message msg = null;

    try {
        msg = msgp.parseMsg(file);
    } catch (UnsupportedOperationException | IOException e) {
        System.err.print("File does not exist or is not a valid msg file");
        //e.printStackTrace();
        System.exit(1);
    }

    // Show info (as JSON)
    if (options.has("i")) {
        Map<String, Object> data = new HashMap<String, Object>();

        String date;

        try {
            Date st = msg.getClientSubmitTime();
            date = st.toString();
        } catch (Exception g) {
            try {
                date = msg.getDate().toString();
            } catch (Exception e) {
                date = "[UNAVAILABLE]";
            }
        }

        data.put("date", date);
        data.put("subject", msg.getSubject());
        data.put("from", "\"" + msg.getFromName() + "\" <" + msg.getFromEmail() + ">");
        data.put("to", "\"" + msg.getToRecipient().toString());

        String cc = "";
        for (RecipientEntry r : msg.getCcRecipients()) {
            if (cc.length() > 0)
                cc.concat("; ");

            cc.concat(r.toString());
        }

        data.put("cc", cc);

        data.put("body_html", msg.getBodyHTML());
        data.put("body_rtf", msg.getBodyRTF());
        data.put("body_text", msg.getBodyText());

        // Attachments
        List<Map<String, String>> atts = new ArrayList<Map<String, String>>();
        for (Attachment a : msg.getAttachments()) {
            HashMap<String, String> info = new HashMap<String, String>();

            if (a instanceof FileAttachment) {
                FileAttachment fa = (FileAttachment) a;

                info.put("type", "file");
                info.put("filename", fa.getFilename());
                info.put("size", Long.toString(fa.getSize()));
            } else {
                info.put("type", "message");
            }

            atts.add(info);
        }

        data.put("attachments", atts);

        JSONObject json = new JSONObject(data);

        try {
            System.out.print(json.toString(4));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // OR return an attachment in BASE64
    else if (options.has("a")) {
        Integer anum = Integer.parseInt((String) options.valueOf("a"));

        Encoder b64 = Base64.getEncoder();

        List<Attachment> atts = msg.getAttachments();

        if (atts.size() <= anum) {
            System.out.print("Attachment " + anum.toString() + " does not exist");
        }

        Attachment att = atts.get(anum);

        if (att instanceof FileAttachment) {
            FileAttachment fatt = (FileAttachment) att;
            System.out.print(b64.encodeToString(fatt.getData()));
        } else {
            System.err.print("Attachment " + anum.toString() + " is a message - That's not implemented yet :(");
        }
    }
    // OR print the message body
    else if (options.has("b")) {
        System.out.print(msg.getConvertedBodyHTML());
    } else {
        System.err.print(
                "Specify either -i to return msg information or -a <num> to print an attachment as a BASE64 string");
    }

}

From source file:org.hcmut.emr.SessionBuilder.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    try (BufferedReader br = new BufferedReader(
            new FileReader("/home/sinhlk/myspace/emr/src/main/resources/patern"))) {
        ObjectMapper jsonMapper = new ObjectMapper();
        String line = br.readLine();
        Map<String, String> result = new HashMap<String, String>();
        List<NameValuePair> list = new ArrayList<>();

        while (line != null) {
            if (line != null && line != "") {
                list.add(new BasicNameValuePair(line.trim().toLowerCase(), SessionBuilder.buildValue(line)));
                result.put(line.trim().toLowerCase(), SessionBuilder.buildValue(line));
                line = br.readLine();//  w  w w .  j  a v  a 2  s. c om
            }
        }
        System.out.println(jsonMapper.writeValueAsString(list));
        File file = new File("/home/sinhlk/myspace/emr/src/main/resources/session.js");
        jsonMapper.writeValue(file, list);
    }

}

From source file:evaluation.evaluation1VMPolicyGeneration.java

public static void main(String[] args) {

    int VMNumber = 5;
    int attributeNumber = 20;

    JSONObject obj = new JSONObject();
    obj.put("name", "clientTemplate");
    obj.put("context", "VM-deployment");
    //obj.put("Context", new Integer);

    HashMap serviceRequirement = new HashMap();

    HashMap serviceDescription = new HashMap();
    serviceRequirement.put("VM1_volume", "1_GB");
    serviceDescription.put("VM1_purpose", "dev");
    serviceDescription.put("VM1_data", "private");
    serviceDescription.put("VM1_application", "internal");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM1_other" + j, "other");
    }//w w w .  ja  va 2s  .c o  m

    serviceRequirement.put("VM2_volume", "2_GB");
    serviceDescription.put("VM2_purpose", "prod");
    serviceDescription.put("VM2_data", "public");
    serviceDescription.put("VM2_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM2_other" + j, "other");
    }

    serviceRequirement.put("VM3_volume", "1_GB");
    serviceDescription.put("VM3_purpose", "test");
    serviceDescription.put("VM3_data", "public");
    serviceDescription.put("VM3_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM3_other" + j, "other");
    }

    serviceRequirement.put("VM4_volume", "12_GB");
    serviceDescription.put("VM4_purpose", "prod");
    serviceDescription.put("VM4_data", "public");
    serviceDescription.put("VM4_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM4_other" + j, "other");
    }

    for (int i = 5; i < VMNumber; i++) {
        serviceRequirement.put("VM" + i + "_volume", "20_GB");
        serviceDescription.put("VM" + i + "_purpose", "prod");
        serviceDescription.put("VM" + i + "_data", "public");
        serviceDescription.put("VM" + i + "_application", "business");
        for (int j = 5; j < attributeNumber; j++) {
            serviceDescription.put("VM" + i + "_other" + j, "other");
        }

    }

    obj.put("serviceRequirement", serviceRequirement);
    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("VM1_availability", "more_97_percentage");
    gauranteeTerm.put("VM2_availability", "more_99_percentage");
    gauranteeTerm.put("VM3_availability", "more_95_percentage");
    gauranteeTerm.put("VM4_availability", "more_99_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    HashMap host_rule1 = new HashMap();
    HashMap VM_rule1 = new HashMap();
    host_rule1.put("certificate", "true");
    VM_rule1.put("purpose", "dev");

    ArrayList rule1 = new ArrayList();
    rule1.add("permission");
    rule1.add(host_rule1);
    rule1.add(VM_rule1);

    HashMap host_rule1_2 = new HashMap();
    HashMap VM_rule1_2 = new HashMap();
    host_rule1_2.put("certificate", "true");
    VM_rule1_2.put("purpose", "prod");

    ArrayList rule1_2 = new ArrayList();
    rule1_2.add("permission");
    rule1_2.add(host_rule1_2);
    rule1_2.add(VM_rule1_2);

    HashMap host_rule1_3 = new HashMap();
    HashMap VM_rule1_3 = new HashMap();
    host_rule1_3.put("certificate", "true");
    VM_rule1_3.put("purpose", "test");

    ArrayList rule1_3 = new ArrayList();
    rule1_3.add("permission");
    rule1_3.add(host_rule1_3);
    rule1_3.add(VM_rule1_3);

    HashMap host_rule2 = new HashMap();
    HashMap VM_rule2 = new HashMap();
    host_rule2.put("location", "France");
    VM_rule2.put("ID", "VM2");

    ArrayList rule2 = new ArrayList();
    rule2.add("permission");
    rule2.add(host_rule2);
    rule2.add(VM_rule2);

    HashMap host_rule2_1 = new HashMap();
    HashMap VM_rule2_1 = new HashMap();
    host_rule2_1.put("location", "UK");
    VM_rule2_1.put("ID", "VM2");

    ArrayList rule2_1 = new ArrayList();
    rule2_1.add("permission");
    rule2_1.add(host_rule2_1);
    rule2_1.add(VM_rule2_1);

    HashMap host_rule3 = new HashMap();
    HashMap VM_rule3 = new HashMap();
    host_rule3.put("location", "France");
    VM_rule3.put("application", "business");

    ArrayList rule3 = new ArrayList();
    rule3.add("permission");
    rule3.add(host_rule3);
    rule3.add(VM_rule3);

    HashMap host_rule3_1 = new HashMap();
    HashMap VM_rule3_1 = new HashMap();
    host_rule3_1.put("location", "UK");
    VM_rule3_1.put("application", "business");

    ArrayList rule3_1 = new ArrayList();
    rule3_1.add("permission");
    rule3_1.add(host_rule3_1);
    rule3_1.add(VM_rule3_1);

    HashMap VMSeperation_rule_1_1 = new HashMap();
    HashMap VMSeperation_rule_1_2 = new HashMap();

    VMSeperation_rule_1_1.put("ID", "VM1");
    VMSeperation_rule_1_2.put("ID", "VM3");

    ArrayList rule4 = new ArrayList();
    rule4.add("separation");
    rule4.add(VMSeperation_rule_1_1);
    rule4.add(VMSeperation_rule_1_2);

    ArrayList policyInConstraint1 = new ArrayList();
    policyInConstraint1.add(rule1);
    policyInConstraint1.add(rule1_2);
    policyInConstraint1.add(rule1_3);

    policyInConstraint1.add(rule2);
    policyInConstraint1.add(rule2_1);

    policyInConstraint1.add(rule3);
    policyInConstraint1.add(rule3_1);

    policyInConstraint1.add(rule4);

    ArrayList creationConstraint1 = new ArrayList();
    creationConstraint1.add("RP4");
    creationConstraint1.add("true");
    creationConstraint1.add("true");
    creationConstraint1.add(policyInConstraint1);

    ArrayList totalConstraint = new ArrayList();
    totalConstraint.add(creationConstraint1);

    obj.put("creationConstraint", totalConstraint);

    try {

        FileWriter file = new FileWriter("confClient" + File.separator + "test3.json");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(obj);

    /*
            
    JSONParser parser = new JSONParser();
            
    try {
            
    Object obj2 = parser.parse(new FileReader("test2.json"));
            
    JSONObject jsonObject = (JSONObject) obj2;
            
        HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription");
                 
        method.printHashMap(serviceDescription2);
                
                
        HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm");
                 
        method.printHashMap(gauranteeTerm2);
                
                
                
        ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint");
                
        method.printArrayList(creationConstraint);
            
            
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParseException e) {
    e.printStackTrace();
    }
            
            
            
            
            
    */

}

From source file:eu.trentorise.game.Application.java

public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(AppConfig.class);
    ctx.register(MongoConfig.class);
    ctx.refresh();/*from   ww  w. ja  va 2s.  c  o  m*/
    Workflow gameWorkflow = ctx.getBean("workflow", Workflow.class);

    /**
     * input map known fields
     * 
     * bikeDistance walkDistance busDistance trainDistance carDistance ->
     * double , distances must be expressed in km
     * 
     * bikeSharing -> boolean
     * 
     * park -> park id
     * 
     * sustainable -> boolean
     * 
     * p+r -> boolean
     * 
     * 
     * 
     */

    Map<String, Object> data = new HashMap<String, Object>();
    // data.put("bikeDistance", 8.43);
    // data.put("walkDistance", 3.100);
    // data.put("carDistance", 0.00);
    // data.put("busDistance", 0.00);
    // data.put("bikesharing", true);
    // data.put("sustainable", true);
    // data.put("p+r", true);
    // data.put("park", "MANIFATTURA");
    gameWorkflow.apply("demo-game", "save_itinerary", "1", data, null);
}

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();/*ww w  . j av  a2 s . com*/

    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:com.joliciel.jochre.yiddish.JochreYiddish.java

public static void main(String[] args) throws Exception {
    Map<String, String> argMap = new HashMap<String, String>();

    for (String arg : args) {
        int equalsPos = arg.indexOf('=');
        String argName = arg.substring(0, equalsPos);
        String argValue = arg.substring(equalsPos + 1);
        argMap.put(argName, argValue);//from  ww  w . j  av a 2s.c  o  m
    }

    JochreYiddish jochre = new JochreYiddish();
    jochre.execute(argMap);
}

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();/*www.j  av a2  s.  co 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:edu.cuhk.hccl.evaluation.EvaluationApp.java

public static void main(String[] args) throws IOException, TasteException {
    File realFile = new File(args[0]);
    File estimateFile = new File(args[1]);

    // Build real-rating map
    Map<String, long[]> realMap = buildRatingMap(realFile);

    // Build estimate-rating map
    Map<String, long[]> estimateMap = buildRatingMap(estimateFile);

    // Compare realMap with estimateMap
    Map<Integer, List<Double>> realList = new HashMap<Integer, List<Double>>();
    Map<Integer, List<Double>> estimateList = new HashMap<Integer, List<Double>>();

    // Use set to store non-duplicate pairs only
    Set<String> noRatingList = new HashSet<String>();

    for (String pair : realMap.keySet()) {
        long[] realRatings = realMap.get(pair);
        long[] estimateRatings = estimateMap.get(pair);

        if (realRatings == null || estimateRatings == null)
            continue;

        for (int i = 0; i < realRatings.length; i++) {
            long real = realRatings[i];
            long estimate = estimateRatings[i];

            // continue if the aspect rating can not be estimated due to incomplete reviews
            if (estimate <= 0) {
                noRatingList.add(pair.replace("@", "\t"));
                continue;
            }/*from  ww  w  .  java2s .c  o m*/

            if (real > 0 && estimate > 0) {
                if (!realList.containsKey(i))
                    realList.put(i, new ArrayList<Double>());

                realList.get(i).add((double) real);

                if (!estimateList.containsKey(i))
                    estimateList.put(i, new ArrayList<Double>());

                estimateList.get(i).add((double) estimate);
            }
        }
    }

    System.out.println("[INFO] RMSE, MAE for estimate ratings: ");
    System.out.println("------------------------------");
    System.out.println("Index \t RMSE \t MAE");
    for (int i = 1; i < 6; i++) {
        double rmse = Metric.computeRMSE(realList.get(i), estimateList.get(i));
        double mae = Metric.computeMAE(realList.get(i), estimateList.get(i));

        System.out.printf("%d \t %.3f \t %.3f \n", i, rmse, mae);
    }

    System.out.println("------------------------------");

    if (noRatingList.size() > 0) {
        String noRatingFileName = "evaluation-no-ratings.txt";
        FileUtils.writeLines(new File(noRatingFileName), noRatingList, false);

        System.out.println("[INFO] User-item pairs with no ratings are saved in file: " + noRatingFileName);
    } else {
        System.out.println("[INFO] All user-item pairs have ratings.");
    }
}

From source file:net.java.sen.tools.MkCompoundTable.java

/**
 * Build compound word table.//from  w w  w .  ja v  a 2 s.com
 */
public static void main(String args[]) {
    ResourceBundle rb = ResourceBundle.getBundle("dictionary");
    int pos_start = Integer.parseInt(rb.getString("pos_start"));
    int pos_size = Integer.parseInt(rb.getString("pos_size"));

    try {
        log.info("reading compound word information ... ");
        HashMap compoundTable = new HashMap();

        log.info("load dic: " + rb.getString("compound_word_file"));
        BufferedReader dicStream = new BufferedReader(new InputStreamReader(
                new FileInputStream(rb.getString("compound_word_file")), rb.getString("dic.charset")));

        String t;
        int line = 0;

        StringBuffer pos_b = new StringBuffer();
        while ((t = dicStream.readLine()) != null) {
            CSVParser parser = new CSVParser(t);
            String csv[] = parser.nextTokens();
            if (csv.length < (pos_size + pos_start)) {
                throw new RuntimeException("format error:" + line);
            }

            pos_b.setLength(0);
            for (int i = pos_start; i < (pos_start + pos_size - 1); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }

            pos_b.append(csv[pos_start + pos_size - 1]);
            pos_b.append(',');

            for (int i = pos_start + pos_size; i < (csv.length - 2); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }
            pos_b.append(csv[csv.length - 2]);
            compoundTable.put(pos_b.toString(), csv[csv.length - 1]);
        }
        dicStream.close();
        log.info("done.");
        log.info("writing compound word table ... ");
        ObjectOutputStream os = new ObjectOutputStream(
                new FileOutputStream(rb.getString("compound_word_table")));
        os.writeObject(compoundTable);
        os.close();
        log.info("done.");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:eu.annocultor.converters.geonames.GeonamesDumpToRdf.java

public static void main(String[] args) throws Exception {
    File root = new File("input_source");

    // load country-continent match
    countryToContinent/*www  . j  a v a 2 s. com*/
            .load((new GeonamesDumpToRdf()).getClass().getResourceAsStream("/country-to-continent.properties"));

    // creating files
    Map<String, BufferedWriter> files = new HashMap<String, BufferedWriter>();
    Map<String, Boolean> started = new HashMap<String, Boolean>();

    for (Object string : countryToContinent.keySet()) {
        String continent = countryToContinent.getProperty(string.toString());
        File dir = new File(root, continent);
        if (!dir.exists()) {
            dir.mkdir();
        }
        files.put(string.toString(), new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(new File(root, continent + "/" + string + ".rdf")), "UTF-8")));
        System.out.println(continent + "/" + string + ".rdf");
        started.put(string.toString(), false);
    }

    System.out.println(started);

    Pattern countryPattern = Pattern
            .compile("<inCountry rdf\\:resource\\=\"http\\://www\\.geonames\\.org/countries/\\#(\\w\\w)\"/>");
    long counter = 0;
    LineIterator it = FileUtils.lineIterator(new File(root, "all-geonames-rdf.txt"), "UTF-8");
    try {
        while (it.hasNext()) {
            String text = it.nextLine();
            if (text.startsWith("http://sws.geonames"))
                continue;

            // progress
            counter++;
            if (counter % 100000 == 0) {
                System.out.print("*");
            }
            //         System.out.println(counter);
            // get country
            String country = null;
            Matcher matcher = countryPattern.matcher(text);
            if (matcher.find()) {
                country = matcher.group(1);
            }
            //         System.out.println(country);
            if (country == null)
                country = "null";
            text = text.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><rdf:RDF",
                    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><rdf:RDF");
            if (started.get(country) == null)
                throw new Exception("Unknow country " + country);
            if (started.get(country).booleanValue()) {
                // remove RDF opening
                text = text.substring(text.indexOf("<rdf:RDF "));
                text = text.substring(text.indexOf(">") + 1);
            }
            // remove RDF ending
            text = text.substring(0, text.indexOf("</rdf:RDF>"));
            files.get(country).append(text + "\n");
            if (!started.get(country).booleanValue()) {
                // System.out.println("Started with country " + country);
            }
            started.put(country, true);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }

    for (Object string : countryToContinent.keySet()) {
        boolean hasStarted = started.get(string.toString()).booleanValue();
        if (hasStarted) {
            BufferedWriter bf = files.get(string.toString());
            bf.append("</rdf:RDF>");
            bf.flush();
            bf.close();
        }
    }
    return;
}