Example usage for java.util Map replace

List of usage examples for java.util Map replace

Introduction

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

Prototype

default V replace(K key, V value) 

Source Link

Document

Replaces the entry for the specified key only if it is currently mapped to some value.

Usage

From source file:apps.Source2XML.java

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

    options.addOption("i", null, true, "input file");
    options.addOption("o", null, true, "output file");
    options.addOption("reparse_xml", null, false, "reparse each XML entry to ensure the parser doesn't fail");

    Joiner commaJoin = Joiner.on(',');

    options.addOption("source_type", null, true,
            "document source type: " + commaJoin.join(SourceFactory.getDocSourceList()));

    Joiner spaceJoin = Joiner.on(' ');

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter outputFile = null;

    int docNum = 0;

    if (USE_LEMMATIZER && USE_STEMMER) {
        System.err.println("Bug/inconsistent code: cann't use the stemmer and lemmatizer at the same time!");
        System.exit(1);/*from  ww  w  .j a  va2 s .com*/
    }

    //Stemmer stemmer = new Stemmer();
    KrovetzStemmer stemmer = new KrovetzStemmer();

    System.out.println("Using Stanford NLP?        " + USE_STANFORD);
    System.out.println("Using Stanford lemmatizer? " + USE_LEMMATIZER);
    System.out.println("Using stemmer?             " + USE_STEMMER
            + (USE_STEMMER ? " (class: " + stemmer.getClass().getCanonicalName() + ")" : ""));

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

        String inputFileName = null, outputFileName = null;

        if (cmd.hasOption("i")) {
            inputFileName = cmd.getOptionValue("i");
        } else {
            Usage("Specify 'input file'", options);
        }

        if (cmd.hasOption("o")) {
            outputFileName = cmd.getOptionValue("o");
        } else {
            Usage("Specify 'output file'", options);
        }

        outputFile = new BufferedWriter(
                new OutputStreamWriter(CompressUtils.createOutputStream(outputFileName)));

        String sourceName = cmd.getOptionValue("source_type");

        if (sourceName == null)
            Usage("Specify document source type", options);

        boolean reparseXML = options.hasOption("reparse_xml");

        DocumentSource inpDocSource = SourceFactory.createDocumentSource(sourceName, inputFileName);
        DocumentEntry inpDoc = null;
        TextCleaner textCleaner = new TextCleaner(
                new DictNoComments(new File("data/stopwords.txt"), true /* lower case */), USE_STANFORD,
                USE_LEMMATIZER);

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

        outputMap.put(UtilConst.XML_FIELD_DOCNO, null);
        outputMap.put(UtilConst.XML_FIELD_TEXT, null);

        XmlHelper xmlHlp = new XmlHelper();

        if (reparseXML)
            System.out.println("Will reparse every XML entry to verify correctness!");

        while ((inpDoc = inpDocSource.next()) != null) {
            ++docNum;

            ArrayList<String> toks = textCleaner.cleanUp(inpDoc.mDocText);
            ArrayList<String> goodToks = new ArrayList<String>();
            for (String s : toks)
                if (s.length() <= MAX_WORD_LEN && // Exclude long and short words
                        s.length() >= MIN_WORD_LEN && isGoodWord(s))
                    goodToks.add(USE_STEMMER ? stemmer.stem(s) : s);

            String partlyCleanedText = spaceJoin.join(goodToks);
            String cleanText = XmlHelper.removeInvaildXMLChars(partlyCleanedText);
            // isGoodWord combiend with Stanford tokenizer should be quite restrictive already
            //cleanText = replaceSomePunct(cleanText);

            outputMap.replace(UtilConst.XML_FIELD_DOCNO, inpDoc.mDocId);
            outputMap.replace(UtilConst.XML_FIELD_TEXT, cleanText);

            String xml = xmlHlp.genXMLIndexEntry(outputMap);

            if (reparseXML) {
                try {
                    XmlHelper.parseDocWithoutXMLDecl(xml);
                } catch (Exception e) {
                    System.err.println("Error re-parsing xml for document ID: " + inpDoc.mDocId);
                    System.exit(1);
                }
            }

            /*
            {
              System.out.println(inpDoc.mDocId);
              System.out.println("=====================");
              System.out.println(partlyCleanedText);
              System.out.println("=====================");
              System.out.println(cleanText);
            } 
            */

            try {
                outputFile.write(xml);
                outputFile.write(NL);
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("Error processing/saving a document!");
            }

            if (docNum % 1000 == 0)
                System.out.println(String.format("Processed %d documents", docNum));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        Usage("Cannot parse arguments" + e, options);
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    } finally {
        System.out.println(String.format("Processed %d documents", docNum));

        try {
            if (null != outputFile) {
                outputFile.close();
                System.out.println("Output file is closed! all seems to be fine...");
            }
        } catch (IOException e) {
            System.err.println("IO exception: " + e);
            e.printStackTrace();
        }
    }
}

From source file:Main.java

/**
 * Returns an unmodifiable view of the specified {@code mapSet}. This
 *  method allows modules to provide users with "read-only" access to
 * {@link Map}, but also to the value {@link Set}.
 *
 * @param <K>/*from  ww  w  . j  a va  2 s.c o  m*/
 *            the class of the map keys
 * @param <V>
 *            the class of the set values
 * @param mapSet
 *            the {@link Map} of {@link Set} for which an unmodifiable view
 *            is to be returned
 * @return an unmodifiable view of the specified map.
 *
 * @see Collections#unmodifiableMap(Map)
 * @see Collections#unmodifiableSet(Set)
 * @since 4.2
 */
@Nonnull
public static <K, V> Map<K, Set<V>> unmodifiableMapSet(@Nullable final Map<K, Set<V>> mapSet) {
    if (mapSet == null) {
        return Collections.emptyMap();
    }

    for (final Map.Entry<K, Set<V>> entry : mapSet.entrySet()) {
        final K key = entry.getKey();
        final Set<V> value = entry.getValue();

        mapSet.replace(key, Collections.unmodifiableSet(value));
    }

    return Collections.unmodifiableMap(mapSet);
}

From source file:Main.java

static <E> Map<Boolean, List<E>> partitionBy(List<E> elements, Predicate<E> predicate) {
    //TODO Implement me
    Map<Boolean, List<E>> map = new HashMap<>();
    List<E> trueList = new ArrayList<>();
    List<E> falseList = new ArrayList<>();
    for (E element : elements) {
        if (predicate.test(element)) {
            trueList.add(element);//from  w  ww.  j  a  v  a2  s.  c o m
        } else
            falseList.add(element);
    }
    map.replace(true, trueList);
    map.replace(false, falseList);
    return map;
}

From source file:org.workspace7.moviestore.controller.ShoppingCartController.java

/**
 * @param movieId/* ww w .ja  v a 2  s.c o m*/
 * @param qty
 * @param session
 * @return
 */
@GetMapping("/cart/add")
public @ResponseBody String addItemToCart(@RequestParam("movieId") String movieId,
        @RequestParam("quantity") int qty, HttpSession session) {

    MovieCart movieCart;

    if (session.getAttribute(SESSION_ATTR_MOVIE_CART) == null) {
        log.info("No Cart Exists for the session, creating one");
        movieCart = new MovieCart();
        movieCart.setOrderId(UUID.randomUUID().toString());
    } else {
        log.info("Cart Exists for the session, will be updated");
        movieCart = (MovieCart) session.getAttribute(SESSION_ATTR_MOVIE_CART);
    }

    log.info("Adding/Updating {} with Quantity {} to cart ", movieId, qty);

    Map<String, Integer> movieItems = movieCart.getMovieItems();

    if (movieItems.containsKey(movieId)) {
        movieItems.replace(movieId, qty);
    } else {
        movieItems.put(movieId, qty);
    }

    log.info("Movie Cart:{}", movieCart);

    //update the session back
    session.setAttribute(SESSION_ATTR_MOVIE_CART, movieCart);

    return String.valueOf(movieCart.getMovieItems().size());
}

From source file:org.ff4j.services.ff4j.FF4JServicesStepDef.java

@When("^the user requests to check if the feature is flipped with feature uid as \"([^\"]*)\" and parameters$")
public void the_user_requests_to_check_if_the_feature_is_flipped_with_feature_uid_as_and_parameters(
        String featureUID, Map<String, String> params) throws Throwable {
    Map<String, String> hashedParams = new HashMap<String, String>(params);
    Set<String> keys = hashedParams.keySet();
    for (String key : keys) {
        hashedParams.replace(key, hashedParams.get(key).replace("or", "|"));
    }//w  w  w .ja  v  a  2s  .  c o m
    try {
        actualResponse = ff4jServices.check(featureUID, hashedParams);
    } catch (Throwable t) {
        exception = t;
    }
}

From source file:fr.univlorraine.mondossierweb.controllers.RechercheController.java

public void accessToRechercheArborescente(String code, String type) {
    Map<String, String> parameterMap = new HashMap<>();
    parameterMap.put("code", code);
    parameterMap.put("type", type);
    if (type.equals(Utils.TYPE_CMP))
        parameterMap.replace("type", Utils.CMP);
    if (type.equals(Utils.TYPE_VET))
        parameterMap.replace("type", Utils.VET);
    if (type.equals(Utils.TYPE_ELP))
        parameterMap.replace("type", Utils.ELP);
    MainUI.getCurrent().navigateToRechercheArborescente(parameterMap);
}

From source file:com.flowlogix.jeedao.primefaces.JPALazyDataModel.java

/**
 * Utility method for replacing a predicate in the filter list
 * /*from w w  w .j ava2  s.  co m*/
 * @param filters filter list
 * @param element element to be replace
 * @param fp lambda to get the new Filter predicate
 */
public void replaceFilter(Map<String, FilterData> filters, String element, FilterReplacer fp) {
    FilterData elt = filters.get(element);
    if (elt != null && StringUtils.isNotBlank(elt.getFieldValue())) {
        filters.replace(element,
                new FilterData(elt.getFieldValue(), fp.get(elt.getPredicate(), elt.getFieldValue())));
    }
}

From source file:io.rhiot.component.pubnub.PubNubOperationsTest.java

@Test
public void testSetAndGetState() throws Exception {
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(PubNubConstants.OPERATION, "SET_STATE");
    headers.put(PubNubConstants.UUID, "myuuid");
    JSONObject state = new JSONObject("{\"state\":\"active\", \"lat\":\"55.645499\", \"lon\":\"12.370967\"}");
    template.sendBodyAndHeaders("direct:publish", state, headers);
    headers.replace(PubNubConstants.OPERATION, "GET_STATE");
    JSONObject response = template.requestBodyAndHeaders("direct:publish", null, headers, JSONObject.class);
    assertNotNull(response);//  w w  w  .  j a  v  a  2  s .  co  m
    assertEquals(state, response);
}

From source file:fr.univlorraine.mondossierweb.controllers.RechercheController.java

public void accessToDetail(String code, String type, String annee) {
    Map<String, String> parameterMap = new HashMap<>();
    parameterMap.put("code", code);
    parameterMap.put("type", type);
    parameterMap.put("annee", annee);
    if (type.equals(Utils.TYPE_CMP) || type.equals(Utils.CMP)) {
        parameterMap.replace("type", Utils.CMP);
        MainUI.getCurrent().navigateToRechercheArborescente(parameterMap);
    }/*from  www  . j a  va2  s  . c o  m*/

    if (type.equals(Utils.TYPE_VET) || type.equals(Utils.VET) || type.equals(Utils.ELP)
            || type.equals(Utils.TYPE_ELP)) {
        if (type.equals(Utils.TYPE_VET))
            parameterMap.replace("type", Utils.VET);
        if (type.equals(Utils.TYPE_ELP))
            parameterMap.replace("type", Utils.ELP);
        MainUI.getCurrent().navigateToListeInscrits(parameterMap);
    }

    if (type.equals(Utils.TYPE_ETU) || type.equals(Utils.ETU)) {
        parameterMap.replace("type", Utils.ETU);
        MainUI.getCurrent().setEtudiant(new Etudiant(code));
        etudiantController.recupererEtatCivil();
        //Si l'tudiant n'existe pas
        if (MainUI.getCurrent().getEtudiant() == null) {
            MainUI.getCurrent().afficherErreurView();
        } else {
            MainUI.getCurrent().navigateToDossierEtudiant(parameterMap);
        }
    }
}