Java Code Examples for com.google.common.collect.BiMap#entrySet()

The following examples show how to use com.google.common.collect.BiMap#entrySet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MapHex.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Execute a tile replacement. This method should only be called from
 * TileMove objects. It is also used to undo tile lays.
 *
 * @param newTile        The new tile to be laid on this hex.
 * @param newOrientation The orientation of the new tile (0-5).
 * @param newStops       The new stops used now
 */
private void executeTileLay(Tile newTile, HexSide newOrientation,
                            BiMap<Stop, Station> newStops) {

    // TODO: Is the check for null still required?
    if (currentTile.value() != null) {
        currentTile.value().remove(this);
    }

    log.debug("On hex {} replacing tile {}/{} by {}/{}", getId(), currentTile.value().getId(), currentTileRotation, newTile.getId(), newOrientation);

    newTile.add(this);
    currentTile.set(newTile);
    currentTileRotation.set(newOrientation);

    stops.clear();
    if (newStops != null) {
        for ( Map.Entry<Stop, Station> entry  : newStops.entrySet()) {
            stops.put(entry.getValue(), entry.getKey());
            entry.getKey().setRelatedStation(entry.getValue());
            log.debug("Tile #{} station {} has tracks to {}", newTile.getId(), entry.getValue().getNumber(), getConnectionString(entry.getValue()));
        }
    }
}
 
Example 2
Source File: AccessibilityHierarchyAndroid.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Associates {@link ViewHierarchyElementAndroid}s based on labeling ({@code android:labelFor})
 * relationships
 *
 * @param originMap A map from condensed unique IDs to the originating {@link
 *     AccessibilityNodeInfo} structures from which a {@link ViewHierarchyElementAndroid} was
 *     constructed, as populated by {@link AccessibilityHierarchyAndroid} constructors.
 */
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void resolveLabelForRelationshipsAmongInfos(
    BiMap<Long, AccessibilityNodeInfo> originMap) {
  for (Map.Entry<Long, AccessibilityNodeInfo> entry : originMap.entrySet()) {
    AccessibilityNodeInfo labeledNode = entry.getValue().getLabelFor();
    if (labeledNode != null) {
      Long labeledElementId = originMap.inverse().get(labeledNode);
      if (labeledElementId != null) {
        ViewHierarchyElementAndroid labelElement = getViewById(entry.getKey());
        ViewHierarchyElementAndroid labeledElement = getViewById(labeledElementId);
        labeledElement.setLabeledBy(labelElement);
      }
    }
  }
}
 
Example 3
Source File: AccessibilityHierarchyAndroid.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * For every View in {@code originMap} that has a labelFor value, set labeledBy on the
 * ViewHierarchyElementAndroid that represents the View with the referenced View ID.
 */
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void resolveLabelForRelationshipsAmongViews(
    Context context, BiMap<Long, View> originMap) {
  for (Map.Entry<Long, View> entry : originMap.entrySet()) {
    int labeledViewId = entry.getValue().getLabelFor();
    if (labeledViewId != View.NO_ID) {
      ViewHierarchyElementAndroid labelElement = getViewById(entry.getKey());
      ViewHierarchyElementAndroid labeledElement = findElementByViewId(labeledViewId, originMap);
      if (labeledElement == null) {
        LogUtils.w(
            TAG, "View not found for labelFor = %1$s", resourceName(context, labeledViewId));
      } else {
        labeledElement.setLabeledBy(labelElement);
      }
    }
  }
}
 
Example 4
Source File: AccessibilityHierarchyAndroid.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * For every TouchDelegate with a rectangular hit region, record the region on the delegatee's
 * ViewHierarchyElement using {@link ViewHierarchyElement#addTouchDelegateBounds(Rect)}
 */
@RequiresApi(Build.VERSION_CODES.Q)
private void resolveTouchDelegateRelationshipsAmongInfos(
    BiMap<Long, AccessibilityNodeInfo> originMap) {
  for (Map.Entry<Long, AccessibilityNodeInfo> entry : originMap.entrySet()) {
    TouchDelegateInfo delegateInfo = entry.getValue().getTouchDelegateInfo();
    if (delegateInfo != null) {
      for (int i = 0; i < delegateInfo.getRegionCount(); ++i) {
        Region hitRegion = delegateInfo.getRegionAt(i);
        if ((hitRegion != null) && hitRegion.isRect()) {
          AccessibilityNodeInfo delegateeNode = delegateInfo.getTargetForRegion(hitRegion);
          ViewHierarchyElement delegatee =
              (delegateeNode != null) ? findElementByNodeInfo(delegateeNode, originMap) : null;
          if (delegatee != null) {
            android.graphics.Rect hitRect = hitRegion.getBounds();
            delegatee.addTouchDelegateBounds(
                new Rect(hitRect.left, hitRect.top, hitRect.right, hitRect.bottom));
          }
        }
      }
    }
  }
}
 
Example 5
Source File: ExportServiceImpl.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * Exports All Applications from an Organization
 */
private void exportApplicationsFromOrg( UUID organizationUUID, final Map<String, Object> config,
                                        final JobExecution jobExecution, S3Export s3Export ) throws Exception {

    //retrieves export entity
    Export export = getExportEntity( jobExecution );
    String appFileName = null;

    BiMap<UUID, String> applications = managementService.getApplicationsForOrganization( organizationUUID );

    for ( Map.Entry<UUID, String> application : applications.entrySet() ) {

        if ( application.getValue().equals(
                managementService.getOrganizationByUuid( organizationUUID ).getName() + "/exports" ) ) {
            continue;
        }

        appFileName = prepareOutputFileName( application.getValue(), null );

        File ephemeral = collectionExportAndQuery( application.getKey(), config, export, jobExecution );

        fileTransfer( export, appFileName, ephemeral, config, s3Export );
    }
}
 
Example 6
Source File: ExtendedDirectoryLayerTest.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultCanAllocateIndependentKeysInParallel() {
    final ScopedDirectoryLayer directoryLayer = ScopedDirectoryLayer.global(database);

    Map<String, Long> mappingsFromOld = new ConcurrentHashMap<>();
    Map<String, Long> mappingsFromNew = new ConcurrentHashMap<>();
    List<CompletableFuture<?>> operations = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        String oldDirLayerKey = i + "-old-dl-key";
        String newDirLayerKey = i + "-new-dl-key";
        operations.add(directoryLayer.resolve(oldDirLayerKey).thenApply(value -> mappingsFromOld.put(oldDirLayerKey, value)));
        operations.add(globalScope.resolve(newDirLayerKey).thenApply(value -> mappingsFromNew.put(newDirLayerKey, value)));
    }
    CompletableFuture.allOf(operations.toArray(new CompletableFuture<?>[0])).join();

    // Implicitly checks that there are no duplicate keys or values in the two maps
    BiMap<String, Long> completeMapping = ImmutableBiMap.<String, Long>builder()
            .putAll(mappingsFromOld)
            .putAll(mappingsFromNew)
            .build();

    for (Map.Entry<String, Long> entry : completeMapping.entrySet()) {
        try (FDBRecordContext context = database.openContext()) {
            assertThat("the FDB directory layer sees the mapping",
                    directoryLayer.mustResolve(context, entry.getKey()).join(), is(entry.getValue()));
            assertThat("the ScopedDirectoryLayer sees the mapping",
                    globalScope.mustResolve(context, entry.getKey()).join(), is(entry.getValue()));
        }
    }
}
 
Example 7
Source File: RecommendMgr.java    From librec-to-movies with Apache License 2.0 5 votes vote down vote up
public void initData(SparseMatrix dataMatrix) throws LibrecException {
	Table<Integer, Integer, Double> dataTable = dataMatrix.getDataTable();
	BiMap<String, Integer> userIds = dataModel.getUserMappingData();
	BiMap<String, Integer> itemIds = dataModel.getItemMappingData();
	SparseMatrix dateTimeDataSet = (SparseMatrix) dataModel.getDatetimeDataSet();
	Table<Integer, Integer, Double> dateTimeTable = dateTimeDataSet.getDataTable();
	for (Map.Entry<String, Integer> userId : userIds.entrySet()) {
		for (Map.Entry<String, Integer> itemId : itemIds.entrySet()) {
			Object scValue = dataTable.get(userId.getValue(), itemId.getValue());
			Object dtValue = dateTimeTable.get(userId.getValue(), itemId.getValue());
			if (scValue != null && dtValue != null) {
				Long user_id = Long.parseLong(userId.getKey());
				Long movie_id = Long.parseLong(itemId.getKey());
				Double score = (Double)scValue;
				Double datetime = (Double)dtValue;
				Rating rating = new Rating(user_id, movie_id, score);
				User user = User.findUser(user_id);
				if (user == null) continue;
				MovieEx movie = (MovieEx) MovieEx.findMovie(movie_id);
				if (movie == null) continue;
				try {
					user.addMovie(movie, score, datetime);
					movie.addUser(user, score, datetime);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw new LibrecException("load rating set error");
				}
				//rating.save();
				Rating.allRatings.add(rating);
			}
		}
	}
}
 
Example 8
Source File: AccessibilityHierarchyAndroid.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 5 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private void resolveAccessibilityTraversalRelationshipsAmongInfos(
    BiMap<Long, AccessibilityNodeInfo> originMap) {
  for (Map.Entry<Long, AccessibilityNodeInfo> entry : originMap.entrySet()) {
    AccessibilityNodeInfo beforeNode = entry.getValue().getTraversalBefore();
    AccessibilityNodeInfo afterNode = entry.getValue().getTraversalAfter();
    if (beforeNode != null || afterNode != null) {
      ViewHierarchyElementAndroid currentElement = getViewById(entry.getKey());
      if (beforeNode != null) {
        ViewHierarchyElementAndroid beforeElement = findElementByNodeInfo(beforeNode, originMap);
        if (beforeElement == null) {
          LogUtils.w(TAG, "Element not found for accessibilityTraversalBefore.");
        } else {
          currentElement.setAccessibilityTraversalBefore(beforeElement);
        }
      }
      if (afterNode != null) {
        ViewHierarchyElementAndroid afterElement = findElementByNodeInfo(afterNode, originMap);
        if (afterElement == null) {
          LogUtils.w(TAG, "Element not found for accessibilityTraversalAfter.");
        } else {
          currentElement.setAccessibilityTraversalAfter(afterElement);
        }
      }
    }
  }
}
 
Example 9
Source File: AccessibilityHierarchyAndroid.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Find the element corresponding to the View in value of {@code originMap} whose ID is {@code
 * targetViewId}, or {@code null} if no view is found with that ID.
 */
private @Nullable ViewHierarchyElementAndroid findElementByViewId(
    int targetViewId, BiMap<Long, View> originMap) {
  for (Map.Entry<Long, View> matchingEntry : originMap.entrySet()) {
    if (matchingEntry.getValue().getId() == targetViewId) {
      return getViewById(matchingEntry.getKey());
    }
  }
  return null;
}
 
Example 10
Source File: ScatterAgentMetaData.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
public Set<Map.Entry<Integer, DotAgentInfo>> entrySet() {
    BiMap<Integer, DotAgentInfo> inverse = metaData.inverse();
    return inverse.entrySet();
}
 
Example 11
Source File: SqlQueryBuilder.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
public PreparedStatement createStatementFromSQL(Connection connection, String parameterizedSQL,
    Map<String, Object> parameterMap, Class<? extends AbstractEntity> entityClass)
        throws Exception {
  String tableName =
      entityMappingHolder.tableToEntityNameMap.inverse().get(entityClass.getSimpleName());
  parameterizedSQL = "select * from " + tableName + " " + parameterizedSQL;
  parameterizedSQL = parameterizedSQL.replace(entityClass.getSimpleName(), tableName);
  StringBuilder psSql = new StringBuilder();
  List<String> paramNames = new ArrayList<String>();
  Matcher m = PARAM_PATTERN.matcher(parameterizedSQL);

  int index = 0;
  while (m.find(index)) {
    psSql.append(parameterizedSQL.substring(index, m.start()));
    String name = m.group(1);
    index = m.end();
    if (parameterMap.containsKey(name)) {
      psSql.append("?");
      paramNames.add(name);
    } else {
      throw new IllegalArgumentException(
          "Unknown parameter '" + name + "' at position " + m.start());
    }
  }

  // Any stragglers?
  psSql.append(parameterizedSQL.substring(index));
  String sql = psSql.toString();
  BiMap<String, String> dbNameToEntityNameMapping =
      entityMappingHolder.columnMappingPerTable.get(tableName);
  for (Entry<String, String> entry : dbNameToEntityNameMapping.entrySet()) {
    String dbName = entry.getKey();
    String entityName = entry.getValue();
    sql = sql.toString().replaceAll(entityName, dbName);
  }
  LOG.debug("Generated SQL:{} ", sql);
  PreparedStatement ps = connection.prepareStatement(sql);
  int parameterIndex = 1;
  LinkedHashMap<String, ColumnInfo> columnInfo =
      entityMappingHolder.columnInfoPerTable.get(tableName);
  for (String entityFieldName : paramNames) {
    String[] entityFieldNameParts = entityFieldName.split("__", 2);
    if (entityFieldNameParts.length > 1)
      LOG.info("Using field name decomposition: '{}' to '{}'", entityFieldName, entityFieldNameParts[0]);
    String dbFieldName = dbNameToEntityNameMapping.inverse().get(entityFieldNameParts[0]);

    Object val = parameterMap.get(entityFieldName);
    if (Enum.class.isAssignableFrom(val.getClass())) {
      val = val.toString();
    }
    LOG.debug("Setting {} to {}", dbFieldName, val);
    ps.setObject(parameterIndex++, val, columnInfo.get(dbFieldName).sqlType);
  }

  return ps;
}
 
Example 12
Source File: WarehouseExport.java    From usergrid with Apache License 2.0 4 votes vote down vote up
private void exportApplicationsForOrg( Entry<UUID, String> orgIdAndName, String queryString ) throws Exception {

        logger.info( "organization: {} / {}", orgIdAndName.getValue(), orgIdAndName.getKey() );

        String orgName = orgIdAndName.getValue();

        BiMap<UUID, String> applications = managementService.getApplicationsForOrganization( orgIdAndName.getKey() );
        for ( Entry<UUID, String> appIdAndName : applications.entrySet() ) {

            String appName = appIdAndName.getValue();
            appName = appName.substring( appName.indexOf( '/' ) + 1 );

            logger.info( "application {} / {}", appName, appIdAndName.getKey() );

            EntityManager em = emf.getEntityManager( appIdAndName.getKey() );
            Map<String, String[]> cfm = getCollectionFieldMap();

            // Loop through the collections of the Application
            Set<String> collections = em.getApplicationCollections();
            for ( String collectionName : collections ) {

                // set up for retrieving only the necessary properties
                String entityType = InflectionUtils.singularize( collectionName );
                String[] props = cfm.get( entityType );
                Collection<String> properties =
                        new ArrayList<String>( BASE_ATTRIBUTES.length + ( props != null ? props.length : 0 ) );
                properties.addAll( Arrays.asList( BASE_ATTRIBUTES ) );
                if ( props != null ) {
                    properties.addAll( Arrays.asList( props ) );
                }

                Query query = Query.fromQL( queryString );
                query.setLimit( MAX_ENTITY_FETCH );
                query.setResultsLevel( Query.Level.REFS );
                Results results = em.searchCollection( em.getApplicationRef(), collectionName, query );

                while ( results.size() > 0 ) {

                    List<Entity> entities = em.getPartialEntities( results.getIds(), properties );

                    for ( Entity entity : entities ) {
                        write( orgName, appName, entity, em );
                    }

                    if ( results.getCursor() == null ) {
                        break;
                    }

                    query.setCursor( results.getCursor() );
                    results = em.searchCollection( em.getApplicationRef(), collectionName, query );
                }
            }
        }
    }