本文整理汇总了Java中fj.data.Option类的典型用法代码示例。如果您正苦于以下问题:Java Option类的具体用法?Java Option怎么用?Java Option使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Option类属于fj.data包,在下文中一共展示了Option类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sumBatchResult
import fj.data.Option; //导入依赖的package包/类
private static Option<Integer> sumBatchResult(int[] xs)
{
int result = 0;
for (int x: xs)
{
if (x >= 0)
{
result += x;
}
else if (x == Statement.SUCCESS_NO_INFO)
{
return Option.none();
}
else if (x == Statement.EXECUTE_FAILED)
{
throw new IllegalStateException("a batch command failed but an sql exception was not raised by the driver!");
}
else
{
throw new IllegalStateException("unrecognized batch return code " + x);
}
}
return Option.some(result);
}
示例2: unique
import fj.data.Option; //导入依赖的package包/类
/**
* Given an existing {@link DB<Iterable<A>>}, converts it to an operation that either returns one result, none at all,
* or throws if there is more than one result in the result set.
*
* This is useful if you are issuing a query by a single primary key. Such a query is never expected to return > 1 results
* (in which case the returned DB will throw upon interpretation), but can return no results (which is expressed in the
* return type)
*/
public static <A> DB<Option<A>> unique(DB<? extends Iterable<A>> op)
{
return op.map(xs ->
{
Iterator<A> it = xs.iterator();
if (!it.hasNext())
{
return none();
}
A result = it.next();
if (it.hasNext())
{
throw new RuntimeException("unique with more than one element");
}
return some(result);
});
}
示例3: run
import fj.data.Option; //导入依赖的package包/类
@Override
public Option<Integer> run(Connection c) throws SQLException
{
if (Collections.isEmpty(as))
{
return Option.none();
}
if (!isInsert(sql))
{
throwIfAutoCommit(c);
}
try (PreparedStatement preparedStatement = c.prepareStatement(sql))
{
return binder.f(preparedStatement);
}
}
示例4: endDrag
import fj.data.Option; //导入依赖的package包/类
public void endDrag( final PullerNode pullerNode ) {
blueKnots.append( redKnots ).foreach( _removeHighlight );
Option<KnotNode> attachNode = getAttachNode( pullerNode );
if ( attachNode.isSome() ) {
Point2D hands = pullerNode.getGlobalAttachmentPoint();
Point2D knot = attachNode.some().getGlobalFullBounds().getCenter2D();
Vector2D delta = new Vector2D( hands, knot );
Dimension2D localDelta = rootNode.globalToLocal( new Dimension2DDouble( delta.x, delta.y ) );
pullerNode.animateToPositionScaleRotation( pullerNode.getOffset().getX() + localDelta.getWidth(), pullerNode.getOffset().getY() + localDelta.getHeight(), pullerNode.scale, 0,
//if the rope is moving, automatically translate to the right location otherwise the target will be puller arrives
mode.get() == Mode.GOING ? 0 : ANIMATION_DURATION );
//attach everything
attachNode.some().setPullerNode( pullerNode );
pullerNode.setKnot( attachNode.some() );
updateForceListeners();
}
else {
detach( pullerNode );
pullerNode.animateHome();
}
}
示例5: getAttachNode
import fj.data.Option; //导入依赖的package包/类
private Option<KnotNode> getAttachNode( final PullerNode pullerNode ) {
List<KnotNode> knots = pullerNode.color == BLUE ? blueKnots : redKnots;
List<KnotNode> free = knots.filter( _free ).filter( new F<KnotNode, Boolean>() {
@Override public Boolean f( final KnotNode knotNode ) {
return knotPullerDistance( knotNode, pullerNode ) < 80;
}
} );
if ( free.length() > 0 ) {
KnotNode closest = free.minimum( FJUtils.ord( new F<KnotNode, Double>() {
@Override public Double f( final KnotNode k ) {
return knotPullerDistance( k, pullerNode );
}
} ) );
return Option.some( closest );
}
else { return Option.none(); }
}
示例6: f
import fj.data.Option; //导入依赖的package包/类
@Override public MatchingGameState f( final MatchingGameState state ) {
int points = state.getChecks() == 0 ? 2 : 1;
final boolean correct = state.getLeftScaleValue() == state.getRightScaleValue();
//Send a message to indicate whether it was right or wrong and how many points the user got
SimSharingManager.sendModelMessage( ModelComponents.answer, ModelComponentTypes.answer, ModelActions.checked,
ParameterSet.parameterSet( ParameterKeys.isCorrect, correct ).
with( ParameterKeys.levelID, state.levelID ).
with( ParameterKeys.points, correct ? points : 0 ).
with( ParameterKeys.correct, correct ).
with( ParameterKeys.leftScaleNumerator, state.getLeftScaleNumerator() ).
with( ParameterKeys.leftScaleDenominator, state.getLeftScaleDenominator() ).
with( ParameterKeys.rightScaleNumerator, state.getRightScaleNumerator() ).
with( ParameterKeys.rightScaleDenominator, state.getRightScaleDenominator() ).
with( ParameterKeys.leftScaleRepresentation, state.getLeftScaleRepresentation() ).
with( ParameterKeys.rightScaleRepresentation, state.getRightScaleRepresentation() ) );
return correct ?
state.withChecks( state.info.checks + 1 ).
withMode( USER_CHECKED_CORRECT_ANSWER ).
withScore( state.info.score + points ).
withLastWrongAnswer( Option.<Answer>none() ) :
state.withChecks( state.info.checks + 1 ).withMode( SHOWING_WHY_ANSWER_WRONG ).recordWrongAnswer();
}
示例7: getToolbarOffset
import fj.data.Option; //导入依赖的package包/类
private static double getToolbarOffset( final int levelIndex, final BuildAFractionModel model, final SceneContext context, final BooleanProperty soundEnabled, boolean fractionLab, final boolean showContainerNodeOnStartup ) {
ShapeSceneNode node = new ShapeSceneNode( levelIndex, model, context, soundEnabled, Option.<Double>none(), fractionLab, showContainerNodeOnStartup );
//Re-layout the toolbox based on the location of the title
double desiredToolboxCenter = node.title.getFullBounds().getCenterX();
double originalToolboxCenter = node.toolboxNode.getFullBounds().getCenterX();
double delta = desiredToolboxCenter - originalToolboxCenter;
//make sure it doesn't go off the screen to the left
double originalToolboxX = node.toolboxNode.getFullBounds().getX();
final double newToolboxX = originalToolboxX + delta;
if ( newToolboxX < INSET ) {
delta = INSET - originalToolboxX;
}
return delta;
}
示例8: animateSliceToBucket
import fj.data.Option; //导入依赖的package包/类
public PieSet animateSliceToBucket( CellPointer cell, long randomSeed ) {
//Cell that should be moved
//May choose a slice that is on its way to a pie
final Slice prototype = sliceFactory.createPieCell( pies.length(), cell.container, cell.cell, denominator );
final Option<Slice> sliceOption = slices.find( new F<Slice, Boolean>() {
@Override public Boolean f( Slice m ) {
return ( m.position.equals( prototype.position ) && m.angle == prototype.angle ) || m.movingToward( prototype );
}
} );
final Slice slice = sliceOption.isSome() ? sliceOption.some() : slices.find( new F<Slice, Boolean>() {
@Override public Boolean f( Slice s ) {
return s.position.getY() == prototype.position.getY();
}
} ).some();
//Could be none if still animating
return animateSliceToBucket( slice, randomSeed );
}
示例9: testConflicts
import fj.data.Option; //导入依赖的package包/类
public void testConflicts() throws Exception {
final int id1 = db.createAccount(new BigDecimal(0));
final int id2 = db.createAccount(new BigDecimal(0));
final Semaphore semaphore = new Semaphore(2);
semaphore.acquire(2);
final Runnable runnable =
new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
db.transferMultipleTimes(id1, id2, new BigDecimal(1), 100);
} catch (SQLException e) {
throw new Error(e);
}
}
semaphore.release();
}
};
new Thread(runnable).start();
new Thread(runnable).start();
semaphore.acquire(2);
assertEquals(Option.some(new BigDecimal(2000)), db.getBalance(id2));
}
示例10: write
import fj.data.Option; //导入依赖的package包/类
@Override public IO<WriteResult<K, S, E>> write(Option<S> expectedSeq, Instant time,
Iterable<E> events) {
return () -> {
ArrayList<Event<K, S, E>> persistedEvents = new ArrayList<>();
S seq = expectedSeq.map(sequence::next).orSome(sequence.first());
Iterator<E> iterator = events.iterator();
while (iterator.hasNext()) {
Event<K, S, E> event = Events.Event(key, seq, time, iterator.next());
if (streamMap.putIfAbsent(seq, event) == null) {
persistedEvents.add(event);
seq = sequence.next(seq);
} else {
// null seq => the sequence already exist in the stream:
return WriteResults.DuplicateEventSeq();
}
}
return Success(commitSuccessfulWrite(persistedEvents, seq));
};
}
示例11: read
import fj.data.Option; //导入依赖的package包/类
@Override public <R> IO<R> read(Option<S> fromSeq, Fold<Event<K, S, E>, R> streamFold) {
return () -> streamFold.match(new Fold.Case<Event<K, S, E>, R, R>() {
@Override
public <Stepper> R fold(Stepper init, F2<Stepper, Event<K, S, E>, Step<R, Stepper>> onElement,
F<Stepper, R> onEndOfStream, Supplier<R> onEmpty) {
return scanLeft(
(event, stepper) -> stepper.bind(s -> onElement.f(s, event)), Steps.<R, Stepper>yield(init),
fromSeq.map(
fromSeqExclusive -> streamMap.subMap(fromSeqExclusive, false, seqFollowingLastCommit.get(), false))
.orSome(() -> streamMap.headMap(seqFollowingLastCommit.get()))
.values()
.stream()
).reduce((s1, s2) -> s2)
.map(s -> Steps.caseOf(s).done(identity()).yield(onEndOfStream))
.orElseGet(onEmpty);
}
});
}
示例12: of
import fj.data.Option; //导入依赖的package包/类
static <K, S, E, R> StreamIOAlgebra<K, S, E, R> of(EventStream<K, S, E> eventStream) {
return new StreamIOAlgebra<K, S, E, R>() {
@Override public IO<R> Read(Option<S> fromSeq, Fold<Event<K, S, E>, R> streamFold) {
return eventStream.read(fromSeq, streamFold);
}
@Override public IO<R> Latest(TypeEq<Option<Event<K, S, E>>, R> resultType) {
return eventStream.latest().map(resultType::coerce);
}
@Override public <Q> StreamIOAlgebra<K, S, E, Q> vary() {
return of(eventStream);
}
};
}
示例13: main
import fj.data.Option; //导入依赖的package包/类
public static void main(String[] args) throws IOException {
MemoryEventStorage<AccountNumber, Long, AccountEvent> memoryEventStorage = new MemoryEventStorage<>(Sequence.longs);
MemorySnapshotStorage<AccountNumber, Long, AccountState> snapshotStorage = new MemorySnapshotStorage<>(Sequence.longs);
AccountCommandService accountCommandService = new AccountCommandService(memoryEventStorage, snapshotStorage);
AccountNumber accountNumber = AccountNumber(1);
AccountCommand openAccountCmd = Open(Amount(BigDecimal.TEN).get(), BigDecimal.ZERO.subtract(BigDecimal.TEN));
IO<CommandDecision<AccountCommandRefusedReason, Event<AccountNumber, Long, AccountEvent>>> openAccount = accountCommandService.execute(accountNumber, openAccountCmd);
IO<CommandDecision<AccountCommandRefusedReason, Event<AccountNumber, Long, AccountEvent>>> openAccount2 = accountCommandService.execute(AccountNumber(2), openAccountCmd);
IO<CommandDecision<AccountCommandRefusedReason, Event<AccountNumber, Long, AccountEvent>>> withdraw = accountCommandService.execute(accountNumber, Withdraw(Amount(new BigDecimal("20")).get()));
IO<CommandDecision<AccountCommandRefusedReason, Event<AccountNumber, Long, AccountEvent>>> deposit = accountCommandService.execute(accountNumber, Credit(Amount(new BigDecimal("30")).get()));
System.out.println(
openAccount
.bind(__ -> withdraw)
.bind(__ -> withdraw)
.bind(__ -> deposit)
.bind(__ -> openAccount)
.bind(__ -> memoryEventStorage.stream(accountNumber).read(Option.none(), Fold.toList()))
//.bind(__ -> snapshotStorage.snapshots(accountNumber).get(SequenceQueries.Before(3L)))
.run());
}
示例14: read_return_write_actions
import fj.data.Option; //导入依赖的package包/类
public Property read_return_write_actions(
Function<K, Predicate<WStreamAction<K, S, E, Boolean>>> actionInterpreter) {
return property(keys, events, key -> event -> {
WStreamAction<K, S, E, Option<S>> lastSeqA = ReadEventStream(Option.none(), Fold.last())
.map(last -> last.map(Events::getSeq));
WStreamAction<K, S, E, Boolean> compareEventsA = lastSeqA.bind(lastSeq -> {
WStreamAction<K, S, E, List<Event<K, S, E>>> writeEventsA =
WriteEvents(lastSeq, Instant.EPOCH, single(event))
.map(WriteResults::getEvents)
.map(es -> es.orSome(nil()));
WStreamAction<K, S, E, List<Event<K, S, E>>> readEventsA = ReadEventStream(lastSeq, Fold.toList());
return writeEventsA.bind(writtenEvents ->
readEventsA.map(readEvents -> writtenEvents.length() == 1 && writtenEvents.equals(readEvents))
);
}
);
return prop(actionInterpreter.apply(key).test(compareEventsA));
});
}
示例15: concurrent_write_fails
import fj.data.Option; //导入依赖的package包/类
public Property concurrent_write_fails(EventStorage<K, S, E> eventStorage) {
return property(keys, events, key -> event -> {
WritableEventStream<K, S, E> stream = eventStorage.stream(key);
Option<S> lastSeq =
stream.read(none(), Fold.last())
.runUnchecked()
.map(Events::getSeq);
stream
.write(lastSeq, Instant.EPOCH, single(event))
.runUnchecked();
WriteResult<K, S, E> concurrentWrite = stream
.write(lastSeq, Instant.EPOCH, single(event))
.runUnchecked();
return prop(concurrentWrite.events().isNone());
});
}