List of usage examples for com.google.common.collect BiMap inverse
BiMap<V, K> inverse();
From source file:com.opengamma.bbg.loader.BloombergSecurityTypeResolver.java
@Override public Map<ExternalIdBundle, SecurityType> getSecurityType(Collection<ExternalIdBundle> identifiers) { ArgumentChecker.notNull(identifiers, "identifiers"); final Map<ExternalIdBundle, SecurityType> result = Maps.newHashMap(); final BiMap<String, ExternalIdBundle> bundle2Bbgkey = BloombergDataUtils .convertToBloombergBuidKeys(identifiers, _referenceDataProvider); Map<String, FudgeMsg> securityTypeResult = ReferenceDataProviderUtils.getFields(bundle2Bbgkey.keySet(), BBG_FIELDS, _referenceDataProvider); for (ExternalIdBundle identifierBundle : identifiers) { String bbgKey = bundle2Bbgkey.inverse().get(identifierBundle); if (bbgKey != null) { FudgeMsg fudgeMsg = securityTypeResult.get(bbgKey); if (fudgeMsg != null) { String bbgSecurityType = fudgeMsg.getString(BloombergConstants.FIELD_SECURITY_TYPE); String futureCategory = fudgeMsg.getString(BloombergConstants.FIELD_FUTURES_CATEGORY); SecurityType securityType = null; if (bbgSecurityType != null) { if (bbgSecurityType.toUpperCase().contains(" FUTURE")) { s_logger.debug("s_futureTypes {}", s_futureTypes); securityType = s_futureTypes.get(futureCategory); } else if (bbgSecurityType.toUpperCase().contains(" OPTION")) { // Special case handling for EQUITY_INDEX_DIVIDEND_FUTURE_OPTION which we // are otherwise unable to distinguish from EQUITY_INDEX_FUTURE_OPTION String name = fudgeMsg.getString(BloombergConstants.FIELD_NAME); securityType = isEquityIndexFutureDividendOption(futureCategory, name) ? SecurityType.EQUITY_INDEX_DIVIDEND_FUTURE_OPTION : s_optionTypes.get(futureCategory); } else if (bbgSecurityType.toUpperCase().endsWith("SWAP")) { securityType = s_swapTypes.get(bbgSecurityType); } else { securityType = s_miscTypes.get(bbgSecurityType); }// ww w .ja v a 2s . c om } if (securityType != null) { result.put(identifierBundle, securityType); } else { s_logger.warn("Unknown security type of {} for {}", bbgSecurityType, identifierBundle); } } } } return result; }
From source file:de.iteratec.iteraplan.elasticeam.util.I18nMap.java
/** * Adds a new metamodel element and name to the map. * /* www .j ava 2 s . c om*/ * @param locale * The locale of the name. * @param key * The name. * @param value * The metamodel element. */ public void set(Locale locale, String key, N value) { if (!this.valueByLocalizedName.containsKey(locale)) { BiMap<String, N> localeValues = HashBiMap.create(); this.valueByLocalizedName.put(locale, localeValues); } BiMap<String, N> localeValues = this.valueByLocalizedName.get(locale); if (localeValues.containsKey(key) && !value.equals(localeValues.get(key))) { throw new MetamodelException(ElasticeamException.GENERAL_ERROR, "Duplicate locale name " + key + " in locale " + locale + "."); } if (key == null) { localeValues.inverse().remove(value); } else { if (localeValues.inverse().containsKey(value)) { localeValues.inverse().remove(value); } localeValues.put(key, value); } }
From source file:com.wolvereness.overmapped.OverMapped.java
private void process() throws Throwable { validateInput();/*from w w w . j av a2 s . co m*/ final MultiProcessor executor = MultiProcessor.newMultiProcessor(cores - 1, new ThreadFactoryBuilder().setDaemon(true) .setNameFormat(OverMapped.class.getName() + "-processor-%d") .setUncaughtExceptionHandler(this).build()); final Future<?> fileCopy = executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { if (original != null) { if (original.exists()) { original.delete(); } Files.copy(input, original); } return null; } }); final Future<Iterable<?>> mappings = executor.submit(new Callable<Iterable<?>>() { @Override public Iterable<?> call() throws Exception { final Object yaml = new Yaml().load(Files.toString(maps, Charset.forName("UTF8"))); if (yaml instanceof Iterable) return (Iterable<?>) yaml; if (yaml instanceof Map) return ImmutableList.of(yaml); throw new ClassCastException(String.format("%s (%s) implements neither %s nor %s", yaml, yaml == null ? Object.class : yaml.getClass(), Iterable.class, Map.class)); } }); final Map<String, ByteClass> byteClasses = newLinkedHashMap(); final List<Pair<ZipEntry, byte[]>> fileEntries = newArrayList(); readClasses(executor, byteClasses, fileEntries); try { reorderEntries(byteClasses); } catch (final CircularOrderException ex) { final Throwable throwable = new MojoFailureException("Circular class hiearchy detected"); throwable.initCause(ex); throw throwable; } final Multimap<String, String> depends = processDepends(byteClasses); final Multimap<String, String> rdepends = processReverseDepends(depends); final BiMap<String, String> nameMaps = HashBiMap.create(byteClasses.size()); final BiMap<String, String> inverseNameMaps = nameMaps.inverse(); final BiMap<Signature, Signature> signatureMaps = HashBiMap.create(); final BiMap<Signature, Signature> inverseSignatureMaps = signatureMaps.inverse(); final Map<Signature, Integer> flags = newHashMap(); final Remapper inverseMapper = new Remapper() { @Override public String map(final String typeName) { final String name = inverseNameMaps.get(typeName); if (name != null) return name; return typeName; } }; prepareSignatures(byteClasses, rdepends, nameMaps, signatureMaps); final Signature.MutableSignature signature = Signature.newMutableSignature("", "", ""); final Set<String> searchCache = newHashSet(); for (final Object mapping : mappings.get()) { final Map<?, ?> map = (Map<?, ?>) mapping; for (final SubRoutine subRoutine : SubRoutine.SUB_ROUTINES) { try { subRoutine.invoke(this, byteClasses, depends, rdepends, nameMaps, inverseNameMaps, signatureMaps, inverseSignatureMaps, inverseMapper, signature, searchCache, flags, map); } catch (final Exception ex) { final Throwable throwable = new MojoFailureException("Failed to parse mappings in " + mapping); throwable.initCause(ex); throw throwable; } } } try { fileCopy.get(); } catch (final ExecutionException ex) { throw new MojoFailureException(String.format("Could not copy `%s' to `%s'", input, original)); } writeToFile(executor, byteClasses, fileEntries, nameMaps, signatureMaps, flags); executor.shutdown(); final Pair<Thread, Throwable> uncaught = this.uncaught; if (uncaught != null) throw new MojoExecutionException(String.format("Uncaught exception in %s", uncaught.getLeft()), uncaught.getRight()); }
From source file:org.biokoframework.systema.injection.SystemAMainModule.java
@Override protected void configureMain() { bindProperty("systemName").to("system-a"); bindProperty("systemVersion").to("1.0"); bindProperty("Commands").to(SystemACommands.class); bind(IHandlerLocator.class).to(AnnotationHandlerLocator.class); BiMap<String, String> headerToFieldMap = HashBiMap.create(); headerToFieldMap.put("Engaged-Auth-Token", "authToken"); headerToFieldMap.put("Engaged-Auth-Token-Expire", "authTokenExpire"); headerToFieldMap = Maps.unmodifiableBiMap(headerToFieldMap); bind(new TypeLiteral<Map<String, String>>() { }).annotatedWith(Names.named("httpHeaderToFieldsMap")).toInstance(headerToFieldMap); bind(new TypeLiteral<Map<String, String>>() { }).annotatedWith(Names.named("fieldsHttpHeaderToMap")).toInstance(headerToFieldMap.inverse()); }
From source file:com.zimbra.cs.account.callback.CheckPortConflict.java
private void checkServerWithNewDefaults(Server server, BiMap<String, String> newDefaults, Map<String, Object> configAttrsToModify) throws ServiceException { Map<String, String> ports = new HashMap<String, String>(); for (String attrName : sPortAttrs) { String newValue = null;//from w ww . j av a2 s . c o m String curValue = server.getAttr(attrName, false); // value on the server entry if (curValue == null) newValue = newDefaults.inverse().get(attrName); // will inherit from new default else newValue = curValue; if (conflict(server, ports, newValue, attrName)) { String conflictWith = ports.get(newValue); // throw only when the attr is one of the attrs being modified, otherwise, just let it pass. if (configAttrsToModify.containsKey(attrName) || configAttrsToModify.containsKey(conflictWith)) throw ServiceException.INVALID_REQUEST("port " + newValue + " conflict between " + attrName + " and " + ports.get(newValue) + " on server " + server.getName(), null); } else ports.put(newValue, attrName); } }
From source file:com.google.android.apps.common.testing.accessibility.framework.AccessibilityInfoHierarchyCheck.java
/** * Delegate a legacy {@link AccessibilityNodeInfo} based check to a more recent {@link * AccessibilityHierarchyCheck}// w ww . j a va 2 s. c o m * * @param root The root node of the hierarchy to check * @param fromCheck The legacy check which calls this method * @param toCheck The AccessibilityHierarchyCheck to be run * @param context The {@link Context} used to capture hierarchy and device state * @param metadata An optional {@link Metadata} that may contain check metadata defined by {@link * AccessibilityCheckMetadata} * @return A list of interesting results encountered while running the check. The list will be * empty if the check passes without incident */ @SuppressWarnings("deprecation") // AccessibilityInfoCheckResult used for legacy check delegation protected List<AccessibilityInfoCheckResult> runDelegationCheckOnInfo(AccessibilityNodeInfo root, AccessibilityCheck fromCheck, AccessibilityHierarchyCheck toCheck, Context context, @Nullable Metadata metadata) { Locale locale = Locale.ENGLISH; // Construct the AccessibilityHierarchy from the actual root, as to capture all available // information within the hierarchy. AccessibilityNodeInfo current = AccessibilityNodeInfo.obtain(root); AccessibilityNodeInfo next = current.getParent(); while (next != null) { current.recycle(); current = next; next = next.getParent(); } AccessibilityNodeInfo actualRoot = current; BiMap<Long, AccessibilityNodeInfo> mapFromElementIdToInfo = HashBiMap.<Long, AccessibilityNodeInfo>create(); AccessibilityHierarchy hierarchy = AccessibilityHierarchy.newBuilder(actualRoot, context) .setNodeInfoOriginMap(mapFromElementIdToInfo).build(); // Although we captured our hierarchy from the actual root view, we pass along information about // the provided "root" in order to constrain evaluation to the provided sub-hierarchy. Long rootId = mapFromElementIdToInfo.inverse().get(root); ViewHierarchyElement evalRoot = (rootId != null) ? hierarchy.getViewById(rootId) : null; if (evalRoot == null) { LogUtils.log(this, Log.ERROR, "Unable to determine root during accessibility check delegation, using full hierarchy."); } // Run the delegated check List<AccessibilityHierarchyCheckResult> hierarchyCheckResults = toCheck.runCheckOnHierarchy(hierarchy, evalRoot, metadata); // Remap results to the original format ArrayList<AccessibilityInfoCheckResult> results = new ArrayList<>(hierarchyCheckResults.size()); for (AccessibilityHierarchyCheckResult hierarchyCheckResult : hierarchyCheckResults) { ViewHierarchyElement element = hierarchyCheckResult.getElement(); AccessibilityNodeInfo checkedInfo = (element != null) ? mapFromElementIdToInfo.get(element.getCondensedUniqueId()) : null; results.add(new AccessibilityInfoCheckResult(fromCheck.getClass(), hierarchyCheckResult.getType(), hierarchyCheckResult.getMessage(locale), checkedInfo)); } return results; }
From source file:edu.umd.cs.psl.evaluation.debug.CmdDebugger.java
private void printGroundKernels(Collection<GroundKernel> evidences) { BiMap<Integer, Atom> biatomHandles = HashBiMap.create(); int counter = 1; for (GroundKernel e : evidences) { String str = printGroundKernels(e); StringBuilder dep = new StringBuilder(); dep.append("--> Affected Atoms: "); Collection<Atom> atoms = e.getAtoms(); for (Atom a : atoms) { int atomNr = -1; if (biatomHandles.containsValue(a)) { atomNr = biatomHandles.inverse().get(a); } else { atomNr = counter;/*from w ww.j a v a 2 s . c o m*/ counter++; biatomHandles.put(atomNr, a); } str.replace(a.toString(), a.toString() + " [" + atomNr + "]"); dep.append(AtomPrinter.atomDetails(a)).append(" [" + atomNr + "]").append(" , "); } println(str); println(dep.toString()); } atomHandles = biatomHandles; }
From source file:com.google.android.apps.common.testing.accessibility.framework.uielement.AccessibilityHierarchy.java
/** * Find the element with the condensed unique ID corresponding to the {@code targetNode} in the * value of {@code originMap}, or {@code null} if no element is found with that ID. * * @param originMap A map from condensed unique IDs to the originating {@link * AccessibilityNodeInfo} structures from which a {@link ViewHierarchyElement} was * constructed, as populated by {@link AccessibilityHierarchy} constructors. *///w w w . j av a2 s . co m private @Nullable ViewHierarchyElement findElementByNodeInfo(AccessibilityNodeInfo targetNode, BiMap<Long, AccessibilityNodeInfo> originMap) { Long viewId = originMap.inverse().get(targetNode); if (viewId == null) { return null; } return getViewById(viewId); }
From source file:org.ldp4j.application.lifecycle.EnvironmentImpl.java
private void addPublication(final BiMap<ResourceId, String> rootResourceMap, RootResource candidateResource) throws ApplicationConfigurationException { candidateResource.validate();/* w w w . j a v a 2s . c o m*/ ResourceId resourceId = candidateResource.resourceId(); String path = candidateResource.path(); String prevPath = rootResourceMap.get(resourceId); if (prevPath != null && !prevPath.equals(path)) { throw new ApplicationConfigurationException( "Resource " + toString(resourceId) + "' is already published (" + prevPath + ")"); } ResourceId prevResource = rootResourceMap.inverse().get(path); if (prevResource != null && !prevResource.equals(resourceId)) { throw new ApplicationConfigurationException( "Path '" + path + "' is already used for resource " + toString(prevResource)); } rootResourceMap.put(resourceId, path); }
From source file:de.iteratec.iteraplan.elasticeam.model.compare.impl.DiffBuilderImpl.java
/** * Modifies the "rightValues" collection of assigned elements by adding from "leftValues" and/or * removing elements according to the rules of the active {@link DiffMode}. *//*from w w w.j a va2 s . c om*/ private Collection<UniversalModelExpression> fixRelationshipRightValuesForDiffMode( Collection<UniversalModelExpression> rightValues, Collection<UniversalModelExpression> leftValues, RelationshipEndExpression re, BiMap<UniversalModelExpression, UniversalModelExpression> left2right) { List<UniversalModelExpression> droppedLefts = Lists.newArrayList(leftValues); droppedLefts.removeAll(matchUMEs(rightValues, left2right.inverse())); RelationshipEndExpression opposite = re.getRelationship().getOppositeEndFor(re); boolean manyToManyCase = opposite.getUpperBound() > 1; Collection<UniversalModelExpression> rightValuesToBeApplied = copyCollection(rightValues); switch (mode) { case ADDITIVE: if (manyToManyCase) { // In additive mode we don't drop assignments in many-to-many relations, hence // the adding of the elements which were marked as dropped rightValuesToBeApplied.addAll(droppedLefts); break; } // If upper bound of the opposite = 1 we need to consider changed references on the "to one" side of the // relation which result in a removal of references on the "to many" side. // That's why in that case we create the diff as if in v_partial mode //$FALL-THROUGH$ case V_PARTIAL: if (!manyToManyCase) { // Check, whether one of the right values to be applied results from an illegal change. // Changing an assignment in a to-one relation if the originally assigned element is not // in the right side model is an illegal change. for (Iterator<UniversalModelExpression> i = rightValuesToBeApplied.iterator(); i.hasNext();) { UniversalModelExpression leftUME = left2right.inverse().get(i.next()); if (leftUME != null && matchResult.getLeftUnmatchedForType(opposite.getType()) .contains(leftUME.getConnected(opposite))) { i.remove(); } } } // Assignments can only be removed in v_partial mode if both originally connected elements // are present in the right side model. for (UniversalModelExpression leftUME : droppedLefts) { if (matchResult.getLeftUnmatchedForType(re.getType()).contains(leftUME)) { // originally connected element not found in right model => retain assignment rightValuesToBeApplied.add(leftUME); } } break; case STRICT: // nothing to do, just use the assignments as they are in the right side model break; default: LOGGER.error("Unsupported diff mode \"{0}\".", mode); throw new IteraplanTechnicalException(IteraplanErrorMessages.INTERNAL_ERROR); } return rightValuesToBeApplied; }