Java Code Examples for java.util.Map.clear()

The following are Jave code examples for showing how to use clear() of the java.util.Map class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: googles-monorepo-demo   File: MapsTransformValuesTest.java   View Source Code Vote up 6 votes
public void testTransformReflectsUnderlyingMap() {
  Map<String, Integer> underlying = Maps.newHashMap();
  underlying.put("a", 1);
  underlying.put("b", 2);
  underlying.put("c", 3);
  Map<String, String> map
      = Maps.transformValues(underlying, Functions.toStringFunction());
  assertEquals(underlying.size(), map.size());

  underlying.put("d", 4);
  assertEquals(underlying.size(), map.size());
  assertEquals("4", map.get("d"));

  underlying.remove("c");
  assertEquals(underlying.size(), map.size());
  assertFalse(map.containsKey("c"));

  underlying.clear();
  assertEquals(underlying.size(), map.size());
}
 
Example 2
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   View Source Code Vote up 6 votes
/**
 * This test method takes an image with Exif Orientation information and checks if it is automatially rotated.
 */
public void testAutoRotateImage() throws Exception
{
    NodeRef companyHome = repositoryHelper.getCompanyHome();

    //Check image is there
    String imageSource = "images/rotated_gray21.512.jpg";
    File imageFile = retrieveValidImageFile(imageSource);

    //Create node and save contents
    final NodeRef newNodeForRotate = createNode(companyHome, "rotateImageNode", ContentModel.TYPE_CONTENT);
    setImageContentOnNode(newNodeForRotate, MimetypeMap.MIMETYPE_IMAGE_JPEG, imageFile);

    //Test auto rotates
    final Map<String, Serializable> parameterValues = new HashMap<String, Serializable>();        
    resizeImageAndCheckOrientation(newNodeForRotate, parameterValues, BLACK, WHITE);     
    
    //Test doesn't auto rotate
    parameterValues.clear();
    parameterValues.put(ImageRenderingEngine.PARAM_AUTO_ORIENTATION, false);
    resizeImageAndCheckOrientation(newNodeForRotate, parameterValues, WHITE, BLACK);     
    
    //Clean up
    nodeService.deleteNode(newNodeForRotate);
}
 
Example 3
Project: aws-sdk-java-v2   File: ParallelScanIntegrationTest.java   View Source Code Vote up 6 votes
private static void putTestData() {
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    Random random = new Random();
    for (int hashKeyValue = 0; hashKeyValue < itemNumber; hashKeyValue++) {
        item.put(HASH_KEY_NAME, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build());
        item.put(ATTRIBUTE_RANDOM, AttributeValue.builder().n(Integer.toString(random.nextInt(itemNumber))).build());
        if (hashKeyValue < itemNumber / 2) {
            item.put(ATTRIBUTE_FOO, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build());
        } else {
            item.put(ATTRIBUTE_BAR, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build());
        }

        dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).build());
        item.clear();
    }
}
 
Example 4
Project: cuttlefish   File: WeightedKCoreLayout.java   View Source Code Vote up 6 votes
private void computeWeightedDegree(final Map<Node, Integer> degree,
		Map<Node, Integer> weightedDegree, final double alpha,
		final double beta) {

	double weightSum;
	double w;

	weightedDegree.clear();
	for (Node v : degree.keySet()) {
		weightSum = 0;

		for (Edge e : graph.getEdges(v)) {
			Node opposite = graph.getOpposite(v, e);
			if (degree.containsKey(opposite)) {
				weightSum += normalizedWeight.get(e);
			}
		}

		w = Math.pow(degree.get(v), alpha) * Math.pow(weightSum, beta);
		w = Math.pow(w, 1 / (alpha + beta));
		weightedDegree.put(v, (int) Math.round(w));
	}
}
 
Example 5
Project: hadoop   File: TestApps.java   View Source Code Vote up 6 votes
@Test
public void testSetEnvFromInputStringWithQuotes() {
  Map<String, String> environment = new HashMap<String, String>();
  String envString = "YARN_CONTAINER_RUNTIME_TYPE=docker"
    + ",YARN_CONTAINER_RUNTIME_DOCKER_IMAGE=hadoop-docker"
    + ",YARN_CONTAINER_RUNTIME_DOCKER_LOCAL_RESOURCE_MOUNTS=\"/dir1:/targetdir1,/dir2:/targetdir2\""
    + ",YARN_CONTAINER_RUNTIME_DOCKER_ENVIRONMENT_VARIABLES=\"HADOOP_CONF_DIR=$HADOOP_CONF_DIR,HADOOP_HDFS_HOME=/hadoop\""
    ;

  Apps.setEnvFromInputString(environment, envString, File.pathSeparator);
  assertEquals("docker", environment.get("YARN_CONTAINER_RUNTIME_TYPE"));
  assertEquals("hadoop-docker", environment.get("YARN_CONTAINER_RUNTIME_DOCKER_IMAGE"));
  assertEquals("/dir1:/targetdir1,/dir2:/targetdir2", environment.get("YARN_CONTAINER_RUNTIME_DOCKER_LOCAL_RESOURCE_MOUNTS"));
  assertEquals("HADOOP_CONF_DIR=,HADOOP_HDFS_HOME=/hadoop", environment.get("YARN_CONTAINER_RUNTIME_DOCKER_ENVIRONMENT_VARIABLES"));

  environment.clear();

  environment.put("HADOOP_CONF_DIR", "etc/hadoop");
  Apps.setEnvFromInputString(environment, envString, File.pathSeparator);
  assertEquals("docker", environment.get("YARN_CONTAINER_RUNTIME_TYPE"));
  assertEquals("hadoop-docker", environment.get("YARN_CONTAINER_RUNTIME_DOCKER_IMAGE"));
  assertEquals("/dir1:/targetdir1,/dir2:/targetdir2", environment.get("YARN_CONTAINER_RUNTIME_DOCKER_LOCAL_RESOURCE_MOUNTS"));
  assertEquals("HADOOP_CONF_DIR=etc/hadoop,HADOOP_HDFS_HOME=/hadoop", environment.get("YARN_CONTAINER_RUNTIME_DOCKER_ENVIRONMENT_VARIABLES"));
}
 
Example 6
Project: sling-org-apache-sling-launchpad-integration-tests   File: PostServletUpdateTest.java   View Source Code Vote up 6 votes
public void testMixinTypes() throws IOException, JsonException {
    
    // create a node without mixin node types
    final Map <String, String> props = new HashMap <String, String> ();
    props.put("jcr:primaryType","nt:unstructured");
    final String location = testClient.createNode(postUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX, props);
    
    // assert no mixins
    String content = getContent(location + ".json", CONTENT_TYPE_JSON);
    JsonObject json = JsonUtil.parseObject(content);
    assertFalse("jcr:mixinTypes not expected to be set", json.containsKey("jcr:mixinTypes"));
    
    // add mixin
    props.clear();
    props.put("jcr:mixinTypes", "mix:versionable");
    testClient.createNode(location, props);
    
    content = getContent(location + ".json", CONTENT_TYPE_JSON);
    json = JsonUtil.parseObject(content);
    assertTrue("jcr:mixinTypes expected after setting them", json.containsKey("jcr:mixinTypes"));
    
    Object mixObject = json.get("jcr:mixinTypes");
    assertTrue("jcr:mixinTypes must be an array", mixObject instanceof JsonArray);
    
    JsonArray mix = (JsonArray) mixObject;
    assertTrue("jcr:mixinTypes must have a single entry", mix.size() == 1);
    assertEquals("jcr:mixinTypes must have correct value", "mix:versionable", mix.getString(0));

    // remove mixin
    props.clear();
    props.put("jcr:[email protected]", "-");
    testClient.createNode(location, props);

    content = getContent(location + ".json", CONTENT_TYPE_JSON);
    json = JsonUtil.parseObject(content);
    final boolean noMixins = !json.containsKey("jcr:mixinTypes") || json.getJsonArray("jcr:mixinTypes").size() == 0;
    assertTrue("no jcr:mixinTypes expected after clearing it", noMixins);
}
 
Example 7
Project: sling-org-apache-sling-launchpad-integration-tests   File: PostServletMoveTest.java   View Source Code Vote up 6 votes
public void testMoveNodeDeepRelative() throws IOException {
    final String testPath = TEST_BASE_PATH + "/new/"
        + System.currentTimeMillis();
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src", props);

    props.clear();
    props.put(SlingPostConstants.RP_OPERATION,
        SlingPostConstants.OPERATION_MOVE);
    props.put(SlingPostConstants.RP_DEST, "deep/new");

    try {
        testClient.createNode(HTTP_BASE_URL + testPath + "/src", props);
        fail("Moving node to non existing parent location should fail.");
    } catch (HttpStatusCodeException hsce) {
        // actually the status is not 200, but we get "browser" clear stati
        if (hsce.getActualStatus() != 200) {
            throw hsce;
        }
    }
}
 
Example 8
Project: sling-org-apache-sling-launchpad-integration-tests   File: PostServletCopyTest.java   View Source Code Vote up 6 votes
public void testCopyNodeDeepAbsolute() throws IOException {
    final String testPath = TEST_BASE_PATH + "/new_fail/"
        + System.currentTimeMillis();
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src", props);

    props.clear();
    props.put(SlingPostConstants.RP_OPERATION,
        SlingPostConstants.OPERATION_COPY);
    props.put(SlingPostConstants.RP_DEST, "/some/not/existing/structure");
    try {
        testClient.createNode(HTTP_BASE_URL + testPath + "/*", props);
        // not quite correct. should check status response
        fail("Moving node to non existing parent location should fail.");
    } catch (HttpStatusCodeException hsce) {
        // actually the status is not 200, but we get "browser" clear stati
        if (hsce.getActualStatus() != 200) {
            throw hsce;
        }
    }
}
 
Example 9
Project: googles-monorepo-demo   File: MapsTest.java   View Source Code Vote up 6 votes
public void testFilteredKeysFilteredReflectsBackingChanges() {
  Map<String, Integer> unfiltered = createUnfiltered();
  Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
  unfiltered.put("two", 2);
  unfiltered.put("three", 3);
  unfiltered.put("four", 4);
  assertEquals(ImmutableMap.of("two", 2, "three", 3, "four", 4), unfiltered);
  assertEquals(ImmutableMap.of("three", 3, "four", 4), filtered);

  unfiltered.remove("three");
  assertEquals(ImmutableMap.of("two", 2, "four", 4), unfiltered);
  assertEquals(ImmutableMap.of("four", 4), filtered);

  unfiltered.clear();
  assertEquals(ImmutableMap.of(), unfiltered);
  assertEquals(ImmutableMap.of(), filtered);
}
 
Example 10
Project: monarch   File: StringMapLoopsJUnitTest.java   View Source Code Vote up 6 votes
static void test(int i, int nkeys, String[] key, Class mapClass) throws Exception {
  System.out.print("Threads: " + i + "\t:");
  Map map = (Map) mapClass.newInstance();
  // Uncomment to start with a non-empty table
  // for (int j = 0; j < nkeys; j += 4) // start 1/4 occupied
  // map.put(key[j], key[j]);
  LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
  CyclicBarrier barrier = new CyclicBarrier(i + 1, timer);
  for (int t = 0; t < i; ++t)
    pool.execute(new Runner(t, map, key, barrier));
  barrier.await();
  barrier.await();
  long time = timer.getTime();
  long tpo = time / (i * (long) nops);
  System.out.print(LoopHelpers.rightJustify(tpo) + " ns per op");
  double secs = (double) (time) / 1000000000.0;
  System.out.println("\t " + secs + "s run time");
  map.clear();
}
 
Example 11
Project: uavstack   File: TailFileTaskJob.java   View Source Code Vote up 5 votes
@SuppressWarnings("rawtypes")
@Override
protected void work() {

    Map<TailFile, List<Map>> serverlogs = null;
    try {
        TailFile tf = (TailFile) this.get("tfevent");
        this.setCurrenttfref((CopyOfProcessOfLogagent) this.get("tfref"));
        // tfref = ((TaildirLogComponent) this.get("tfref"));
        serverlogs = this.getCurrenttfref().tailFileProcessSeprate(tf, true);

        for (Entry<TailFile, List<Map>> applogs : serverlogs.entrySet()) {
            if (log.isDebugEnable()) {
                log.debug(this, "### Logvalue ###: " + applogs.getValue());
            }
        }

        if (!(serverlogs.isEmpty())) {
            this.getCurrenttfref().sendLogDataBatch(serverlogs);
        }
        else {
            if (log.isDebugEnable()) {
                log.debug(this, "serverlogs is emptry!!!");
            }
        }

    }
    catch (Throwable t) {
        log.err(this, "Unable to tail files.", t);
    }
    finally {
        if (null != serverlogs) {
            serverlogs.clear();
        }
    }
}
 
Example 12
Project: weld-junit   File: ContextImpl.java   View Source Code Vote up 5 votes
public void deactivate() {
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();
    if (ctx == null) {
        return;
    }
    for (ContextualInstance<?> instance : ctx.values()) {
        try {
            instance.destroy();
        } catch (Exception e) {
            // LOGGER.warning("Unable to destroy instance" + instance.get() + " for bean: " + instance.getContextual());
        }
    }
    ctx.clear();
    currentContext.remove();
}
 
Example 13
Project: neo-java   File: IndexedSet.java   View Source Code Vote up 5 votes
@Override
public void clear() {
	innerSet.clear();
	for (final Function<E, Object> fn : indexMap.keySet()) {
		final Map<Object, Set<E>> map = indexMap.get(fn);
		map.clear();
	}
}
 
Example 14
Project: AlphaLibary   File: SimpleScoreboard.java   View Source Code Vote up 4 votes
@SuppressWarnings("deprecation")
private void update() {
    if (!holder.isOnline()) {
        deactivate();
        return;
    }
    // Title
    String handlerTitle = handler.getTitle(holder);
    String finalTitle = handlerTitle != null ? handlerTitle : ChatColor.BOLD.toString();
    if (!objective.getDisplayName().equals(finalTitle))
        objective.setDisplayName(ChatColor.translateAlternateColorCodes('&', finalTitle));
    // Entries
    List<Entry> passed = handler.getEntries(holder);
    Map<String, Integer> appeared = new HashMap<>();
    Map<FakeEntry, Integer> current = new HashMap<>();
    if (passed == null) return;
    for (Entry entry : passed) {
        // Handle the entry
        String key = entry.getName();
        Integer score = entry.getPosition();
        if (key.length() > 48) key = key.substring(0, 47);
        String appearance;
        if (key.length() > 16) {
            appearance = key.substring(16);
        } else {
            appearance = key;
        }
        if (!appeared.containsKey(appearance)) appeared.put(appearance, -1);
        appeared.put(appearance, appeared.get(appearance) + 1);
        // Get fake player
        FakeEntry faker = getFakePlayer(key, appeared.get(appearance));
        // Set score
        objective.getScore(faker.name).setScore(score);
        // Update references
        entryCache.put(faker, score);
        current.put(faker, score);
    }
    appeared.clear();
    // Remove duplicated or non-existent entries
    for (FakeEntry fakeEntry : entryCache.keySet()) {
        if (!current.containsKey(fakeEntry)) {
            entryCache.remove(fakeEntry);
            scoreboard.resetScores(fakeEntry.getName());
        }
    }
}
 
Example 15
Project: wxcard   File: ClassifyServiceImpl.java   View Source Code Vote up 4 votes
@Override
public Map updateClassify(Map map) throws Exception {
	cardClassifyDaoImpl.updateClassify(map);
	map.clear();
	return map;
}
 
Example 16
Project: empiria.player   File: ConnectionSurfacesManager.java   View Source Code Vote up 4 votes
public void resetAll(Map<ConnectionPairEntry<String, String>, ConnectionSurface> connectedSurfaces) {
    for (ConnectionSurface surface : connectedSurfaces.values()) {
        surface.removeFromParent();
    }
    connectedSurfaces.clear();
}
 
Example 17
Project: syndesis   File: SqlConnectorConnectorAutoConfiguration.java   View Source Code Vote up 4 votes
@PostConstruct
public void postConstructSqlConnectorComponent() {
    Map<String, Object> parameters = new HashMap<>();
    for (Map.Entry<String, SqlConnectorConnectorConfigurationCommon> entry : configuration
            .getConfigurations().entrySet()) {
        parameters.clear();
        SqlConnectorComponent connector = new SqlConnectorComponent(
                entry.getKey());
        connector.setCamelContext(camelContext);
        try {
            IntrospectionSupport.getProperties(entry.getValue(),
                    parameters, null, false);
            CamelPropertiesHelper.setCamelProperties(camelContext,
                    connector, parameters, false);
            connector.setOptions(parameters);
            if (ObjectHelper.isNotEmpty(customizers)) {
                for (ConnectorCustomizer<SqlConnectorComponent> customizer : customizers) {
                    boolean useCustomizer = (customizer instanceof HasId)
                            ? HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.connector.customizer",
                                    "camel.connector.sql-connector."
                                            + entry.getKey()
                                            + ".customizer",
                                    ((HasId) customizer).getId())
                            : HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.connector.customizer",
                                    "camel.connector.sql-connector."
                                            + entry.getKey()
                                            + ".customizer");
                    if (useCustomizer) {
                        LOGGER.debug(
                                "Configure connector {}, with customizer {}",
                                connector, customizer);
                        customizer.customize(connector);
                    }
                }
            }
            camelContext.addComponent(entry.getKey(), connector);
        } catch (Exception e) {
            throw new BeanCreationException(entry.getKey(), e.getMessage(),
                    e);
        }
    }
}
 
Example 18
Project: connectors   File: HttpGetConnectorAutoConfiguration.java   View Source Code Vote up 4 votes
@PostConstruct
public void postConstructHttpGetComponent() {
    Map<String, Object> parameters = new HashMap<>();
    for (Map.Entry<String, HttpGetConnectorConfigurationCommon> entry : configuration
            .getConfigurations().entrySet()) {
        parameters.clear();
        HttpGetComponent connector = new HttpGetComponent();
        connector.setCamelContext(camelContext);
        try {
            IntrospectionSupport.getProperties(entry.getValue(),
                    parameters, null, false);
            CamelPropertiesHelper.setCamelProperties(camelContext,
                    connector, parameters, false);
            connector.setOptions(parameters);
            if (ObjectHelper.isNotEmpty(customizers)) {
                for (ConnectorCustomizer<HttpGetComponent> customizer : customizers) {
                    boolean useCustomizer = (customizer instanceof HasId)
                            ? HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.connector.customizer",
                                    "camel.connector.http-get-connector."
                                            + entry.getKey()
                                            + ".customizer",
                                    ((HasId) customizer).getId())
                            : HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.connector.customizer",
                                    "camel.connector.http-get-connector."
                                            + entry.getKey()
                                            + ".customizer");
                    if (useCustomizer) {
                        LOGGER.debug(
                                "Configure connector {}, with customizer {}",
                                connector, customizer);
                        customizer.customize(connector);
                    }
                }
            }
            camelContext.addComponent(entry.getKey(), connector);
        } catch (Exception e) {
            throw new BeanCreationException(entry.getKey(), e.getMessage(),
                    e);
        }
    }
}
 
Example 19
Project: syndesis   File: SalesforceGetSObjectConnectorAutoConfiguration.java   View Source Code Vote up 4 votes
@PostConstruct
public void postConstructSalesforceGetSObjectComponent() {
    Map<String, Object> parameters = new HashMap<>();
    for (Map.Entry<String, SalesforceGetSObjectConnectorConfigurationCommon> entry : configuration
            .getConfigurations().entrySet()) {
        parameters.clear();
        SalesforceGetSObjectComponent connector = new SalesforceGetSObjectComponent(
                entry.getKey());
        connector.setCamelContext(camelContext);
        try {
            IntrospectionSupport.getProperties(entry.getValue(),
                    parameters, null, false);
            CamelPropertiesHelper.setCamelProperties(camelContext,
                    connector, parameters, false);
            connector.setOptions(parameters);
            if (ObjectHelper.isNotEmpty(customizers)) {
                for (ConnectorCustomizer<SalesforceGetSObjectComponent> customizer : customizers) {
                    boolean useCustomizer = (customizer instanceof HasId)
                            ? HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.connector.customizer",
                                    "camel.connector.salesforce-get-sobject."
                                            + entry.getKey()
                                            + ".customizer",
                                    ((HasId) customizer).getId())
                            : HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.connector.customizer",
                                    "camel.connector.salesforce-get-sobject."
                                            + entry.getKey()
                                            + ".customizer");
                    if (useCustomizer) {
                        LOGGER.debug(
                                "Configure connector {}, with customizer {}",
                                connector, customizer);
                        customizer.customize(connector);
                    }
                }
            }
            camelContext.addComponent(entry.getKey(), connector);
        } catch (Exception e) {
            throw new BeanCreationException(entry.getKey(), e.getMessage(),
                    e);
        }
    }
}
 
Example 20
Project: hadoop   File: TestDistCpWithXAttrs.java   View Source Code Vote up 4 votes
@Test
public void testPreserveXAttrs() throws Exception {
  DistCpTestUtils.assertRunDistCp(DistCpConstants.SUCCESS, rootedSrcName,
      "/dstPreserveXAttrs", "-px", conf);

  // dstDir1
  Map<String, byte[]> xAttrs = Maps.newHashMap();
  xAttrs.put(name1, value1);
  xAttrs.put(name2, value2);
  DistCpTestUtils.assertXAttrs(dstDir1, fs, xAttrs);
  
  // dstSubDir1
  xAttrs.clear();
  xAttrs.put(name1, value1);
  xAttrs.put(name3, new byte[0]);
  DistCpTestUtils.assertXAttrs(dstSubDir1, fs, xAttrs);
  
  // dstFile1
  xAttrs.clear();
  xAttrs.put(name1, value1);
  xAttrs.put(name2, value2);
  xAttrs.put(name3, new byte[0]);
  DistCpTestUtils.assertXAttrs(dstFile1, fs, xAttrs);
  
  // dstDir2
  xAttrs.clear();
  xAttrs.put(name2, value2);
  DistCpTestUtils.assertXAttrs(dstDir2, fs, xAttrs);
  
  // dstFile2
  xAttrs.clear();
  xAttrs.put(name1, value1);
  xAttrs.put(name4, new byte[0]);
  DistCpTestUtils.assertXAttrs(dstFile2, fs, xAttrs);
  
  // dstFile3
  xAttrs.clear();
  xAttrs.put(name3, new byte[0]);
  xAttrs.put(name4, new byte[0]);
  DistCpTestUtils.assertXAttrs(dstFile3, fs, xAttrs);
  
  // dstFile4
  xAttrs.clear();
  DistCpTestUtils.assertXAttrs(dstFile4, fs, xAttrs);
}