com.google.common.base.Optional Java Examples
The following examples show how to use
com.google.common.base.Optional.
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: RyaStreamsCommandsTest.java From rya with Apache License 2.0 | 6 votes |
@Test public void printRyaStreamsDetails_configured() throws Exception { // Mock the object that performs the configure operation. final RyaClient mockCommands = mock(RyaClient.class); final GetInstanceDetails getDetails = mock(GetInstanceDetails.class); when(mockCommands.getGetInstanceDetails()).thenReturn(getDetails); // When getting the instance details, ensure they do have RyaStreamsDetails to print. final RyaDetails details = mock(RyaDetails.class); when(details.getRyaStreamsDetails()).thenReturn(Optional.of(new RyaStreamsDetails("localhost", 6))); when(getDetails.getDetails(eq("unitTest"))).thenReturn(Optional.of(details)); // Mock a shell state and connect it to a Rya instance. final SharedShellState state = new SharedShellState(); state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mockCommands); state.connectedToInstance("unitTest"); // Execute the command. final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class)); final String message = commands.printRyaStreamsDetails(); final String expected = "Kafka Hostname: localhost, Kafka Port: 6"; assertEquals(expected, message); }
Example #2
Source File: AvroUtils.java From incubator-gobblin with Apache License 2.0 | 6 votes |
/** * Helper method that does the actual work for {@link #getField(Schema, String)} * @param schema passed from {@link #getFieldSchema(Schema, String)} * @param pathList passed from {@link #getFieldSchema(Schema, String)} * @param field keeps track of the index used to access the list pathList * @return the field */ private static Optional<Field> getFieldHelper(Schema schema, List<String> pathList, int field) { Field curField = schema.getField(pathList.get(field)); if (field + 1 == pathList.size()) { return Optional.fromNullable(curField); } Schema fieldSchema = curField.schema(); switch (fieldSchema.getType()) { case UNION: throw new AvroRuntimeException("Union of complex types cannot be handled : " + schema); case MAP: return AvroUtils.getFieldHelper(fieldSchema.getValueType(), pathList, ++field); case RECORD: return AvroUtils.getFieldHelper(fieldSchema, pathList, ++field); case ARRAY: return AvroUtils.getFieldHelper(fieldSchema.getElementType(), pathList, ++field); default: throw new AvroRuntimeException("Invalid type " + fieldSchema.getType() + " in schema : " + schema); } }
Example #3
Source File: Actions.java From buck with Apache License 2.0 | 6 votes |
public ImmutableMultimap<Integer, Record> getResultingSourceMapping(@NonNull XmlDocument xmlDocument) throws ParserConfigurationException, SAXException, IOException { SourceFile inMemory = SourceFile.UNKNOWN; XmlDocument loadedWithLineNumbers = XmlLoader.load( xmlDocument.getSelectors(), xmlDocument.getSystemPropertyResolver(), inMemory, xmlDocument.prettyPrint(), XmlDocument.Type.MAIN, Optional.<String>absent() /* mainManifestPackageName */); ImmutableMultimap.Builder<Integer, Record> mappingBuilder = ImmutableMultimap.builder(); for (XmlElement xmlElement : loadedWithLineNumbers.getRootNode().getMergeableElements()) { parse(xmlElement, mappingBuilder); } return mappingBuilder.build(); }
Example #4
Source File: JobRunnerForBranchCause.java From github-integration-plugin with MIT License | 6 votes |
/** * Cancel previous builds for specified PR id. */ private static boolean cancelQueuedBuildByBranchName(final String branch) { Queue queue = getJenkinsInstance().getQueue(); for (Queue.Item item : queue.getItems()) { Optional<Cause> cause = from(item.getAllActions()) .filter(instanceOf(CauseAction.class)) .transformAndConcat(new CausesFromAction()) .filter(instanceOf(GitHubBranchCause.class)) .firstMatch(new CauseHasBranch(branch)); if (cause.isPresent()) { queue.cancel(item); return true; } } return false; }
Example #5
Source File: CalculateTestExpressionServiceTest.java From jtwig-core with Apache License 2.0 | 6 votes |
@Test public void calculateIfFound() throws Exception { RenderRequest request = mock(RenderRequest.class); Position position = mock(Position.class); TestExpression testExpression = mock(TestExpression.class); Expression argument = mock(Expression.class); TestExpressionCalculator testExpressionCalculator = mock(TestExpressionCalculator.class); Object expected = new Object(); when(testExpressionCalculatorSelector.calculatorFor(testExpression)).thenReturn(Optional.of(testExpressionCalculator)); when(testExpressionCalculator.calculate(request, position, testExpression, argument)).thenReturn(expected); Object result = underTest.calculate(request, position, testExpression, argument); assertSame(expected, result); }
Example #6
Source File: IndexFile.java From sfs with Apache License 2.0 | 6 votes |
protected Optional<ChecksummedPositional<XIndexBlock>> parse(ChecksummedPositional<byte[]> checksummedPositional) { try { if (checksummedPositional.isChecksumValid()) { byte[] frame = checksummedPositional.getValue(); if (frame != null && frame.length > 0) { XIndexBlock indexBlock = parseFrom(frame); return of(new ChecksummedPositional<XIndexBlock>(checksummedPositional.getPosition(), indexBlock, checksummedPositional.getActualChecksum()) { @Override public boolean isChecksumValid() { return true; } }); } } LOGGER.warn("Invalid checksum for index block @ position " + checksummedPositional.getPosition()); return absent(); } catch (Throwable e) { LOGGER.warn("Error parsing index block @ position " + checksummedPositional.getPosition(), e); return absent(); } }
Example #7
Source File: MesosStateService.java From shardingsphere-elasticjob-cloud with Apache License 2.0 | 6 votes |
private Collection<JSONObject> findExecutors(final JSONArray frameworks, final String appName) throws JSONException { List<JSONObject> result = Lists.newArrayList(); Optional<String> frameworkIDOptional = frameworkIDService.fetch(); String frameworkID; if (frameworkIDOptional.isPresent()) { frameworkID = frameworkIDOptional.get(); } else { return result; } for (int i = 0; i < frameworks.length(); i++) { JSONObject framework = frameworks.getJSONObject(i); if (!framework.getString("id").equals(frameworkID)) { continue; } JSONArray executors = framework.getJSONArray("executors"); for (int j = 0; j < executors.length(); j++) { JSONObject executor = executors.getJSONObject(j); if (null == appName || appName.equals(getExecutorId(executor).split("@-@")[0])) { result.add(executor); } } } return result; }
Example #8
Source File: NiciraNvpApi.java From cosmic with Apache License 2.0 | 6 votes |
/** * GET list of items * * @param uuid * @return * @throws NiciraNvpApiException */ private <T> List<T> find(final Optional<String> uuid, final Class<T> clazz) throws NiciraNvpApiException { final String uri = prefixMap.get(clazz); Map<String, String> params = defaultListParams; if (uuid.isPresent()) { params = new HashMap<>(defaultListParams); params.put(UUID_QUERY_PARAMETER, uuid.get()); } final NiciraNvpList<T> entities; try { entities = restConnector.executeRetrieveObject(listTypeMap.get(clazz), uri, params); } catch (final CosmicRESTException e) { throw new NiciraNvpApiException(e); } if (entities == null) { throw new NiciraNvpApiException("Unexpected response from API"); } return entities.getResults(); }
Example #9
Source File: HiveMetaStoreEventHelper.java From incubator-gobblin with Apache License 2.0 | 6 votes |
private static Map<String, String> getAdditionalMetadata(HiveTable table, Optional<HivePartition> partition, Optional<Exception> error) { ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String> builder().put(DB_NAME, table.getDbName()).put(TABLE_NAME, table.getTableName()); if (table.getLocation().isPresent()) { builder.put("Location", table.getLocation().get()); } if (partition.isPresent()) { builder.put("Partition", partition.get().toString()); } if (error.isPresent()) { builder.put(ERROR_MESSAGE, error.get().getMessage()); } return builder.build(); }
Example #10
Source File: RyaStreamsCommandsTest.java From rya with Apache License 2.0 | 6 votes |
@Test(expected = RuntimeException.class) public void addQuery_insertQueryNotCorrectType() throws Exception { // Mock the object that performs the rya streams operation. final RyaStreamsClient mockClient = mock(RyaStreamsClient.class); final AddQuery addQuery = mock(AddQuery.class); when(mockClient.getAddQuery()).thenReturn(addQuery); final String sparql = "SELECT * WHERE { ?a ?b ?c }"; final StreamsQuery addedQuery = new StreamsQuery(UUID.randomUUID(), sparql, true, true); when(addQuery.addQuery(eq(sparql), eq(false), eq(true))).thenReturn(addedQuery); // Mock a SPARQL prompt that a user entered a query through. final SparqlPrompt prompt = mock(SparqlPrompt.class); when(prompt.getSparql()).thenReturn(Optional.of(sparql)); // Mock a shell state and connect it to a Rya instance. final SharedShellState state = new SharedShellState(); state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class)); state.connectedToInstance("unitTest"); state.connectedToRyaStreams(mockClient); // Execute the command. final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class)); commands.addQuery(true, true); }
Example #11
Source File: ScheduleExecutorTest.java From digdag with Apache License 2.0 | 6 votes |
@Test public void testRunWithinSkipDelayedBy() throws Exception { // set skip_delayed_by 30 workflowConfig.getNestedOrSetEmpty("schedule") .set("skip_delayed_by", "30s") .set("daily>", "12:00:00"); // Indicate that there is no active attempt for this workflow when(sessionStore.getActiveAttemptsOfWorkflow(eq(PROJECT_ID), eq(WORKFLOW_NAME), anyInt(), any(Optional.class))) .thenReturn(ImmutableList.of()); // Run the schedule executor at now + 29 scheduleExecutor.runScheduleOnce(now.plusSeconds(29)); // Verify that task was started. verify(scheduleExecutor).startSchedule(any(StoredSchedule.class), any(Scheduler.class), any(StoredWorkflowDefinitionWithProject.class)); // Verify that the schedule progressed to the next time verify(scs).updateNextScheduleTimeAndLastSessionTime(SCHEDULE_ID, nextScheduleTime, now); }
Example #12
Source File: Replica.java From circus-train with Apache License 2.0 | 5 votes |
/** * Checks if there is a replica table and validates the replication modes. * * @throws CircusTrainException if the replica is invalid and the table can't be replicated. */ public void validateReplicaTable(String replicaDatabaseName, String replicaTableName) { try (CloseableMetaStoreClient client = getMetaStoreClientSupplier().get()) { Optional<Table> oldReplicaTable = getTable(client, replicaDatabaseName, replicaTableName); if (oldReplicaTable.isPresent()) { LOG.debug("Existing table found, checking that it is a valid replica."); determineValidityOfReplica(replicationMode, oldReplicaTable.get()); } } }
Example #13
Source File: TypeInstanceReference.java From binnavi with Apache License 2.0 | 5 votes |
/** * Creates a new {@link TypeInstanceReference}. * * @param address The {@link IAddress} of the {@link INaviInstruction} where the * {@link TypeInstanceReference} is associated to. * @param position The position of the {@link INaviOperandTree} in the {@link INaviInstruction} * where the {@link TypeInstanceReference} is associated to. * @param node The {@link INaviOperandTreeNode} to which the {@link TypeInstanceReference} is * associated. * @param typeInstance The {@link TypeInstance} this {@link TypeInstanceReference} references. * @param view The {@link INaviView view} in which this reference is shown. */ public TypeInstanceReference(final IAddress address, final int position, final Optional<INaviOperandTreeNode> node, final TypeInstance typeInstance, final INaviView view) { this.address = Preconditions.checkNotNull(address, "Error: address argument can not be null"); Preconditions.checkArgument(position >= 0, "Error: the operand position must be larger or equal to zero"); this.position = position; this.node = Preconditions.checkNotNull(node, "Error: node argument can not be null"); this.typeInstance = Preconditions.checkNotNull(typeInstance, "Error: typeInstance argument can not be null"); this.view = Preconditions.checkNotNull(view, "Error: view argument can not be null"); }
Example #14
Source File: AppConstraintEvaluatorTest.java From shardingsphere-elasticjob-cloud with Apache License 2.0 | 5 votes |
@Test public void assertLackJobConfig() throws Exception { Mockito.when(facadeService.load("test")).thenReturn(Optional.<CloudJobConfiguration>absent()); SchedulingResult result = taskScheduler.scheduleOnce(Collections.singletonList(getTask("test")), Collections.singletonList(getLease(0, 1.5, 192))); Assert.assertThat(result.getResultMap().size(), Is.is(1)); Assert.assertThat(getAssignedTaskNumber(result), Is.is(1)); }
Example #15
Source File: KBPEATestUtils.java From tac-kbp-eal with MIT License | 5 votes |
@Override public AssessedResponse apply(Response input) { return AssessedResponse.of(input, ResponseAssessment.of( Optional.of(FieldAssessment.CORRECT), Optional.of(FieldAssessment.CORRECT), Optional.of(FieldAssessment.CORRECT), Optional.of(KBPRealis.Actual), Optional.of(FieldAssessment.CORRECT), Optional.of(FillerMentionType.NOMINAL))); }
Example #16
Source File: WeightedBoomerang.java From SPDS with Eclipse Public License 2.0 | 5 votes |
public static boolean isArrayStore(Statement s) { Optional<Stmt> optUnit = s.getUnit(); if (optUnit.isPresent()) { Stmt stmt = optUnit.get(); if (stmt instanceof AssignStmt && ((AssignStmt) stmt).getLeftOp() instanceof ArrayRef) { return true; } } return false; }
Example #17
Source File: CollectionFuture.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
@Override public List<V> combine(List<Optional<V>> values) { List<V> result = newArrayListWithCapacity(values.size()); for (Optional<V> element : values) { result.add(element != null ? element.orNull() : null); } return unmodifiableList(result); }
Example #18
Source File: ULocalVarIdent.java From Refaster with Apache License 2.0 | 5 votes |
@Override public JCIdent inline(Inliner inliner) throws CouldNotResolveImportException { Optional<LocalVarBinding> binding = inliner.getOptionalBinding(key()); return inliner.maker().Ident(binding.isPresent() ? binding.get().getName() : inliner.asName(identifier())); }
Example #19
Source File: BasicAnnotationProcessor.java From auto with Apache License 2.0 | 5 votes |
/** * The {@link Element} whose fully-qualified name is {@link #name()}. Absent if the relevant * method on {@link Elements} returns {@code null}. */ Optional<? extends Element> getElement(Elements elements) { return Optional.fromNullable( kind == Kind.PACKAGE_NAME ? elements.getPackageElement(name) : elements.getTypeElement(name)); }
Example #20
Source File: TestReadAheadEntryReader.java From distributedlog with Apache License 2.0 | 5 votes |
private ReadAheadEntryReader createEntryReader(String streamName, DLSN fromDLSN, BKDistributedLogManager dlm, DistributedLogConfiguration conf) throws Exception { BKLogReadHandler readHandler = dlm.createReadHandler( Optional.<String>absent(), true); LogSegmentEntryStore entryStore = new BKLogSegmentEntryStore( conf, ConfUtils.getConstDynConf(conf), zkc, bkc, scheduler, null, NullStatsLogger.INSTANCE, AsyncFailureInjector.NULL); return new ReadAheadEntryReader( streamName, fromDLSN, conf, readHandler, entryStore, scheduler, Ticker.systemTicker(), new AlertStatsLogger(NullStatsLogger.INSTANCE, "test-alert")); }
Example #21
Source File: HiveCopyEntityHelperTest.java From incubator-gobblin with Apache License 2.0 | 5 votes |
@Test public void testAddTableDeregisterSteps() throws Exception { HiveDataset dataset = Mockito.mock(HiveDataset.class); Mockito.when(dataset.getProperties()).thenReturn(new Properties()); HiveCopyEntityHelper helper = Mockito.mock(HiveCopyEntityHelper.class); Mockito.when(helper.getDeleteMethod()).thenReturn(DeregisterFileDeleteMethod.NO_DELETE); Mockito.when(helper.getTargetURI()).thenReturn(Optional.of("/targetURI")); Mockito.when(helper.getHiveRegProps()).thenReturn(new HiveRegProps(new State())); Mockito.when(helper.getDataset()).thenReturn(dataset); Mockito.when(helper.addTableDeregisterSteps(Mockito.any(List.class), Mockito.any(String.class), Mockito.anyInt(), Mockito.any(org.apache.hadoop.hive.ql.metadata.Table.class))).thenCallRealMethod(); org.apache.hadoop.hive.ql.metadata.Table meta_table = Mockito.mock(org.apache.hadoop.hive.ql.metadata.Table.class); org.apache.hadoop.hive.metastore.api.Table api_table = Mockito.mock(org.apache.hadoop.hive.metastore.api.Table.class); Mockito.when(api_table.getDbName()).thenReturn("TestDB"); Mockito.when(api_table.getTableName()).thenReturn("TestTable"); Mockito.when(meta_table.getTTable()).thenReturn(api_table); List<CopyEntity> copyEntities = new ArrayList<CopyEntity>(); String fileSet = "testFileSet"; int initialPriority = 0; int priority = helper.addTableDeregisterSteps(copyEntities, fileSet, initialPriority, meta_table); Assert.assertTrue(priority == 1); Assert.assertTrue(copyEntities.size() == 1); Assert.assertTrue(copyEntities.get(0) instanceof PostPublishStep); PostPublishStep p = (PostPublishStep) (copyEntities.get(0)); Assert .assertTrue(p.getStep().toString().contains("Deregister table TestDB.TestTable on Hive metastore /targetURI")); }
Example #22
Source File: IntegrationBasicSuite.java From incubator-gobblin with Apache License 2.0 | 5 votes |
private void startTaskDriver() throws Exception { for (Config taskDriverConfig: this.taskDriverConfigs) { GobblinTaskRunner runner = new GobblinTaskRunner(TestHelper.TEST_APPLICATION_NAME, taskDriverConfig.getString(TEST_INSTANCE_NAME_KEY), TestHelper.TEST_APPLICATION_ID, "1", taskDriverConfig, Optional.absent()); this.taskDrivers.add(runner); // Need to run in another thread since the start call will not return until the stop method // is called. Thread workerThread = new Thread(runner::start); workerThread.start(); } }
Example #23
Source File: ReflectionSuggester.java From dremio-oss with Apache License 2.0 | 5 votes |
@Override public int compare(final ColumnStats left, final ColumnStats right) { return Long.compare( Optional.fromNullable(left.getCardinality()).or(Long.MAX_VALUE), Optional.fromNullable(right.getCardinality()).or(Long.MAX_VALUE) ); }
Example #24
Source File: OMVolumeRequest.java From hadoop-ozone with Apache License 2.0 | 5 votes |
/** * Create Ozone Volume. This method should be called after acquiring user * and volume Lock. * @param omMetadataManager * @param omVolumeArgs * @param volumeList * @param dbVolumeKey * @param dbUserKey * @param transactionLogIndex * @throws IOException */ protected void createVolume(final OMMetadataManager omMetadataManager, OmVolumeArgs omVolumeArgs, UserVolumeInfo volumeList, String dbVolumeKey, String dbUserKey, long transactionLogIndex) { // Update cache: Update user and volume cache. omMetadataManager.getUserTable().addCacheEntry(new CacheKey<>(dbUserKey), new CacheValue<>(Optional.of(volumeList), transactionLogIndex)); omMetadataManager.getVolumeTable().addCacheEntry( new CacheKey<>(dbVolumeKey), new CacheValue<>(Optional.of(omVolumeArgs), transactionLogIndex)); }
Example #25
Source File: MetricsResource.java From dropwizard-experiment with MIT License | 5 votes |
@GET @Path("/meter/{name}.gif") @Produces("image/gif") public String meterGif(@PathParam("name") String name, @QueryParam("value") Optional<Long> value) { metrics.meter(name).mark(value.or(1L)); return gif; }
Example #26
Source File: CatalogServiceHelper.java From dremio-oss with Apache License 2.0 | 5 votes |
public Optional<CatalogEntity> getCatalogEntityByPath(List<String> path) throws NamespaceException { NameSpaceContainer entity = getNamespaceEntity(new NamespaceKey(path)); if (entity == null) { // if we can't find it in the namespace, check if its a non-promoted file/folder in a filesystem source Optional<CatalogItem> internalItem = getInternalItemByPath(path); if (!internalItem.isPresent()) { return Optional.absent(); } return getCatalogEntityFromCatalogItem(internalItem.get()); } else { return getCatalogEntityFromNamespaceContainer(extractFromNamespaceContainer(entity).get()); } }
Example #27
Source File: SearchHitMaintainObjectEndableWrite.java From sfs with Apache License 2.0 | 5 votes |
protected Observable<PersistentObject> deleteOldUnAckdVersions(PersistentObject persistentObject) { return defer(() -> { long now = currentTimeMillis(); return aVoid() .filter(aVoid -> now - persistentObject.getUpdateTs().getTimeInMillis() >= VerifyRepairAllContainerObjects.CONSISTENCY_THRESHOLD) .map(aVoid -> persistentObject) .flatMap(persistentObject1 -> Observable.from(persistentObject1.getVersions())) // don't bother trying to delete old versions that are marked as // deleted since we have another method that will take care of that // at some point in the future .filter(version -> !version.isDeleted()) .flatMap(transientVersion -> Observable.from(transientVersion.getSegments())) .filter(transientSegment -> !transientSegment.isTinyData()) .flatMap(transientSegment -> Observable.from(transientSegment.getBlobs())) .filter(transientBlobReference -> !transientBlobReference.isAcknowledged()) .filter(transientBlobReference -> { Optional<Integer> oVerifyFailCount = transientBlobReference.getVerifyFailCount(); return oVerifyFailCount.isPresent() && oVerifyFailCount.get() >= VerifyRepairAllContainerObjects.VERIFY_RETRY_COUNT; }) .flatMap(transientBlobReference -> just(transientBlobReference) .flatMap(new DeleteBlobReference(vertxContext)) .filter(deleted -> deleted) .map(deleted -> { if (Boolean.TRUE.equals(deleted)) { transientBlobReference.setDeleted(deleted); } return (Void) null; })) .onErrorResumeNext(throwable -> { LOGGER.warn("Handling Error", throwable); return Defer.aVoid(); }) .count() .map(new ToType<>(persistentObject)); }); }
Example #28
Source File: MaintenanceScheduler.java From emodb with Apache License 2.0 | 5 votes |
public MaintenanceScheduler(MaintenanceDAO maintenanceDao, Optional<TableMutexManager> tableMutexManager, String selfDataCenter, CacheRegistry cacheRegistry, MoveTableTask task) { _maintDao = checkNotNull(maintenanceDao, "maintenanceDao"); _tableMutexManager = checkNotNull(tableMutexManager, "tableMutexManager"); _selfDataCenter = checkNotNull(selfDataCenter, "selfDataCenter"); _tableCacheHandle = cacheRegistry.lookup("tables", true); cacheRegistry.addListener(this); task.setScheduler(this); }
Example #29
Source File: Proto.java From immutables with Apache License 2.0 | 5 votes |
@Value.Lazy public Styles styles() { StyleInfo styleInfo = determineStyle().or(environment().defaultStyles()); Optional<String[]> depluralize = depluralize(); if (depluralize.isPresent()) { styleInfo = ImmutableStyleInfo.copyOf(styleInfo) .withDepluralize(true) .withDepluralizeDictionary(concat(styleInfo.depluralizeDictionary(), depluralize.get())); } return styleInfo.getStyles(); }
Example #30
Source File: BackendAdminUsernamePasswordAuthenticationProvider.java From spring-boot-security-example with MIT License | 5 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Optional<String> username = (Optional) authentication.getPrincipal(); Optional<String> password = (Optional) authentication.getCredentials(); if (credentialsMissing(username, password) || credentialsInvalid(username, password)) { throw new BadCredentialsException(INVALID_BACKEND_ADMIN_CREDENTIALS); } return new UsernamePasswordAuthenticationToken(username.get(), null, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_BACKEND_ADMIN")); }