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:collection.PhysicalWebCollection.java

/**
 * Given a list of PwPairs, return a filtered list such that only one PwPair from each group
 * is included.// w  w  w  . j av a  2  s. c  o  m
 * @param allPairs Input PwPairs list.
 * @param outGroupMap Optional output map from discovered group IDs to UrlGroups, may be null.
 * @return Filtered PwPairs list.
 */
private static List<PwPair> removeDuplicateGroupIds(List<PwPair> allPairs, Map<String, UrlGroup> outGroupMap,
        Comparator<PwPair> comparator) {
    List<PwPair> filteredPairs = new ArrayList<>();
    Map<String, UrlGroup> groupMap = outGroupMap;
    if (groupMap == null) {
        groupMap = new HashMap<>();
    } else {
        groupMap.clear();
    }

    for (PwPair pwPair : allPairs) {
        PwsResult pwsResult = pwPair.getPwsResult();
        String groupId = pwsResult.getGroupId();
        if (groupId == null || groupId.equals("")) {
            // Pairs without a group are always included
            filteredPairs.add(pwPair);
        } else {
            // Create the group if it doesn't exist
            UrlGroup urlGroup = groupMap.get(groupId);
            if (urlGroup == null) {
                urlGroup = new UrlGroup(groupId);
                groupMap.put(groupId, urlGroup);
            }
            urlGroup.addPair(pwPair);
        }
    }

    for (UrlGroup urlGroup : groupMap.values()) {
        filteredPairs.add(urlGroup.getTopPair(comparator));
    }

    return filteredPairs;
}

From source file:de.xwic.appkit.core.util.CollectionUtil.java

/**
 * @param where map to clear and add to/*from  w  w  w . j a v a  2  s  .c om*/
 * @param fromWhere what to add
 * @throws NullPointerException if <code>where</code> is empty
 */
public static <K, V> void clearAndPutAll(final Map<? super K, ? super V> where,
        final Map<? extends K, ? extends V> fromWhere) throws NullPointerException {
    if (where == fromWhere) {
        return;
    }
    where.clear();
    if (!isEmpty(fromWhere)) {
        where.putAll(fromWhere);
    }
}

From source file:org.activiti.crystalball.simulator.GenerateProcessEngineState.java

private static void generatePlaybackOriginal() throws InterruptedException, IOException {
    String PROCESS_KEY = "playback";
    RepositoryService repositoryService;
    RuntimeService runtimeService;//from   ww  w.  j  a v a2  s  .c  o  m
    TaskService taskService;
    IdentityService identityService;
    HistoryService historyService;
    ProcessEngine processEngine;
    String liveDB = TEMP_DIR + "/Playback";

    // delete previous DB instalation and set property to point to the current file
    File prevDB = new File(liveDB + ".h2.db");

    String previousLiveDB = System.getProperty("liveDB");

    System.setProperty("liveDB", liveDB);
    if (prevDB.exists())
        prevDB.delete();
    prevDB = null;

    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            "org/activiti/crystalball/simulator/LiveEngine-context.xml");
    Calendar calendar = Calendar.getInstance();
    calendar.set(2013, 01, 25, 14, 30, 00);
    ClockUtil.setCurrentTime(calendar.getTime());

    repositoryService = appContext.getBean(RepositoryService.class);
    runtimeService = appContext.getBean(RuntimeService.class);
    taskService = appContext.getBean(TaskService.class);
    identityService = appContext.getBean(IdentityService.class);
    historyService = appContext.getBean(HistoryService.class);

    processEngine = appContext.getBean(ProcessEngine.class);

    // deploy processes
    repositoryService.createDeployment()
            .addClasspathResource("org/activiti/crystalball/simulator/Playback.bpmn").deploy();

    // init identity service
    identityService.saveGroup(identityService.newGroup("Group1"));
    identityService.saveUser(identityService.newUser("user1"));

    identityService.createMembership("user1", "Group1");

    // start processes 
    Map<String, Object> variables2 = new HashMap<String, Object>();
    variables2.put("x", 3);
    Map<String, Object> variables1 = new HashMap<String, Object>();
    variables1.put("x", 1);
    Map<String, Object> variables0 = new HashMap<String, Object>();
    variables0.put("x", 0);

    ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-1",
            variables0);
    calendar.add(Calendar.SECOND, 1);
    ClockUtil.setCurrentTime(calendar.getTime());
    ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-2",
            variables1);
    calendar.add(Calendar.SECOND, 1);
    ClockUtil.setCurrentTime(calendar.getTime());
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-3", variables0);

    // put first 5 tasks to the next node
    List<Task> taskList = taskService.createTaskQuery().taskCandidateUser("user1").list();
    for (Task t : taskList) {
        taskService.claim(t.getId(), "user1");
    }

    // complete these tasks
    for (Task t : taskList) {
        // wait some time  to have some data in history 
        calendar.add(Calendar.SECOND, 1);
        ClockUtil.setCurrentTime(calendar.getTime());
        // complete task
        taskService.complete(t.getId(), variables2);
    }

    // audit trail images generator
    AuditTrailProcessDiagramGenerator generator = new AuditTrailProcessDiagramGenerator();
    generator.setHistoryService(historyService);
    generator.setRepositoryService((RepositoryServiceImpl) repositoryService);
    generator.setWriteUpdates(true);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put(AuditTrailProcessDiagramGenerator.PROCESS_INSTANCE_ID, processInstance1.getId());

    ImageIO.write(ImageIO.read(generator.generateLayer("png", params)), "png",
            new File(TEMP_DIR + "/playback-auditTrail1.png"));

    params.clear();
    params.put(AuditTrailProcessDiagramGenerator.PROCESS_INSTANCE_ID, processInstance2.getId());

    ImageIO.write(ImageIO.read(generator.generateLayer("png", params)), "png",
            new File(TEMP_DIR + "/playback-auditTrail2.png"));

    processEngine.close();

    appContext.close();

    if (previousLiveDB != null)
        System.setProperty("liveDB", previousLiveDB);
    else
        System.setProperty("liveDB", "");

}

From source file:com.datatorrent.stram.support.StramTestSupport.java

public static void setEnv(Map<String, String> newenv) throws Exception {
    try {/*from  w w w .j  ava2 s .c  o  m*/
        Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        theEnvironmentField.setAccessible(true);
        Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
        env.putAll(newenv);
        Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
        cienv.putAll(newenv);
    } catch (NoSuchFieldException e) {
        Class[] classes = Collections.class.getDeclaredClasses();
        Map<String, String> env = System.getenv();
        for (Class cl : classes) {
            if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
                Field field = cl.getDeclaredField("m");
                field.setAccessible(true);
                Object obj = field.get(env);
                Map<String, String> map = (Map<String, String>) obj;
                map.clear();
                map.putAll(newenv);
            }
        }
    }
}

From source file:org.vader.common.spring.TransactionScope.java

private static void registerSynchronization() {
    LOG.debug("Registers transaction synchronization");
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override/* w w  w  .  j  a va2  s.c  o m*/
        public void suspend() {
            LOG.debug("Push new transaction scope");
            SCOPES.get().push(new HashMap<String, ScopeEntry>());
        }

        @Override
        public void resume() {
            LOG.debug("Pop old transaction scope");
            SCOPES.get().pop();
        }

        @Override
        public void afterCompletion(int status) {
            final Map<String, ScopeEntry> scope = getCurrentScope();
            LOG.debug("Destroying {} beans", scope.size());
            for (Map.Entry<String, ScopeEntry> entry : scope.entrySet()) {
                for (Runnable runnable : entry.getValue().getCallbacks()) {
                    LOG.debug("Executes destruction callback for bean={}", entry.getKey());
                    runnable.run();
                }
            }
            scope.clear();
            LOG.debug("Destruction completed");
        }
    });
}

From source file:com.linkedin.pinot.controller.helix.core.realtime.PinotLLCRealtimeSegmentManager.java

protected static IdealState updateForNewRealtimeSegment(IdealState idealState, final List<String> newInstances,
        final String oldSegmentNameStr, final String newSegmentNameStr) {
    if (oldSegmentNameStr != null) {
        // Update the old ones to be ONLINE
        Set<String> oldInstances = idealState.getInstanceSet(oldSegmentNameStr);
        for (String instance : oldInstances) {
            idealState.setPartitionState(oldSegmentNameStr, instance,
                    PinotHelixSegmentOnlineOfflineStateModelGenerator.ONLINE_STATE);
        }/* w  w  w  . j a va  2s. c om*/
    }

    // We may have (for whatever reason) a different instance list in the idealstate for the new segment.
    // If so, clear it, and then set the instance state for the set of instances that we know should be there.
    Map<String, String> stateMap = idealState.getInstanceStateMap(newSegmentNameStr);
    if (stateMap != null) {
        stateMap.clear();
    }
    for (String instance : newInstances) {
        idealState.setPartitionState(newSegmentNameStr, instance,
                PinotHelixSegmentOnlineOfflineStateModelGenerator.CONSUMING_STATE);
    }

    return idealState;
}

From source file:com.tobedevoured.naether.NaetherTest.java

private static void setEnv(Map<String, String> newenv) {
    try {//from  w  w w .  j  a  va 2  s  .c  o m
        Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        theEnvironmentField.setAccessible(true);
        Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
        env.putAll(newenv);
        Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
        cienv.putAll(newenv);
    } catch (NoSuchFieldException e) {
        try {
            Class[] classes = Collections.class.getDeclaredClasses();
            Map<String, String> env = System.getenv();
            for (Class cl : classes) {
                if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
                    Field field = cl.getDeclaredField("m");
                    field.setAccessible(true);
                    Object obj = field.get(env);
                    Map<String, String> map = (Map<String, String>) obj;
                    map.clear();
                    map.putAll(newenv);
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

From source file:com.evolveum.midpoint.gui.api.util.WebModelServiceUtils.java

public static <O extends ObjectType> List<ObjectReferenceType> createObjectReferenceList(Class<O> type,
        PageBase page, Map<String, String> referenceMap) {
    referenceMap.clear();

    OperationResult result = new OperationResult(OPERATION_LOAD_OBJECT_REFS);
    //        Task task = page.createSimpleTask(OPERATION_LOAD_PASSWORD_POLICIES);

    try {/* ww  w  . j av a  2  s. co  m*/
        List<PrismObject<O>> objects = searchObjects(type, null, result, page);
        result.recomputeStatus();
        if (objects != null) {
            List<ObjectReferenceType> references = new ArrayList<>();

            for (PrismObject<O> object : objects) {
                referenceMap.put(object.getOid(), WebComponentUtil.getName(object));
                references.add(ObjectTypeUtil.createObjectRef(object));

            }
            return references;
        }
    } catch (Exception e) {
        result.recordFatalError("Couldn't load password policies.", e);
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load password policies", e);
    }

    // TODO - show error somehow
    // if(!result.isSuccess()){
    //    getPageBase().showResult(result);
    // }

    return null;

}

From source file:com.redhat.rhn.manager.ssm.SsmOperationManager.java

/**
 * Creates a new operation, defaulting the status to "in progress".
 * <p/>/*from  ww  w .  j ava  2 s.c  o  m*/
 * For efficiency, this call assumes the following:
 * <ul>
 * <li>The set of servers that are taking place in the operation are already in the
 * database as an RhnSet (the name of set is passed into this call).</li>
 * <li>The server ID is stored in the first element (i.e. "element" in the set table).
 * </ul>
 * <p/>
 * This should be a safe assumption since, at very least, if all servers are taking
 * place in the operation they are already in the SSM RhnSet. If only a subset
 * is needed, a nested select can be used to drop them into a new set, preventing
 * the need to have another insert per server for this call.
 *
 * @param user        user under which to associate the operation; cannot be
 *                    <code>null</code>
 * @param description high level description of what the operation is doing;
 *                    cannot be <code>null</code>
 * @param rhnSetLabel references a RhnSet with the server IDs to associate with the
 *                    new operation; if this is <code>null</code> no mappings will
 *                    be created at this time
 * @return the id of the created operation
 */
public static long createOperation(User user, String description, String rhnSetLabel) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }

    if (description == null) {
        throw new IllegalArgumentException("description cannot be null");
    }

    SelectMode selectMode;
    WriteMode writeMode;
    Map<String, Object> params = new HashMap<String, Object>();

    // Select the operation ID manually from the sequence so we can add the mappings
    // from the operation to the servers
    selectMode = ModeFactory.getMode("ssm_operation_queries", "get_seq_nextval");
    DataResult nextValResult = selectMode.execute(params);
    Map<String, Object> nextValMap = (Map<String, Object>) nextValResult.get(0);
    long operationId = (Long) nextValMap.get("nextval");

    // Add the operation data
    writeMode = ModeFactory.getWriteMode("ssm_operation_queries", "create_operation");

    params.clear();
    params.put("op_id", operationId);
    params.put("user_id", user.getId());
    params.put("description", description);
    params.put("status", SsmOperationStatus.IN_PROGRESS.getText());

    writeMode.executeUpdate(params);

    // Add the server/operation mappings
    if (rhnSetLabel != null) {
        associateServersWithOperation(operationId, user.getId(), rhnSetLabel);
    }

    return operationId;
}

From source file:com.zb.app.common.util.PinyinParser.java

/**
 * ???(??)/*  w  w w .j  a v  a 2 s . co  m*/
 * 
 * @param args
 */
private static Set<String> parseTheChineseByObject(List<Map<String, Integer>> list) {
    Map<String, Integer> first = null; // ?,???
    // ????
    for (int i = 0; i < list.size(); i++) {
        // ???Map
        Map<String, Integer> temp = new Hashtable<String, Integer>();
        // first
        if (first != null) {
            // ????
            for (String s : first.keySet()) {
                for (String s1 : list.get(i).keySet()) {
                    String str = s + s1;
                    temp.put(str, 1);
                }
            }
            // ???
            if (temp != null && temp.size() > 0) {
                first.clear();
            }
        } else {
            for (String s : list.get(i).keySet()) {
                String str = s;
                temp.put(str, 1);
            }
        }
        // ???
        if (temp != null && temp.size() > 0) {
            first = temp;
        }
    }
    Set<String> result = new HashSet<String>();
    if (first != null) {
        // ????
        for (String str : first.keySet()) {
            result.add(str);
        }
    }
    return result;
}