Java Code Examples for java.util.Map.Entry.setValue()

The following are Jave code examples for showing how to use setValue() of the java.util.Map.Entry 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: Desktop-master View Source Vote up 8 votes
/** make the translations of this add-on known system-wide. */
public static void registerAddOnResources(final AddOnProperties addOn, final ResourceController resourceController) {
    HashSet<String> languages = new HashSet<String>();
    languages.add(resourceController.getLanguageCode());
    languages.add(resourceController.getDefaultLanguageCode());
    for (String language : languages) {
    	final Map<String, String> resources = addOn.getTranslations().get(language);
    	if (resources != null) {
    	    for (Entry<String, String> entry : resources.entrySet()) {
    	        if (entry.getValue().indexOf('\\') != -1) {
    	            // convert \uFFFF sequences
    	            entry.setValue(StringEscapeUtils.unescapeJava(entry.getValue()));
    	        }
    	    }
    		resourceController.addLanguageResources(language, addOptionPanelPrefix(resources, addOn.getName()));
    		resourceController.addLanguageResources(language, resources);
    	}
    }
   }
 
Example 2
Project: richfaces-master View Source Vote up 6 votes
public void toggleSort() {
    for (Entry<String, SortOrder> entry : sortOrders.entrySet()) {
        SortOrder newOrder;

        if (entry.getKey().equals(sortProperty)) {
            if (entry.getValue() == SortOrder.ascending) {
                newOrder = SortOrder.descending;
            } else {
                newOrder = SortOrder.ascending;
            }
        } else {
            newOrder = SortOrder.unsorted;
        }

        entry.setValue(newOrder);
    }
}
 
Example 3
Project: SideScrollerGDW2012-Max-master View Source Vote up 6 votes
/**
 * @param input The data for the TTF font.
 * @param size The font size to use to determine kerning pixel offsets.
 * @throws IOException If the font could not be read.
 */
public void load (InputStream input, int size) throws IOException {
	this.size = size;
	if (input == null) throw new IllegalArgumentException("input cannot be null.");
	readTableDirectory(input);
	if (headOffset == -1) throw new IOException("HEAD table not found.");
	if (kernOffset == -1) {
		values = Collections.EMPTY_MAP;
		return;
	}
	values = new HashMap(256);
	if (headOffset < kernOffset) {
		readHEAD(input);
		readKERN(input);
	} else {
		readKERN(input);
		readHEAD(input);
	}
	input.close();

	for (Iterator entryIter = values.entrySet().iterator(); entryIter.hasNext();) {
		Entry entry = (Entry)entryIter.next();
		// Scale the offset values using the font size.
		List valueList = (List)entry.getValue();
		for (ListIterator valueIter = valueList.listIterator(); valueIter.hasNext();) {
			int value = ((Integer)valueIter.next()).intValue();
			int glyphCode = value & 0xffff;
			int offset = value >> 16;
			offset = Math.round(offset * scale);
			if (offset == 0)
				valueIter.remove();
			else
				valueIter.set(new Integer((offset << 16) | glyphCode));
		}
		if (valueList.isEmpty()) {
			entryIter.remove();
		} else {
			// Replace ArrayList with int[].
			int[] valueArray = new int[valueList.size()];
			int i = 0;
			for (Iterator valueIter = valueList.iterator(); valueIter.hasNext(); i++)
				valueArray[i] = ((Integer)valueIter.next()).intValue();
			entry.setValue(valueArray);
			kerningPairCount += valueArray.length;
		}
	}
}
 
Example 4
Project: McMMOPlus-master View Source Vote up 6 votes
@Override
public void run() {
    for (Iterator<Entry<LivingEntity, Integer>> bleedIterator = bleedList.entrySet().iterator(); bleedIterator.hasNext(); ) {
        Entry<LivingEntity, Integer> entry = bleedIterator.next();
        LivingEntity entity = entry.getKey();

        if (entry.getValue() <= 0 || !entity.isValid()) {
            bleedIterator.remove();
            continue;
        }

        int damage;

        if (entity instanceof Player) {
            damage = 1;
            Player player = (Player) entity;

            if (!player.isOnline()) {
                continue;
            }

            // Never kill with Bleeding
            if (player.getHealth() - damage > 0) {
                CombatUtils.dealDamage(player, damage);
                ParticleEffectUtils.playBleedEffect(entity);
            }

            entry.setValue(entry.getValue() - damage);

            if (entry.getValue() <= 0) {
                player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleeding.Stopped"));
            }
        }
        else {
            damage = 2;

            // Anticipate the entity's death to prevent CME because of our EntityDeathEvent listener
            if (entity.getHealth() - damage > 0) {
                entry.setValue(entry.getValue() - 1);
            }
            else {
                bleedIterator.remove();
            }

            CombatUtils.dealDamage(entity, damage);
            ParticleEffectUtils.playBleedEffect(entity);
        }
    }
}
 
Example 5
Project: jtotus-master View Source Vote up 6 votes
private MethodResults simpleMinWins(MethodResults result) {

        HashMap<String, Double> resultMap = result.getResults();

        Double[] results = resultMap.values().toArray(new Double[0]);
        Arrays.sort(results);

        Set<Entry<String, Double>> set = resultMap.entrySet();
        

        for (int i = results.length - 1; i >= 0; i--) {
            Iterator<Entry<String, Double>> entryIter = set.iterator();
            
            while (entryIter.hasNext()) {
                Entry<String, Double> tmpEntry = entryIter.next();
                
                if (tmpEntry.getValue() == results[i]) {
                    //System.out.printf("Hope:%d  is  %d\n", tmpEntry.getValue().intValue(), results.length - 1 - i);
                    tmpEntry.setValue(Double.valueOf(results.length - 1 - i));
                }
            }
        }

        return result;
    }
 
Example 6
Project: sisu-guice-master View Source Vote up 6 votes
@Override public Map<K, V> get() {
  // We can initialize the internal table efficiently this way and then swap the values
  // one by one.
  Map<K, Object> map = new LinkedHashMap<K, Object>(mapProvider.get());
  for (Entry<K, Object> entry : map.entrySet()) {
    @SuppressWarnings("unchecked")  // we initialized the entries with providers
    ValueProvider<V> provider = (ValueProvider<V>)entry.getValue();
    V value = provider.get();
    checkConfiguration(value != null,
        "Map injection failed due to null value for key \"%s\", bound at: %s",
        entry.getKey(),
        provider.getValueBinding().getSource());
    entry.setValue(value);
  }
  @SuppressWarnings("unchecked")  // if we exited the loop then we replaced all Providers
  Map<K, V> typedMap = (Map<K, V>) map;
  return Collections.unmodifiableMap(typedMap);
}
 
Example 7
Project: cloudtm-data-platform-master View Source Vote up 6 votes
@Test(dataProvider = "readWriteRemove", enabled = false)
public void testReadWriteRemove(int capacity, int numKeys, int concurrency, int readerThreads, int writerThreads, int removerThreads) throws Exception {
   System.out.printf("Testing independent read/write/remove performance with capacity %d, keys %d, concurrency level %d, readers %d, writers %d, removers %d\n",
         capacity, numKeys, concurrency, readerThreads, writerThreads, removerThreads);

   generateKeyList(numKeys);
   Map<String, Map<String, Integer>> maps = createMaps(capacity, numKeys, concurrency);

   for (Entry<String, Map<String, Integer>> e : maps.entrySet()) {
      mapTestReadWriteRemove(e.getKey(), e.getValue(), numKeys, readerThreads, writerThreads, removerThreads);
      e.setValue(null);
   }
}
 
Example 8
Project: molgenis-master View Source Vote up 6 votes
/**
 * Get fields for this entity as well as from the interfaces it implements.
 * 
 * @return vector of fields implemented by this entity or its interfaces
 * @throws MolgenisModelException
 */
public Vector<Field> getImplementedFields() throws MolgenisModelException
{
	// use map so we can override fields in subclasses
	Map<String, Field> all_fields = new LinkedHashMap<String, Field>();

	// first fields of the interfaces
	for (Entity iface : this.getAllImplements())
	{
		Vector<Field> ifaceFields = new Vector<Field>(iface.getAllFields());
		// Collections.copy(ifaceFields, iface.getAllFields());
		for (Field ifaceField : ifaceFields)
		{
			// ifaceField.setEntity(this);
			all_fields.put(ifaceField.getName().toLowerCase(), ifaceField);
		}
	}

	// then of self...
	for (Field f : getFields())
	{
		all_fields.put(f.getName().toLowerCase(), f);
	}

	// clean all abstract entities
	if (!this.isAbstract()) for (Entry<String, Field> entry : all_fields.entrySet())
	{
		if (entry.getValue().getEntity().isAbstract())
		{
			// copy the field and change entity
			Field value = new Field(entry.getValue());
			value.setEntity(this);
			entry.setValue(value);
		}
	}

	return new Vector<Field>(all_fields.values());
}
 
Example 9
Project: ivy-plugin-master View Source Vote up 6 votes
public Builder(BuildListener listener,Map<ModuleName,ProxyImpl2> proxies, Collection<IvyModule> modules, List<String> goals, Map<String,String> systemProps) {
    super(listener,goals,systemProps);
    this.sourceProxies = proxies;
    this.proxies = new HashMap<ModuleName, IvyBuildProxy2>(proxies);
    for (Entry<ModuleName,IvyBuildProxy2> e : this.proxies.entrySet())
        e.setValue(new FilterImpl(e.getValue()));

    for (IvyModule m : modules)
        modulePublishers.put(m.getModuleName(),m.createModulePublishers());
}
 
Example 10
Project: alien4cloud-master View Source Vote up 6 votes
private void mergeGetInputProperties(Map<String, AbstractPropertyValue> from, Map<String, AbstractPropertyValue> to) {
    if (from != null && to != null) {
        for (Entry<String, AbstractPropertyValue> entry : to.entrySet()) {
            AbstractPropertyValue fromValue = from.get(entry.getKey());
            if (fromValue instanceof FunctionPropertyValue) {
                entry.setValue(fromValue);
            }
        }
    }
}
 
Example 11
Project: REST-OCD-Services-master View Source Vote up 5 votes
private List<Pair<Integer, Integer>> determineMostSimilarCommunityPairs(Matrix similarities) throws InterruptedException {
	double maxSimilarity = Double.NEGATIVE_INFINITY;
	double currentSimilarity;
	TreeMap<Integer, Integer> mergedCommunities = new TreeMap<Integer, Integer>();
	Set<Integer> updatedCommunities = new HashSet<Integer>();
	int oldCommunity;
	int newCommunity;
	for(int j=0; j<similarities.columns() - 1; j++) {
		for(int i=j+1; i<similarities.rows(); i++) {
			if(Thread.interrupted()) {
				throw new InterruptedException();
			}
			currentSimilarity = similarities.get(i, j);
			if(currentSimilarity >= maxSimilarity) {
				if(currentSimilarity > maxSimilarity) {
					mergedCommunities.clear();
					maxSimilarity = currentSimilarity;
				}
				newCommunity = j;
				if(mergedCommunities.containsKey(j)) {
					oldCommunity = mergedCommunities.get(j);
					if(oldCommunity <= newCommunity) {
						newCommunity = oldCommunity;
					}
					else {
						updatedCommunities.add(oldCommunity);
					}
				}
				if(mergedCommunities.containsKey(i)) {
					oldCommunity = mergedCommunities.get(i);
					if(oldCommunity <= newCommunity) {
						newCommunity = oldCommunity;
					}
					else {
						updatedCommunities.add(oldCommunity);
					}
				}
				if(updatedCommunities.size() > 0) {
					for(Entry<Integer, Integer> entry : mergedCommunities.entrySet()) {
						if(updatedCommunities.contains(entry.getValue())) {
							entry.setValue(newCommunity);
						}
					}
				}
				mergedCommunities.put(j, newCommunity);
				mergedCommunities.put(i, newCommunity);
			}
		}
	}
	List<Pair<Integer, Integer>> mostSimilarPairs = new ArrayList<Pair<Integer, Integer>>();
	Entry<Integer, Integer> lastPair;
	while(mergedCommunities.size() > 0) {
		if(Thread.interrupted()) {
			throw new InterruptedException();
		}
		lastPair = mergedCommunities.lastEntry();
		if(lastPair.getKey() != lastPair.getValue()) {
			mostSimilarPairs.add(new Pair<Integer, Integer>(lastPair.getValue(), lastPair.getKey()));
		}
		mergedCommunities.remove(lastPair.getKey());
	}
	return mostSimilarPairs;
}
 
Example 12
Project: HDP-2.2-Patched-master View Source Vote up 5 votes
@Override
@SuppressWarnings("unchecked") // dispatcher not typed
public Integer call() {
  final ContainerLaunchContext launchContext = container.getLaunchContext();
  Map<Path,List<String>> localResources = null;
  ContainerId containerID = container.getContainerId();
  String containerIdStr = ConverterUtils.toString(containerID);
  final List<String> command = launchContext.getCommands();
  int ret = -1;

  // CONTAINER_KILLED_ON_REQUEST should not be missed if the container
  // is already at KILLING
  if (container.getContainerState() == ContainerState.KILLING) {
    dispatcher.getEventHandler().handle(
        new ContainerExitEvent(containerID,
            ContainerEventType.CONTAINER_KILLED_ON_REQUEST,
            Shell.WINDOWS ? ExitCode.FORCE_KILLED.getExitCode() :
                ExitCode.TERMINATED.getExitCode(),
            "Container terminated before launch."));
    return 0;
  }

  try {
    localResources = container.getLocalizedResources();
    if (localResources == null) {
      throw RPCUtil.getRemoteException(
          "Unable to get local resources when Container " + containerID +
          " is at " + container.getContainerState());
    }

    final String user = container.getUser();
    // /////////////////////////// Variable expansion
    // Before the container script gets written out.
    List<String> newCmds = new ArrayList<String>(command.size());
    String appIdStr = app.getAppId().toString();
    String relativeContainerLogDir = ContainerLaunch
        .getRelativeContainerLogDir(appIdStr, containerIdStr);
    Path containerLogDir =
        dirsHandler.getLogPathForWrite(relativeContainerLogDir, false);
    for (String str : command) {
      // TODO: Should we instead work via symlinks without this grammar?
      newCmds.add(str.replace(ApplicationConstants.LOG_DIR_EXPANSION_VAR,
          containerLogDir.toString()));
    }
    launchContext.setCommands(newCmds);

    Map<String, String> environment = launchContext.getEnvironment();
    // Make a copy of env to iterate & do variable expansion
    for (Entry<String, String> entry : environment.entrySet()) {
      String value = entry.getValue();
      entry.setValue(
          value.replace(
              ApplicationConstants.LOG_DIR_EXPANSION_VAR,
              containerLogDir.toString())
          );
    }
    // /////////////////////////// End of variable expansion

    FileContext lfs = FileContext.getLocalFSFileContext();

    Path nmPrivateContainerScriptPath =
        dirsHandler.getLocalPathForWrite(
            getContainerPrivateDir(appIdStr, containerIdStr) + Path.SEPARATOR
                + CONTAINER_SCRIPT);
    Path nmPrivateTokensPath =
        dirsHandler.getLocalPathForWrite(
            getContainerPrivateDir(appIdStr, containerIdStr)
                + Path.SEPARATOR
                + String.format(ContainerLocalizer.TOKEN_FILE_NAME_FMT,
                    containerIdStr));

    DataOutputStream containerScriptOutStream = null;
    DataOutputStream tokensOutStream = null;

    // Select the working directory for the container
    Path containerWorkDir =
        dirsHandler.getLocalPathForWrite(ContainerLocalizer.USERCACHE
            + Path.SEPARATOR + user + Path.SEPARATOR
            + ContainerLocalizer.APPCACHE + Path.SEPARATOR + appIdStr
            + Path.SEPARATOR + containerIdStr,
            LocalDirAllocator.SIZE_UNKNOWN, false);

    String pidFileSuffix = String.format(ContainerLaunch.PID_FILE_NAME_FMT,
        containerIdStr);

    // pid file should be in nm private dir so that it is not 
    // accessible by users
    pidFilePath = dirsHandler.getLocalPathForWrite(
        ResourceLocalizationService.NM_PRIVATE_DIR + Path.SEPARATOR 
        + pidFileSuffix);
    List<String> localDirs = dirsHandler.getLocalDirs();
    List<String> logDirs = dirsHandler.getLogDirs();

    List<String> containerLogDirs = new ArrayList<String>();
    for( String logDir : logDirs) {
      containerLogDirs.add(logDir + Path.SEPARATOR + relativeContainerLogDir);
    }

    if (!dirsHandler.areDisksHealthy()) {
      ret = ContainerExitStatus.DISKS_FAILED;
      throw new IOException("Most of the disks failed. "
          + dirsHandler.getDisksHealthReport());
    }

    try {
      // /////////// Write out the container-script in the nmPrivate space.
      List<Path> appDirs = new ArrayList<Path>(localDirs.size());
      for (String localDir : localDirs) {
        Path usersdir = new Path(localDir, ContainerLocalizer.USERCACHE);
        Path userdir = new Path(usersdir, user);
        Path appsdir = new Path(userdir, ContainerLocalizer.APPCACHE);
        appDirs.add(new Path(appsdir, appIdStr));
      }
      containerScriptOutStream =
        lfs.create(nmPrivateContainerScriptPath,
            EnumSet.of(CREATE, OVERWRITE));

      // Set the token location too.
      environment.put(
          ApplicationConstants.CONTAINER_TOKEN_FILE_ENV_NAME, 
          new Path(containerWorkDir, 
              FINAL_CONTAINER_TOKENS_FILE).toUri().getPath());
      // Sanitize the container's environment
      sanitizeEnv(environment, containerWorkDir, appDirs, containerLogDirs,
        localResources);
      
      // Write out the environment
      writeLaunchEnv(containerScriptOutStream, environment, localResources,
          launchContext.getCommands());
      
      // /////////// End of writing out container-script

      // /////////// Write out the container-tokens in the nmPrivate space.
      tokensOutStream =
          lfs.create(nmPrivateTokensPath, EnumSet.of(CREATE, OVERWRITE));
      Credentials creds = container.getCredentials();
      creds.writeTokenStorageToStream(tokensOutStream);
      // /////////// End of writing out container-tokens
    } finally {
      IOUtils.cleanup(LOG, containerScriptOutStream, tokensOutStream);
    }

    // LaunchContainer is a blocking call. We are here almost means the
    // container is launched, so send out the event.
    dispatcher.getEventHandler().handle(new ContainerEvent(
          containerID,
          ContainerEventType.CONTAINER_LAUNCHED));

    // Check if the container is signalled to be killed.
    if (!shouldLaunchContainer.compareAndSet(false, true)) {
      LOG.info("Container " + containerIdStr + " not launched as "
          + "cleanup already called");
      ret = ExitCode.TERMINATED.getExitCode();
    }
    else {
      exec.activateContainer(containerID, pidFilePath);
      ret = exec.launchContainer(container, nmPrivateContainerScriptPath,
              nmPrivateTokensPath, user, appIdStr, containerWorkDir,
              localDirs, logDirs);
    }
  } catch (Throwable e) {
    LOG.warn("Failed to launch container.", e);
    dispatcher.getEventHandler().handle(new ContainerExitEvent(
        containerID, ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, ret,
        e.getMessage()));
    return ret;
  } finally {
    completed.set(true);
    exec.deactivateContainer(containerID);
  }

  if (LOG.isDebugEnabled()) {
    LOG.debug("Container " + containerIdStr + " completed with exit code "
              + ret);
  }
  if (ret == ExitCode.FORCE_KILLED.getExitCode()
      || ret == ExitCode.TERMINATED.getExitCode()) {
    // If the process was killed, Send container_cleanedup_after_kill and
    // just break out of this method.
    dispatcher.getEventHandler().handle(
          new ContainerExitEvent(containerID,
              ContainerEventType.CONTAINER_KILLED_ON_REQUEST, ret,
              "Container exited with a non-zero exit code " + ret));
    return ret;
  }

  if (ret != 0) {
    LOG.warn("Container exited with a non-zero exit code " + ret);
    this.dispatcher.getEventHandler().handle(new ContainerExitEvent(
        containerID,
        ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, ret,
        "Container exited with a non-zero exit code " + ret));
    return ret;
  }

  LOG.info("Container " + containerIdStr + " succeeded ");
  dispatcher.getEventHandler().handle(
      new ContainerEvent(containerID,
          ContainerEventType.CONTAINER_EXITED_WITH_SUCCESS));
  return 0;
}
 
Example 13
Project: geoserver-enterprise-master View Source Vote up 5 votes
/**
 * Call.
 * 
 * @return the map
 * @throws Exception the exception
 */
@Override
public Map<String, Object> call() throws Exception {

    final Name processName = status.getProcessName();
    try {
        // start execution
        resourceManager.setCurrentExecutionId(status.getExecutionId());

        ProcessFactory pf = Processors.createProcessFactory(processName);
        if (pf == null) {
            throw new WPSException("No such process: " + processName);
        }

        // execute the process
        Process p = pf.create(processName);
        if (p == null) {
            throw new WPSException("Unabe to create process: " + processName);
        }

        // execute and get the output
        status.setPhase(ProcessState.RUNNING);
        Map<String, Object> result = p.execute(inputs, listener);
        String executionId = status.executionId;

        // analyze status
        if (listener.exception != null) {
            // FAILED rethrow and then catch below
            throw listener.exception;
        } else {
            // SUCCESS

            for (Entry<String, Object> entry : result.entrySet()) {
                if (entry.getKey().equalsIgnoreCase("result")) {
                    // move to WPS directory if needed
                    Object value = entry.getValue();
                    if (value instanceof File) {
                        final File outputFile = (File) value;

                        // target file
                        final File resultFile = resourceManager
                                .getStoredResponseFile(executionId);
                        final String parentDir = resultFile.getParent();
                        final File targetFile = new File(parentDir,
                                FilenameUtils.getBaseName(resultFile.getAbsolutePath())
                                        + ".zip");
                        if (!outputFile.getCanonicalPath().equals(
                                targetFile.getCanonicalPath())) {
                            // move while renaming
                            FileUtils.moveFile(outputFile, targetFile);
                            entry.setValue(targetFile);// replace value for this key
                            value = targetFile;
                        }
                    }

                    // set real output
                    if (status instanceof ClusterExecutionStatus) {
                        ((ClusterExecutionStatus) status).setOutput(value);
                    }
                    break;
                }
            }

        }
        return result;
    } catch (Throwable e) {
        listener.exceptionOccurred(e);
        status.setPhase(ProcessState.FAILED);
        throw new WPSException("Process failed", e);
    } finally {
        // update status unless cancelled
        if (status.getPhase() == ProcessState.RUNNING) {
            status.setPhase(ProcessState.COMPLETED);
        }
    }
}