private <T extends OWLEntity> T createNew(String entityName, final Class<T> entityType) throws OWLEntityCreationException { String localName = getLocalName(entityName); Optional<IRI> prefix = getPrefix(entityName); IRI baseIri = prefix.orElseGet(() -> null); return entityFactory.createOWLEntity(entityType, localName, baseIri).getOWLEntity(); }
@Test public void testOptional() { Optional<String> fullName = Optional.ofNullable(null); Assert.assertEquals("Optional.empty", fullName.toString()); Assert.assertEquals("[none]", fullName.orElseGet(() -> "[none]")); Assert.assertEquals("[none2]", fullName.orElse("[none2]")); }
@Rank(Integer.MAX_VALUE) @Singleton @Override public Client provide() { if (!httpServer.isStarted()) { throw new TestException("test server not started"); } Object testInstance = testContext.getTestInstance(); Class<? extends Object> testClass = testInstance.getClass(); Optional<ClientConfig> optional = of(testClass.getDeclaredMethods()) .filter(p -> p.getDeclaredAnnotation(Config.class) != null) .filter(p -> p.getParameterCount() == 0) .filter(p -> p.getReturnType().isAssignableFrom(ClientConfig.class)) .findFirst() .map(p -> reflectionUtil.invokeMethod(testInstance, p)) .map(ClientConfig.class::cast); ClientConfig clientConfig = optional.orElseGet(ClientConfig::new); JerseyTest jerseyTest = testContext.getTestInstance().getClass().getAnnotation(JerseyTest.class); if (jerseyTest.logTraffic() && !clientConfig.isRegistered(LoggingFilter.class)) { clientConfig.register(new LoggingFilter(log, jerseyTest.dumpEntity())); } return ClientBuilder.newClient(clientConfig); }
static void optionalTest() { // 不要这样,这与!=null没什么区别 Optional<String> stringOptional = Optional.of("alibaba"); if (stringOptional.isPresent()) { System.out.println(stringOptional.get().length()); } Optional<String> optionalValue = Optional.of("alibaba"); // 下面是推荐的常用操作 optionalValue.ifPresent(s -> System.out.println(s + " contains red")); // 增加到集合汇总 List<String> results = Lists.newArrayList(); optionalValue.ifPresent(results::add); // 增加到集合中,并返回操作结果 Optional<Boolean> added = optionalValue.map(results::add); // 无值的optional Optional<String> optionalString = Optional.empty(); // 不存在值,返回“No word” String result = optionalValue.orElse("No word"); // 没值,计算一个默认值 result = optionalString.orElseGet(() -> System.getProperty("user.dir")); // 无值,抛一个异常 try { result = optionalString.orElseThrow(NoSuchElementException::new); } catch (Throwable t) { t.getCause(); } }
@Test public void _07_옵션_다루기() { final Optional<String> optional = words.stream().filter(w -> w.contains("red")).findFirst(); try { optional.ifPresent( v -> { throw new RuntimeException(); }); assert false; // 이 행은 실행되면 안됨. } catch (RuntimeException e) { } // 비어있는 경우는 실행되지 않음. Optional.empty() .ifPresent( v -> { throw new RuntimeException(); }); Set<String> results = new HashSet<>(); optional.ifPresent(results::add); assertThat(results.contains("tired"), is(true)); // 실행 결과를 받고 싶은 경우에는 map 사용. results = new HashSet<>(); Optional<Boolean> added = optional.map(results::add); assertThat(added, is(Optional.of(Boolean.TRUE))); // 대상이 빈경우에는 empty Optional 반환 Optional<Boolean> a = Optional.empty().map(v -> true); assertThat(a.isPresent(), is(false)); Optional<String> emptyOptional = Optional.empty(); // orElse로 기본값 지정 가능 String result = emptyOptional.orElse("기본값"); assertThat(result, is("기본값")); // 기본값 생성하는 코드 호출 가능 result = emptyOptional.orElseGet(() -> System.getProperty("user.dir")); assertThat(result, is(System.getProperty("user.dir"))); // 값이 없는 경우 예외 던지기 try { emptyOptional.orElseThrow(NoSuchElementException::new); assert false; } catch (NoSuchElementException e) { } }
private void setCSSContextVariables( IApplicationContext applicationContext, IEclipseContext context) { boolean highContrastMode = getApplicationDisplay().getHighContrast(); Optional<String> cssURI = highContrastMode ? Optional.empty() : getArgValue(IWorkbench.CSS_URI_ARG, applicationContext, false); cssURI.ifPresent( cssURIValue -> { context.set(IWorkbench.CSS_URI_ARG, cssURIValue); }); Optional<String> themeId = highContrastMode ? Optional.of(HIGH_CONTRAST_THEME_ID) : getArgValue(E4Application.THEME_ID, applicationContext, false); if (!themeId.isPresent() && !cssURI.isPresent()) { context.set(E4Application.THEME_ID, DEFAULT_THEME_ID); } else { context.set(E4Application.THEME_ID, themeId.orElseGet(() -> null)); } // validate static CSS URI cssURI .filter(cssURIValue -> !cssURIValue.startsWith("platform:/plugin/")) .ifPresent( cssURIValue -> { System.err.println( "Warning. Use the \"platform:/plugin/Bundle-SymbolicName/path/filename.extension\" URI for the parameter: " + IWorkbench.CSS_URI_ARG); // $NON-NLS-1$ context.set(E4Application.THEME_ID, cssURIValue); }); Optional<String> cssResourcesURI = getArgValue(IWorkbench.CSS_RESOURCE_URI_ARG, applicationContext, false); cssResourcesURI.ifPresent( cssResourcesURIValue -> { context.set(IWorkbench.CSS_RESOURCE_URI_ARG, cssResourcesURIValue); }); }
public ServerStorageImpl( final String databaseId, final String tableName, final ChangeTrackerImpl changeTracker) throws ServerStorageException { this.databaseId = databaseId; this.tableName = tableName; this.changeTracker = changeTracker; this.database.bind(FrameworkServiceImpl.getDatabasePoolService().requestConnection(databaseId)); final Optional<TableSchema> trySchema = FrameworkServiceImpl.getConfigService() .getActiveEnvironment() .getDatabaseConfig(databaseId) .schema() .get() .getSchemaOf(tableName); // Estimate tables without provided schema // Create empty schema final TableSchema providedSchema = trySchema.orElseGet( () -> { return new TableSchema() { private final List<MappingMetaData> entries = Collections.emptyList(); @Override public SchemaPolicy getPolicy() { return SchemaPolicy.LAZY; } @Override public String getStructure() { return UnknownServerStorageStructure.class.getCanonicalName(); } @Override public String getName() { return tableName; } @Override public ClientStorageFormat getFormat() { throw new UnsupportedOperationException(); } @Override public List<MappingMetaData> getEntries() { return entries; } }; }); final TableSchema schema; final Function<MappingMetaData, Optional<TypeToken<?>>> typeReceiver; if (!providedSchema.getPolicy().hasPermissionToComplete()) { schema = providedSchema; typeReceiver = metaData -> Optional.empty(); } else { final Pair<TableSchema, Function<MappingMetaData, Optional<TypeToken<?>>>> result = estimateSchema(providedSchema); schema = result.first(); typeReceiver = result.second(); } this.structureName = schema.getStructure(); mapper = new JsonMapper<>( schema, SQLToPropertyMappingAdapterHolder.<T>get(), Arrays.asList(ServerStorageStructurePrivateBase.class), ServerStorageStructureBaseImplementation.class, typeReceiver); statementObject = tableName + PreparedStatements.STATEMENT_SELECT_ROW.toString() + (/*FIXME*/ INCREMENT++); selectLowPart = createSelectFormat(); statementFormat = createStatementFormat(); this.database.addListener( new ChangeListener<Database>() { @Override public void changed( final ObservableValue<? extends Database> observable, final Database oldValue, final Database newValue) { alive.unbind(); if (Objects.nonNull(newValue)) { alive.bind(newValue.alive()); registerStatements(); } else alive.set(false); } }); registerStatements(); }
@Override default Ty TmAbbBind(Term t, Optional<Ty> tyOpt) { return tyOpt.orElseGet(() -> m().empty()); }
/** * This routine implements the main operator lookup process. Each operator is tested using an * applicability predicate; if the test suceeds that same operator is returned, otherwise a * dummy symbol is returned. */ final Symbol doLookup(Predicate<Symbol> applicabilityTest) { return Stream.of(alternatives.orElseGet(this::initOperators)) .filter(applicabilityTest) .findFirst() .orElse(syms.noSymbol); }