Example usage for java.util Map clear

List of usage examples for java.util Map clear

Introduction

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

Prototype

void clear();

Source Link

Document

Removes all of the mappings from this map (optional operation).

Usage

From source file:org.parancoe.web.PopulateInitialDataContextListener.java

@Override
public void contextInitialized(ServletContextEvent evt) {
    ctx = (ApplicationContext) evt.getServletContext()
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    Set<Class> fixtureClasses = new LinkedHashSet<Class>(getFixtureClasses());
    if (fixtureClasses.isEmpty()) {
        log.info("Skipping initial data population (no models)");
        return;/* w  w  w .j av  a2  s  .  c  o  m*/
    }

    Map<Class, List> fixtures = YamlFixtureHelper.loadFixturesFromResource("initialData/", fixtureClasses);
    log.info("Populating initial data for models...");

    SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    //Attach transaction to thread
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
    TransactionSynchronizationManager.initSynchronization();

    try {
        for (Class clazz : fixtures.keySet()) {
            List modelFixtures = fixtures.get(clazz);
            if (modelFixtures.isEmpty()) {
                log.warn("No data for {}, did you created the fixture file?",
                        YamlFixtureHelper.getModelName(clazz));
                continue;
            }
            populateTableForModel(clazz, modelFixtures);
        }
        fixtures.clear();
        log.info("Populating initial data for models done!");
        session.getTransaction().commit();
        if (session.isOpen()) {
            session.close();
        }
    } catch (Exception e) {
        log.error("Error while populating initial data for models {}", e.getMessage(), e);
        log.debug("Rolling back the populating database transaction");
        session.getTransaction().rollback();
    } finally {
        try {
            if (session.isOpen()) {
                session.close();
            }
        } catch (Exception e) {
            /*do nothing*/
        }
        TransactionSynchronizationManager.unbindResource(sessionFactory);
        TransactionSynchronizationManager.clearSynchronization();
    }
}

From source file:com.aurel.track.fieldType.bulkSetters.SystemDateBulkSetter.java

/**
 * Gets the value from the submitted display value
 * The value should be either a date or a map with date and boolean or integer with boolean 
 * (when shift both start date and end date at the same time) 
 * @param displayStringMap// ww w . jav  a  2s. co  m
 * @param locale
 */
@Override
public Object fromDisplayString(Map<String, String> displayStringMap, Locale locale) {
    if (displayStringMap == null) {
        return null;
    }
    String value = displayStringMap.get(getKeyPrefix());
    if (value == null) {
        return null;
    }
    switch (getRelation()) {
    case BulkRelations.MOVE_BY_DAYS:
        Map<Integer, Object> daysAndCheckbox = new HashMap<Integer, Object>();
        Integer intValue = null;
        try {
            intValue = Integer.valueOf(value);
        } catch (Exception e) {
            //remove the value with the wrong type (if for example the old value, according the old relation was a Date)
            displayStringMap.clear();
            LOGGER.info("Converting the " + value + " to Integer from display string failed with "
                    + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        daysAndCheckbox.put(Integer.valueOf(0), intValue);
        Boolean adjustByDays = Boolean.FALSE;
        try {
            adjustByDays = Boolean.valueOf(displayStringMap.get(getAdjustCheckBoxKey(getFieldID())));
        } catch (Exception e) {
        }
        daysAndCheckbox.put(Integer.valueOf(1), adjustByDays);
        return daysAndCheckbox;
    case BulkRelations.SET_TO:
        //Date dateValue = DateTimeUtils.getInstance().parseISODateTime(value);
        Date dateValue = DateTimeUtils.getInstance().parseGUIDate(value, locale);
        if (dateValue == null) {
            //remove the value with the wrong type (if for example the old value, according the old relation was an Integer)
            displayStringMap.clear();
        }
        return dateValue;
    case BulkRelations.SET_EARLIEST_STARTING_FROM:
    case BulkRelations.SET_LATEST_ENDING_AT:
        Map<Integer, Object> dateAndCheckbox = new HashMap<Integer, Object>();
        //String dateValueStr = displayStringMap.get(getDateFieldKey(getFieldID()));
        Date date = DateTimeUtils.getInstance().parseGUIDate(value, locale);
        if (date == null) {
            //remove the value with the wrong type (if for example the old value, according the old relation was an Integer)
            displayStringMap.clear();
        } else {
            dateAndCheckbox.put(Integer.valueOf(0), date);
        }
        Boolean adjustByDate = Boolean.FALSE;
        try {
            adjustByDate = Boolean.valueOf(displayStringMap.get(getAdjustCheckBoxKey(getFieldID())));
        } catch (Exception e) {
        }
        dateAndCheckbox.put(Integer.valueOf(1), adjustByDate);
        return dateAndCheckbox;
    }
    return null;
}

From source file:com.globalsight.machineTranslation.AbstractTranslator.java

private String[] trMs2(Locale sourceLocale, Locale targetLocale, String[] segments)
        throws MachineTranslationException {
    String seg = null;/*from w ww  . j a  v a2  s  .  c  om*/
    List<String> heads = new ArrayList<String>();
    String[] segmentsNoStyleInfo = new String[segments.length];
    for (int i = 0; i < segments.length; i++) {
        seg = segments[i];
        String head = seg.substring(0, seg.indexOf(">") + 1);
        heads.add(head);

        BaseTmTuv srcTuv = TmUtil.createTmSegment(seg, 0, null, "unknown", true);
        segmentsNoStyleInfo[i] = GxmlUtil.stripRootTag(srcTuv.getSegment());
    }

    List<String> translatedList = new ArrayList<String>();
    List<String> subList = new ArrayList<String>();
    int charCount = 0;
    for (int i = 0; i < segmentsNoStyleInfo.length; i++) {
        if (segmentsNoStyleInfo[i].length() > TMProfileConstants.MT_MS_MAX_CHARACTER_NUM) {
            if (subList.size() > 0) {
                translatedList.addAll(doMSTranslation(subList, sourceLocale, targetLocale));
            }
            translatedList.add("");
            subList.clear();
            charCount = 0;
        } else if (charCount + segmentsNoStyleInfo[i].length() > TMProfileConstants.MT_MS_MAX_CHARACTER_NUM) {
            i--;
            translatedList.addAll(doMSTranslation(subList, sourceLocale, targetLocale));
            subList.clear();
            charCount = 0;
        } else {
            subList.add(segmentsNoStyleInfo[i]);
            charCount += segmentsNoStyleInfo[i].length();
        }
    }
    if (subList.size() > 0) {
        translatedList.addAll(doMSTranslation(subList, sourceLocale, targetLocale));
        subList.clear();
        charCount = 0;
    }
    String[] results = new String[segments.length];
    Map<String, String> separatedSegmentMap = new HashMap<String, String>();
    String injected = null;
    for (int i = 0; i < translatedList.size(); i++) {
        if (StringUtil.isEmpty(translatedList.get(i))) {
            results[i] = "";
            continue;
        }
        separatedSegmentMap.clear();
        separatedSegmentMap.put("0", translatedList.get(i));
        try {
            injected = TmUtil.composeCompleteText(segments[i], separatedSegmentMap);
            // MS Translator will add extra space before < and after > like
            // "> <", " <" and "> ".
            // If original segment has "><", not regardless it has "> <" or not.
            if (segments[i].indexOf("><") > -1) {
                injected = StringUtil.replace(injected, "> <", "><");
            }
            //              injected = StringUtil.replace(injected, "> ", ">");
            //              injected = StringUtil.replace(injected, " <", "<");
            injected = heads.get(i) + injected + "</segment>";

            results[i] = MTHelper.fixInternalTextAfterMTTranslation(segments[i], injected);
        } catch (Exception e) {
            results[i] = null;
            CATEGORY.error(e);
        }
    }

    return results;
}

From source file:com.basho.riak.client.TestRiakObject.java

@Test
public void userMetaEncapsulationIsAsGoodAsDirectAccess() {
    final Map<String, String> userMeta = new HashMap<String, String>();
    userMeta.put("acl", "admin");
    userMeta.put("my-meta", "my-value");

    final RiakObject riakObject = new RiakObject("b", "k", "v".getBytes(), "", null, userMeta, "", "", "");

    assertTrue(riakObject.hasUsermeta());
    assertTrue(riakObject.hasUsermetaItem("acl"));
    assertTrue(riakObject.hasUsermetaItem("my-meta"));

    userMeta.clear();

    assertTrue(riakObject.hasUsermetaItem("acl"));
    assertTrue(riakObject.hasUsermetaItem("my-meta"));

    riakObject.addUsermetaItem("my-meta2", "my-value2");

    assertTrue(riakObject.hasUsermetaItem("my-meta2"));
    assertEquals("my-value2", riakObject.getUsermetaItem("my-meta2"));

    riakObject.removeUsermetaItem("acl");

    assertFalse(riakObject.hasUsermetaItem("acl"));

    final Map<String, String> leakedUserMeta = riakObject.getUsermeta();

    assertEquals("my-value2", leakedUserMeta.get("my-meta2"));
    assertEquals("my-value", leakedUserMeta.get("my-meta"));

    // still writes through
    leakedUserMeta.put("my-meta3", "my-value3");
    assertTrue(riakObject.hasUsermetaItem("my-meta3"));
    assertEquals("my-value3", riakObject.getUsermetaItem("my-meta3"));
}

From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java

@Override
public void initNewCluster(ClusterConfig config) throws RestApiException {
    // We need two requests, one to set the memory quota, the other
    // to set the authentication params.
    HttpPost memInit = new HttpPost();
    Map<String, String> params = new HashMap<String, String>();
    params.put("memoryQuota", "" + config.memoryQuota);
    memInit.setEntity(makeFormEntity(params));
    try {/*w ww  .  ja v  a  2  s.co  m*/
        getResponseJson(memInit, P_POOLS_DEFAULT, 200);
    } catch (IOException ex) {
        throw new RestApiException(ex);
    }

    params.clear();
    HttpPost authInit = new HttpPost();
    params.put("port", "SAME");
    params.put("username", this.user);
    params.put("password", this.passwd);
    authInit.setEntity(makeFormEntity(params));
    try {
        getResponseJson(authInit, P_SETTINGS_WEB, 200);
    } catch (IOException ex) {
        throw new RestApiException(ex);
    }
}

From source file:co.marcin.novaguilds.command.guild.CommandGuildJoin.java

@Override
public void execute(CommandSender sender, String[] args) throws Exception {
    NovaPlayer nPlayer = PlayerManager.getPlayer(sender);
    List<NovaGuild> invitedTo = nPlayer.getInvitedTo();

    if (nPlayer.hasGuild()) {
        Message.CHAT_CREATEGUILD_HASGUILD.send(sender);
        return;/*from  w  w  w  .  jav  a 2s.co  m*/
    }

    if (invitedTo.isEmpty() && args.length != 1) {
        Message.CHAT_PLAYER_INVITE_LIST_NOTHING.send(sender);
        return;
    }

    String guildName;

    //one or more guilds
    if (invitedTo.size() == 1) {
        if (args.length == 0) {
            guildName = invitedTo.get(0).getName();
        } else {
            guildName = args[0];
        }
    } else {
        if (args.length == 0) {
            Message.CHAT_PLAYER_INVITE_LIST_HEADER.send(sender);

            String invitedListString = "";
            int i = 0;
            for (NovaGuild invitedGuild : invitedTo) {
                String guildRow = Message.CHAT_PLAYER_INVITE_LIST_ITEM.get();
                guildRow = org.apache.commons.lang.StringUtils.replace(guildRow, "{GUILDNAME}",
                        invitedGuild.getName());
                guildRow = org.apache.commons.lang.StringUtils.replace(guildRow, "{TAG}",
                        invitedGuild.getTag());

                invitedListString += guildRow;

                if (i < invitedTo.size() - 1) {
                    invitedListString += Message.CHAT_PLAYER_INVITE_LIST_SEPARATOR.get();
                }
                i++;
            }

            sender.sendMessage(StringUtils.fixColors(invitedListString));
            return;
        } else {
            guildName = args[0];
        }
    }

    NovaGuild guild = GuildManager.getGuildFind(guildName);

    if (guild == null) {
        Message.CHAT_GUILD_NAMENOTEXIST.send(sender);
        return;
    }

    if (!nPlayer.isInvitedTo(guild) && !guild.isOpenInvitation()) {
        Message.CHAT_PLAYER_INVITE_NOTINVITED.send(sender);
        return;
    }

    //items
    List<ItemStack> joinItems = GroupManager.getGroup(sender).getItemStackList(NovaGroup.Key.JOIN_ITEMS);

    if (!joinItems.isEmpty()) {
        List<ItemStack> missingItems = InventoryUtils.getMissingItems(((Player) sender).getInventory(),
                joinItems);

        if (!missingItems.isEmpty()) {
            Message.CHAT_CREATEGUILD_NOITEMS.send(sender);
            sender.sendMessage(StringUtils.getItemList(missingItems));

            return;
        }
    }

    Map<VarKey, String> vars = new HashMap<>();

    //money
    double joinMoney = GroupManager.getGroup(sender).getDouble(NovaGroup.Key.JOIN_MONEY);
    if (joinMoney > 0 && !nPlayer.hasMoney(joinMoney)) {
        vars.put(VarKey.REQUIREDMONEY, String.valueOf(joinMoney));
        Message.CHAT_GUILD_NOTENOUGHMONEY.vars(vars).send(sender);
        return;
    }

    if (!joinItems.isEmpty()) {
        InventoryUtils.removeItems((Player) sender, joinItems);
    }

    if (joinMoney > 0) {
        nPlayer.takeMoney(joinMoney);
    }

    if (guild.isFull()) {
        Message.CHAT_GUILD_ISFULL.send(sender);
        return;
    }

    guild.addPlayer(nPlayer);
    nPlayer.deleteInvitation(guild);
    TagUtils.refresh();
    TabUtils.refresh();
    Message.CHAT_GUILD_JOINED.send(sender);
    guild.showVaultHologram(nPlayer.getPlayer());

    vars.clear();
    vars.put(VarKey.PLAYER, sender.getName());
    vars.put(VarKey.GUILDNAME, guild.getName());
    Message.BROADCAST_GUILD_JOINED.vars(vars).broadcast();
}

From source file:com.esd.ps.RegListController.java

/**
 * ?//w  ww.  j a  v a2s .co  m
 * 
 * @param session
 * @param page
 * @param beginDateate
 * @param endDateate
 * @return
 */
@RequestMapping(value = "/regList", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> regListPost(HttpSession session, int page, String beginDate, String endDate) {
    logger.debug("beginDateate:{},endDateate:{}", beginDate, endDate);
    Map<String, Object> map = new HashMap<String, Object>();
    int districtId = Integer.parseInt(session.getAttribute(Constants.ID).toString());
    List<RegistrationTrans> list = new ArrayList<RegistrationTrans>();
    if (endDate.trim().length() > 0 || !endDate.isEmpty()) {
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat(Constants.DATE_FORMAT);
            SimpleDateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT_HAVE_LINE);
            Date myDate = formatter.parse(endDate);
            Calendar c = Calendar.getInstance();
            c.setTime(myDate);
            c.add(Calendar.DATE, 1);
            myDate = c.getTime();
            endDate = sdf1.format(myDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    int totle = registrationService.getCountByTimeAndDistrictId(districtId, beginDate, endDate);
    if (totle == 0) {
        map.clear();
        map.put(Constants.TOTLE, totle);
        map.put(Constants.TOTLE_PAGE, Math.ceil((double) totle / (double) Constants.ROW));
        map.put(Constants.LIST, list);
        return map;
    }
    List<Registration> regList = registrationService.getByTimeAndDistrictId(districtId, beginDate, endDate,
            page, Constants.ROW);
    SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
    for (Iterator<Registration> iterator = regList.iterator(); iterator.hasNext();) {
        Registration registration = (Registration) iterator.next();
        RegistrationTrans rt = new RegistrationTrans();
        rt.setAddress(registration.getAddress());
        rt.setCard(registration.getCard());
        rt.setCreateTime(sdf.format(registration.getCreateTime()));
        rt.setDes(registration.getDes());
        rt.setName(registration.getName());
        rt.setPhone(registration.getPhone());
        rt.setQq(registration.getQq());

        list.add(rt);
    }
    map.clear();
    map.put(Constants.TOTLE, totle);
    map.put(Constants.TOTLE_PAGE, Math.ceil((double) totle / (double) Constants.ROW));
    map.put(Constants.LIST, list);
    return map;
}

From source file:com.china317.gmmp.gmmp_report_analysis.App.java

private static void InOutMoreRecordsStoreIntoDB(Map<String, AlarmMore> iniOutMoreRecords,
        ApplicationContext context) {/*from w  w  w  .  j a va2 s . co m*/
    Connection conn = null;
    String sql = "";
    try {
        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientLybc");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = iniOutMoreRecords.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            AlarmMore pos = iniOutMoreRecords.get(key);
            sql = "insert into TAB_ALARM_MORE " + " (LICENCE,denoter,fisrt_Time,BEGIN_TIME,END_TIME,road) "
                    + " values (" + "'" + pos.getLicense() + "'," + "'" + pos.getDenoter() + "'," + "'"
                    + pos.getFirstTime() + "'," + "'" + pos.getBeginTime() + "'," + "'" + pos.getEndTime()
                    + "'," + "'" + pos.getRoad() + "')";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB TAB_ALARM_MORE success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        iniOutMoreRecords.clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.linkedin.pinot.queries.RealtimeQueriesSentinelTest.java

@Test
public void testAggregation() throws Exception {
    int counter = 0;
    final Map<ServerInstance, DataTable> instanceResponseMap = new HashMap<ServerInstance, DataTable>();
    final List<TestSimpleAggreationQuery> aggCalls = AVRO_QUERY_GENERATOR
            .giveMeNSimpleAggregationQueries(10000);
    for (final TestSimpleAggreationQuery aggCall : aggCalls) {
        LOGGER.info("running " + counter + " : " + aggCall.pql);
        final BrokerRequest brokerRequest = REQUEST_COMPILER.compileToBrokerRequest(aggCall.pql);
        InstanceRequest instanceRequest = new InstanceRequest(counter++, brokerRequest);
        instanceRequest.setSearchSegments(new ArrayList<String>());
        instanceRequest.getSearchSegments().add("testTable_testTable");
        QueryRequest queryRequest = new QueryRequest(instanceRequest);
        DataTable instanceResponse = QUERY_EXECUTOR.processQuery(queryRequest);
        instanceResponseMap.clear();
        instanceResponseMap.put(new ServerInstance("localhost:0000"), instanceResponse);
        final BrokerResponseNative brokerResponse = REDUCE_SERVICE.reduceOnDataTable(brokerRequest,
                instanceResponseMap);//from   w ww.  j  ava2s .  com
        LOGGER.info("BrokerResponse is " + brokerResponse.getAggregationResults().get(0));
        LOGGER.info("Result from avro is : " + aggCall.result);
        Double actual = Double.parseDouble(brokerResponse.getAggregationResults().get(0).getValue().toString());
        Double expected = aggCall.result;
        try {
            Assert.assertEquals(actual, expected);
        } catch (AssertionError e) {
            System.out.println("********************************");
            System.out.println("query : " + aggCall.pql);
            System.out.println("actual : " + actual);
            System.out.println("expected : " + aggCall.result);
            System.out.println("********************************");
            throw e;
        }

    }
}

From source file:com.github.braully.graph.operation.GraphCalcCaratheodoryNumberBinaryStrategy.java

@Override
public Map<String, Object> doOperation(UndirectedSparseGraphTO<Integer, Integer> graph) {
    OperationConvexityGraphResult processedCaratheodroySet = null;
    Map<String, Object> result = null;
    if (graph == null) {
        return result;
    }/*ww  w .  j  a  va2 s  .  co m*/
    int vertexCount = graph.getVertexCount();
    int maxSizeSet = (vertexCount + 1) / 2;
    int currentSize = maxSizeSet;
    int left = 0;
    int rigth = maxSizeSet;
    result = new HashMap<>();

    if (vertexCount >= THRESHOLD_HEURISTIC_FEED) {
        GraphCaratheodoryHeuristicHybrid graphCaratheodoryHeuristicHybrid = new GraphCaratheodoryHeuristicHybrid();
        Set<Integer> caratheodorySet = graphCaratheodoryHeuristicHybrid.buildMaxCaratheodorySet(graph);
        if (caratheodorySet != null) {
            left = caratheodorySet.size() + 1;
            processedCaratheodroySet = hsp3(graph, caratheodorySet);
            result.putAll(processedCaratheodroySet.toMap());
        }
        processedCaratheodroySet = findCaratheodroySetBruteForce(graph, left);
        if (processedCaratheodroySet == null || processedCaratheodroySet.caratheodorySet == null) {
            return result;
        } else {
            result.clear();
            result.putAll(processedCaratheodroySet.toMap());
            left = left + 1;
        }
    }

    while (left <= rigth) {
        currentSize = (left + rigth) / 2;
        processedCaratheodroySet = findCaratheodroySetBruteForce(graph, currentSize);
        if (processedCaratheodroySet != null && processedCaratheodroySet.caratheodorySet != null
                && !processedCaratheodroySet.caratheodorySet.isEmpty()) {
            result.clear();
            result.putAll(processedCaratheodroySet.toMap());
            left = currentSize + 1;
        } else {
            rigth = currentSize - 1;
        }
    }
    return result;
}