TypevarContext(TypeElement element, String renderedTypeString) { List<? extends TypeParameterElement> typeParameters = element.getTypeParameters(); if (!typeParameters.isEmpty()) { this.arguments = SourceTypes.extract(renderedTypeString).getValue(); this.parameters = Lists.newArrayList(); for (TypeParameterElement p : typeParameters) { parameters.add(p.getSimpleName().toString()); } // we allow having no arguments in a string as raw type/unspecified argument scenario Verify.verify(arguments.isEmpty() || (parameters.size() == arguments.size()), parameters + " =/> " + arguments); } else { this.parameters = Collections.emptyList(); this.arguments = Collections.emptyList(); } }
private boolean signature(Statement.Builder builder) { Term t = terms.peek(); if (t.is("@")) { do { builder.addAnnotations(terms.next()); Verify.verify(terms.peek().isWordOrNumber()); builder.addAnnotations(terms.next()); } while (terms.peek().is(".")); if (terms.peek().is("(")) { builder.addAllAnnotations(collectUntilMatching(")")); } return false; } else if (t.is("<")) { builder.addAllSignature(collectUntilMatching(">")); return false; } else if (t.is("class")) { builder.addSignature(terms.next()); return true; } else { builder.addSignature(terms.next()); return false; } }
/** Waits for the supplier to return a present value. */ private <T> T await(Supplier<Optional<T>> compute) throws IOException { AtomicReference<T> result = new AtomicReference<>(); BooleanSupplier condition = () -> { Optional<T> value = compute.get(); if (value.isPresent()) { result.set(value.get()); } return value.isPresent(); }; try { monitor.enterWhen(monitor.newGuard(condition)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } try { return Verify.verifyNotNull(result.get()); } finally { monitor.leave(); } }
/** * Classifies an identifier's case format. */ static JavaCaseFormat from(String name) { Verify.verify(!name.isEmpty()); boolean firstUppercase = false; boolean hasUppercase = false; boolean hasLowercase = false; boolean first = true; for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (!Character.isAlphabetic(c)) { continue; } if (first) { firstUppercase = Character.isUpperCase(c); first = false; } hasUppercase |= Character.isUpperCase(c); hasLowercase |= Character.isLowerCase(c); } if (firstUppercase) { return hasLowercase ? UPPER_CAMEL : UPPERCASE; } else { return hasUppercase ? LOWER_CAMEL : LOWERCASE; } }
/** * Encodes an arbitrary bitstring into a RAPPOR report. * * @param bits A bitstring in which only the least significant numBits bits may be 1. */ private byte[] encodeBits(BitSet bits) { BitSet permanentRandomizedResponse = computePermanentRandomizedResponse(bits); BitSet encodedBitSet = computeInstantaneousRandomizedResponse(permanentRandomizedResponse); // BitSet.toByteArray only returns enough bytes to capture the most significant bit // that is set. For example, a BitSet with no bits set could return a length-0 array. // In contrast, we guarantee that our output is sized according to numBits. byte[] encodedBytes = encodedBitSet.toByteArray(); byte[] output = new byte[(numBits + 7) / 8]; Verify.verify(encodedBytes.length <= output.length); System.arraycopy( encodedBytes, // src 0, // srcPos output, // dest 0, // destPos encodedBytes.length); // length return output; }
/** * Transform frontend metadata for a particular client into its {@link LeaderFrontendState} counterpart. * * @param shard parent shard * @return Leader frontend state */ @Nonnull LeaderFrontendState toLeaderState(@Nonnull final Shard shard) { // Note: we have to make sure to *copy* all current state and not leak any views, otherwise leader/follower // interactions would get intertwined leading to inconsistencies. final Map<LocalHistoryIdentifier, LocalFrontendHistory> histories = new HashMap<>(); for (FrontendHistoryMetadataBuilder e : currentHistories.values()) { if (e.getIdentifier().getHistoryId() != 0) { final AbstractFrontendHistory state = e.toLeaderState(shard); Verify.verify(state instanceof LocalFrontendHistory); histories.put(e.getIdentifier(), (LocalFrontendHistory) state); } } final AbstractFrontendHistory singleHistory; final FrontendHistoryMetadataBuilder singleHistoryMeta = currentHistories.get( new LocalHistoryIdentifier(identifier, 0)); if (singleHistoryMeta == null) { final ShardDataTree tree = shard.getDataStore(); singleHistory = StandaloneFrontendHistory.create(shard.persistenceId(), getIdentifier(), tree); } else { singleHistory = singleHistoryMeta.toLeaderState(shard); } return new LeaderFrontendState(shard.persistenceId(), getIdentifier(), shard.getDataStore(), purgedHistories.copy(), singleHistory, histories); }
@Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { final int metaSize = in.readInt(); Preconditions.checkArgument(metaSize >= 0, "Invalid negative metadata map length %s", metaSize); // Default pre-allocate is 4, which should be fine final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder = ImmutableMap.builder(); for (int i = 0; i < metaSize; ++i) { final ShardDataTreeSnapshotMetadata<?> m = (ShardDataTreeSnapshotMetadata<?>) in.readObject(); if (m != null) { metaBuilder.put(m.getType(), m); } else { LOG.warn("Skipping null metadata"); } } metadata = metaBuilder.build(); rootNode = Verify.verifyNotNull(SerializationUtils.deserializeNormalizedNode(in)); }
@Override public final ClientLocalHistory createLocalHistory() { final LocalHistoryIdentifier historyId = new LocalHistoryIdentifier(getIdentifier(), nextHistoryId.getAndIncrement()); final long stamp = lock.readLock(); try { if (aborted != null) { Throwables.throwIfUnchecked(aborted); throw new RuntimeException(aborted); } final ClientLocalHistory history = new ClientLocalHistory(this, historyId); LOG.debug("{}: creating a new local history {}", persistenceId(), history); Verify.verify(histories.put(historyId, history) == null); return history; } finally { lock.unlockRead(stamp); } }
/** * Sends Gossip status to other members in the cluster. * <br> * 1. If there are no member, ignore the tick. <br> * 2. If there's only 1 member, send gossip status (bucket versions) to it. <br> * 3. If there are more than one member, randomly pick one and send gossip status (bucket versions) to it. */ @VisibleForTesting void receiveGossipTick() { final Address address; switch (clusterMembers.size()) { case 0: //no members to send gossip status to return; case 1: address = clusterMembers.get(0); break; default: final int randomIndex = ThreadLocalRandom.current().nextInt(0, clusterMembers.size()); address = clusterMembers.get(randomIndex); break; } LOG.trace("Gossiping to [{}]", address); getLocalStatusAndSendTo(Verify.verifyNotNull(peers.get(address))); }
@SuppressWarnings("unchecked") // Callers shouldn't be accessing this method. /* package */ PineappleField(Field field) { this.field = checkNotNull(field, "Null field"); checkArgument( field.isAccessible() || Modifier.isPublic(field.getModifiers()) && Modifier.isPublic(field.getDeclaringClass().getModifiers()), "Field isn't accessible: %s", field ); this.declaringClass = (Class<T>) field.getDeclaringClass(); this.fieldType = (Class<V>) field.getType(); this.modifiers = field.getModifiers(); this.primitiveType = PrimitiveType.fromClass(field.getType()); Verify.verify(this.isPrimitive() == field.getType().isPrimitive()); }
private static ImmutableMap<Block, BiFunction<WetServer, IBlockState, ? extends WetBlockState>> scanClasspath() { ImmutableMap.Builder<Block, BiFunction<WetServer, IBlockState, ? extends WetBlockState>> builder = ImmutableMap.builder(); Reflections reflections = new Reflections(getReflectionsConfiguration("org.fountainmc.world.block")); Set<Class<?>> types = reflections.getTypesAnnotatedWith(BlockStateImpl.class); if (types != null) { for (Class<?> type : types) { Verify.verify(WetBlockState.class.isAssignableFrom(type), "Class %s isn't instanceof WetBlockState", type.getTypeName()); for (String blockName : ImmutableList.copyOf(type.getAnnotation(BlockStateImpl.class).value())) { Block block = Verify.verifyNotNull(Block.getBlockFromName(blockName), "Class %s specified unknown block name minecraft:%s.", type.getTypeName(), blockName); builder.put(block, (server, state) -> { try { Constructor<?> constructor = type.getConstructor(WetServer.class, IBlockState.class); return (WetBlockState) constructor.newInstance(server, state); } catch (Exception e) { e.printStackTrace(); } return null; }); } } } return builder.build(); }
public CombatTagLegacySupport() { CombatTagApi api = null; Plugin plugin = Bukkit.getPluginManager().getPlugin(PLUGIN_NAME); try { api = CombatTagApi.getInstance(); } catch (NoClassDefFoundError | NoSuchMethodError e) { // Old version or not installed try { if (plugin instanceof CombatTag) { api = new CombatTagApi((CombatTag) plugin); } } catch (NoClassDefFoundError | NoSuchMethodError ignored) {} } Verify.verify((plugin == null) == (api == null), "Could %s plugin, but could %s api!", plugin == null ? "not find" : "find", api == null ? "not find" : "find"); this.api = api; this.plugin = plugin; }
@Nullable @Override public Object evaluateImpl(Long f) { Native.LongPtr out = new Native.LongPtr(); boolean status = Native.modelEval(z3context, model, f, false, out); Verify.verify(status, "Error during model evaluation"); long outValue = out.value; if (z3creator.isConstant(outValue)) { return z3creator.convertValue(outValue); } // Z3 does not give us a direct API to query for "irrelevant" ASTs during evaluation. // The only hint we get is that the input AST is not simplified down to a constant: // thus, it is assumed to be irrelevant. return null; }
/** * Returns a list of commits between two references. * @param repoPath path to local git repository. * @param startRef start reference. * @param endRef end reference. * @return a list of commits. * @throws IOException if I/O error occurs. * @throws GitAPIException if an error occurs when accessing Git API. */ private static Set<RevCommit> getCommitsBetweenReferences(String repoPath, String startRef, String endRef) throws IOException, GitAPIException { final FileRepositoryBuilder builder = new FileRepositoryBuilder(); final Path path = Paths.get(repoPath); final Repository repo = builder.findGitDir(path.toFile()).readEnvironment().build(); final ObjectId startCommit = getActualRefObjectId(repo, startRef); Verify.verifyNotNull(startCommit, "Start reference \"" + startRef + "\" is invalid!"); final ObjectId endCommit = getActualRefObjectId(repo, endRef); final Iterable<RevCommit> commits = new Git(repo).log().addRange(startCommit, endCommit).call(); return Sets.newLinkedHashSet(commits); }
/** Classifies an identifier's case format. */ static JavaCaseFormat from(String name) { Verify.verify(!name.isEmpty()); boolean firstUppercase = false; boolean hasUppercase = false; boolean hasLowercase = false; boolean first = true; for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (!Character.isAlphabetic(c)) { continue; } if (first) { firstUppercase = Character.isUpperCase(c); first = false; } hasUppercase |= Character.isUpperCase(c); hasLowercase |= Character.isLowerCase(c); } if (firstUppercase) { return hasLowercase ? UPPER_CAMEL : UPPERCASE; } else { return hasUppercase ? LOWER_CAMEL : LOWERCASE; } }
void createTable(final DOMDataWriteTransaction tx) { final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> tb = ImmutableNodes.mapEntryBuilder(); tb.withNodeIdentifier((NodeIdentifierWithPredicates) this.tableId.getLastPathArgument()); tb.withChild(EMPTY_TABLE_ATTRIBUTES); // tableId is keyed, but that fact is not directly visible from YangInstanceIdentifier, see BUG-2796 final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) this.tableId.getLastPathArgument(); for (final Map.Entry<QName, Object> e : tableKey.getKeyValues().entrySet()) { tb.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue())); } final ChoiceNode routes = this.tableSupport.emptyRoutes(); Verify.verifyNotNull(routes, "Null empty routes in %s", this.tableSupport); tx.put(LogicalDatastoreType.OPERATIONAL, this.tableId, tb.withChild(ImmutableChoiceNodeBuilder.create(routes).withNodeIdentifier( new NodeIdentifier(TablesUtil.BMP_ROUTES_QNAME)).build()).build()); }
@Override public void createEmptyTableStructure(final DOMDataWriteTransaction tx, final YangInstanceIdentifier tableId) { final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> tb = ImmutableNodes.mapEntryBuilder(); tb.withNodeIdentifier((NodeIdentifierWithPredicates)tableId.getLastPathArgument()); tb.withChild(EMPTY_TABLE_ATTRIBUTES); // tableId is keyed, but that fact is not directly visible from YangInstanceIdentifier, see BUG-2796 final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) tableId.getLastPathArgument(); for (final Entry<QName, Object> e : tableKey.getKeyValues().entrySet()) { tb.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue())); } final ChoiceNode routes = this.ribSupport.emptyRoutes(); Verify.verifyNotNull(routes, "Null empty routes in %s", this.ribSupport); Verify.verify(Routes.QNAME.equals(routes.getNodeType()), "Empty routes have unexpected identifier %s, expected %s", routes.getNodeType(), Routes.QNAME); tx.put(LogicalDatastoreType.OPERATIONAL, tableId, tb.withChild(routes).build()); }
MainNode<K, V> toCompressed(final TrieMap<?, ?> ct, final int lev, final Gen gen) { int bmp = bitmap; int i = 0; BasicNode[] arr = array; BasicNode[] tmparray = new BasicNode[arr.length]; while (i < arr.length) { // construct new bitmap BasicNode sub = arr[i]; if (sub instanceof INode) { final INode<?, ?> in = (INode<?, ?>) sub; final MainNode<?, ?> inodemain = Verify.verifyNotNull(in.gcasRead(ct)); tmparray [i] = resurrect(in, inodemain); } else if (sub instanceof SNode) { tmparray [i] = sub; } i += 1; } return new CNode<K, V>(gen, bmp, tmparray).toContracted(lev); }
static <K, V> V[] adjustedArray(final Map<K, Integer> offsets, final List<K> keys, final V[] array) { Verify.verify(offsets.size() == keys.size(), "Offsets %s do not match keys %s", offsets, keys); // This relies on the fact that offsets has an ascending iterator final Iterator<K> oi = offsets.keySet().iterator(); final Iterator<K> ki = keys.iterator(); while (oi.hasNext()) { final K o = oi.next(); final K k = ki.next(); if (!k.equals(o)) { return adjustArray(offsets, keys, array); } } return array; }
private void checkMinMaxElements(final YangInstanceIdentifier path, final NodeModification nodeMod, final Optional<TreeNode> current, final Version version) throws DataValidationFailedException { if (!(nodeMod instanceof ModifiedNode)) { LOG.debug("Could not validate {}, does not implement expected class {}", nodeMod, ModifiedNode.class); return; } final ModifiedNode modification = (ModifiedNode) nodeMod; // We need to actually perform the operation to get deal with merge in a sane manner. We know the modification // is immutable, so the result of validation will probably not change. final Optional<TreeNode> maybeApplied = delegate.apply(modification, current, version); Verify.verify(maybeApplied.isPresent()); final TreeNode applied = maybeApplied.get(); validateMinMaxElements(path, modification.getIdentifier(), applied.getData()); // Everything passed. We now have a snapshot of the result node, it would be too bad if we just threw it out. // We know what the result of an apply operation is going to be *if* the following are kept unchanged: // - the 'current' node // - the schemacontext (therefore, the fact this object is associated with the modification) // // So let's stash the result. We will pick it up during apply operation. modification.setValidatedNode(this, current, applied); }
@Override protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) { /* * The node which we are merging exists. We now need to expand any child operations implied by the value. Once * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the * heavy lifting of applying the children recursively (either through here or through applyWrite(). */ final NormalizedNode<?, ?> value = modification.getWrittenValue(); Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value); @SuppressWarnings({"unchecked", "rawtypes"}) final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue(); for (final NormalizedNode<?, ?> c : children) { final PathArgument id = c.getIdentifier(); modification.modifyChild(id, resolveChildOperation(id), version); } return applyTouch(modification, currentMeta, version); }
private void enforceCases(final NormalizedNode<?, ?> normalizedNode) { Verify.verify(normalizedNode instanceof ChoiceNode); final Collection<DataContainerChild<?, ?>> children = ((ChoiceNode) normalizedNode).getValue(); if (!children.isEmpty()) { final DataContainerChild<?, ?> firstChild = children.iterator().next(); final CaseEnforcer enforcer = Verify.verifyNotNull(caseEnforcers.get(firstChild.getIdentifier()), "Case enforcer cannot be null. Most probably, child node %s of choice node %s does not belong " + "in current tree type.", firstChild.getIdentifier(), normalizedNode.getIdentifier()); // Make sure no leaves from other cases are present for (final CaseEnforcer other : exclusions.get(enforcer)) { for (final PathArgument id : other.getAllChildIdentifiers()) { final Optional<NormalizedNode<?, ?>> maybeChild = NormalizedNodes.getDirectChild(normalizedNode, id); Preconditions.checkArgument(!maybeChild.isPresent(), "Child %s (from case %s) implies non-presence of child %s (from case %s), which is %s", firstChild.getIdentifier(), enforcer, id, other, maybeChild.orElse(null)); } } // Make sure all mandatory children are present enforcer.enforceOnTreeNode(normalizedNode); } }
/** * Constructor. * * @param ctx * context of statement. */ protected DeclaredEffectiveStatementBase(final StmtContext<A, D, ?> ctx) { super(ctx); this.argument = ctx.getStatementArgument(); this.statementSource = ctx.getStatementSource(); /* * Share original instance of declared statement between all effective * statements which have been copied or derived from this original * declared statement. */ @SuppressWarnings("unchecked") final StmtContext<?, D, ?> lookupCtx = (StmtContext<?, D, ?>) ctx.getOriginalCtx().orElse(ctx); declaredInstance = Verify.verifyNotNull(lookupCtx.buildDeclared(), "Statement %s failed to build declared statement", lookupCtx); }
private static void performRefine(final Mutable<?, ?, ?> subStmtCtx, final StmtContext<?, ?, ?> usesParentCtx) { final Object refineArgument = subStmtCtx.getStatementArgument(); InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier), subStmtCtx.getStatementSourceReference(), "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument); final Optional<StmtContext<?, ?, ?>> optRefineTargetCtx = SchemaNodeIdentifierBuildNamespace.findNode( usesParentCtx, (SchemaNodeIdentifier) refineArgument); InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx.getStatementSourceReference(), "Refine target node %s not found.", refineArgument); final StmtContext<?, ?, ?> refineTargetNodeCtx = optRefineTargetCtx.get(); if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) { LOG.trace("Refine node '{}' in uses '{}' has target node unknown statement '{}'. " + "Refine has been skipped. At line: {}", subStmtCtx.getStatementArgument(), subStmtCtx.getParentContext().getStatementArgument(), refineTargetNodeCtx.getStatementArgument(), subStmtCtx.getStatementSourceReference()); subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx); return; } Verify.verify(refineTargetNodeCtx instanceof StatementContextBase); addOrReplaceNodes(subStmtCtx, (StatementContextBase<?, ?, ?>) refineTargetNodeCtx); subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx); }
@Override public void enterStatement(final StatementContext ctx) { final StatementSourceReference ref = DeclarationInTextSource.atPosition(sourceName, ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); final String keywordTxt = Verify.verifyNotNull(ctx.getChild(KeywordContext.class, 0)).getText(); final QName validStatementDefinition = getValidStatementDefinition(prefixes, stmtDef, keywordTxt, ref); final int childId = counters.peek().getAndIncrement(); counters.push(new Counter()); if (stmtDef == null || validStatementDefinition == null || !toBeSkipped.isEmpty()) { SourceException.throwIf(writer.getPhase() == ModelProcessingPhase.FULL_DECLARATION, ref, "%s is not a YANG statement or use of extension.", keywordTxt); toBeSkipped.add(keywordTxt); return; } final ArgumentContext argumentCtx = ctx.getChild(ArgumentContext.class, 0); final String argument = argumentCtx != null ? ArgumentContextUtils.stringFromStringContext(argumentCtx, yangVersion, ref) : null; writer.startStatement(childId, validStatementDefinition, argument, ref); }
ContextHolder toContext() throws YangParserException { final SchemaContext schemaContext = Verify.verifyNotNull(parser.buildSchemaContext()); final Set<Module> modules = new HashSet<>(); for (Module module : schemaContext.getModules()) { final SourceIdentifier modId = Util.moduleToIdentifier(module); LOG.debug("Looking for source {}", modId); if (modelsInProject.containsKey(modId)) { LOG.debug("Module {} belongs to current project", module); modules.add(module); for (Module sub : module.getSubmodules()) { final SourceIdentifier subId = Util.moduleToIdentifier(sub); if (modelsInProject.containsKey(subId)) { LOG.warn("Submodule {} not found in input files", sub); } } } } return new ContextHolder(schemaContext, modules, modelsInProject.keySet()); }
final RangeConstraint<N> calculateRangeConstraint(final RangeConstraint<N> baseRangeConstraint) { if (ranges == null) { return baseRangeConstraint; } // Run through alternatives and resolve them against the base type final RangeSet<N> baseRangeSet = baseRangeConstraint.getAllowedRanges(); Verify.verify(!baseRangeSet.isEmpty(), "Base type %s does not define constraints", getBaseType()); final Range<N> baseRange = baseRangeSet.span(); final List<ValueRange> resolvedRanges = ensureResolvedRanges(ranges, baseRange); // Next up, ensure the of boundaries match base constraints final RangeSet<N> typedRanges = ensureTypedRanges(resolvedRanges, baseRange.lowerEndpoint().getClass()); // Now verify if new ranges are strict subset of base ranges if (!baseRangeSet.enclosesAll(typedRanges)) { throw new InvalidRangeConstraintException(typedRanges, "Range constraint %s is not a subset of parent constraint %s", typedRanges, baseRangeSet); } return new ResolvedRangeConstraint<>(constraint, typedRanges); }
YangDataEffectiveStatementImpl(final StmtContext<String, YangDataStatement, ?> ctx) { super(ctx); QName maybeQNameArgumentInit; try { maybeQNameArgumentInit = StmtContextUtils.qnameFromArgument(ctx, argument()); } catch (IllegalArgumentException e) { maybeQNameArgumentInit = getNodeType(); } this.maybeQNameArgument = maybeQNameArgumentInit; path = ctx.getParentContext().getSchemaPath().get().createChild(maybeQNameArgument); container = findFirstEffectiveSubstatement(ContainerEffectiveStatement.class).get(); // TODO: this is strong binding of two API contracts. Unfortunately ContainerEffectiveStatement design is // incomplete. Verify.verify(container instanceof ContainerSchemaNode); }
@Override public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour( final Class<N> type) { NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type); if (potential == null) { final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type); if (potentialRaw != null) { potential = createNamespaceContext(potentialRaw); supportedNamespaces.put(type, potential); } else { throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase " + currentPhase); } } Verify.verify(type.equals(potential.getIdentifier())); /* * Safe cast, previous checkState checks equivalence of key from which * type argument are derived */ return (NamespaceBehaviourWithListeners<K, V, N>) potential; }
/** * Variation of {@link #get} that throws an informative exception if the attribute * can't be resolved due to intrinsic contradictions in the configuration. */ private <T> T getAndValidate(String attributeName, Type<T> type) throws EvalException { SelectorList<T> selectorList = getSelectorList(attributeName, type); if (selectorList == null) { // This is a normal attribute. return super.get(attributeName, type); } List<T> resolvedList = new ArrayList<>(); for (Selector<T> selector : selectorList.getSelectors()) { ConfigKeyAndValue<T> resolvedPath = resolveSelector(attributeName, selector); if (!selector.isValueSet(resolvedPath.configKey)) { // Use the default. We don't have access to the rule here, so pass null to // Attribute.getValue(). This has the result of making attributes with condition // predicates ineligible for "None" values. But no user-facing attributes should // do that anyway, so that isn't a loss. Attribute attr = getAttributeDefinition(attributeName); Verify.verify(attr.getCondition() == Predicates.<AttributeMap>alwaysTrue()); resolvedList.add((T) attr.getDefaultValue(null)); } else { resolvedList.add(resolvedPath.value); } } return resolvedList.size() == 1 ? resolvedList.get(0) : type.concat(resolvedList); }
@Override public String getOutputDirectoryName() { List<PythonVersion> allowedVersions = Arrays.asList(PythonVersion.TARGET_PYTHON_VALUES); Verify.verify( allowedVersions.size() == 2, // If allowedVersions.size() == 1, we don't need this method. ">2 possible defaultPythonVersion values makes output directory clashes possible"); // Skip this check if --force_python is set. That's because reportInvalidOptions reports // bad --force_python settings with a clearer user error (and Bazel's configuration // initialization logic calls reportInvalidOptions after this method). if (!ignorePythonVersionAttribute && !allowedVersions.contains(defaultPythonVersion)) { throw new IllegalStateException( String.format("defaultPythonVersion=%s not allowed: must be in %s to prevent output " + "directory clashes", defaultPythonVersion, Joiner.on(", ").join(allowedVersions))); } return (defaultPythonVersion == PythonVersion.PY3) ? "py3" : null; }
/** * Returns the transition that produces the "artifact owner" for this configuration, or null * if this configuration is its own owner. */ @Nullable public PatchTransition getArtifactOwnerTransition() { PatchTransition ownerTransition = null; for (Fragment fragment : fragments.values()) { PatchTransition fragmentTransition = fragment.getArtifactOwnerTransition(); if (fragmentTransition != null) { if (ownerTransition != null) { Verify.verify(ownerTransition == fragmentTransition, String.format( "cannot determine owner transition: fragments returning both %s and %s", ownerTransition.toString(), fragmentTransition.toString())); } ownerTransition = fragmentTransition; } } return ownerTransition; }
/** * Returns a copy of the output deps using the same key and value ordering as the input deps. * * @param originalDeps the input deps with the ordering to preserve * @param resolvedDeps the unordered output deps * @param attributesAndLabels collection of <attribute, depLabel> pairs guaranteed to match * the ordering of originalDeps.entries(). This is a performance optimization: see * {@link #resolveConfigurations#attributesAndLabels} for details. */ private static OrderedSetMultimap<Attribute, Dependency> sortResolvedDeps( OrderedSetMultimap<Attribute, Dependency> originalDeps, Multimap<AttributeAndLabel, Dependency> resolvedDeps, ArrayList<AttributeAndLabel> attributesAndLabels) { Iterator<AttributeAndLabel> iterator = attributesAndLabels.iterator(); OrderedSetMultimap<Attribute, Dependency> result = OrderedSetMultimap.create(); for (Map.Entry<Attribute, Dependency> depsEntry : originalDeps.entries()) { AttributeAndLabel attrAndLabel = iterator.next(); if (depsEntry.getValue().hasExplicitConfiguration()) { result.put(attrAndLabel.attribute, depsEntry.getValue()); } else { Collection<Dependency> resolvedDepWithSplit = resolvedDeps.get(attrAndLabel); Verify.verify(!resolvedDepWithSplit.isEmpty()); if (resolvedDepWithSplit.size() > 1) { List<Dependency> sortedSplitList = new ArrayList<>(resolvedDepWithSplit); Collections.sort(sortedSplitList, SPLIT_DEP_ORDERING); resolvedDepWithSplit = sortedSplitList; } result.putAll(depsEntry.getKey(), resolvedDepWithSplit); } } return result; }
/** * Finds the given environment in the given set and returns the default environments for its * group. */ private static Collection<EnvironmentWithGroup> getDefaults(Label env, EnvironmentCollection allEnvironments) { EnvironmentGroup group = null; for (EnvironmentGroup candidateGroup : allEnvironments.getGroups()) { if (candidateGroup.getDefaults().contains(env)) { group = candidateGroup; break; } } Verify.verifyNotNull(group); ImmutableSet.Builder<EnvironmentWithGroup> builder = ImmutableSet.builder(); for (Label defaultEnv : group.getDefaults()) { builder.add(EnvironmentWithGroup.create(defaultEnv, group)); } return builder.build(); }
/** * Initializes the default native {@link FileSystem} instance as a platform native * (Unix or Windows) file system. If it's not initialized, then initialize it, * otherwise verify if the type of the instance is correct. */ public static synchronized FileSystem getNativeFileSystem() { if (OS.getCurrent() == OS.WINDOWS) { if (defaultNativeFileSystem == null) { defaultNativeFileSystem = new WindowsFileSystem(); } else { Verify.verify(defaultNativeFileSystem instanceof WindowsFileSystem); } } else { if (defaultNativeFileSystem == null) { try { defaultNativeFileSystem = (FileSystem) Class.forName(TestConstants.TEST_REAL_UNIX_FILE_SYSTEM) .getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new IllegalStateException(e); } } else { Verify.verify(defaultNativeFileSystem instanceof UnixFileSystem); } } return defaultNativeFileSystem; }
/** * This is more advanced and does not make use of the stub. You should not normally need to do * this, but here is how you would. */ void advancedAsyncCall() { ClientCall<HelloRequest, HelloReply> call = channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT); final CountDownLatch latch = new CountDownLatch(1); call.start(new ClientCall.Listener<HelloReply>() { @Override public void onClose(Status status, Metadata trailers) { Verify.verify(status.getCode() == Status.Code.INTERNAL); Verify.verify(status.getDescription().contains("Narwhal")); // Cause is not transmitted over the wire. latch.countDown(); } }, new Metadata()); call.sendMessage(HelloRequest.newBuilder().setName("Marge").build()); call.halfClose(); if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) { throw new RuntimeException("timeout!"); } }
private boolean signature(Statement.Builder builder) { Term t = terms.peek(); if (t.is("@")) { do { builder.addAnnotations(terms.next()); Verify.verify(terms.peek().isWordOrNumber()); builder.addAnnotations(terms.next()); } while (terms.peek().is(".")); if (terms.peek().is("(")) { builder.addAllAnnotations(collectUntilMatching(")")); } return false; } else if (t.is("<")) { builder.addAllSignature(collectUntilMatching(">")); return false; } else if (t.is("class") || t.is("interface")) { builder.addSignature(terms.next()); return true; } else { builder.addSignature(terms.next()); return false; } }
private void block(Statement.Builder builder, boolean classDecl) { if (classDecl) { Verify.verify(terms.peek().is("{")); terms.next(); while (terms.hasNext() && !terms.peek().is("}")) { builder.addDefinitions(statement()); } Verify.verify(terms.next().is("}")); } else { builder.addAllBlock(collectUntilMatching("}")); } }
private boolean readNext() { Verify.verify(hasMore, "invalid call"); try { for (int i = 0; i < in.length; i++) { int len = 0; bb[i].clear(); hasMore &= ((len = channel[i].read(bb[i])) != -1); bb[i].flip(); } } catch (IOException e) { e.printStackTrace(); } return hasMore; }