List of usage examples for com.google.common.collect Iterables tryFind
public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate)
From source file:org.killbill.billing.jaxrs.resources.AdminResource.java
@PUT @Consumes(APPLICATION_JSON)/*from w ww. j a v a 2s . co m*/ @Produces(APPLICATION_JSON) @Path("/payments/{paymentId:" + UUID_PATTERN + "}/transactions/{paymentTransactionId:" + UUID_PATTERN + "}") @ApiOperation(value = "Update existing paymentTransaction and associated payment state") @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid account data supplied") }) public Response updatePaymentTransactionState(final AdminPaymentJson json, @PathParam("paymentId") final String paymentIdStr, @PathParam("paymentTransactionId") final String paymentTransactionIdStr, @HeaderParam(HDR_CREATED_BY) final String createdBy, @HeaderParam(HDR_REASON) final String reason, @HeaderParam(HDR_COMMENT) final String comment, @javax.ws.rs.core.Context final HttpServletRequest request) throws PaymentApiException { final CallContext callContext = context.createContext(createdBy, reason, comment, request); final Payment payment = paymentApi.getPayment(UUID.fromString(paymentIdStr), false, false, ImmutableList.<PluginProperty>of(), callContext); final UUID paymentTransactionId = UUID.fromString(paymentTransactionIdStr); final PaymentTransaction paymentTransaction = Iterables .tryFind(payment.getTransactions(), new Predicate<PaymentTransaction>() { @Override public boolean apply(final PaymentTransaction input) { return input.getId().equals(paymentTransactionId); } }).orNull(); adminPaymentApi.fixPaymentTransactionState(payment, paymentTransaction, TransactionStatus.valueOf(json.getTransactionStatus()), json.getLastSuccessPaymentState(), json.getCurrentPaymentStateName(), ImmutableList.<PluginProperty>of(), callContext); return Response.status(Status.OK).build(); }
From source file:brooklyn.networking.sdn.SdnProviderImpl.java
@Override public void deallocateNetwork(VirtualNetwork network) { String networkId = network.getAttribute(VirtualNetwork.NETWORK_ID); Optional<Entity> found = Iterables.tryFind(getAttribute(SDN_APPLICATIONS).getMembers(), EntityPredicates.attributeEqualTo(VirtualNetwork.NETWORK_ID, networkId)); if (found.isPresent()) { Entity group = found.get(); getAttribute(SDN_APPLICATIONS).removeMember(group); getAttribute(SDN_APPLICATIONS).removeChild(group); Entities.unmanage(group);//from w w w . j a va2 s . c om } else { LOG.warn("Cannot find group containing {} network entities", networkId); } getAttribute(SDN_NETWORKS).removeMember(network); // TODO actually deprovision the network if possible? }
From source file:org.eclipse.mylyn.internal.gerrit.core.remote.GerritReviewRemoteFactory.java
private boolean hasCommit(List<ICommit> parentCommits, final ICommit commit) { Optional<ICommit> optional = Iterables.tryFind(parentCommits, new Predicate<ICommit>() { public boolean apply(ICommit candidateCommit) { return commit.getId().equals(candidateCommit.getId()); }/* w w w . j a v a 2 s.c om*/ }); return optional.isPresent(); }
From source file:org.killbill.billing.util.security.api.DefaultSecurityApi.java
private void invalidateJDBCAuthorizationCache(final String username) { final Collection<Realm> realms = ((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getRealms(); final KillBillJdbcRealm killBillJdbcRealm = (KillBillJdbcRealm) Iterables .tryFind(realms, new Predicate<Realm>() { @Override/*from w w w .j a va2 s . c o m*/ public boolean apply(@Nullable final Realm input) { return (input instanceof KillBillJdbcRealm); } }).orNull(); if (killBillJdbcRealm != null) { final SimplePrincipalCollection principals = new SimplePrincipalCollection(); principals.add(username, killBillJdbcRealm.getName()); killBillJdbcRealm.clearCachedAuthorizationInfo(principals); } }
From source file:com.github.sevntu.checkstyle.checks.design.StaticMethodCandidateCheck.java
/** * Check expressions in the given frame for being acceptable is static methods. * @param frame the frame to check./*from w w w .j a v a2s. c o m*/ * @return true if the currently checked method * is still a static method candidate. */ private static boolean isFrameExpressionsAcceptable(final Frame frame) { final Predicate<DetailAST> predicate = new Predicate<DetailAST>() { @Override public boolean apply(DetailAST ast) { return !isExprAcceptable(frame, ast); } }; final Optional<DetailAST> result = Iterables.tryFind(frame.expressions, predicate); return !result.isPresent(); }
From source file:com.hanhuy.android.vision.FacePreview.java
public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, acquire the camera and tell it where // to draw./*from w ww . j a v a2 s. co m*/ int count = Camera.getNumberOfCameras(); final Camera.CameraInfo info = new Camera.CameraInfo(); Optional<Integer> found = Iterables.tryFind(ContiguousSet .create(com.google.common.collect.Range.closedOpen(0, count), DiscreteDomain.integers()), new Predicate<Integer>() { @Override public boolean apply(Integer input) { Camera.getCameraInfo(input, info); return info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT; } }); mCamera = found.isPresent() ? Camera.open(found.get()) : Camera.open(); mCamera.setDisplayOrientation((info.orientation + 90) % 360); try { mCamera.setPreviewDisplay(holder); } catch (IOException exception) { mCamera.release(); mCamera = null; // TODO: add more exception handling logic here } }
From source file:org.jclouds.vcloud.director.v1_5.compute.strategy.VCloudDirectorComputeServiceAdapter.java
@Override public NodeAndInitialCredentials<Vm> createNodeWithGroupEncodedIntoName(String group, String name, Template template) {//from ww w .ja v a 2 s . c o m checkNotNull(template, "template was null"); checkNotNull(template.getOptions(), "template options was null"); String imageId = checkNotNull(template.getImage().getId(), "template image id must not be null"); String locationId = checkNotNull(template.getLocation().getId(), "template location id must not be null"); final String hardwareId = checkNotNull(template.getHardware().getId(), "template image id must not be null"); VCloudDirectorTemplateOptions templateOptions = VCloudDirectorTemplateOptions.class .cast(template.getOptions()); Vdc vdc = getVdc(locationId); final Reference networkReference; if (template.getOptions().getNetworks().isEmpty()) { Org org = getOrgForSession(); Network.FenceMode fenceMode = Network.FenceMode.NAT_ROUTED; Optional<Network> optionalNetwork = tryFindNetworkInVDCWithFenceMode(api, vdc, fenceMode); if (!optionalNetwork.isPresent()) { throw new IllegalStateException( "Can't find a network with fence mode: " + fenceMode + "in org " + org.getFullName()); } networkReference = Reference.builder().href(optionalNetwork.get().getHref()) .name(optionalNetwork.get().getName()).build(); } else { String networkName = Iterables.getOnlyElement(template.getOptions().getNetworks()); networkReference = tryFindNetworkInVDC(vdc, networkName); } VAppTemplate vAppTemplate = api.getVAppTemplateApi().get(imageId); Set<Vm> vms = getAvailableVMsFromVAppTemplate(vAppTemplate); // TODO now get the first vm to be added to vApp, what if more? Vm toAddVm = Iterables.get(vms, 0); // customize toAddVm GuestCustomizationSection guestCustomizationSection = api.getVmApi() .getGuestCustomizationSection(toAddVm.getHref()); guestCustomizationSection = guestCustomizationSection.toBuilder().resetPasswordRequired(false).build(); Statement guestCustomizationScript = ((VCloudDirectorTemplateOptions) (template.getOptions())) .getGuestCustomizationScript(); if (guestCustomizationScript != null) { guestCustomizationSection = guestCustomizationSection.toBuilder() // TODO differentiate on guestOS .customizationScript(guestCustomizationScript.render(OsFamily.WINDOWS)).build(); } SourcedCompositionItemParam vmItem = createVmItem(toAddVm, networkReference.getName(), guestCustomizationSection); ComposeVAppParams compositionParams = ComposeVAppParams.builder().name(name) .instantiationParams(instantiationParams(vdc, networkReference)) .sourcedItems(ImmutableList.of(vmItem)).build(); VApp vApp = api.getVdcApi().composeVApp(vdc.getId(), compositionParams); Task compositionTask = Iterables.getFirst(vApp.getTasks(), null); logger.debug(">> awaiting vApp(%s) deployment", vApp.getId()); boolean vAppDeployed = waitForTask(compositionTask, timeouts.nodeRunning); logger.trace("<< vApp(%s) deployment completed(%s)", vApp.getId(), vAppDeployed); if (!vAppDeployed) { // TODO Destroy node? But don't have VM id yet. final String message = format("vApp(%s, %s) not composed within %d ms (task %s).", name, vApp.getId(), timeouts.nodeRunning, compositionTask.getHref()); logger.warn(message); throw new IllegalStateException(message); } if (!vApp.getTasks().isEmpty()) { for (Task task : vApp.getTasks()) { logger.debug(">> awaiting vApp(%s) composition", vApp.getId()); boolean vAppReady = waitForTask(task, timeouts.nodeRunning); logger.trace("<< vApp(%s) composition completed(%s)", vApp.getId(), vAppReady); if (!vAppReady) { // TODO Destroy node? But don't have VM id yet. final String message = format("vApp(%s, %s) post-compose not ready within %d ms (task %s).", name, vApp.getId(), timeouts.nodeRunning, task.getHref()); logger.warn(message); throw new IllegalStateException(message); } } } URI vAppHref = checkNotNull(vApp.getHref(), format("vApp %s must not have a null href", vApp.getId())); VApp composedVApp = api.getVAppApi().get(vAppHref); VAppChildren children = checkNotNull(composedVApp.getChildren(), format("composedVApp %s must not have null children", composedVApp.getId())); Vm vm = Iterables.getOnlyElement(children.getVms()); if (!vm.getTasks().isEmpty()) { for (Task task : vm.getTasks()) { logger.debug(">> awaiting vm(%s) deployment", vApp.getId()); boolean vmReady = waitForTask(task, timeouts.nodeRunning); logger.trace("<< vApp(%s) deployment completed(%s)", vApp.getId(), vmReady); if (!vmReady) { final String message = format( "vApp(%s, %s) post-compose VM(%s) not ready within %d ms (task %s), so it will be destroyed", name, vApp.getId(), vm.getHref(), timeouts.nodeRunning, task.getHref()); logger.warn(message); destroyNode(vm.getId()); throw new IllegalStateException(message); } } } // Configure VirtualHardware on a VM Optional<Hardware> hardwareOptional = Iterables.tryFind(listHardwareProfiles(), new Predicate<Hardware>() { @Override public boolean apply(Hardware input) { return input.getId().equals(hardwareId); } }); // virtualCpus and memory templateOptions get the precedence over the default values given by hardwareId Integer virtualCpus = templateOptions.getVirtualCpus() == null ? getCoresFromHardware(hardwareOptional) : templateOptions.getVirtualCpus(); Integer ram = templateOptions.getMemory() == null ? getRamFromHardware(hardwareOptional) : templateOptions.getMemory(); Integer disk = templateOptions.getDisk(); if (virtualCpus == null || ram == null) { String msg; if (hardwareOptional.isPresent()) { msg = format( "vCPUs and RAM stats not available in hardware %s, and not configured in template options", hardwareId); } else { msg = format( "vCPUs and RAM stats not available - no hardware matching id %s, and not configured in template options; destroying VM", hardwareId); } logger.error(msg + "; destroying VM and failing"); destroyNode(vm.getId()); throw new IllegalStateException(msg); } VirtualHardwareSection virtualHardwareSection = api.getVmApi().getVirtualHardwareSection(vm.getHref()); Predicate<ResourceAllocationSettingData> processorPredicate = resourceTypeEquals( ResourceAllocationSettingData.ResourceType.PROCESSOR); virtualHardwareSection = updateVirtualHardwareSection(virtualHardwareSection, processorPredicate, virtualCpus + " virtual CPU(s)", BigInteger.valueOf(virtualCpus.intValue())); Predicate<ResourceAllocationSettingData> memoryPredicate = resourceTypeEquals( ResourceAllocationSettingData.ResourceType.MEMORY); virtualHardwareSection = updateVirtualHardwareSection(virtualHardwareSection, memoryPredicate, ram + " MB of memory", BigInteger.valueOf(ram.intValue())); if (disk != null) { Predicate<ResourceAllocationSettingData> diskPredicate = resourceTypeEquals( ResourceAllocationSettingData.ResourceType.DISK_DRIVE); Predicate<ResourceAllocationSettingData> elementPredicate = elementNameEquals("Hard disk 1"); virtualHardwareSection = updateVirtualHardwareSectionDisk(virtualHardwareSection, Predicates.and(diskPredicate, elementPredicate), BigInteger.valueOf(disk.intValue())); } // NOTE this is not efficient but the vCD API v1.5 don't support editing hardware sections during provisioning Task editVirtualHardwareSectionTask = api.getVmApi().editVirtualHardwareSection(vm.getHref(), virtualHardwareSection); logger.debug(">> awaiting vm(%s) to be edited", vm.getId()); boolean vmEdited = waitForTask(editVirtualHardwareSectionTask, timeouts.nodeRunning); logger.trace("<< vApp(%s) to be edited completed(%s)", vm.getId(), vmEdited); if (!vmEdited) { final String message = format( "vApp(%s, %s) VM(%s) edit not completed within %d ms (task %s); destroying VM", name, vApp.getId(), vm.getHref(), timeouts.nodeRunning, editVirtualHardwareSectionTask.getHref()); logger.warn(message); destroyNode(vm.getId()); throw new IllegalStateException(message); } Task deployTask = api.getVAppApi().deploy(vApp.getHref(), DeployVAppParams.builder().powerOn().build()); logger.debug(">> awaiting vApp(%s) to be powered on", vApp.getId()); boolean vAppPoweredOn = waitForTask(deployTask, timeouts.nodeRunning); logger.trace("<< vApp(%s) to be powered on completed(%s)", vApp.getId(), vAppPoweredOn); if (!vAppPoweredOn) { final String message = format( "vApp(%s, %s) power-on not completed within %d ms (task %s); destroying VM", name, vApp.getId(), timeouts.nodeRunning, deployTask.getHref()); logger.warn(message); destroyNode(vm.getId()); throw new IllegalStateException(message); } // Reload the VM; the act of "deploy" can change things like the password in the guest customization composedVApp = api.getVAppApi().get(vAppHref); children = checkNotNull(composedVApp.getChildren(), format("composedVApp %s must not have null children", composedVApp.getId())); vm = Iterables.getOnlyElement(children.getVms()); // Infer the login credentials from the VM, defaulting to "root" user LoginCredentials defaultCredentials = VCloudDirectorComputeUtils.getCredentialsFrom(vm); LoginCredentials.Builder credsBuilder; if (defaultCredentials == null) { credsBuilder = LoginCredentials.builder().user("root"); } else { credsBuilder = defaultCredentials.toBuilder(); if (defaultCredentials.getUser() == null) { credsBuilder.user("root"); } } // If login overrides are supplied in TemplateOptions, always prefer those. String overriddenLoginUser = template.getOptions().getLoginUser(); String overriddenLoginPassword = template.getOptions().getLoginPassword(); String overriddenLoginPrivateKey = template.getOptions().getLoginPrivateKey(); if (overriddenLoginUser != null) { credsBuilder.user(overriddenLoginUser); } if (overriddenLoginPassword != null) { credsBuilder.password(overriddenLoginPassword); } if (overriddenLoginPrivateKey != null) { credsBuilder.privateKey(overriddenLoginPrivateKey); } return new NodeAndInitialCredentials<Vm>(vm, vm.getId(), credsBuilder.build()); }
From source file:org.opencms.xml.containerpage.CmsFormatterConfiguration.java
/** * Gets the detail formatter to use for the given type and container width.<p> * * @param types the container types (comma separated) * @param containerWidth the container width * * @return the detail formatter to use// www . j a v a 2s.com */ public I_CmsFormatterBean getDetailFormatter(String types, int containerWidth) { // detail formatters must still match the type or width Predicate<I_CmsFormatterBean> checkValidDetailFormatter = Predicates .and(new MatchesTypeOrWidth(types, containerWidth, true), new IsDetail()); Optional<I_CmsFormatterBean> result = Iterables.tryFind(m_allFormatters, checkValidDetailFormatter); return result.orNull(); }
From source file:io.druid.indexing.kafka.supervisor.KafkaSupervisor.java
public KafkaSupervisor(final TaskStorage taskStorage, final TaskMaster taskMaster, final IndexerMetadataStorageCoordinator indexerMetadataStorageCoordinator, final KafkaIndexTaskClientFactory taskClientFactory, final ObjectMapper mapper, final KafkaSupervisorSpec spec) { this.taskStorage = taskStorage; this.taskMaster = taskMaster; this.indexerMetadataStorageCoordinator = indexerMetadataStorageCoordinator; this.sortingMapper = mapper.copy().configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); this.spec = spec; this.dataSource = spec.getDataSchema().getDataSource(); this.ioConfig = spec.getIoConfig(); this.tuningConfig = spec.getTuningConfig(); this.taskTuningConfig = KafkaTuningConfig.copyOf(this.tuningConfig); this.supervisorId = String.format("KafkaSupervisor-%s", dataSource); this.exec = Execs.singleThreaded(supervisorId); this.scheduledExec = Execs.scheduledSingleThreaded(supervisorId + "-Scheduler-%d"); int workerThreads = (this.tuningConfig.getWorkerThreads() != null ? this.tuningConfig.getWorkerThreads() : Math.min(10, this.ioConfig.getTaskCount())); this.workerExec = MoreExecutors .listeningDecorator(Execs.multiThreaded(workerThreads, supervisorId + "-Worker-%d")); log.info("Created worker pool with [%d] threads for dataSource [%s]", workerThreads, this.dataSource); this.taskInfoProvider = new TaskInfoProvider() { @Override// w ww. ja v a2 s. co m public TaskLocation getTaskLocation(final String id) { Preconditions.checkNotNull(id, "id"); Optional<TaskRunner> taskRunner = taskMaster.getTaskRunner(); if (taskRunner.isPresent()) { Optional<? extends TaskRunnerWorkItem> item = Iterables .tryFind(taskRunner.get().getRunningTasks(), new Predicate<TaskRunnerWorkItem>() { @Override public boolean apply(TaskRunnerWorkItem taskRunnerWorkItem) { return id.equals(taskRunnerWorkItem.getTaskId()); } }); if (item.isPresent()) { return item.get().getLocation(); } } else { log.error("Failed to get task runner because I'm not the leader!"); } return TaskLocation.unknown(); } @Override public Optional<TaskStatus> getTaskStatus(String id) { return taskStorage.getStatus(id); } }; int chatThreads = (this.tuningConfig.getChatThreads() != null ? this.tuningConfig.getChatThreads() : Math.min(10, this.ioConfig.getTaskCount() * this.ioConfig.getReplicas())); this.taskClient = taskClientFactory.build(taskInfoProvider, dataSource, chatThreads, this.tuningConfig.getHttpTimeout(), this.tuningConfig.getChatRetries()); log.info("Created taskClient with dataSource[%s] chatThreads[%d] httpTimeout[%s] chatRetries[%d]", dataSource, chatThreads, this.tuningConfig.getHttpTimeout(), this.tuningConfig.getChatRetries()); }
From source file:org.killbill.billing.tenant.dao.DefaultTenantDao.java
private boolean isSystemKey(final String key) { return Iterables.tryFind(ImmutableList.copyOf(TenantKey.values()), new Predicate<TenantKey>() { @Override/* www . java2 s. c om*/ public boolean apply(final TenantKey input) { return key.startsWith(input.toString()); } }).orNull() != null; }