com.google.common.base.Verify Java Examples
The following examples show how to use
com.google.common.base.Verify.
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: TypeNameClassifier.java From javaide with GNU General Public License v3.0 | 6 votes |
/** * 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; } }
Example #2
Source File: ChoiceModificationStrategy.java From yangtools with Eclipse Public License 1.0 | 6 votes |
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); } }
Example #3
Source File: OffsetMapCache.java From yangtools with Eclipse Public License 1.0 | 6 votes |
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; }
Example #4
Source File: RangeRestrictedTypeBuilder.java From yangtools with Eclipse Public License 1.0 | 6 votes |
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); }
Example #5
Source File: BuildGlobalContext.java From yangtools with Eclipse Public License 1.0 | 6 votes |
@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; }
Example #6
Source File: RuleContextConstraintSemantics.java From bazel with Apache License 2.0 | 6 votes |
/** * 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) { EnvironmentLabels group = null; for (EnvironmentLabels 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(); }
Example #7
Source File: TypeNameClassifier.java From java-n-IDE-for-Android with Apache License 2.0 | 6 votes |
/** * 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; } }
Example #8
Source File: FtdClientPool.java From ftdc with Apache License 2.0 | 6 votes |
/** * 释放连接 * @param channel * @return */ public Future<Void> release(Channel channel) { Verify.verifyNotNull(channel, "channel不允许为NULL"); InetSocketAddress remoteAddress = (InetSocketAddress)channel.remoteAddress(); if(logger.isDebugEnabled()) { logger.debug("{} channel released", remoteAddress); } FixedChannelPool fixedChannelPool = pollMap.get(remoteAddress); Future<Void> releaseFuture = fixedChannelPool.release(channel); if(!releaseFuture.isSuccess()) { Throwable cause = releaseFuture.cause(); if(cause != null) { logger.error("rlease local channel {}, remote channel {}, happens error {}", channel.localAddress(), channel.remoteAddress(), ExceptionUtils.getStackTrace(releaseFuture.cause())); } } return releaseFuture; }
Example #9
Source File: ErrorHandlingClient.java From grpc-java with Apache License 2.0 | 6 votes |
/** * 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!"); } }
Example #10
Source File: NotesBuilder.java From contribution with GNU Lesser General Public License v2.1 | 6 votes |
/** * 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); }
Example #11
Source File: ServiceHelperCompat.java From intellij with Apache License 2.0 | 6 votes |
public static <T> void registerService( ComponentManager componentManager, Class<T> key, T implementation, Disposable parentDisposable) { @SuppressWarnings({"rawtypes", "unchecked"}) // #api193: wildcard generics added in 2020.1 List<? extends IdeaPluginDescriptor> loadedPlugins = (List) PluginManager.getLoadedPlugins(); Optional<? extends IdeaPluginDescriptor> platformPlugin = loadedPlugins.stream() .filter(descriptor -> descriptor.getName().startsWith("IDEA CORE")) .findAny(); Verify.verify(platformPlugin.isPresent()); ((ComponentManagerImpl) componentManager) .registerServiceInstance(key, implementation, platformPlugin.get()); }
Example #12
Source File: FullUnorderedScanExpression.java From fdb-record-layer with Apache License 2.0 | 6 votes |
@SuppressWarnings("UnstableApiUsage") @Nonnull @Override public PlannerGraph rewritePlannerGraph(@Nonnull List<? extends PlannerGraph> childGraphs) { Verify.verify(childGraphs.isEmpty()); final PlannerGraph.DataNodeWithInfo dataNodeWithInfo; dataNodeWithInfo = new PlannerGraph.DataNodeWithInfo(NodeInfo.BASE_DATA, ImmutableList.of("record types: {{types}}"), ImmutableMap.of("types", Attribute.gml(getRecordTypes().stream().map(Attribute::gml).collect(ImmutableList.toImmutableList())))); return PlannerGraph.fromNodeAndChildGraphs( new PlannerGraph.LogicalOperatorNodeWithInfo(this, NodeInfo.SCAN_OPERATOR, ImmutableList.of(), ImmutableMap.of()), ImmutableList.of(PlannerGraph.fromNodeAndChildGraphs( dataNodeWithInfo, childGraphs))); }
Example #13
Source File: ImportTransform.java From DataflowTemplates with Apache License 2.0 | 6 votes |
private void validateGcsFiles( ProcessContext c, String table, TableManifest manifest) { org.apache.beam.sdk.extensions.gcp.util.GcsUtil gcsUtil = c.getPipelineOptions().as(GcsOptions.class).getGcsUtil(); // Convert file names to GcsPaths. List<GcsPath> gcsPaths = Lists.transform( manifest.getFilesList(), f -> GcsPath.fromUri(importDirectory.get()).resolve(f.getName())); List<String> checksums = FileChecksum.getGcsFileChecksums(gcsUtil, gcsPaths); for (int i = 0; i < gcsPaths.size(); i++) { GcsPath path = gcsPaths.get(i); String fileName = gcsPaths.get(i).getFileName().getObject(); String expectedHash = manifest.getFiles(i).getMd5(); String actualHash = checksums.get(i); Verify.verify( expectedHash.equals(actualHash), "Inconsistent file: %s expected hash %s actual hash %s", fileName, expectedHash, actualHash); c.output(KV.of(table, path.toString())); } }
Example #14
Source File: ErrorHandlingClient.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
void futureCallCallback() { GreeterFutureStub stub = GreeterGrpc.newFutureStub(channel); ListenableFuture<HelloReply> response = stub.sayHello(HelloRequest.newBuilder().setName("Maggie").build()); final CountDownLatch latch = new CountDownLatch(1); Futures.addCallback( response, new FutureCallback<HelloReply>() { @Override public void onSuccess(@Nullable HelloReply result) { // Won't be called, since the server in this example always fails. } @Override public void onFailure(Throwable t) { Status status = Status.fromThrowable(t); Verify.verify(status.getCode() == Status.Code.INTERNAL); Verify.verify(status.getDescription().contains("Crybaby")); // Cause is not transmitted over the wire.. latch.countDown(); } }, directExecutor()); if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) { throw new RuntimeException("timeout!"); } }
Example #15
Source File: JavaInputAstVisitor.java From google-java-format with Apache License 2.0 | 5 votes |
private void visitAnnotatedArrayType(Tree node) { TypeWithDims extractedDims = DimensionHelpers.extractDims(node, SortedDims.YES); builder.open(plusFour); scan(extractedDims.node, null); Deque<List<? extends AnnotationTree>> dims = new ArrayDeque<>(extractedDims.dims); maybeAddDims(dims); Verify.verify(dims.isEmpty()); builder.close(); }
Example #16
Source File: JndiResourceResolverFactory.java From grpc-java with Apache License 2.0 | 5 votes |
@Override public List<SrvRecord> resolveSrv(String host) throws Exception { if (logger.isLoggable(Level.FINER)) { logger.log( Level.FINER, "About to query SRV records for {0}", new Object[]{host}); } List<String> rawSrvRecords = recordFetcher.getAllRecords("SRV", "dns:///" + host); if (logger.isLoggable(Level.FINER)) { logger.log( Level.FINER, "Found {0} SRV records", new Object[]{rawSrvRecords.size()}); } List<SrvRecord> srvRecords = new ArrayList<>(rawSrvRecords.size()); Exception first = null; Level level = Level.WARNING; for (String rawSrv : rawSrvRecords) { try { String[] parts = whitespace.split(rawSrv); Verify.verify(parts.length == 4, "Bad SRV Record: %s", rawSrv); // SRV requires the host name to be absolute if (!parts[3].endsWith(".")) { throw new RuntimeException("Returned SRV host does not end in period: " + parts[3]); } srvRecords.add(new SrvRecord(parts[3], Integer.parseInt(parts[2]))); } catch (RuntimeException e) { logger.log(level, "Failed to construct SRV record " + rawSrv, e); if (first == null) { first = e; level = Level.FINE; } } } if (srvRecords.isEmpty() && first != null) { throw first; } return Collections.unmodifiableList(srvRecords); }
Example #17
Source File: OffsetMapCache.java From yangtools with Eclipse Public License 1.0 | 5 votes |
private static <K, V> V[] adjustArray(final Map<K, Integer> offsets, final List<K> keys, final V[] array) { @SuppressWarnings("unchecked") final V[] ret = (V[]) Array.newInstance(array.getClass().getComponentType(), array.length); int offset = 0; for (final K k : keys) { final Integer o = Verify.verifyNotNull(offsets.get(k), "Key %s not present in offsets %s", k, offsets); ret[o] = array[offset++]; } return ret; }
Example #18
Source File: WorkspaceFactoryHelper.java From bazel with Apache License 2.0 | 5 votes |
private static void overwriteRule(Package.Builder pkg, Rule rule) throws Package.NameConflictException { Preconditions.checkArgument(rule.getOutputFiles().isEmpty()); Target old = pkg.getTarget(rule.getName()); if (old != null) { if (old instanceof Rule) { Verify.verify(((Rule) old).getOutputFiles().isEmpty()); } pkg.removeTarget(rule); } pkg.addRule(rule); }
Example #19
Source File: Bootstrap.java From SonarPet with GNU General Public License v3.0 | 5 votes |
@Override public void onLoad() { getLogger().info("Downloading SonarPet's libraries"); try { boolean accessDenied = false; try { Files.createDirectories(LocalRepository.standard().getLocation()); Verify.verify(Files.isDirectory(LocalRepository.standard().getLocation())); } catch (AccessDeniedException e) { accessDenied = true; } final LocalRepository localRepo; if (accessDenied || !Files.isWritable(LocalRepository.standard().getLocation())) { getLogger().warning("Using fallback local repo since the standard one isn't writable"); localRepo = LocalRepository.create("fallback-repo", getFile().toPath().resolve("maven")); } else { localRepo = LocalRepository.standard(); } MavenDependencyInfo dependencyInfo = MavenDependencyInfo.parseResource("dependencies.json"); dependencyInfo.injectDependencies((URLClassLoader) getClass().getClassLoader(), (dependency) -> { Path path; if ((path = localRepo.findPath(dependency)) != null) { getLogger().fine(() -> "Using cached version of " + dependency); return path; } ResolvedMavenArtifact resolved = dependencyInfo.find(dependency); getLogger().info(() -> "Downloading " + dependency + " from " + resolved.getRepository().getName()); return localRepo.downloadFrom(resolved); }); plugin = new EchoPetPlugin(this); } catch (IOException | MavenException t) { getLogger().log(Level.SEVERE, "Unable to load libraries", t); setEnabled(false); return; } if (metrics != null) { metrics = new Metrics(this); plugin.configureMetrics(metrics); } }
Example #20
Source File: UndeclaredEffectiveStatementBase.java From yangtools with Eclipse Public License 1.0 | 5 votes |
protected UndeclaredEffectiveStatementBase(final StmtContext<A, D, ?> ctx) { super(ctx); this.statementDefinition = ctx.getPublicDefinition(); this.argument = ctx.getStatementArgument(); this.statementSource = ctx.getStatementSource(); final D declareInstance = ctx.buildDeclared(); Verify.verify(declareInstance == null, "Statement %s resulted in declared statement %s", declareInstance); }
Example #21
Source File: AbstractImportStatementSupport.java From yangtools with Eclipse Public License 1.0 | 5 votes |
@Override public final void onPreLinkageDeclared(final Mutable<String, ImportStatement, ImportEffectiveStatement> stmt) { /* * Add ModuleIdentifier of a module which is required by this module. * Based on this information, required modules are searched from library * sources. */ stmt.addRequiredSource(RevisionImport.getImportedSourceIdentifier(stmt)); final String moduleName = stmt.coerceStatementArgument(); final ModelActionBuilder importAction = stmt.newInferenceAction(SOURCE_PRE_LINKAGE); final Prerequisite<StmtContext<?, ?, ?>> imported = importAction.requiresCtx(stmt, PreLinkageModuleNamespace.class, moduleName, SOURCE_PRE_LINKAGE); importAction.mutatesCtx(stmt.getRoot(), SOURCE_PRE_LINKAGE); importAction.apply(new InferenceAction() { @Override public void apply(final InferenceContext ctx) { final StmtContext<?, ?, ?> importedModuleContext = imported.resolve(ctx); Verify.verify(moduleName.equals(importedModuleContext.getStatementArgument())); final URI importedModuleNamespace = importedModuleContext.getFromNamespace(ModuleNameToNamespace.class, moduleName); Verify.verifyNotNull(importedModuleNamespace); final String impPrefix = SourceException.throwIfNull( firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class), stmt.getStatementSourceReference(), "Missing prefix statement"); stmt.addToNs(ImpPrefixToNamespace.class, impPrefix, importedModuleNamespace); } @Override public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) { InferenceException.throwIf(failed.contains(imported), stmt.getStatementSourceReference(), "Imported module [%s] was not found.", moduleName); } }); }
Example #22
Source File: GitRepository.java From copybara with Apache License 2.0 | 5 votes |
/** * Resolves a git reference to the SHA-1 reference */ public String parseRef(String ref) throws RepoException, CannotResolveRevisionException { // Runs rev-list on the reference and remove the extra newline from the output. CommandOutputWithStatus result = gitAllowNonZeroExit( NO_INPUT, ImmutableList.of("rev-list", "-1", ref, "--"), DEFAULT_TIMEOUT); if (!result.getTerminationStatus().success()) { throw new CannotResolveRevisionException("Cannot find reference '" + ref + "'"); } String sha1 = result.getStdout().trim(); Verify.verify(SHA1_PATTERN.matcher(sha1).matches(), "Should be resolved to a SHA-1: %s", sha1); return sha1; }
Example #23
Source File: PaginatedList.java From copybara with Apache License 2.0 | 5 votes |
/** * Return a PaginatedList with the next/last/etc. fields populated if linkHeader is not null. */ @SuppressWarnings("unchecked") public PaginatedList<T> withPaginationInfo(String apiPrefix, @Nullable String linkHeader) { if (linkHeader == null) { return this; } String next = null; String prev = null; String last = null; String first = null; for (String e : Splitter.on(',').trimResults().split(linkHeader)) { Matcher matcher = LINK_HEADER_PATTERN.matcher(e); Verify.verify(matcher.matches(), "'%s' doesn't match Link regex. Header: %s", e, linkHeader); String url = matcher.group(1); String rel = matcher.group(2); Verify.verify(url.startsWith(apiPrefix)); url = url.substring(apiPrefix.length()); switch (rel) { case "first": first = url; break; case "prev": prev = url; break; case "next": next = url; break; case "last": last = url; break; default: // fall out } } return new PaginatedList<>(this, first, prev, next, last); }
Example #24
Source File: ErrorHandlingClient.java From grpc-java with Apache License 2.0 | 5 votes |
void asyncCall() { GreeterStub stub = GreeterGrpc.newStub(channel); HelloRequest request = HelloRequest.newBuilder().setName("Homer").build(); final CountDownLatch latch = new CountDownLatch(1); StreamObserver<HelloReply> responseObserver = new StreamObserver<HelloReply>() { @Override public void onNext(HelloReply value) { // Won't be called. } @Override public void onError(Throwable t) { Status status = Status.fromThrowable(t); Verify.verify(status.getCode() == Status.Code.INTERNAL); Verify.verify(status.getDescription().contains("Overbite")); // Cause is not transmitted over the wire.. latch.countDown(); } @Override public void onCompleted() { // Won't be called, since the server in this example always fails. } }; stub.sayHello(request, responseObserver); if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) { throw new RuntimeException("timeout!"); } }
Example #25
Source File: PipelineArgumentsTab.java From google-cloud-eclipse with Apache License 2.0 | 5 votes |
private PipelineOptionsHierarchy getPipelineOptionsHierarchy(IProgressMonitor monitor) { if (launchConfiguration != null) { Verify.verify(project != null && project.isAccessible()); try { return pipelineOptionsHierarchyFactory.forProject(project, launchConfiguration.getMajorVersion(), monitor); } catch (PipelineOptionsRetrievalException e) { DataflowUiPlugin.logWarning( "Couldn't retrieve Pipeline Options Hierarchy for project %s", project); //$NON-NLS-1$ return pipelineOptionsHierarchyFactory.global(monitor); } } return pipelineOptionsHierarchyFactory.global(monitor); }
Example #26
Source File: MavenUtils.java From google-cloud-eclipse with Apache License 2.0 | 5 votes |
/** * Perform some Maven-related action that may result in a change to the local Maven repositories, * ensuring that required {@link ISchedulingRule scheduling rules} are held. */ public static <T> T runOperation(IProgressMonitor monitor, MavenRepositoryOperation<T> operation) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, 10); ISchedulingRule rule = mavenResolvingRule(); boolean acquireRule = Job.getJobManager().currentRule() == null; if (acquireRule) { Job.getJobManager().beginRule(rule, progress.split(2)); } try { Verify.verify( Job.getJobManager().currentRule().contains(rule), "require holding superset of rule: " + rule); IMavenExecutionContext context = MavenPlugin.getMaven().createExecutionContext(); return context.execute( (context2, monitor2) -> { // todo we'd prefer not to depend on m2e here RepositorySystem system = MavenPluginActivator.getDefault().getRepositorySystem(); return operation.run(context2, system, SubMonitor.convert(monitor2)); }, progress.split(8)); } finally { if (acquireRule) { Job.getJobManager().endRule(rule); } } }
Example #27
Source File: LengthRestrictedTypeBuilder.java From yangtools with Eclipse Public License 1.0 | 5 votes |
private static Integer resolveLength(final Number unresolved, final Range<Integer> span) { if (unresolved instanceof Integer) { return (Integer) unresolved; } if (unresolved instanceof UnresolvedNumber) { return ((UnresolvedNumber)unresolved).resolveLength(span); } return Verify.verifyNotNull(NumberUtil.converterTo(Integer.class)).apply(unresolved); }
Example #28
Source File: FieldScopeLogic.java From curiostack with MIT License | 5 votes |
@Override public void validate( Descriptor rootDescriptor, FieldDescriptorValidator fieldDescriptorValidator) { if (isRecursive) { Verify.verify( fieldDescriptorValidator == FieldDescriptorValidator.ALLOW_ALL, "Field descriptor validators are not supported " + "for non-recursive field matcher logics."); } }
Example #29
Source File: FieldScopeLogic.java From curiostack with MIT License | 5 votes |
@Override public void validate( Descriptor rootDescriptor, FieldDescriptorValidator fieldDescriptorValidator) { Verify.verify( fieldDescriptorValidator == FieldDescriptorValidator.ALLOW_ALL, "PartialScopeLogic doesn't support custom field validators."); checkArgument( expectedDescriptor.equals(rootDescriptor), "Message given to FieldScopes.fromSetFields() does not have the same descriptor as the " + "message being tested. Expected %s, got %s.", expectedDescriptor.getFullName(), rootDescriptor.getFullName()); }
Example #30
Source File: DetailErrorSample.java From grpc-java with Apache License 2.0 | 5 votes |
/** * 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(trailers.containsKey(DEBUG_INFO_TRAILER_KEY)); try { Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO)); } catch (IllegalArgumentException e) { throw new VerifyException(e); } latch.countDown(); } }, new Metadata()); call.sendMessage(HelloRequest.newBuilder().build()); call.halfClose(); if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) { throw new RuntimeException("timeout!"); } }