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:co.cask.cdap.internal.app.services.http.handlers.ConsoleSettingsHttpHandlerTest.java

@Test
public void testSettings() throws Exception {
    //Check if settings are empty
    Map<String, String> propMap = Maps.newHashMap();
    JsonObject emptyElement = getProperty(200).getAsJsonObject();
    Assert.assertEquals(2, emptyElement.entrySet().size());
    Assert.assertEquals(propMap, GSON.fromJson(emptyElement.get("property"), MAP_STRING_STRING_TYPE));

    //Put some settings and verify if its persisted
    propMap.put("k1", "43242!@#!@#");
    propMap.put("@##@!#", "v2131231!@#!");
    putProperty(propMap, 200);//from w ww  . j  a  v a2  s  .co  m
    JsonObject jsonObject = getProperty(200).getAsJsonObject();
    Assert.assertEquals(2, jsonObject.entrySet().size());
    Assert.assertEquals(propMap, GSON.fromJson(jsonObject.get("property"), MAP_STRING_STRING_TYPE));

    //Delete the settings and verify that its empty
    propMap.clear();
    deleteProperty(200);
    jsonObject = getProperty(200).getAsJsonObject();
    Assert.assertEquals(2, jsonObject.entrySet().size());
    Assert.assertEquals(propMap, GSON.fromJson(jsonObject.get("property"), MAP_STRING_STRING_TYPE));
}

From source file:ch.fhnw.digibp.smm.process.util.CamundaInitialDataGenerator.java

@PostConstruct
public void createUsers() {
    final IdentityService identityService = processEngine.getIdentityService();

    if (identityService.isReadOnly()) {
        LOGGER.info("Identity api provider is Read Only, not creating any demo users.");
        return;/* www  . ja  v  a2s . c om*/
    }

    if (identityService.createUserQuery().userId("demo").singleResult() == null) {
        LOGGER.info("Generating demo user for MSc BIS");
        User user = identityService.newUser("demo");
        user.setFirstName("Demo");
        user.setLastName("Demo");
        user.setPassword("demo");
        user.setEmail("demo@camunda.org");
        identityService.saveUser(user);
    }

    final AuthorizationService authorizationService = processEngine.getAuthorizationService();

    // create group
    if (identityService.createGroupQuery().groupId(Groups.CAMUNDA_ADMIN).singleResult() == null) {
        Group camundaAdminGroup = identityService.newGroup(Groups.CAMUNDA_ADMIN);
        camundaAdminGroup.setName("camunda BPM Administrators");
        camundaAdminGroup.setType(Groups.GROUP_TYPE_SYSTEM);
        identityService.saveGroup(camundaAdminGroup);

        // create ADMIN authorizations on all built-in resources
        for (Resource resource : Resources.values()) {
            if (authorizationService.createAuthorizationQuery().groupIdIn(Groups.CAMUNDA_ADMIN)
                    .resourceType(resource).resourceId(ANY).count() == 0) {
                AuthorizationEntity userAdminAuth = new AuthorizationEntity(AUTH_TYPE_GRANT);
                userAdminAuth.setGroupId(Groups.CAMUNDA_ADMIN);
                userAdminAuth.setResource(resource);
                userAdminAuth.setResourceId(ANY);
                userAdminAuth.addPermission(ALL);
                authorizationService.saveAuthorization(userAdminAuth);
            }
        }
    }

    if (identityService.createUserQuery().userId("demo").memberOfGroup("camunda-admin")
            .singleResult() == null) {
        identityService.createMembership("demo", "camunda-admin");
    }

    // create default filters
    FilterService filterService = processEngine.getFilterService();

    if (filterService.createFilterQuery().filterName("My Tasks").singleResult() == null) {
        LOGGER.info("Generating default filters");
        Map<String, Object> filterProperties = new HashMap<String, Object>();
        filterProperties.put("description", "Tasks assigned to me");
        filterProperties.put("priority", -10);
        filterProperties.put("refresh", true);
        TaskService taskService = processEngine.getTaskService();
        TaskQuery query = taskService.createTaskQuery().taskAssigneeExpression("${currentUser()}");
        Filter myTasksFilter = filterService.newTaskFilter().setName("My Tasks").setProperties(filterProperties)
                .setOwner("demo").setQuery(query);
        filterService.saveFilter(myTasksFilter);

        filterProperties.clear();
        filterProperties.put("description", "Tasks assigned to my Groups");
        filterProperties.put("priority", -5);
        filterProperties.put("refresh", true);
        query = taskService.createTaskQuery().taskCandidateGroupInExpression("${currentUserGroups()}")
                .taskUnassigned();
        Filter groupTasksFilter = filterService.newTaskFilter().setName("My Group Tasks")
                .setProperties(filterProperties).setOwner("demo").setQuery(query);
        filterService.saveFilter(groupTasksFilter);

        // global read authorizations for these filters
        Authorization globalMyTaskFilterRead = authorizationService
                .createNewAuthorization(Authorization.AUTH_TYPE_GLOBAL);
        globalMyTaskFilterRead.setResource(FILTER);
        globalMyTaskFilterRead.setResourceId(myTasksFilter.getId());
        globalMyTaskFilterRead.addPermission(READ);
        authorizationService.saveAuthorization(globalMyTaskFilterRead);

        Authorization globalGroupFilterRead = authorizationService
                .createNewAuthorization(Authorization.AUTH_TYPE_GLOBAL);
        globalGroupFilterRead.setResource(FILTER);
        globalGroupFilterRead.setResourceId(groupTasksFilter.getId());
        globalGroupFilterRead.addPermission(READ);
        authorizationService.saveAuthorization(globalGroupFilterRead);
    }
}

From source file:org.tiefaces.components.websheet.chart.ChartHelper.java

/**
 * initial chart map for XSSF format file. XSSF file is actually the only
 * format in POI support chart object./*w ww. j a  v a2s. co m*/
 *
 * @param wb
 *            xssf workbook.
 * @param chartsData
 *            the charts data
 */
private void initXSSFChartsMap(final XSSFWorkbook wb, final ChartsData chartsData) {

    initAnchorsMap(wb, chartsData);
    Map<String, ClientAnchor> anchorMap = chartsData.getChartAnchorsMap();

    Map<String, BufferedImage> chartMap = chartsData.getChartsMap();
    Map<String, ChartData> chartDataMap = chartsData.getChartDataMap();
    chartMap.clear();
    chartDataMap.clear();

    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        XSSFSheet sheet = wb.getSheetAt(i);
        XSSFDrawing drawing = sheet.createDrawingPatriarch();
        List<XSSFChart> charts = drawing.getCharts();
        if ((charts != null) && (!charts.isEmpty())) {
            for (XSSFChart chart : charts) {
                generateSingleXSSFChart(chart, getChartIdFromParent(chart, sheet.getSheetName()), sheet,
                        anchorMap, chartMap, chartDataMap);
            }
        }
    }

}

From source file:diva.rest.model.DivaRoot.java

public void generateRule() {

    Map<String, Integer> priorities = new HashMap<String, Integer>();
    AdaptRule adaptRule = AdaptRule.INSTANCE;
    List<String> propertyNames = ServiceAttribute.INSTANCE.listCommonAttributes();
    for (String name : adaptRule.allRuleNames()) {
        priorities.clear();
        for (String propName : propertyNames) {
            priorities.put(propName, adaptRule.getPriority(name, propName));
        }/*from  ww w . ja v  a 2 s.c o  m*/
        priorities.put("Failure", 16);
        this.fillRule(name, adaptRule.getRule(name), priorities);
    }

}

From source file:com.espertech.esper.core.EPRuntimeIsolatedImpl.java

private void processScheduleHandles(ArrayBackedCollection<ScheduleHandle> handles) {
    if (ThreadLogUtil.ENABLED_TRACE) {
        ThreadLogUtil.trace("Found schedules for", handles.size());
    }//from  w w w  . j  a v  a 2 s .co  m

    if (handles.size() == 0) {
        return;
    }

    // handle 1 result separatly for performance reasons
    if (handles.size() == 1) {
        Object[] handleArray = handles.getArray();
        EPStatementHandleCallback handle = (EPStatementHandleCallback) handleArray[0];

        EPRuntimeImpl.processStatementScheduleSingle(handle, unisolatedServices, isolatedTimeEvalContext);

        handles.clear();
        return;
    }

    Object[] matchArray = handles.getArray();
    int entryCount = handles.size();

    // sort multiple matches for the event into statements
    Map<EPStatementHandle, Object> stmtCallbacks = schedulePerStmtThreadLocal.get();
    stmtCallbacks.clear();
    for (int i = 0; i < entryCount; i++) // need to use the size of the collection
    {
        EPStatementHandleCallback handleCallback = (EPStatementHandleCallback) matchArray[i];
        EPStatementHandle handle = handleCallback.getEpStatementHandle();
        ScheduleHandleCallback callback = handleCallback.getScheduleCallback();

        Object entry = stmtCallbacks.get(handle);

        // This statement has not been encountered before
        if (entry == null) {
            stmtCallbacks.put(handle, callback);
            continue;
        }

        // This statement has been encountered once before
        if (entry instanceof ScheduleHandleCallback) {
            ScheduleHandleCallback existingCallback = (ScheduleHandleCallback) entry;
            ArrayDeque<ScheduleHandleCallback> entries = new ArrayDeque<ScheduleHandleCallback>();
            entries.add(existingCallback);
            entries.add(callback);
            stmtCallbacks.put(handle, entries);
            continue;
        }

        // This statement has been encountered more then once before
        ArrayDeque<ScheduleHandleCallback> entries = (ArrayDeque<ScheduleHandleCallback>) entry;
        entries.add(callback);
    }
    handles.clear();

    for (Map.Entry<EPStatementHandle, Object> entry : stmtCallbacks.entrySet()) {
        EPStatementHandle handle = entry.getKey();
        Object callbackObject = entry.getValue();

        EPRuntimeImpl.processStatementScheduleMultiple(handle, callbackObject, unisolatedServices,
                isolatedTimeEvalContext);

        if ((isPrioritized) && (handle.isPreemptive())) {
            break;
        }
    }
}

From source file:com.bittorrent.mpetazzoni.tracker.TrackerService.java

/**
 * Parse the query parameters using our defined BYTE_ENCODING.
 *
 * <p>/*from  w w w . java2  s.  co  m*/
 * Because we're expecting byte-encoded strings as query parameters, we
 * can't rely on SimpleHTTP's QueryParser which uses the wrong encoding for
 * the job and returns us unparsable byte data. We thus have to implement
 * our own little parsing method that uses BYTE_ENCODING to decode
 * parameters from the URI.
 * </p>
 *
 * <p>
 * <b>Note:</b> array parameters are not supported. If a key is present
 * multiple times in the URI, the latest value prevails. We don't really
 * need to implement this functionality as this never happens in the
 * Tracker HTTP protocol.
 * </p>
 *
 * @param request The request's full URI, including query parameters.
 * @return The {@link AnnounceRequestMessage} representing the client's
 * announce request.
 */
private HTTPAnnounceRequestMessage parseQuery(Request request) throws IOException, MessageValidationException {
    Map<String, BEValue> params = new HashMap<String, BEValue>();

    try {
        String uri = request.getAddress().toString();
        for (String pair : uri.split("[?]")[1].split("&")) {
            String[] keyval = pair.split("[=]", 2);
            if (keyval.length == 1) {
                this.recordParam(params, keyval[0], null);
            } else {
                this.recordParam(params, keyval[0], keyval[1]);
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        params.clear();
    }

    // Make sure we have the peer IP, fallbacking on the request's source
    // address if the peer didn't provide it.
    if (params.get("ip") == null) {
        params.put("ip", new BEValue(request.getClientAddress().getAddress().getHostAddress(),
                TrackedTorrent.BYTE_ENCODING));
    }

    return HTTPAnnounceRequestMessage.parse(BEncoder.bencode(params));
}

From source file:edu.cornell.med.icb.io.TestConditionsParser.java

public void testDictionary() throws IOException, ConditionsParsingException {
    final String input = "a=123,b=456,c=def\t123\t5,6,7\n" + "#comment\n" + "c=567,d=843,e=3bf";
    final Reader source = new StringReader(input);

    final ConditionsParser parser = new ConditionsParser();
    parser.addField(new ConditionField(ConditionField.FieldType.MAP, "one"));
    parser.addField(new ConditionField(ConditionField.FieldType.VALUE, "two"));
    parser.addField(new ConditionField(ConditionField.FieldType.VALUE, "three").setList(true));

    parser.beginParse(source);/*from w ww .j a  v a 2s.c om*/

    final Map<String, String> expectedDict = new HashMap<String, String>();

    assertTrue(parser.hasNext());
    expectedDict.clear();
    expectedDict.put("a", "123");
    expectedDict.put("b", "456");
    expectedDict.put("c", "def");
    checkMap(expectedDict, parser.parseFieldMap("one"));
    assertEquals(1, parser.getLineNumber());
    assertEquals("123", parser.parseFieldValueString("two"));
    checkIntArray(new int[] { 5, 6, 7 }, parser.parseFieldValueIntArray("three"));
    assertTrue(parser.hasNext());
    expectedDict.clear();
    expectedDict.put("c", "567");
    expectedDict.put("d", "843");
    expectedDict.put("e", "3bf");
    checkMap(expectedDict, parser.parseFieldMap("one"));
    assertEquals("", parser.parseFieldValueString("two"));
    checkIntArray(ArrayUtils.EMPTY_INT_ARRAY, parser.parseFieldValueIntArray("three"));
    assertEquals(3, parser.getLineNumber());
    assertFalse(parser.hasNext());

    IOUtils.closeQuietly(source);
}

From source file:cop.maven.plugins.AbstractRamlConfigMojoTest.java

@Test
public void shouldAddStringValueWhenStringValue() throws Exception {
    Map<String, Object> src = new HashMap<>();
    src.put("key", "val");
    src.put("foo", "");

    Map<String, Object> map = new HashMap<>();

    put(mojo, map, src, "foo");
    assertThat(map).isEmpty();/*  w ww  . j  av a2s .  c  o m*/

    put(mojo, map, src, "key");
    assertThat(map).hasSize(1);
    assertThat(map.get("key")).isEqualTo("val");

    mojo.setEvaluate("");
    map.clear();
    put(mojo, map, src, "key");
    assertThat(map).isEmpty();
}

From source file:interactivespaces.util.process.BaseNativeApplicationRunner.java

/**
 * Attempt the run.// w  w w  .  j av a 2s . c o  m
 *
 * @param firstTime
 *          {@code true} if this is the first attempt
 *
 * @return the process that was created
 *
 * @throws InteractiveSpacesException
 *           was not able to start the process the first time
 */
private Process attemptRun(boolean firstTime) throws InteractiveSpacesException {
    try {
        ProcessBuilder builder = new ProcessBuilder(commandLine);

        Map<String, String> processEnvironment = builder.environment();
        if (cleanEnvironment) {
            processEnvironment.clear();
        }
        modifyEnvironment(processEnvironment, environment);

        builder.directory(executableFolder);

        log.info(String.format("Starting up native code in folder %s", executableFolder.getAbsolutePath()));

        return builder.start();
    } catch (Exception e) {
        // Placed here so we can get the exception when thrown.
        if (firstTime) {
            runnerState.set(NativeApplicationRunnerState.STARTUP_FAILED);
            handleApplicationStartupFailed();

            throw new InteractiveSpacesException("Can't start up native application " + appName, e);
        }

        return null;
    }
}

From source file:ai.grakn.test.graql.analytics.DegreeTest.java

@Ignore //TODO: Stabalise this test. It fails way too often.
@Test/*from  ww  w .  j  a  v a2 s  .c  om*/
public void testDegreesAndPersist() throws Exception {
    // TODO: Fix on TinkerGraphComputer
    assumeFalse(usingTinker());

    // create instances
    EntityType thing = graph.putEntityType("thing");
    EntityType anotherThing = graph.putEntityType("another");

    String entity1 = thing.addEntity().getId();
    String entity2 = thing.addEntity().getId();
    String entity3 = thing.addEntity().getId();
    String entity4 = anotherThing.addEntity().getId();

    RoleType role1 = graph.putRoleType("role1");
    RoleType role2 = graph.putRoleType("role2");
    thing.playsRole(role1).playsRole(role2);
    anotherThing.playsRole(role1).playsRole(role2);
    RelationType related = graph.putRelationType("related").hasRole(role1).hasRole(role2);

    // relate them
    String id1 = related.addRelation().putRolePlayer(role1, graph.getConcept(entity1))
            .putRolePlayer(role2, graph.getConcept(entity2)).getId();
    String id2 = related.addRelation().putRolePlayer(role1, graph.getConcept(entity2))
            .putRolePlayer(role2, graph.getConcept(entity3)).getId();
    String id3 = related.addRelation().putRolePlayer(role1, graph.getConcept(entity2))
            .putRolePlayer(role2, graph.getConcept(entity4)).getId();
    graph.commit();

    // compute degrees on subgraph
    Graql.compute().degree().in("thing", "related").persist().withGraph(graph).execute();

    Map<String, Long> correctDegrees = new HashMap<>();
    correctDegrees.clear();
    correctDegrees.put(entity1, 1L);
    correctDegrees.put(entity2, 3L);
    correctDegrees.put(entity3, 1L);
    correctDegrees.put(id1, 2L);
    correctDegrees.put(id2, 2L);
    correctDegrees.put(id3, 1L);

    // assert persisted degrees are correct
    checkDegrees(correctDegrees);

    // compute again and again ...
    long numVertices = 0;
    for (int i = 0; i < 2; i++) {
        graph.graql().compute().degree().in("thing", "related").persist().execute();
        graph = factory.getGraph();
        checkDegrees(correctDegrees);

        // assert the number of vertices remain the same
        if (i == 0) {
            numVertices = graph.graql().compute().count().execute();
        } else {
            assertEquals(numVertices, graph.graql().compute().count().execute().longValue());
        }
    }

    // compute degrees on all types, again and again ...
    correctDegrees.put(entity4, 1L);
    correctDegrees.put(id3, 2L);
    for (int i = 0; i < 2; i++) {
        graph.graql().compute().degree().persist().execute();
        graph = factory.getGraph();
        checkDegrees(correctDegrees);

        // assert the number of vertices remain the same
        assertEquals(numVertices, graph.graql().compute().count().execute().longValue());
    }
}