Java Code Examples for java.util.Set#removeAll()

The following examples show how to use java.util.Set#removeAll() . 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: AbstractOntopiaResource.java    From ontopia with Apache License 2.0 6 votes vote down vote up
/**
 * Blocks the use of specified mime types for this resource, as it is known that the converter for that mime type
 * cannot produce the representation for the Resource's target class.
 * @param types The mime types to block
 */
protected void blockMimeType(MediaType... types) {
	List<Preference<MediaType>> acceptedMediaTypes = getClientInfo().getAcceptedMediaTypes();
	if (acceptedMediaTypes.size() > types.length) {
		return;
	}	

	Set<MediaType> accepted = new HashSet<>(acceptedMediaTypes.size());
	for (Preference<MediaType> p : acceptedMediaTypes) {
		accepted.add(p.getMetadata());
	}
	
	accepted.removeAll(Arrays.asList(types));
	
	if (accepted.isEmpty()) {
		throw OntopiaRestErrors.UNSUPPORTED_MIME_TYPE.build(getClass().getName(), Arrays.toString(types));
	}
}
 
Example 2
Source File: CollectionUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 两个集合差集 ( 扣除 ) 处理
 * @param collection1 第一个集合
 * @param collection2 第二个集合
 * @param <T>         泛型
 * @return 差集 ( 扣除 ) 集合
 */
public static <T> Collection<T> subtract(final Collection<T> collection1, final Collection<T> collection2) {
    try {
        // 先进行交集处理
        Collection<T> intersectionC = intersection(collection1, collection2);
        // 保存到新的集合中
        Set<T> sets = new LinkedHashSet<>(collection1);
        // 进行移除
        sets.removeAll(intersectionC);
        // 返回集合
        return sets;
    } catch (Exception e) {
        JCLogUtils.eTag(TAG, e, "subtract");
    }
    return null;
}
 
Example 3
Source File: EdOrgExtractHelperTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void getBulkExtractAppsTest() {
    when(repository.findAll("application", new NeutralQuery())).thenReturn(
            Arrays.asList(
                    buildAppEntity("1", true, true),
                    buildAppEntity("2", false, false),
                    buildAppEntity("3", true, false),
                    buildAppEntity("4", false, true),
                    buildAppEntity("5", true, true)
            )
    );

    Set<String> bulkExtractApps = helper.getBulkExtractApps();
    bulkExtractApps.removeAll(Arrays.asList("1","5"));
    assertTrue(bulkExtractApps.isEmpty());
}
 
Example 4
Source File: TeamAddCommand.java    From UHC with MIT License 6 votes vote down vote up
@Override
protected boolean runCommand(CommandSender sender, OptionSet options) {
    final Team team = teamSpec.value(options);
    final Set<OfflinePlayer> players = Sets.newHashSet(playersSpec.values(options));
    players.removeAll(team.getPlayers());

    for (final OfflinePlayer player : players) {
        team.addPlayer(player);
    }

    final Set<OfflinePlayer> finalTeam = team.getPlayers();

    final String members = finalTeam.size() == 0
            ? ChatColor.DARK_GRAY + "No members"
            : Joiner.on(", ").join(Iterables.transform(team.getPlayers(), FunctionalUtil.PLAYER_NAME_FETCHER));

    sender.sendMessage(messages.evalTemplate(
            "added",
            ImmutableMap.of(
                    "count", players.size(),
                    "players", members
            )
    ));
    return false;
}
 
Example 5
Source File: PresentationManagerImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private String[] makeTypeIds( NodeImpl root, Graph gr, Set rootSet )
{
    Set nonRootSet = new HashSet( gr ) ;
    nonRootSet.removeAll( rootSet ) ;

    // List<String> for the typeids
    List result = new ArrayList() ;

    if (rootSet.size() > 1) {
        // If the rootSet has more than one element, we must
        // put the type id of the implementation class first.
        // Root represents the implementation class here.
        result.add( root.getTypeId() ) ;
    }

    addNodes( result, rootSet ) ;
    addNodes( result, nonRootSet ) ;

    return (String[])result.toArray( new String[result.size()] ) ;
}
 
Example 6
Source File: ConfigurationPropertyValueHintExpansionStrategy.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Override
public boolean addProposals(String text, StreamDefinition streamDefinition, int detailLevel,
		List<CompletionProposal> collector) {
	LinkedList<StreamAppDefinition> streamAppDefinitions = this.streamDefinitionService.getAppDefinitions(streamDefinition);
	Set<String> propertyNames = new HashSet<>(
			StreamDefinitionServiceUtils.getDeploymentOrderIterator(streamAppDefinitions).next().getProperties().keySet());
	propertyNames.removeAll(CompletionUtils.IMPLICIT_PARAMETER_NAMES);
	if (text.endsWith(" ") || propertyNames.isEmpty()) {
		return false;
	}

	String propertyName = recoverPropertyName(text);

	StreamAppDefinition lastApp = StreamDefinitionServiceUtils.getDeploymentOrderIterator(streamAppDefinitions).next();
	String alreadyTyped = lastApp.getProperties().get(propertyName);

	AppRegistration lastAppRegistration = this.collectorSupport.findAppRegistration(lastApp.getName(),
			CompletionUtils.determinePotentialTypes(lastApp, streamAppDefinitions.size() > 1));
	if (lastAppRegistration != null) {
		return this.collectorSupport.addAlreadyTypedValueHintsProposals(text, lastAppRegistration, collector, propertyName, valueHintProviders, alreadyTyped);
	}
	return false;
}
 
Example 7
Source File: ConsumerConnectionState.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
public void handleRemoveConsumers(Collection<String> topics, String app) {
    consumerLock.writeLock().lock();
    try {
        Set<String> topicSet = getOrCreateAddedTopicSet(app);
        List<String> removeTopics = null;

        for (String topic : topics) {
            if (topicSet.contains(topic)) {
                if (removeTopics == null) {
                    removeTopics = Lists.newLinkedList();
                }
                removeTopics.add(topic);
            }
        }

        if (CollectionUtils.isEmpty(removeTopics)) {
            return;
        }
        if (doHandleRemoveConsumers(removeTopics, app)) {
            topicSet.removeAll(removeTopics);
        }
    } finally {
        consumerLock.writeLock().unlock();
    }
}
 
Example 8
Source File: ComTrackableUserFormLinkAction.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private void replaceCommonLinkProperties(ComTrackableUserFormLinkForm form, HttpServletRequest request) throws Exception {
	ComAdmin admin = AgnUtils.getAdmin(request);
	if (admin.permissionAllowed(Permission.MAILING_EXTEND_TRACKABLE_LINKS)) {
		// Only clear properties of all links in db if adminuser is allowed to
		UserForm userForm = userFormDao.getUserForm(form.getFormID(), admin.getCompanyID());
		if (userForm != null) {
			for (ComTrackableUserFormLink link : userForm.getTrackableLinks().values()) {
				Set<LinkProperty> linkProperties = new HashSet<>(link.getProperties());

				// Remove all old commonLinkProperties
                   List<LinkProperty> common = new ArrayList<>(userForm.getCommonLinkExtensions());
                   common.retainAll(linkProperties);
                   linkProperties.removeAll(common);

                   updateLinkPropertiesParameters(request, linkProperties);
				link.setProperties(new ArrayList<>(linkProperties));
				userFormDao.storeUserFormTrackableLinkProperties(link);
			}
		}
	}
}
 
Example 9
Source File: MiniKdc.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a MiniKdc.
 *
 * @param conf MiniKdc configuration.
 * @param workDir working directory, it should be the build directory. Under
 * this directory an ApacheDS working directory will be created, this
 * directory will be deleted when the MiniKdc stops.
 * @throws Exception thrown if the MiniKdc could not be created.
 */
public MiniKdc(Properties conf, File workDir) throws Exception {
  if (!conf.keySet().containsAll(PROPERTIES)) {
    Set<String> missingProperties = new HashSet<String>(PROPERTIES);
    missingProperties.removeAll(conf.keySet());
    throw new IllegalArgumentException("Missing configuration properties: "
            + missingProperties);
  }
  this.workDir = new File(workDir, Long.toString(System.currentTimeMillis()));
  if (! workDir.exists()
          && ! workDir.mkdirs()) {
    throw new RuntimeException("Cannot create directory " + workDir);
  }
  LOG.info("Configuration:");
  LOG.info("---------------------------------------------------------------");
  for (Map.Entry<?, ?> entry : conf.entrySet()) {
    LOG.info("  {}: {}", entry.getKey(), entry.getValue());
  }
  LOG.info("---------------------------------------------------------------");
  this.conf = conf;
  port = Integer.parseInt(conf.getProperty(KDC_PORT));
  if (port == 0) {
    ServerSocket ss = new ServerSocket(0, 1, InetAddress.getByName
            (conf.getProperty(KDC_BIND_ADDRESS)));
    port = ss.getLocalPort();
    ss.close();
  }
  String orgName= conf.getProperty(ORG_NAME);
  String orgDomain = conf.getProperty(ORG_DOMAIN);
  realm = orgName.toUpperCase(Locale.ENGLISH) + "."
          + orgDomain.toUpperCase(Locale.ENGLISH);
}
 
Example 10
Source File: MissingRequiredPropertiesAnnotator.java    From intellij-kubernetes with Apache License 2.0 5 votes vote down vote up
private void addErrors(final @NotNull AnnotationHolder annotationHolder, final Model model, final PsiElement errorTarget, final YAMLMapping mapping) {
    final Set<String> existingKeys = mapping.getKeyValues().stream().map(YAMLKeyValue::getKeyText).collect(Collectors.toSet());

    // Find out the keys that are needed, and remove any which have been defined
    // The resulting set are the properties required but not added
    final Set<String> requiredProperties = new HashSet<>(model.getRequiredProperties());
    requiredProperties.removeAll(existingKeys);

    if (!requiredProperties.isEmpty()) {
        annotationHolder.createWarningAnnotation(errorTarget, "Missing required properties on " + model.getId() + ": " + String.join(", ", requiredProperties))
                        .registerFix(new CreateMissingPropertiesIntentionAction(requiredProperties, mapping));
    }
}
 
Example 11
Source File: TestingProject.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public Set<String> fractionsThatShouldBeMissing() {
    Set<String> allFractions = Stream.of(IncludedTechnology.values())
            .map(IncludedTechnology::fraction)
            .collect(Collectors.toCollection(HashSet::new));
    allFractions.addAll(AdditionalDependency.allPossibleFractions());
    allFractions.addAll(AdditionalFraction.allPossibleFractions());

    allFractions.removeAll(fractionsThatShouldBePresent());
    return allFractions;
}
 
Example 12
Source File: PingWaiter.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void run() {
    // GemStoneAddition - debugging 34274
    //log.info("findInitialMembers starting");
    Vector responses=findInitialMembers();
    //log.info("findInitialMembers found " + responses.size() + " members");
    synchronized (tLock) {
      t = null; // GemStoneAddition - need to null out so it can be started again in ClientGmsImpl's thread (bug 34274)
    }
    if(parent != null) {
      // GemStoneAddition - make sure required responses have all been received
      if (log.getLogWriter().fineEnabled()) {
        log.getLogWriter().fine("PingWaiter: required responses="+this.requiredResponses
            +"; received="+this.requiredResponsesReceived
            +"; responses="+responses);
      }
      if (this.requiredResponses.size() != this.requiredResponsesReceived.size()) {
        Set missing = new HashSet(this.requiredResponses);
        missing.removeAll(this.requiredResponsesReceived);
        if (log.getLogWriter().fineEnabled()) {
          log.getLogWriter().fine("Find Initial Members failed.  missing responses = " + missing);
        }
        parent.passUp(new Event(Event.FIND_INITIAL_MBRS_FAILED, missing));
      } else {
        if (log.getLogWriter().fineEnabled()) {
          log.getLogWriter().fine("Find Initial Members completed.");
        }
        parent.passUp(new Event(Event.FIND_INITIAL_MBRS_OK, responses));
      }
    }
}
 
Example 13
Source File: SteamDatabaseUpdater.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Transactional
@Scheduled(cron = "0 0 0 * * ?")
public void rebuildApps() {
    ResponseEntity<GetAppListResponse> response = restTemplate.getForEntity(APPS_ENDPOINT, GetAppListResponse.class);
    if (!HttpStatus.OK.equals(response.getStatusCode())) {
        log.warn("Could not get app list, endpoint returned {}", response.getStatusCode());
    }
    if (response.getBody() == null) {
        log.warn("Empty Apps list returned");
        return;
    }
    SteamAppEntry[] apps = response.getBody().getApps();
    long count = appRepository.count();
    if (apps != null && apps.length != count) {
        Map<Long, String> newMap = Stream.of(apps).collect(Collectors.toMap(SteamAppEntry::getAppid, SteamAppEntry::getName));
        Set<Long> existentApps = appRepository.findAllIds();

        // Apps to add
        Set<Long> idsToAdd = new HashSet<>(newMap.keySet());
        idsToAdd.removeAll(existentApps);

        if (!idsToAdd.isEmpty()) {
            List<SteamApp> appsToAdd = idsToAdd.stream().map(e -> {
                SteamApp app = new SteamApp();
                app.setAppId(e);
                app.setName(newMap.get(e));
                return app;
            }).collect(Collectors.toList());
            appRepository.saveAll(appsToAdd);
        }

        // Apps to remove
        existentApps.removeAll(newMap.keySet());
        if (!existentApps.isEmpty()) {
            appRepository.deleteApps(existentApps);
        }
    }
}
 
Example 14
Source File: AbstractMetaComparator.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
/**
 * @param current
 * @param future
 * @return added, modified, delted
 */
protected <Type> Triple<Set<Type>, Set<Type>, Set<Type>> getDiff(Set<Type> current, Set<Type> future) {
	
	Set<Type> added = new HashSet<>(future);
	Set<Type> modified = new HashSet<>(future);
	Set<Type> deleted = new HashSet<>(current);
	
	added.removeAll(deleted);
	modified.retainAll(deleted);
	deleted.removeAll(future);
	
	return new Triple<Set<Type>, Set<Type>, Set<Type>>(added, modified, deleted);
}
 
Example 15
Source File: TestDatabaseShardManager.java    From presto with Apache License 2.0 4 votes vote down vote up
@Test
public void testReplaceShardUuids()
{
    long tableId = createTable("test");
    List<ColumnInfo> columns = ImmutableList.of(new ColumnInfo(1, BIGINT));
    List<String> nodes = ImmutableList.of("node1", "node2", "node3");
    List<UUID> originalUuids = ImmutableList.of(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID());

    List<ShardInfo> oldShards = ImmutableList.<ShardInfo>builder()
            .add(shardInfo(originalUuids.get(0), nodes.get(0)))
            .add(shardInfo(originalUuids.get(1), nodes.get(1)))
            .add(shardInfo(originalUuids.get(2), nodes.get(2)))
            .build();

    shardManager.createTable(tableId, columns, false, OptionalLong.empty());

    long transactionId = shardManager.beginTransaction();
    shardManager.commitShards(transactionId, tableId, columns, oldShards, Optional.empty(), 0);

    List<UUID> expectedUuids = ImmutableList.of(UUID.randomUUID(), UUID.randomUUID());
    List<ShardInfo> newShards = ImmutableList.<ShardInfo>builder()
            .add(shardInfo(expectedUuids.get(0), nodes.get(0)))
            .add(shardInfo(expectedUuids.get(1), nodes.get(0)))
            .build();

    Set<ShardMetadata> shardMetadata = shardManager.getNodeShards(nodes.get(0));
    Set<UUID> replacedUuids = shardMetadata.stream().map(ShardMetadata::getShardUuid).collect(toSet());

    transactionId = shardManager.beginTransaction();
    shardManager.replaceShardUuids(transactionId, tableId, columns, replacedUuids, newShards, OptionalLong.of(0));

    shardMetadata = shardManager.getNodeShards(nodes.get(0));
    Set<UUID> actualUuids = shardMetadata.stream().map(ShardMetadata::getShardUuid).collect(toSet());
    assertEquals(actualUuids, ImmutableSet.copyOf(expectedUuids));

    // Compute expected all uuids for this table
    Set<UUID> expectedAllUuids = new HashSet<>(originalUuids);
    expectedAllUuids.removeAll(replacedUuids);
    expectedAllUuids.addAll(expectedUuids);

    // check that shards are replaced in index table as well
    Set<BucketShards> shardNodes = ImmutableSet.copyOf(shardManager.getShardNodes(tableId, TupleDomain.all()));
    Set<UUID> actualAllUuids = shardNodes.stream()
            .map(BucketShards::getShards)
            .flatMap(Collection::stream)
            .map(ShardNodes::getShardUuid)
            .collect(toSet());
    assertEquals(actualAllUuids, expectedAllUuids);

    // verify that conflicting updates are handled
    newShards = ImmutableList.of(shardInfo(UUID.randomUUID(), nodes.get(0)));
    try {
        transactionId = shardManager.beginTransaction();
        shardManager.replaceShardUuids(transactionId, tableId, columns, replacedUuids, newShards, OptionalLong.of(0));
        fail("expected exception");
    }
    catch (PrestoException e) {
        assertEquals(e.getErrorCode(), TRANSACTION_CONFLICT.toErrorCode());
    }
}
 
Example 16
Source File: AlignmentGenlex.java    From amr with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ILexiconImmutable<LogicalExpression> generate(
		LabeledAmrSentence dataItem,
		IJointModelImmutable<SituatedSentence<AMRMeta>, LogicalExpression, LogicalExpression> model,
		ICategoryServices<LogicalExpression> categoryServices) {
	if (!dataItem.hasAlignments()) {
		LOG.debug(
				"Data item has no alignment information -- returning no entries");
		return new Lexicon<>();
	}

	// Get all factorable constants from the labeled logical form. We use
	// these to track which constants are not covered and issue a log
	// message appropriately.
	final Set<LogicalConstant> allConstants = GetConstantsSet
			.of(AMRServices.underspecifyAndStrip(dataItem.getLabel()))
			.stream().filter(FactoringServices::isFactorable)
			.collect(Collectors.toSet());

	final long startTime = System.currentTimeMillis();

	final TokenSeq tokens = dataItem.getSample().getTokens();
	final int numTokens = tokens.size();
	final Set<Lexeme> lexemes = new HashSet<>();
	for (int start = 0; start < numTokens; ++start) {
		for (int end = start + 1; end <= numTokens; ++end) {
			final TokenSeq seq = tokens.sub(start, end);
			final Set<LogicalExpression> aligned = dataItem
					.getAlignedExpressions(start, end);
			if (aligned != null) {
				for (final LogicalExpression exp : aligned) {
					LOG.debug("Alignment: %s -> %s", seq, exp);
					// Track this for logging.
					final int priorNumLexemes = lexemes.size();
					final List<LogicalConstant> constants = GetConstantsMultiSet
							.of(AMRServices.underspecifyAndStrip(exp))
							.stream()
							.filter(FactoringServices::isFactorable)
							.collect(Collectors.toList());
					// Remove the constants from the set we maintain for
					// logging.
					allConstants.removeAll(constants);

					for (final LexicalTemplate template : repo
							.getTemplates()) {
						for (final List<String> attributes : repo
								.getAttributeLists(template)) {
							for (final List<LogicalConstant> permutation : Collections2
									.permutations(constants)) {
								final Lexeme lexeme = new Lexeme(seq,
										permutation, attributes,
										entryProperties);
								if (!lexemes.contains(lexeme)
										&& template.isValid(lexeme)) {
									LOG.debug("Generated: %s", lexeme);
									lexemes.add(lexeme);
								}
							}
						}
					}
					LOG.debug("Generated %d new lexemes from alignment",
							lexemes.size() - priorNumLexemes);
				}
			}
		}
	}

	LOG.debug("Alignment GENLEX created %d lexemes (%.3fsec)",
			lexemes.size(),
			(System.currentTimeMillis() - startTime) / 1000.0);

	if (!allConstants.isEmpty()) {
		LOG.debug("Constants not covered by generator: %s", allConstants);
	}

	return new FactoredLexicon(lexemes, repo.getTemplates());
}
 
Example 17
Source File: PatchDelegate.java    From EasyMPermission with MIT License 4 votes vote down vote up
public static void checkConflictOfTypeVarNames(BindingTuple binding, EclipseNode typeNode) throws CantMakeDelegates {
	TypeVariableBinding[] typeVars = binding.parameterized.typeVariables();
	if (typeVars == null || typeVars.length == 0) return;
	
	Set<String> usedInOurType = new HashSet<String>();
	EclipseNode enclosingType = typeNode;
	while (enclosingType != null) {
		if (enclosingType.getKind() == Kind.TYPE) {
			TypeParameter[] typeParameters = ((TypeDeclaration)enclosingType.get()).typeParameters;
			if (typeParameters != null) {
				for (TypeParameter param : typeParameters) {
					if (param.name != null) usedInOurType.add(new String(param.name));
				}
			}
		}
		enclosingType = enclosingType.up();
	}
	
	Set<String> usedInMethodSig = new HashSet<String>();
	for (TypeVariableBinding var : typeVars) {
		char[] sourceName = var.sourceName();
		if (sourceName != null) usedInMethodSig.add(new String(sourceName));
	}
	
	usedInMethodSig.retainAll(usedInOurType);
	if (usedInMethodSig.isEmpty()) return;
	
	// We might be delegating a List<T>, and we are making method <T> toArray(). A conflict is possible.
	// But only if the toArray method also uses type vars from its class, otherwise we're only shadowing,
	// which is okay as we'll add a @SuppressWarnings.
	
	TypeVarFinder finder = new TypeVarFinder();
	finder.visitRaw(binding.base);
	
	Set<String> names = new HashSet<String>(finder.getTypeVariables());
	names.removeAll(usedInMethodSig);
	if (!names.isEmpty()) {
		// We have a confirmed conflict. We could dig deeper as this may still be a false alarm, but its already an exceedingly rare case.
		CantMakeDelegates cmd = new CantMakeDelegates();
		cmd.conflicted = usedInMethodSig;
		throw cmd;
	}
}
 
Example 18
Source File: UpdateStatementDUnit.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testUpdateOnTableHavingNoPrimaryOrPartitionKeyDefined_Bug39921() throws Exception {
  try {
    // Start one client and three servers
    startServerVMs(3, 0, "SG1");
    startClientVMs(1, 0, null);
    String updateQuery = "Update EMP.TESTTABLE set type = 10 where ID > 0 ";
    // Create a schema with default server groups GemFire extension
    clientSQLExecute(1, "create schema EMP default server groups (SG1)");

    // Create the table and insert a row
    clientSQLExecute(
        1,
        "create table EMP.TESTTABLE (ID int , "
            + "DESCRIPTION varchar(1024) , ADDRESS varchar(1024) ,type int ) "+getOverflowSuffix());

    // Insert values 1 to 8
    for (int i = 0; i < 8; ++i) {
      clientSQLExecute(1, "insert into EMP.TESTTABLE values (" + (i + 1)
          + ", 'First" + (i + 1) + "', 'J 604" + (i + 1) + "',"+(i+1)+")");
    }

    // Attach a GemFireXDQueryObserver in the server VM

    VM dataStore1 = this.serverVMs.get(0);
    VM dataStore2 = this.serverVMs.get(1);
    VM dataStore3 = this.serverVMs.get(2);
    CacheSerializableRunnable setObserver = getGfxdQueryObserverIntializerForDataStore();
    dataStore1.invoke(setObserver);
    dataStore2.invoke(setObserver);
    dataStore3.invoke(setObserver);
    QueryInfo[] qi = new QueryInfo[1];
    Activation actArr[] = new Activation[1];
    NodesPruningHelper.setupObserverOnClient(qi,actArr);

    TestUtil.setupConnection();
    EmbedStatement es = (EmbedStatement)TestUtil.jdbcConn.createStatement();
    
    int n = es.executeUpdate(updateQuery);
    assertEquals(8, n);
    Object[][] routingInfo = new Object[][] { {
        new Integer(NodesPruningHelper.allnodes) } };

    Set expectedNodesToUpdate = NodesPruningHelper.getExpectedNodes(
        updateQuery, qi[0], routingInfo, getLogWriter());
    Set allNodes = ((PartitionedRegion)qi[0].getRegion()).getRegionAdvisor()
        .adviseDataStore();

    CacheSerializableRunnable validateNoQuerySend = getQueryNonExecutionValidator();

    CacheSerializableRunnable validateQuerySend =  getQueryExecutionValidator();
    this.executeOnVMs(expectedNodesToUpdate, validateQuerySend);      
    allNodes.removeAll(expectedNodesToUpdate);
    this.executeOnVMs(allNodes, validateNoQuerySend);      
    
  }
  finally {
      GemFireXDQueryObserverHolder
      .setInstance(new GemFireXDQueryObserverAdapter());
      clientSQLExecute(1, "Drop table EMP.TESTTABLE ");
      clientSQLExecute(1, "Drop schema EMP restrict");
      //invokeInEveryVM(this.getClass(), "reset");         
  }
}
 
Example 19
Source File: PrepareForCodeGen.java    From jadx with Apache License 2.0 4 votes vote down vote up
/**
 * Check that 'super' or 'this' call in constructor is a first instruction.
 * Otherwise move to top and add a warning if code breaks.
 */
private void moveConstructorInConstructor(MethodNode mth) {
	if (mth.isConstructor()) {
		ConstructorInsn constrInsn = searchConstructorCall(mth);
		if (constrInsn != null && !constrInsn.contains(AFlag.DONT_GENERATE)) {
			Region oldRootRegion = mth.getRegion();
			boolean firstInsn = BlockUtils.isFirstInsn(mth, constrInsn);
			DeclareVariablesAttr declVarsAttr = oldRootRegion.get(AType.DECLARE_VARIABLES);
			if (firstInsn && declVarsAttr == null) {
				// move not needed
				return;
			}

			// move constructor instruction to new root region
			String callType = constrInsn.getCallType().toString().toLowerCase();
			BlockNode blockByInsn = BlockUtils.getBlockByInsn(mth, constrInsn);
			if (blockByInsn == null) {
				mth.addWarn("Failed to move " + callType + " instruction to top");
				return;
			}
			InsnList.remove(blockByInsn, constrInsn);

			Region region = new Region(null);
			region.add(new InsnContainer(Collections.singletonList(constrInsn)));
			region.add(oldRootRegion);
			mth.setRegion(region);

			if (!firstInsn) {
				Set<RegisterArg> regArgs = new HashSet<>();
				constrInsn.getRegisterArgs(regArgs);
				regArgs.remove(mth.getThisArg());
				regArgs.removeAll(mth.getArgRegs());
				if (!regArgs.isEmpty()) {
					mth.addWarn("Illegal instructions before constructor call");
				} else {
					mth.addComment("JADX INFO: " + callType + " call moved to the top of the method (can break code semantics)");
				}
			}
		}
	}
}
 
Example 20
Source File: JQLBuilder.java    From kripton with Apache License 2.0 4 votes vote down vote up
/**
 * Extract fields from annotation.
 *
 * @param <A>
 *            the generic type
 * @param method
 *            the method
 * @param annotationClazz
 *            the annotation clazz
 * @param includePrimaryKey
 *            the include primary key
 * @return the linked hash set
 */
private static <A extends Annotation> LinkedHashSet<String> extractFieldsFromAnnotation(final SQLiteModelMethod method, Class<A> annotationClazz, final boolean includePrimaryKey) {
	final SQLiteEntity entity = method.getEntity();

	List<String> annotatedFieldValues = AnnotationUtility.extractAsStringArray(method.getElement(), annotationClazz, AnnotationAttributeType.FIELDS);
	List<String> annotatedExcludedFieldValues = AnnotationUtility.extractAsStringArray(method.getElement(), annotationClazz, AnnotationAttributeType.EXCLUDED_FIELDS);
	CollectionUtils.trim(annotatedFieldValues);
	CollectionUtils.trim(annotatedExcludedFieldValues);

	final One<Integer> count = new One<>(0);

	// extract properties from managed bean
	final Set<String> allFields = new LinkedHashSet<>();
	forEachFields(method, new OnPropertyListener() {

		@Override
		public void onProperty(SQLProperty item) {
			if (!item.isPrimaryKey() || (item.isPrimaryKey() && includePrimaryKey)) {
				allFields.add(item.getName());
			}

			if (TypeUtility.isEquals(item.getPropertyType().getTypeName(), typeName(entity.getElement()))) {
				count.value0++;
			}
		}
	});

	// use attribute includedFields and excludedFields to mantain or remove
	// properties from selected set.
	if (annotatedFieldValues.size() == 0 && annotatedExcludedFieldValues.size() == 0) {
		// if no fields was selected, select all
		annotatedFieldValues.clear();
		annotatedFieldValues.addAll(allFields);
	} else if (annotatedExcludedFieldValues.size() > 0) {
		for (String fieldName : annotatedExcludedFieldValues) {
			if (!entity.contains(fieldName)) {
				AssertKripton.failUnknownPropertyInJQLException(method, annotationClazz, AnnotationAttributeType.EXCLUDED_FIELDS, fieldName);
			}
		}

		allFields.removeAll(annotatedExcludedFieldValues);

		annotatedFieldValues.clear();
		annotatedFieldValues.addAll(allFields);
	}
	LinkedHashSet<String> result = new LinkedHashSet<>();
	result.addAll(annotatedFieldValues);

	return result;
}