Search in sources :

Example 96 with Optional

use of com.google.common.base.Optional in project distributedlog by twitter.

the class ReadUtils method getLogRecordNotLessThanTxId.

//
// Search Functions
//
/**
     * Get the log record whose transaction id is not less than provided <code>transactionId</code>.
     *
     * <p>
     * It uses a binary-search like algorithm to find the log record whose transaction id is not less than
     * provided <code>transactionId</code> within a log <code>segment</code>. You could think of a log segment
     * in terms of a sequence of records whose transaction ids are non-decreasing.
     *
     * - The sequence of records within a log segment is divided into N pieces.
     * - Find the piece of records that contains a record whose transaction id is not less than provided
     *   <code>transactionId</code>.
     *
     * N could be chosen based on trading off concurrency and latency.
     * </p>
     *
     * @param logName
     *          name of the log
     * @param segment
     *          metadata of the log segment
     * @param transactionId
     *          transaction id
     * @param executorService
     *          executor service used for processing entries
     * @param handleCache
     *          ledger handle cache
     * @param nWays
     *          how many number of entries to search in parallel
     * @return found log record. none if all transaction ids are less than provided <code>transactionId</code>.
     */
public static Future<Optional<LogRecordWithDLSN>> getLogRecordNotLessThanTxId(final String logName, final LogSegmentMetadata segment, final long transactionId, final ExecutorService executorService, final LedgerHandleCache handleCache, final int nWays) {
    if (!segment.isInProgress()) {
        if (segment.getLastTxId() < transactionId) {
            // all log records whose transaction id is less than provided transactionId
            // then return none
            Optional<LogRecordWithDLSN> noneRecord = Optional.absent();
            return Future.value(noneRecord);
        }
    }
    final Promise<Optional<LogRecordWithDLSN>> promise = new Promise<Optional<LogRecordWithDLSN>>();
    final FutureEventListener<LedgerDescriptor> openLedgerListener = new FutureEventListener<LedgerDescriptor>() {

        @Override
        public void onSuccess(final LedgerDescriptor ld) {
            promise.ensure(new AbstractFunction0<BoxedUnit>() {

                @Override
                public BoxedUnit apply() {
                    handleCache.asyncCloseLedger(ld);
                    return BoxedUnit.UNIT;
                }
            });
            long lastEntryId;
            try {
                lastEntryId = handleCache.getLastAddConfirmed(ld);
            } catch (BKException e) {
                promise.setException(e);
                return;
            }
            if (lastEntryId < 0) {
                // it means that the log segment is created but not written yet or an empty log segment.
                // it is equivalent to 'all log records whose transaction id is less than provided transactionId'
                Optional<LogRecordWithDLSN> nonRecord = Optional.absent();
                promise.setValue(nonRecord);
                return;
            }
            // all log records whose transaction id is not less than provided transactionId
            if (segment.getFirstTxId() >= transactionId) {
                final FirstTxIdNotLessThanSelector selector = new FirstTxIdNotLessThanSelector(transactionId);
                asyncReadRecordFromEntries(logName, ld, handleCache, segment, executorService, new SingleEntryScanContext(0L), selector).addEventListener(new FutureEventListener<LogRecordWithDLSN>() {

                    @Override
                    public void onSuccess(LogRecordWithDLSN value) {
                        promise.setValue(Optional.of(selector.result()));
                    }

                    @Override
                    public void onFailure(Throwable cause) {
                        promise.setException(cause);
                    }
                });
                return;
            }
            getLogRecordNotLessThanTxIdFromEntries(logName, ld, segment, transactionId, executorService, handleCache, Lists.newArrayList(0L, lastEntryId), nWays, Optional.<LogRecordWithDLSN>absent(), promise);
        }

        @Override
        public void onFailure(final Throwable cause) {
            String errMsg = "Error opening log segment [" + segment + "] for find record from " + logName;
            promise.setException(new IOException(errMsg, BKException.create(FutureUtils.bkResultCode(cause))));
        }
    };
    handleCache.asyncOpenLedger(segment, false).addEventListener(FutureEventListenerRunnable.of(openLedgerListener, executorService));
    return promise;
}
Also used : Optional(com.google.common.base.Optional) IOException(java.io.IOException) FirstTxIdNotLessThanSelector(com.twitter.distributedlog.selector.FirstTxIdNotLessThanSelector) Promise(com.twitter.util.Promise) FutureEventListener(com.twitter.util.FutureEventListener) BKException(org.apache.bookkeeper.client.BKException) BoxedUnit(scala.runtime.BoxedUnit)

Example 97 with Optional

use of com.google.common.base.Optional in project distributedlog by twitter.

the class FederatedZKLogMetadataStore method fetchLogLocation.

private Future<Optional<URI>> fetchLogLocation(final String logName) {
    final Promise<Optional<URI>> fetchPromise = new Promise<Optional<URI>>();
    Set<URI> uris = subNamespaces.keySet();
    List<Future<Optional<URI>>> fetchFutures = Lists.newArrayListWithExpectedSize(uris.size());
    for (URI uri : uris) {
        fetchFutures.add(fetchLogLocation(uri, logName));
    }
    Future.collect(fetchFutures).addEventListener(new FutureEventListener<List<Optional<URI>>>() {

        @Override
        public void onSuccess(List<Optional<URI>> fetchResults) {
            Optional<URI> result = Optional.absent();
            for (Optional<URI> fetchResult : fetchResults) {
                if (result.isPresent()) {
                    if (fetchResult.isPresent()) {
                        logger.error("Log {} is found in multiple sub namespaces : {} & {}.", new Object[] { logName, result.get(), fetchResult.get() });
                        duplicatedLogName.compareAndSet(null, logName);
                        duplicatedLogFound.set(true);
                        fetchPromise.setException(new UnexpectedException("Log " + logName + " is found in multiple sub namespaces : " + result.get() + " & " + fetchResult.get()));
                        return;
                    }
                } else {
                    result = fetchResult;
                }
            }
            fetchPromise.setValue(result);
        }

        @Override
        public void onFailure(Throwable cause) {
            fetchPromise.setException(cause);
        }
    });
    return fetchPromise;
}
Also used : UnexpectedException(com.twitter.distributedlog.exceptions.UnexpectedException) Optional(com.google.common.base.Optional) URI(java.net.URI) Promise(com.twitter.util.Promise) Future(com.twitter.util.Future) List(java.util.List)

Example 98 with Optional

use of com.google.common.base.Optional in project RFToolsDimensions by McJty.

the class RFToolsDim method imcCallback.

@Mod.EventHandler
public void imcCallback(FMLInterModComms.IMCEvent event) {
    for (FMLInterModComms.IMCMessage message : event.getMessages()) {
        if ("getDimletConfigurationManager".equalsIgnoreCase(message.key)) {
            Optional<Function<IDimletConfigurationManager, Void>> value = message.getFunctionValue(IDimletConfigurationManager.class, Void.class);
            String mod = message.getSender();
            Logging.log("Received RFTools Dimensions dimlet reconfiguration request from mod '" + mod + "'");
            value.get().apply(new DimletConfigurationManager(mod));
        } else if ("getDimensionManager".equalsIgnoreCase(message.key)) {
            Optional<Function<IDimensionManager, Void>> value = message.getFunctionValue(IDimensionManager.class, Void.class);
            String mod = message.getSender();
            Logging.log("Received RFTools dimension manager request from mod '" + mod + "'");
            value.get().apply(new DimensionManager());
        }
    }
}
Also used : Function(com.google.common.base.Function) Optional(com.google.common.base.Optional) IDimletConfigurationManager(mcjty.rftoolsdim.api.dimlet.IDimletConfigurationManager) DimletConfigurationManager(mcjty.rftoolsdim.apiimpl.DimletConfigurationManager) RfToolsDimensionManager(mcjty.rftoolsdim.dimensions.RfToolsDimensionManager) IDimensionManager(mcjty.rftoolsdim.api.dimension.IDimensionManager) DimensionManager(mcjty.rftoolsdim.apiimpl.DimensionManager) IDimensionManager(mcjty.rftoolsdim.api.dimension.IDimensionManager)

Example 99 with Optional

use of com.google.common.base.Optional in project double-espresso by JakeWharton.

the class ViewAssertions method selectedDescendantsMatch.

/**
   * Returns a generic {@link ViewAssertion} that asserts that the descendant views selected by the
   * selector match the specified matcher.
   *
   *  Example: onView(rootView).check(selectedDescendantsMatch(
   * not(isAssignableFrom(TextView.class)), hasContentDescription()));
   */
public static ViewAssertion selectedDescendantsMatch(final Matcher<View> selector, final Matcher<View> matcher) {
    return new ViewAssertion() {

        @SuppressWarnings("unchecked")
        @Override
        public void check(Optional<View> view, Optional<NoMatchingViewException> noViewException) {
            Preconditions.checkArgument(view.isPresent());
            View rootView = view.get();
            final Predicate<View> viewPredicate = new Predicate<View>() {

                @Override
                public boolean apply(View input) {
                    return selector.matches(input);
                }
            };
            Iterator<View> selectedViewIterator = Iterables.filter(breadthFirstViewTraversal(rootView), viewPredicate).iterator();
            List<View> nonMatchingViews = new ArrayList<View>();
            while (selectedViewIterator.hasNext()) {
                View selectedView = selectedViewIterator.next();
                if (!matcher.matches(selectedView)) {
                    nonMatchingViews.add(selectedView);
                }
            }
            if (nonMatchingViews.size() > 0) {
                String errorMessage = HumanReadables.getViewHierarchyErrorMessage(rootView, Optional.of(nonMatchingViews), String.format("At least one view did not match the required matcher: %s", matcher), Optional.of("****DOES NOT MATCH****"));
                throw new AssertionFailedError(errorMessage);
            }
        }
    };
}
Also used : ViewAssertion(com.google.android.apps.common.testing.ui.espresso.ViewAssertion) Optional(com.google.common.base.Optional) ArrayList(java.util.ArrayList) AssertionFailedError(junit.framework.AssertionFailedError) View(android.view.View) Predicate(com.google.common.base.Predicate)

Example 100 with Optional

use of com.google.common.base.Optional in project core-java by SpineEventEngine.

the class GetTargetIdFromCommandShould method return_empty_Optional_if_fail_to_get_ID_from_command_message_without_ID_field.

@Test
public void return_empty_Optional_if_fail_to_get_ID_from_command_message_without_ID_field() {
    final Optional id = GetTargetIdFromCommand.asOptional(StringValue.getDefaultInstance());
    assertFalse(id.isPresent());
}
Also used : Optional(com.google.common.base.Optional) Test(org.junit.Test)

Aggregations

Optional (com.google.common.base.Optional)147 RevFeature (org.locationtech.geogig.api.RevFeature)42 Test (org.junit.Test)31 RevFeatureType (org.locationtech.geogig.api.RevFeatureType)28 ImmutableList (com.google.common.collect.ImmutableList)24 List (java.util.List)24 File (java.io.File)23 RevObjectParse (org.locationtech.geogig.api.plumbing.RevObjectParse)20 Function (com.google.common.base.Function)18 ArrayList (java.util.ArrayList)18 PropertyDescriptor (org.opengis.feature.type.PropertyDescriptor)18 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)17 ObjectId (org.locationtech.geogig.api.ObjectId)17 SimpleFeature (org.opengis.feature.simple.SimpleFeature)16 Resource (org.eclipse.che.ide.api.resources.Resource)15 AddOp (org.locationtech.geogig.api.porcelain.AddOp)14 ImmutableMap (com.google.common.collect.ImmutableMap)13 RevObject (org.locationtech.geogig.api.RevObject)13 NodeRef (org.locationtech.geogig.api.NodeRef)12 Feature (org.opengis.feature.Feature)12