Java Code Examples for java.util.Map.Entry

The following are top voted examples for showing how to use java.util.Map.Entry. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: Desktop   File: AddOnsController.java View source code 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: aws-toolkit-eclipse   File: Schema.java View source code Vote up 7 votes
public String toString() {
    String buffer = "";
    for (Entry<String, SchemaProperty> entry : properties.entrySet()) {
        buffer += " - " + entry.getKey() + ": " + entry.getValue() + "\n"; 
    }
    
    return buffer;
}
 
Example 3
Project: SAPManagerPack   File: SAPEffectRenderer.java View source code Vote up 6 votes
public void renderParticles(Entity viewingEntity, float partTicks, boolean alpha) {
    float rotX = ActiveRenderInfo.rotationX;
    float rotZ = ActiveRenderInfo.rotationZ;
    float rotYZ = ActiveRenderInfo.rotationYZ;
    float rotXY = ActiveRenderInfo.rotationXY;
    float rotXZ = ActiveRenderInfo.rotationXZ;
    EntityFX.interpPosX = viewingEntity.lastTickPosX + (viewingEntity.posX - viewingEntity.lastTickPosX) * partTicks;
    EntityFX.interpPosY = viewingEntity.lastTickPosY + (viewingEntity.posY - viewingEntity.lastTickPosY) * partTicks;
    EntityFX.interpPosZ = viewingEntity.lastTickPosZ + (viewingEntity.posZ - viewingEntity.lastTickPosZ) * partTicks;

    Collection<Entry<Integer, Pair<ResourceLocation, Boolean>>> currLayers = Collections2.filter(this.fxLayers.entrySet(), new SortingFilter(alpha));

    for( Entry<Integer, Pair<ResourceLocation, Boolean>> layer : currLayers ) {
        Pair<ResourceLocation, Boolean> layerData = layer.getValue();
        Collection<EntityParticle> particles = this.particles.get(layer.getKey());
        if( !particles.isEmpty() ) {
            Tessellator tessellator = Tessellator.instance;
            tessellator.startDrawingQuads();

            for( final EntityParticle particle : particles ) {
                if( particle == null ) {
                    continue;
                }

                tessellator.setBrightness(particle.getBrightnessForRender(partTicks));

                try {
                    particle.renderParticle(tessellator, partTicks, rotX, rotXZ, rotZ, rotYZ, rotXY);
                } catch( Throwable throwable ) {
                    throw new RuntimeException("Couldn't render particle!", throwable);
                }
            }

            this.textureManager.bindTexture(layerData.getValue0());
            GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
            if( layerData.getValue1() ) {
                GL11.glEnable(GL11.GL_BLEND);
                OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
            }

            SAPUtils.EVENT_BUS.post(new SAPFxLayerRenderEvent.Pre(layer.getKey(), tessellator));
            tessellator.draw();
            SAPUtils.EVENT_BUS.post(new SAPFxLayerRenderEvent.Post(layer.getKey()));

            if( layerData.getValue1() ) {
                GL11.glDisable(GL11.GL_BLEND);
            }
        }
    }
}
 
Example 4
Project: aws-toolkit-eclipse   File: DeployUtils.java View source code Vote up 6 votes
private static String substituteUserConfiguration(String originalContent,
        Map<String, String> paramAnchorTextAndValues) {

    for (Entry<String, String> entry : paramAnchorTextAndValues.entrySet()) {
        String anchorText = entry.getKey();
        String value = entry.getValue();

        originalContent = originalContent.replace(anchorText, value);
    }

    return originalContent;
}
 
Example 5
Project: de.htwg.se.muehle   File: GridTest.java View source code Vote up 6 votes
@Test
public void testGridIsEmpty(){

    for(Entry<Tuple, Cell> entry : this.matrix.entrySet()){
        Tuple key = entry.getKey();
        Cell value = entry.getValue();
        assertTrue(value.getCell() == TokenValues.EMPTY);
        
        
    }

}
 
Example 6
Project: TinyProtocolAPI   File: TinyProtocol.java View source code Vote up 6 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
		throws Exception {
	final Channel channel = ctx.channel();
	handleLoginStart(channel, msg);

	for (Entry<PacketListener, List<Method>> listener : IN.entrySet()) {
		for (Method method : listener.getValue()) {
			PacketHandler ann = method
					.getAnnotation(PacketHandler.class);
			if (!ann.packet().getName()
					.equals(msg.getClass().getSimpleName()))
				continue;

			PacketEvent evt = new PacketEvent(player, msg);
			method.setAccessible(true);
			method.invoke(listener.getKey(), evt);
			method.setAccessible(false);
			msg = evt.getPacket();
		}
	}
	if (msg != null) {
		super.channelRead(ctx, msg);
	}
}
 
Example 7
Project: TinyProtocolAPI   File: TinyProtocol.java View source code Vote up 6 votes
@Override
public void write(ChannelHandlerContext ctx, Object msg,
		ChannelPromise promise) throws Exception {
	for (Entry<PacketListener, List<Method>> listener : OUT.entrySet()) {
		for (Method method : listener.getValue()) {
			
			PacketHandler ann = method.getAnnotation(PacketHandler.class);
			if (!ann.packet().getName().equals(msg.getClass().getSimpleName()))
				continue;
			PacketEvent evt = new PacketEvent(player, msg);
			method.setAccessible(true);
			method.invoke(listener.getKey(), evt);
			msg = evt.getPacket();
		}
	}

	if (msg != null) {
		super.write(ctx, msg, promise);
	}
}
 
Example 8
Project: bixie   File: BasicReportPrinter.java View source code Vote up 6 votes
protected void consumeReport(Report r) {
	for (Entry<Integer, List<FaultExplanation>> entry : r.getReports().entrySet()) {
		if (!sortedReport.containsKey(entry.getKey())) {
			sortedReport.put(entry.getKey(), new HashMap<String, List<List<Integer>>>());
		}
		Map<String, List<List<Integer>>> sortedLinesPerFile = sortedReport.get(entry.getKey());
		for (FaultExplanation fe : entry.getValue()) {
			if (fe.locations.isEmpty()) {
				continue;
			}
			//get the sorted list of line numbers for this report.
			LinkedHashSet<Integer> lines = new LinkedHashSet<Integer>();
			for (SourceLocation line : fe.locations) {
				lines.add(line.StartLine);
			}
			LinkedList<Integer> sortedLines = new LinkedList<Integer>(lines);
			Collections.sort(sortedLines);
			//get the file name for this report.
			String fname = fe.fileName;
			
			if (!sortedLinesPerFile.containsKey(fname)) {
				sortedLinesPerFile.put(fname, new LinkedList<List<Integer>>());
			}
			sortedLinesPerFile.get(fname).add(sortedLines);
		}
		
	}
}
 
Example 9
Project: bixie   File: Report.java View source code Vote up 6 votes
/**
 * Apply fault localization from the FSE13 paper to all reported 
 * inconsistencies.
 * @param tr 
 */
public void runFaultLocalization() {		
	for (Entry<Integer, Set<Set<BasicBlock>>> entry : this.inconsistentBlocks.entrySet()) {
		for (Set<BasicBlock> inconsistency : entry.getValue()) {
			try {
				runFaultLocalization(entry.getKey(), inconsistency);
			} catch (Throwable e) {
				return;
			}
		}
	}
}
 
Example 10
Project: virgo.kernel   File: ServiceScoper.java View source code Vote up 6 votes
/**
 * Updates the [email protected] StandardScopeServiceRepository} with the service information from the given config files.
 * 
 * @param scopeName the name of the scope.
 * @param configFiles the config files to scope.
 * @throws DeploymentException
 */
private void doScope(Map<ArtifactFS, List<ArtifactFSEntry>> configFiles) throws DeploymentException {
    SpringConfigServiceModelScanner scanner = new SpringConfigServiceModelScanner(this.scopeName, this.repository, this.eventLogger);
    Map<ArtifactFS, BundleManifest> manifests = loadBundleManifests(configFiles.keySet());
    for (Entry<ArtifactFS, List<ArtifactFSEntry>> entry : configFiles.entrySet()) {
        BundleManifest bundleManifest = manifests.get(entry.getKey());
        for (ArtifactFSEntry configFile : entry.getValue()) {
            InputStream is = configFile.getInputStream();
            try {
                scanner.scanConfigFile(bundleManifest.getBundleSymbolicName().getSymbolicName(), bundleManifest.getBundleVersion(),
                    configFile.getPath(), is);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    }
}
 
Example 11
Project: virgo.kernel   File: UsesAnalyser.java View source code Vote up 6 votes
private PackageSources computeUsesClosure(State state, PackageSources packages) {
    // Compute all the exports visible through transitive uses from directPackages
    PackageSources additionalPackages = constructEmptyPackageSources();
    Set<Entry<String, Set<SourcedPackage>>> keys = packages.entrySet();

    Set<String> knownPackages = new HashSet<String>();

    for (Entry<String, Set<SourcedPackage>> key : keys) {
        for (SourcedPackage sp : key.getValue()) {
            ExportPackageDescription source = sp.getSource();
            addUsedImportedPackages(state, additionalPackages, source, source, knownPackages);
        }
    }
    return additionalPackages;
}
 
Example 12
Project: richfaces   File: ITestJsFunction.java View source code Vote up 6 votes
@Test
public void testMouseOverSpecificTdElement() {
    /*
     * Move mouse over all td elements and check whether the showName is same as text of particular td element then move
     * mouse out of td element and check whether the output is empty
     */

    for (Entry<String, WebElement> entry : page.getNames().entrySet()) {
        String name = entry.getKey();
        WebElement element = entry.getValue();
        activate(element);
        Graphene.waitGui().until("The text in output should be same as in the active td!").element(page.getOutput()).text()
            .equalTo(name);
    }
}
 
Example 13
Project: richfaces   File: PersonBean.java View source code 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 14
Project: aws-toolkit-eclipse   File: TemplateEditor.java View source code Vote up 6 votes
private TemplateNode findNode(int documentOffset, TemplateNode node) {
    if (node.getStartLocation().getCharOffset() > documentOffset) {
        throw new RuntimeException("Out of bounds in node search");
    }

    if (node.isObject()) {
        TemplateObjectNode object = (TemplateObjectNode)node;
        for (Entry<String, TemplateNode> entry : object.getFields()) {
            entry.getKey();
            if (match(documentOffset, entry.getValue())) {
                return findNode(documentOffset, entry.getValue());
            }
        }
    } else if (node.isArray()) {
        TemplateArrayNode array = (TemplateArrayNode)node;
        for (TemplateNode member : array.getMembers()) {
            if (match(documentOffset, member)) {
                return findNode(documentOffset, member);
            }
        }
    }
    return node;
}
 
Example 15
Project: virgo.kernel   File: AbstractTrackedPackageImports.java View source code Vote up 6 votes
/**
 * Merge the attributes of the source package import into those of the target package import. Throw
 * [email protected] ImportMergeException} if and only if there is a merge clash.
 * 
 * @param targetPackageImport the package import to be merged and updated
 * @param sourceImportToMerge the package import to be merged in
 * @throws ImportMergeException thrown if there is a merge clash
 */
private void mergeAttributes(ImportedPackage targetPackageImport, ImportedPackage sourceImportToMerge) throws ImportMergeException {
    Map<String, String> targetAttributes = targetPackageImport.getAttributes();
    Map<String, String> sourceAttributes = sourceImportToMerge.getAttributes();

    // Merge attributes before versions so, for example, conflicting bundle symbolic names take precedence over disjoint bundle version ranges.
    for (Entry<String, String> sourceAttributeEntry : sourceAttributes.entrySet()) {
        String sourceAttributeName = sourceAttributeEntry.getKey();
        if (!isVersionAttribute(sourceAttributeName)) {
            String sourceAttributeValue = sourceAttributeEntry.getValue();
            String targetAttributeValue = targetAttributes.get(sourceAttributeName);
            if (targetAttributeValue != null) {
                if (!targetAttributeValue.equals(sourceAttributeValue)) {
                    throw new ImportMergeException(targetPackageImport.getPackageName(), getPackageSources(targetPackageImport),
                        "conflicting values '" + sourceAttributeValue + "', '" + targetAttributeValue + "' of attribute '" + sourceAttributeName
                        + "'");
                }
            } else {
                targetAttributes.put(sourceAttributeName, sourceAttributeValue);
            }
        }
    }
    
    mergeVersionRanges(targetPackageImport, sourceImportToMerge);

    mergeBundleVersionRanges(targetPackageImport, sourceImportToMerge);
}
 
Example 16
Project: richfaces   File: IgnoreScriptsContent.java View source code Vote up 6 votes
private String lookupIdMapping(String id, String newId) {

        // look for most recent mapping match or prefix-match
        String mapping = null;
        for (Entry<String, String> entry : idMapping.entrySet()) {
            final String referenceId = entry.getKey();
            final String mappedId = entry.getValue();

            if (id.equals(referenceId)) {
                return entry.getValue();
            }

            final String referenceIdPrefix = referenceId + ":";
            final String mappedIdPrefix = mappedId + ":";
            if (id.startsWith(referenceIdPrefix)) {
                mapping = id.replaceFirst("^" + referenceIdPrefix, mappedIdPrefix);
            }
        }

        if (mapping == null) {
            mapping = newId;
        }

        idMapping.put(id, newId);

        return mapping;
    }
 
Example 17
Project: phonegap-geolocation   File: RawHeaders.java View source code Vote up 6 votes
/**
 * Creates a new instance from the given map of fields to values. If
 * present, the null field's last element will be used to set the status
 * line.
 */
public static RawHeaders fromMultimap(Map<String, List<String>> map, boolean response)
    throws IOException {
  if (!response) throw new UnsupportedOperationException();
  RawHeaders result = new RawHeaders();
  for (Entry<String, List<String>> entry : map.entrySet()) {
    String fieldName = entry.getKey();
    List<String> values = entry.getValue();
    if (fieldName != null) {
      for (String value : values) {
        result.addLenient(fieldName, value);
      }
    } else if (!values.isEmpty()) {
      result.setStatusLine(values.get(values.size() - 1));
    }
  }
  return result;
}
 
Example 18
Project: jena   File: BaseXMLWriter.java View source code Vote up 6 votes
String xmlnsDecl() {
	workOutNamespaces();
	StringBuilder result = new StringBuilder();
	Iterator<Entry<String, String>> it = ns.entrySet().iterator();
	while (it.hasNext()) {
		Entry<String, String> ent = it.next();
		String prefix = ent.getValue();
		String uri = ent.getKey();
           result.append( newline ).append( "    xmlns" );
		if (prefix.length() > 0) result.append( ':' ).append( prefix );
		result.append( '=' ).append( substitutedAttribute( checkURI( uri ) ) );
	}
	return result.toString();
}
 
Example 19
Project: jena   File: N3JenaWriterCommon.java View source code Vote up 6 votes
protected void processModel(Model model)
{
    prefixMap = model.getNsPrefixMap() ;
    bNodesMap = new HashMap<>() ;

    for ( Iterator<Entry<String, String>> iter = prefixMap.entrySet().iterator() ; iter.hasNext() ; )
    {
        Entry<String, String> e = iter.next() ;
        String prefix = e.getKey() ;
        String uri = e.getValue(); 
        
        // XML namespaces name can include '.'
        // Turtle prefixed names can't.
        if ( ! checkPrefixPart(prefix) ) 
            iter.remove() ;
        else
        {
            if ( checkPrefixPart(prefix) )
                // Build acceptable reverse mapping  
                reversePrefixMap.put(uri, prefix) ;
        }
    }
    
    startWriting() ;
    prepare(model) ;

    writeHeader(model) ;
    writePrefixes(model) ;
    
    if (prefixMap.size() != 0)
        out.println();

    // Do the output.
    writeModel(model) ;

    // Release intermediate memory - allows reuse of a writer
    finishWriting() ;
    bNodesMap = null ;
}
 
Example 20
Project: SideScrollerGDW2012-Max   File: Kerning.java View source code 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 21
Project: McMMOPlus   File: BleedTimerTask.java View source code 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 22
Project: jtotus   File: Normalizer.java View source code 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 23
Project: sisu-guice   File: MapBinder.java View source code 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 24
Project: cloudtm-data-platform   File: MapStressTest.java View source code 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 25
Project: molgenis   File: Entity.java View source code 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 26
Project: ivy-plugin   File: IvyModuleSetBuild.java View source code 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 27
Project: alien4cloud   File: InputsPreProcessorService.java View source code 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 28
Project: NucleusFramework   File: MultiBiMap.java View source code Vote up 6 votes
@Override
public boolean remove(Object o) {
    Set<Entry<K, Collection<V>>> entrySet = _keyToValue.asMap().entrySet();
    //noinspection SuspiciousMethodCalls
    if (!entrySet.contains(o))
        return false;

    for (Entry<K, Collection<V>> entry : entrySet) {
        if (entry.equals(o)) {
            return !MultiBiMap.this.removeAll(entry.getKey()).isEmpty();
        }
    }

    return false;
}
 
Example 29
Project: CarpoolBackend   File: StatisticAnalysisOfDataService.java View source code Vote up 6 votes
public static ArrayList<Entry<Long,Integer>> sortMap(HashMap<Long,Integer> map){
	ArrayList<Entry<Long,Integer>> list = new ArrayList<Entry<Long,Integer>>();		
	Entry<Long,Integer> maxEntry = null;
	Entry<Long,Integer> pre = null;
	while(map.size()>0){
		for(Entry<Long,Integer> entry : map.entrySet()) {
			if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
				maxEntry = entry;
			}
		}
		if(!list.contains(maxEntry))list.add(maxEntry);
		map.remove(maxEntry.getKey());
		if(pre!=null && pre.equals(maxEntry)){
			maxEntry=null;
			pre = null;
		}
		else pre = maxEntry;
	}

	return list;

}
 
Example 30
Project: usergrid   File: Export.java View source code Vote up 6 votes
@Override
public void runTool( CommandLine line ) throws Exception {
    startSpring();

    setVerbose( line );

    // ExportDataCreator dataCreator = new ExportDataCreator(emf,
    // managementService);
    // dataCreator.createTestData();

    applyOrgId( line );
    prepareBaseOutputFileName( line );
    outputDir = createOutputParentDir();
    logger.info( "Export directory: " + outputDir.getAbsolutePath() );

    // Export organizations separately.
    exportOrganizations();

    // Loop through the organizations
    Map<UUID, String> organizations = getOrgs();
    for ( Entry<UUID, String> organization : organizations.entrySet() ) {

        if ( organization.equals( properties.getProperty( "usergrid.test-account.organization" ) ) ) {
            // Skip test data from being exported.
            continue;
        }

        exportApplicationsForOrg( organization );
    }
}
 
Example 31
Project: SchemaCrawler   File: LinterRedundantIndexes.java View source code Vote up 6 votes
private Set<Index> findRedundantIndexes(final Collection<Index> indexes)
{
  final Set<Index> redundantIndexes = new HashSet<>();

  if (indexes == null || indexes.isEmpty())
  {
    return redundantIndexes;
  }

  final Map<Index, List<String>> indexColumns = new HashMap<>(indexes.size());
  for (final Index index: indexes)
  {
    indexColumns.put(index, MetaDataUtility.columnNames(index));
  }

  for (final Entry<Index, List<String>> indexColumnEntry1: indexColumns
    .entrySet())
  {
    for (final Entry<Index, List<String>> indexColumnEntry2: indexColumns
      .entrySet())
    {
      if (!indexColumnEntry1.equals(indexColumnEntry2))
      {
        if (listStartsWith(indexColumnEntry1.getValue(),
                           indexColumnEntry2.getValue()))
        {
          redundantIndexes.add(indexColumnEntry2.getKey());
        }
      }
    }
  }
  return redundantIndexes;
}
 
Example 32
Project: SpaceDefence   File: Statebox.java View source code Vote up 6 votes
public synchronized boolean removeClientSocket(Socket s) {
	for (Entry<Integer, Socket> socket : clients.entrySet()) {
		if (socket.equals(s)) {
			return clients.remove(socket.getKey()) != null;
		}
	}
	return false;
}
 
Example 33
Project: FreeBuilder   File: MultimapSubject.java View source code Vote up 6 votes
ContainmentAssertion<K, V> and(Entry<K, V> entry) {
  expected.add(entry);
  if (!entryIterator.hasNext()) {
    fail("contains", expected, "is missing", entry);
    return new FailedContainmentAssertion();
  }
  Entry<K, V> actualEntry = entryIterator.next();
  if (entry.equals(actualEntry)) {
    return this;
  }

  // The subject does not match the order specified by the user, but the entry may still be
  // present. Delegate to an OutOfOrderContainmentAssertion.
  Multimap<K, V> remaining = ArrayListMultimap.create();
  remaining.put(actualEntry.getKey(), actualEntry.getValue());
  while (entryIterator.hasNext()) {
    actualEntry = entryIterator.next();
    remaining.put(actualEntry.getKey(), actualEntry.getValue());
  }
  expected.remove(expected.size() - 1);
  return new OutOfOrderContainmentAssertion(expected, remaining).and(entry);
}
 
Example 34
Project: schemacrawler   File: LinterRedundantIndices.java View source code Vote up 6 votes
private Set<Index> findRedundantIndices(final Collection<Index> indices)
{
  final Set<Index> redundantIndices = new HashSet<Index>();
  final Map<Index, List<String>> indexColumns = new HashMap<Index, List<String>>(indices
    .size());
  for (final Index index: indices)
  {
    indexColumns.put(index, columns(index));
  }

  for (final Entry<Index, List<String>> indexColumnEntry1: indexColumns
    .entrySet())
  {
    for (final Entry<Index, List<String>> indexColumnEntry2: indexColumns
      .entrySet())
    {
      if (!indexColumnEntry1.equals(indexColumnEntry2))
      {
        if (listStartsWith(indexColumnEntry1.getValue(),
                           indexColumnEntry2.getValue()))
        {
          redundantIndices.add(indexColumnEntry2.getKey());
        }
      }
    }
  }
  return redundantIndices;
}
 
Example 35
Project: REST-OCD-Services   File: WeightedLinkCommunitiesAlgorithm.java View source code 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 36
Project: HDP-2.2-Patched   File: ContainerLaunch.java View source code 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 37
Project: geoserver-enterprise   File: ClusterProcessManager.java View source code 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);
        }
    }
}
 
Example 38
Project: earthsci   File: ColorMapEditor.java View source code Vote up 5 votes
/**
 * Add a new entry in the colour map that is:
 * <ul>
 * <li>Half way between the selected entry and the previous entry (if one
 * exists); or
 * <li>Half way between the selected entry and the min value (if no previous
 * entry exists and selected != min)
 * <li>Half way between the selected entry and the next entry (if min entry
 * is selected); or
 * <li>Half way between the selected entry and the max value (if min entry
 * is selected and no other entry exists); or
 * <li>Half way between the min value and the max value (if no entries exist
 * in the table)
 * </ul>
 * 
 */
private void addNewEntry()
{
	Double newEntryValue = getMinValue();

	Entry<Double, Color> selectedEntry = getSelectedTableEntry();
	if (selectedEntry == null)
	{
		// If nothing selected, either choose the first entry or the mid point
		if (map.isEmpty())
		{
			newEntryValue = getMinValue() + (getMaxValue() - getMinValue()) / 2;
		}
		else
		{
			selectedEntry = map.getFirstEntry();
		}
	}

	if (selectedEntry != null)
	{
		if (map.getSize() == 1)
		{
			// Map only contains one entry
			if (selectedEntry.getKey() == getMinValue())
			{
				// Selected entry is min value - go higher
				newEntryValue = getMinValue() + (getMaxValue() - getMinValue()) / 2;
			}
			else
			{
				// Otherwise go lower
				newEntryValue = getMinValue() + (selectedEntry.getKey() - getMinValue()) / 2;
			}
		}
		else
		{
			// Map contains more than one entry
			if (selectedEntry.equals(map.getFirstEntry()))
			{
				// Selected entry is first entry 
				if (selectedEntry.getKey() == getMinValue())
				{
					// Go between selected and next
					double nextValue = map.getNextEntry(getMinValue()).getKey();
					newEntryValue = getMinValue() + (nextValue - getMinValue()) / 2;
				}
				else
				{
					// Go between selected and min value
					newEntryValue = getMinValue() + (selectedEntry.getKey() - getMinValue()) / 2;
				}
			}
			else
			{
				// Selected entry is not first - go between previous entry
				double previousValue = map.getPreviousEntry(selectedEntry.getKey()).getKey();
				newEntryValue = previousValue + (selectedEntry.getKey() - previousValue) / 2;
			}
		}
	}

	Color newEntryColor = map.getColor(newEntryValue);
	map.addEntry(newEntryValue, newEntryColor);

}