List of usage examples for com.google.common.base Optional orNull
@Nullable public abstract T orNull();
From source file:org.whispersystems.textsecuregcm.sms.TwilioSmsSender.java
public void deliverSmsVerification(String destination, Optional<String> clientType, String verificationCode) throws IOException, TwilioRestException { TwilioRestClient client = new TwilioRestClient(accountId, accountToken); MessageFactory messageFactory = client.getAccount().getMessageFactory(); List<NameValuePair> messageParams = new LinkedList<>(); messageParams.add(new BasicNameValuePair("To", destination)); if (Util.isEmpty(messagingServicesId)) { messageParams.add(new BasicNameValuePair("From", getRandom(random, numbers))); } else {/*w w w. j a v a2s . c om*/ messageParams.add(new BasicNameValuePair("MessagingServiceSid", messagingServicesId)); } if ("ios".equals(clientType.orNull())) { messageParams.add(new BasicNameValuePair("Body", String.format(SmsSender.SMS_IOS_VERIFICATION_TEXT, verificationCode, verificationCode))); } else { messageParams.add(new BasicNameValuePair("Body", String.format(SmsSender.SMS_VERIFICATION_TEXT, verificationCode))); } try { messageFactory.create(messageParams); } catch (RuntimeException damnYouTwilio) { throw new IOException(damnYouTwilio); } smsMeter.mark(); }
From source file:org.mayocat.context.RequestContextInitializer.java
public void requestInitialized(ServletRequestEvent servletRequestEvent) { if (isStaticPath(this.getRequestURI(servletRequestEvent))) { return;//from ww w . j ava 2s. c o m } DefaultWebRequestBuilder requestBuilder = new DefaultWebRequestBuilder(); // 1. Tenant String host = getHost(servletRequestEvent); String path = getPath(servletRequestEvent); Tenant tenant = this.tenantResolver.get().resolve(host, path); DefaultWebContext context = new DefaultWebContext(tenant, null); // Set the context in the context already, even if we haven't figured out if there is a valid user yet. // The context tenant is actually needed to find out the context user and to initialize tenant configurations ((ThreadLocalWebContext) this.context).setContext(context); if (tenant != null) { requestBuilder.tenantRequest(true); if (path.indexOf("/tenant/" + tenant.getSlug()) == 0) { path = StringUtils.substringAfter(path, "/tenant/" + tenant.getSlug()); requestBuilder.tenantPrefix("/tenant/" + tenant.getSlug()); } } else { requestBuilder.tenantRequest(false); } requestBuilder.apiRequest(path.indexOf("/api/") == 0); // 2. Configurations Map<Class, Serializable> configurations = configurationService.getSettings(); context.setSettings(configurations); // 3. User Optional<User> user = Optional.absent(); for (String headerName : Lists.newArrayList("Authorization", "Cookie")) { final String headerValue = Strings.nullToEmpty(this.getHeaderValue(servletRequestEvent, headerName)); for (Authenticator authenticator : this.authenticators.values()) { if (authenticator.respondTo(headerName, headerValue)) { user = authenticator.verify(headerValue, tenant); } } } context.setUser(user.orNull()); if (tenant != null) { // 4. ThemeDefinition context.setTheme(themeManager.getTheme()); } // 5. Locale LocalesSettings localesSettings = configurationService.getSettings(GeneralSettings.class).getLocales(); boolean localeSet = false; List<Locale> alternativeLocales = FluentIterable.from(localesSettings.getOtherLocales().getValue()) .filter(Predicates.notNull()).toList(); String canonicalPath = path; if (!alternativeLocales.isEmpty()) { for (Locale locale : alternativeLocales) { List<String> fragments = ImmutableList.copyOf( Collections2.filter(Arrays.asList(path.split("/")), Predicates.not(IS_NULL_OR_BLANK))); if (fragments.size() > 0 && fragments.get(0).equals(locale.toLanguageTag())) { context.setLocale(locale); context.setAlternativeLocale(true); canonicalPath = StringUtils.substringAfter(canonicalPath, "/" + locale); localeSet = true; break; } } } if (!localeSet) { context.setLocale(localesSettings.getMainLocale().getValue()); context.setAlternativeLocale(false); } if (context.isAlternativeLocale()) { path = StringUtils.substringAfter(path, context.getLocale().toLanguageTag()); } // 6. Request Optional<Breakpoint> breakpoint = this.breakpointDetector.getBreakpoint(getUserAgent(servletRequestEvent)); requestBuilder.baseURI(getBaseURI(servletRequestEvent)).canonicalPath(canonicalPath).path(path) .breakpoint(breakpoint); requestBuilder.secure(isSecure(servletRequestEvent)); context.setRequest(requestBuilder.build()); }
From source file:net.oneandone.troilus.WriteQueryDataImpl.java
@Override public Object getValueToMutate(String name) { Optional<Object> optional = getValuesToMutate().get(name); if (optional == null) { return null; } else {// w w w . j a va 2 s . c o m return optional.orNull(); } }
From source file:com.hivewallet.androidclient.wallet.ui.TransactionsListAdapter.java
private AddressBookEntry lookupEntry(@Nonnull final String address) { final Optional<AddressBookEntry> cachedEntry = addressBookCache.get(address); if (cachedEntry == null) { final AddressBookEntry entry = AddressBookProvider.lookupEntry(context, address); final Optional<AddressBookEntry> optionalEntry = Optional.fromNullable(entry); addressBookCache.put(address, optionalEntry); // cache entry or the fact that it wasn't found return entry; } else {// w ww . j a v a 2 s .c o m return cachedEntry.orNull(); } }
From source file:org.locationtech.geogig.cli.porcelain.Blame.java
@Override public void runInternal(GeogigCLI cli) throws IOException { checkParameter(paths.size() < 2, "Only one path allowed"); checkParameter(!paths.isEmpty(), "A path must be specified"); ConsoleReader console = cli.getConsole(); GeoGIG geogig = cli.getGeogig();//from ww w . j a va 2 s.c o m String path = paths.get(0); try { BlameReport report = geogig.command(BlameOp.class).setPath(path).call(); Map<String, ValueAndCommit> changes = report.getChanges(); Iterator<String> iter = changes.keySet().iterator(); while (iter.hasNext()) { String attrib = iter.next(); ValueAndCommit valueAndCommit = changes.get(attrib); RevCommit commit = valueAndCommit.commit; Optional<?> value = valueAndCommit.value; if (porcelain) { StringBuilder sb = new StringBuilder(); sb.append(attrib).append(' '); sb.append(commit.getId().toString()).append(' '); sb.append(commit.getAuthor().getName().or("")).append(' '); sb.append(commit.getAuthor().getEmail().or("")).append(' '); sb.append(Long.toString(commit.getAuthor().getTimestamp())).append(' '); sb.append(Integer.toString(commit.getAuthor().getTimeZoneOffset())); if (!noValues) { sb.append(" ").append(TextValueSerializer.asString(Optional.of((Object) value.orNull()))); } console.println(sb.toString()); } else { Ansi ansi = newAnsi(console.getTerminal()); ansi.fg(GREEN).a(attrib + ": ").reset(); if (!noValues) { String s = value.isPresent() ? value.get().toString() : "NULL"; ansi.fg(YELLOW).a(s).a(" ").reset(); } ansi.a(commit.getId().toString().substring(0, 7)).a(" "); ansi.a(commit.getAuthor().getName().or("")).a(" "); ansi.a(commit.getAuthor().getEmail().or("")).a(" "); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String date = formatter.format( new Date(commit.getAuthor().getTimestamp() + commit.getAuthor().getTimeZoneOffset())); ansi.a(date); console.println(ansi.toString()); } } } catch (BlameException e) { switch (e.statusCode) { case FEATURE_NOT_FOUND: throw new InvalidParameterException("The supplied path does not exist", e); case PATH_NOT_FEATURE: throw new InvalidParameterException("The supplied path does not resolve to a feature", e); } } }
From source file:org.sourcepit.tpmp.resolver.tycho.TychoSourceIUResolver.java
public void resolveSources(MavenSession session, final TargetPlatform targetPlatform, Collection<String> sourceTargetBundles, TargetPlatformResolutionHandler handler) { final Set<String> sourceTargets = new HashSet<String>(sourceTargetBundles); if (sourceTargets.isEmpty()) { return;/*from w w w .ja v a2s . c om*/ } final Map<String, MavenProject> projectsMap = projectFacade.createVidToProjectMap(session); final P2Resolver resolver = createResolver(); final ClassLoader classLoader = targetPlatform.getClass().getClassLoader(); final P2TargetPlatformDAO tpDAO = new P2TargetPlatformDAO(classLoader); final InstallableUnitDAO iuDAO = tpDAO.getInstallableUnitDAO(); for (final Object unit : tpDAO.getInstallableUnits(targetPlatform)) { if (sourceTargets.isEmpty()) { return; } if (hasSourceCapability(iuDAO, unit)) { final String symbolicName = iuDAO.getId(unit); final String version = iuDAO.getVersion(unit).toString(); final BundleManifest manifest = getManifest(iuDAO, unit); String[] targetIdAndVersion = getTargetIdAndVersion(manifest); if (targetIdAndVersion == null) { targetIdAndVersion = getTargetIdAndVersion(symbolicName, version); } if (targetIdAndVersion != null) { final String targetKey = targetIdAndVersion[0] + "_" + targetIdAndVersion[1]; if (sourceTargets.remove(targetKey)) { final P2ResolutionResult result = resolve(targetPlatform, resolver, symbolicName, version); for (Entry entry : result.getArtifacts()) { final Optional<MavenProject> mavenProject = projectFacade.getMavenProject(projectsMap, targetIdAndVersion[0], targetIdAndVersion[1]); final File location = projectFacade.getLocation(entry, mavenProject); if (location != null && location.exists()) { handler.handlePlugin(entry.getId(), entry.getVersion(), location, false, mavenProject.orNull()); } } } } } } }
From source file:com.google.devtools.build.lib.buildtool.SkyframeBuilder.java
@Override public void buildArtifacts(Reporter reporter, Set<Artifact> artifacts, Set<ConfiguredTarget> parallelTests, Set<ConfiguredTarget> exclusiveTests, Collection<ConfiguredTarget> targetsToBuild, Collection<AspectValue> aspects, Executor executor, Set<ConfiguredTarget> builtTargets, boolean explain, @Nullable Range<Long> lastExecutionTimeRange, TopLevelArtifactContext topLevelArtifactContext) throws BuildFailedException, AbruptExitException, TestExecException, InterruptedException { skyframeExecutor.prepareExecution(modifiedOutputFiles, lastExecutionTimeRange); skyframeExecutor.setFileCache(fileCache); // Note that executionProgressReceiver accesses builtTargets concurrently (after wrapping in a // synchronized collection), so unsynchronized access to this variable is unsafe while it runs. ExecutionProgressReceiver executionProgressReceiver = new ExecutionProgressReceiver( Preconditions.checkNotNull(builtTargets), countTestActions(exclusiveTests), ImmutableSet.<ConfiguredTarget>builder().addAll(parallelTests).addAll(exclusiveTests).build(), skyframeExecutor.getEventBus()); skyframeExecutor.getEventBus().post(new ExecutionProgressReceiverAvailableEvent(executionProgressReceiver)); ResourceManager.instance().setEventBus(skyframeExecutor.getEventBus()); List<ExitCode> exitCodes = new LinkedList<>(); EvaluationResult<?> result;/*from www. j a v a2s . c om*/ ActionExecutionStatusReporter statusReporter = ActionExecutionStatusReporter.create(reporter, executor, skyframeExecutor.getEventBus()); AtomicBoolean isBuildingExclusiveArtifacts = new AtomicBoolean(false); ActionExecutionInactivityWatchdog watchdog = new ActionExecutionInactivityWatchdog( executionProgressReceiver.createInactivityMonitor(statusReporter), executionProgressReceiver.createInactivityReporter(statusReporter, isBuildingExclusiveArtifacts), progressReportInterval); skyframeExecutor.setActionExecutionProgressReportingObjects(executionProgressReceiver, executionProgressReceiver, statusReporter); watchdog.start(); try { result = skyframeExecutor.buildArtifacts(reporter, executor, artifacts, targetsToBuild, aspects, parallelTests, /*exclusiveTesting=*/ false, keepGoing, explain, finalizeActionsToOutputService, numJobs, actionCacheChecker, executionProgressReceiver, topLevelArtifactContext); // progressReceiver is finished, so unsynchronized access to builtTargets is now safe. Optional<ExitCode> exitCode = processResult(reporter, result, keepGoing, skyframeExecutor); Preconditions.checkState( exitCode != null || result.keyNames() .size() == (artifacts.size() + targetsToBuild.size() + aspects.size() + parallelTests.size()), "Build reported as successful but not all artifacts and targets built: %s, %s", result, artifacts); if (exitCode != null) { exitCodes.add(exitCode.orNull()); } // Run exclusive tests: either tagged as "exclusive" or is run in an invocation with // --test_output=streamed. isBuildingExclusiveArtifacts.set(true); for (ConfiguredTarget exclusiveTest : exclusiveTests) { // Since only one artifact is being built at a time, we don't worry about an artifact being // built and then the build being interrupted. result = skyframeExecutor.buildArtifacts(reporter, executor, ImmutableSet.<Artifact>of(), targetsToBuild, aspects, ImmutableSet.of(exclusiveTest), /*exclusiveTesting=*/ true, keepGoing, explain, finalizeActionsToOutputService, numJobs, actionCacheChecker, null, topLevelArtifactContext); exitCode = processResult(reporter, result, keepGoing, skyframeExecutor); Preconditions.checkState(exitCode != null || !result.keyNames().isEmpty(), "Build reported as successful but test %s not executed: %s", exclusiveTest, result); if (exitCode != null) { exitCodes.add(exitCode.orNull()); } } } finally { watchdog.stop(); ResourceManager.instance().unsetEventBus(); skyframeExecutor.setActionExecutionProgressReportingObjects(null, null, null); statusReporter.unregisterFromEventBus(); } if (!exitCodes.isEmpty()) { if (keepGoing) { // Use the exit code with the highest priority. throw new BuildFailedException(null, Collections.max(exitCodes, ExitCodeComparator.INSTANCE)); } else { throw new BuildFailedException(); } } }
From source file:org.opendaylight.yangtools.yang.parser.stmt.reactor.SubstatementContext.java
private SchemaPath createSchemaPath() { final Optional<SchemaPath> maybeParentPath = parent.getSchemaPath(); Verify.verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent); final SchemaPath parentPath = maybeParentPath.get(); if (Utils.isUnknownNode(this)) { return parentPath.createChild(getPublicDefinition().getStatementName()); }// ww w .j ava2 s . c om if (argument instanceof QName) { final QName qname = (QName) argument; if (StmtContextUtils.producesDeclared(this, UsesStatement.class)) { return maybeParentPath.orNull(); } final SchemaPath path; if ((StmtContextUtils.producesDeclared(getParentContext(), ChoiceStatement.class) || Boolean.TRUE.equals(parent.getFromNamespace(AugmentToChoiceNamespace.class, parent))) && isSupportedAsShorthandCase()) { path = parentPath.createChild(qname); } else { path = parentPath; } return path.createChild(qname); } if (argument instanceof String) { // FIXME: This may yield illegal argument exceptions final StatementContextBase<?, ?, ?> originalCtx = getOriginalCtx(); final QName qname = (originalCtx != null) ? Utils.qNameFromArgument(originalCtx, (String) argument) : Utils.qNameFromArgument(this, (String) argument); return parentPath.createChild(qname); } if (argument instanceof SchemaNodeIdentifier && (StmtContextUtils.producesDeclared(this, AugmentStatement.class) || StmtContextUtils.producesDeclared(this, RefineStatement.class) || StmtContextUtils.producesDeclared(this, DeviationStatement.class))) { return parentPath.createChild(((SchemaNodeIdentifier) argument).getPathFromRoot()); } // FIXME: this does not look right return maybeParentPath.orNull(); }
From source file:com.arpnetworking.tsdcore.tailer.StatefulTailer.java
private Optional<Boolean> compareByHash(final Optional<String> prefixHash, final int prefixLength) { final int appliedLength; if (_hash.isPresent()) { appliedLength = REQUIRED_BYTES_FOR_HASH; } else {// www . ja v a2 s. c om appliedLength = prefixLength; } try (final SeekableByteChannel reader = Files.newByteChannel(_file.toPath(), StandardOpenOption.READ)) { final Optional<String> filePrefixHash = computeHash(reader, appliedLength); LOGGER.trace(String.format("Comparing hashes; hash1=%s, hash2=%s, size=%d", prefixHash, filePrefixHash, Integer.valueOf(appliedLength))); return Optional .of(Boolean.valueOf(Objects.equals(_hash.or(prefixHash).orNull(), filePrefixHash.orNull()))); } catch (final IOException e) { return Optional.absent(); } }
From source file:org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext.java
/** * Fetches the requested sideInput, and maintains a view of the cache that doesn't remove items * until the active work item is finished. * * <p>If the side input was not ready, throws {@code IllegalStateException} if the state is * {@literal CACHED_IN_WORKITEM} or returns null otherwise. * * <p>If the side input was ready and null, returns {@literal Optional.absent()}. If the side * input was ready and non-null returns {@literal Optional.present(...)}. *///from w ww . j a va 2 s. c o m @Nullable private <T> Optional<T> fetchSideInput(PCollectionView<T> view, BoundedWindow sideInputWindow, String stateFamily, StateFetcher.SideInputState state, Supplier<Closeable> scopedReadStateSupplier) { Map<BoundedWindow, Object> tagCache = sideInputCache.get(view.getTagInternal()); if (tagCache == null) { tagCache = new HashMap<>(); sideInputCache.put(view.getTagInternal(), tagCache); } if (tagCache.containsKey(sideInputWindow)) { @SuppressWarnings("unchecked") T typed = (T) tagCache.get(sideInputWindow); return Optional.fromNullable(typed); } else { if (state == StateFetcher.SideInputState.CACHED_IN_WORKITEM) { throw new IllegalStateException( "Expected side input to be cached. Tag: " + view.getTagInternal().getId()); } Optional<T> fetched = stateFetcher.fetchSideInput(view, sideInputWindow, stateFamily, state, scopedReadStateSupplier); if (fetched != null) { tagCache.put(sideInputWindow, fetched.orNull()); } return fetched; } }