java8.util.Optional Java Examples

The following examples show how to use java8.util.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: HomeScreenViewModel.java    From ground-android with Apache License 2.0 6 votes vote down vote up
public void addObservation() {
  BottomSheetState state = bottomSheetState.getValue();
  if (state == null) {
    Log.e(TAG, "Missing bottomSheetState");
    return;
  }
  Feature feature = state.getFeature();
  if (feature == null) {
    Log.e(TAG, "Missing feature");
    return;
  }
  Optional<Form> form = feature.getLayer().getForm();
  if (form.isEmpty()) {
    // .TODO: Hide Add Observation button if no forms defined.
    Log.e(TAG, "No forms in layer");
    return;
  }
  Project project = feature.getProject();
  if (project == null) {
    Log.e(TAG, "Missing project");
    return;
  }
  navigator.addObservation(project.getId(), feature.getId(), form.get().getId());
}
 
Example #2
Source File: ProjectRepository.java    From ground-android with Apache License 2.0 6 votes vote down vote up
private Flowable<Loadable<Project>> loadProject(Optional<String> projectId) {
  // Empty id indicates intent to deactivate the current project. Used on sign out.
  if (projectId.isEmpty()) {
    return Flowable.just(Loadable.notLoaded());
  }
  String id = projectId.get();

  return syncProjectWithRemote(id)
      .doOnSubscribe(__ -> Log.d(TAG, "Activating project " + id))
      .doOnError(err -> Log.d(TAG, "Error loading project from remote", err))
      .onErrorResumeNext(
          __ ->
              localDataStore
                  .getProjectById(id)
                  .toSingle()
                  .doOnError(err -> Log.d(TAG, "Error loading project from local db", err)))
      .doOnSuccess(__ -> localValueStore.setLastActiveProjectId(id))
      .toFlowable()
      .compose(Loadable::loadingOnceAndWrap);
}
 
Example #3
Source File: SingleSelectDialogFactory.java    From ground-android with Apache License 2.0 6 votes vote down vote up
AlertDialog create(
    Field field,
    Optional<Response> initialValue,
    Consumer<Optional<Response>> valueChangeCallback) {
  MultipleChoice multipleChoice = field.getMultipleChoice();
  AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
  List<Option> options = multipleChoice.getOptions();
  DialogState state = new DialogState(multipleChoice, initialValue);
  dialogBuilder.setSingleChoiceItems(
      getLabels(multipleChoice), state.checkedItem, state::onSelect);
  dialogBuilder.setCancelable(false);
  dialogBuilder.setTitle(field.getLabel());
  dialogBuilder.setPositiveButton(
      R.string.apply_multiple_choice_changes,
      (dialog, which) -> valueChangeCallback.accept(state.getSelectedValue(field, options)));
  dialogBuilder.setNegativeButton(R.string.cancel, (dialog, which) -> {});
  return dialogBuilder.create();
}
 
Example #4
Source File: ObservationListItemViewHolder.java    From ground-android with Apache License 2.0 6 votes vote down vote up
private void addFieldsFromObservation(Observation observation) {
  binding.fieldLabelRow.removeAllViews();
  binding.fieldValueRow.removeAllViews();

  Form form = observation.getForm();
  // TODO: Clean this up.
  for (int i = 0; i < MAX_COLUMNS && i < form.getElements().size(); i++) {
    Element elem = form.getElements().get(i);
    switch (elem.getType()) {
      case FIELD:
        Field field = elem.getField();
        Optional<Response> response = observation.getResponses().getResponse(field.getId());
        binding.fieldLabelRow.addView(
            newFieldTextView(field.getLabel(), R.style.ObservationListText_FieldLabel));
        binding.fieldValueRow.addView(
            newFieldTextView(
                response.map(r -> r.getSummaryText(field)).orElse(""),
                R.style.ObservationListText_Field));
        break;
      default:
        Log.e(TAG, "Unhandled element type: " + elem.getType());
        break;
    }
  }
}
 
Example #5
Source File: MultiSelectDialogFactory.java    From ground-android with Apache License 2.0 6 votes vote down vote up
AlertDialog create(
    Field field,
    Optional<Response> initialResponse,
    Consumer<Optional<Response>> responseChangeCallback) {
  MultipleChoice multipleChoice = field.getMultipleChoice();
  AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
  List<Option> options = multipleChoice.getOptions();
  final DialogState state = new DialogState(multipleChoice, initialResponse);
  dialogBuilder.setMultiChoiceItems(
      getLabels(multipleChoice), state.checkedItems, (dialog, which, isChecked) -> {});
  dialogBuilder.setCancelable(false);
  dialogBuilder.setTitle(field.getLabel());
  dialogBuilder.setPositiveButton(
      R.string.apply_multiple_choice_changes,
      (dialog, which) -> responseChangeCallback.accept(state.getSelectedValues(options)));
  dialogBuilder.setNegativeButton(R.string.cancel, (dialog, which) -> {});
  return dialogBuilder.create();
}
 
Example #6
Source File: HexGridAreaTest.java    From settlers-remake with MIT License 6 votes vote down vote up
@Test
public void testIterateForResultStopsAfterResult() {
	int expectedVisits = 5;
	Object expectedResultObject = new Object();
	MutableInt counter = new MutableInt(0);

	Optional<Object> actualResultObject = HexGridArea.stream(10, 10, 3, 10).iterateForResult((x, y) -> {
		counter.value++;
		if (counter.value == expectedVisits) {
			return Optional.of(expectedResultObject);
		} else {
			return Optional.empty();
		}
	});

	assertEquals(expectedVisits, counter.value);
	assertTrue(actualResultObject.isPresent());
	assertSame(expectedResultObject, actualResultObject.get());
}
 
Example #7
Source File: CoordinateStream.java    From settlers-remake with MIT License 6 votes vote down vote up
public Optional<ShortPoint2D> min(IIntCoordinateFunction function) {
	MutableInt bestX = new MutableInt(Integer.MIN_VALUE);
	MutableInt bestY = new MutableInt();
	MutableInt bestValue = new MutableInt(Integer.MAX_VALUE);

	iterate((x, y) -> {
		int currValue = function.apply(x, y);
		if (currValue < bestValue.value) {
			bestValue.value = currValue;
			bestX.value = x;
			bestY.value = y;
		}
		return true;
	});

	if (bestX.value != Integer.MIN_VALUE) {
		return Optional.of(new ShortPoint2D(bestX.value, bestY.value));
	} else {
		return Optional.empty();
	}
}
 
Example #8
Source File: DonkeyStrategy.java    From settlers-remake with MIT License 6 votes vote down vote up
protected boolean loadUp(ITradeBuilding tradeBuilding) {
	Optional<EMaterialType> materialType1 = tradeBuilding.tryToTakeMaterial(1).map(MaterialTypeWithCount::getMaterialType);
	Optional<EMaterialType> materialType2 = tradeBuilding.tryToTakeMaterial(1).map(MaterialTypeWithCount::getMaterialType);

	if (!materialType1.isPresent() && !materialType2.isPresent()) {
		reset();
		return false;

	} else {
		super.setMaterial(EMaterialType.BASKET);

		this.materialType1 = materialType1.orElse(null);
		this.materialType2 = materialType2.orElse(null);

		return true;
	}
}
 
Example #9
Source File: MatrixHttpUser.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Optional<_Presence> getPresence() {
    URL path = getClientPath("presence", mxId.getId(), "status");

    MatrixHttpRequest request = new MatrixHttpRequest(new Request.Builder().get().url(path));
    request.addIgnoredErrorCode(404);
    String body = execute(request);
    if (StringUtils.isBlank(body)) {
        return Optional.empty();
    }

    return Optional.of(new Presence(GsonUtil.parseObj(body)));
}
 
Example #10
Source File: MainGrid.java    From settlers-remake with MIT License 5 votes vote down vote up
@Override
public FerryEntrance ferryAtPosition(ShortPoint2D position, byte playerId) {
	Optional<ILogicMovable> ferryOptional = HexGridArea.stream(position.x, position.y, 0, Constants.MAX_FERRY_ENTRANCE_SEARCH_DISTANCE)
													   .filterBounds(width, height)
													   .filter((x, y) -> landscapeGrid.getLandscapeTypeAt(x, y).isWater())
													   .iterateForResult((x, y) -> {
														   ILogicMovable movable = movableGrid.getMovableAt(x, y);
														   return Optional.ofNullable(movable).filter(m -> m.getMovableType() == EMovableType.FERRY);
													   });

	if (!ferryOptional.isPresent()) {
		return null;
	}

	ILogicMovable ferry = ferryOptional.get();
	ShortPoint2D ferryPosition = ferry.getPosition();
	Optional<ShortPoint2D> entranceOptional = HexGridArea.stream(ferryPosition.x, ferryPosition.y, 0, Constants.MAX_FERRY_ENTRANCE_SEARCH_DISTANCE)
														 .filterBounds(width, height)
														 .filter((x, y) -> !isBlocked(x, y))
														 .getFirst();

	if (!entranceOptional.isPresent()) {
		return null;
	}

	return new FerryEntrance(ferry, entranceOptional.get());
}
 
Example #11
Source File: EditObservationFragment.java    From ground-android with Apache License 2.0 5 votes vote down vote up
private void onShowDialog(
    Field field, Optional<Response> currentResponse, Consumer<Optional<Response>> consumer) {
  Cardinality cardinality = field.getMultipleChoice().getCardinality();
  switch (cardinality) {
    case SELECT_MULTIPLE:
      multiSelectDialogFactory.create(field, currentResponse, consumer).show();
      break;
    case SELECT_ONE:
      singleSelectDialogFactory.create(field, currentResponse, consumer).show();
      break;
    default:
      Timber.e("Unknown cardinality: %s", cardinality);
      break;
  }
}
 
Example #12
Source File: AMatrixHttpClient.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
protected Optional<String> extractAsStringFromBody(String body, String jsonObjectName) {
    if (StringUtils.isEmpty(body)) {
        return Optional.empty();
    }

    return GsonUtil.findString(jsonParser.parse(body).getAsJsonObject(), jsonObjectName);
}
 
Example #13
Source File: LocalDataStoreTest.java    From ground-android with Apache License 2.0 5 votes vote down vote up
private static FeatureMutation createTestFeatureMutation(Point point) {
  return FeatureMutation.builder()
      .setId(1L)
      .setFeatureId("feature id")
      .setType(Mutation.Type.CREATE)
      .setUserId("user id")
      .setProjectId("project id")
      .setLayerId("layer id")
      .setNewLocation(Optional.ofNullable(point))
      .setClientTimestamp(new Date())
      .build();
}
 
Example #14
Source File: MatrixHttpUser.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Optional<String> getName() {
    URL path = getClientPath("profile", mxId.getId(), "displayname");

    MatrixHttpRequest request = new MatrixHttpRequest(new Request.Builder().get().url(path));
    request.addIgnoredErrorCode(404);
    String body = executeAuthenticated(request);
    return extractAsStringFromBody(body, "displayname");
}
 
Example #15
Source File: ProjectRepository.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@Inject
public ProjectRepository(
    LocalDataStore localDataStore,
    RemoteDataStore remoteDataStore,
    InMemoryCache cache,
    LocalValueStore localValueStore) {
  this.localDataStore = localDataStore;
  this.remoteDataStore = remoteDataStore;
  this.cache = cache;
  this.localValueStore = localValueStore;

  // BehaviorProcessor re-emits last requested project id to late subscribers.
  this.activateProjectRequests = BehaviorProcessor.create();

  // Stream that emits a value whenever the user changes projects.
  Flowable<Optional<String>> distinctActivateProjectRequests =
      activateProjectRequests
          .distinctUntilChanged()
          .doOnNext(id -> Log.v(TAG, "Requested project id changed: " + id));

  // Stream that emits project loading state when requested id changes. Late subscribers receive
  // the last project or loading state.
  Flowable<Loadable<Project>> activeProject =
      distinctActivateProjectRequests.switchMap(this::loadProject).onBackpressureLatest();

  // Convert project loading state stream to Connectable to prevent loadProject() from being
  // called once for each subscription. Instead, it will be called once on each project change,
  // with each subscriber receiving a cached copy of the result. This is required in addition
  // to onBackpressureLatest() above.
  this.activeProjectStream = activeProject.replay(1).refCount();
}
 
Example #16
Source File: MatrixHttpContentResult.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
public MatrixHttpContentResult(Response response) throws IOException {
    try (ResponseBody body = response.body()) {
        boolean hasBody = Objects.nonNull(body);
        valid = hasBody && response.code() == 200;
        headers = response.headers().toMultimap();

        if (hasBody) {
            contentType = Optional.ofNullable(body.contentType()).map(MediaType::toString);
            data = body.bytes();
        } else {
            contentType = Optional.empty();
            data = new byte[0];
        }
    }
}
 
Example #17
Source File: SingleSelectDialogFactory.java    From ground-android with Apache License 2.0 5 votes vote down vote up
private Optional<Response> getSelectedValue(Field field, List<Option> options) {
  if (checkedItem >= 0) {
    return Optional.of(
        new MultipleChoiceResponse(ImmutableList.of(options.get(checkedItem).getCode())));
  } else {
    return Optional.empty();
  }
}
 
Example #18
Source File: SingleSelectDialogFactory.java    From ground-android with Apache License 2.0 5 votes vote down vote up
public DialogState(MultipleChoice multipleChoice, Optional<Response> initialValue) {
  // TODO: Check type.
  checkedItem =
      initialValue
          .map(MultipleChoiceResponse.class::cast)
          .flatMap(MultipleChoiceResponse::getFirstCode)
          .flatMap(multipleChoice::getIndex)
          .orElse(-1);
}
 
Example #19
Source File: MapObjectsManager.java    From settlers-remake with MIT License 5 votes vote down vote up
public ShortPoint2D pushMaterialForced(int x, int y, EMaterialType materialType) {
	return HexGridArea.stream(x, y, 0, 200)
			.filterBounds(grid.getWidth(), grid.getHeight())
			.filter((currX, currY) -> canForcePushMaterial(currX, currY, materialType))
			.iterateForResult((currX, currY) -> {
				pushMaterial(currX, currY, materialType);
				return Optional.of(new ShortPoint2D(currX, currY));
			}).orElse(null);
}
 
Example #20
Source File: CoordinateStream.java    From settlers-remake with MIT License 5 votes vote down vote up
public <T> Optional<T> iterateForResult(ICoordinateFunction<Optional<T>> function) {
	Mutable<Optional<T>> result = new Mutable<>(Optional.empty());
	iterate((x, y) -> {
		Optional<T> currResult = function.apply(x, y);
		if (currResult.isPresent()) {
			result.object = currResult;
			return false;
		} else {
			return true;
		}
	});
	return result.object;
}
 
Example #21
Source File: PaletteUtils.java    From AndroidAnimationExercise with Apache License 2.0 5 votes vote down vote up
public static int getMagicColor(Resources resources, int id) {
    Palette.Builder builder = new Palette.Builder(BitmapFactory.decodeResource(resources, id));
    Palette palette = builder.generate();
    return Optional.ofNullable(palette)
            .map(PaletteUtils::getSwatch)
            .map(Palette.Swatch::getRgb)
            .orElseGet(() -> 0);
}
 
Example #22
Source File: OriginalMapFileContentReader.java    From settlers-remake with MIT License 5 votes vote down vote up
private Optional<MapResourceInfo> findAndDecryptFilePart(EOriginalMapFilePartType partType) throws MapLoadException {
	MapResourceInfo filePart = findResource(partType);

	if ((filePart == null) || (filePart.size == 0)) {
		return Optional.empty();
	}

	// Decrypt this resource if necessary
	filePart.doDecrypt();

	// Call consumer
	return Optional.of(filePart);
}
 
Example #23
Source File: GsonUtil.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Optional<JsonObject> findObj(JsonObject o, String key) {
    if (!o.has(key)) {
        return Optional.empty();
    }

    return Optional.ofNullable(o.getAsJsonObject(key));
}
 
Example #24
Source File: MatrixHttpRoom.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Optional<MatrixErrorInfo> tryLeave() {
    try {
        leave();
        return Optional.empty();
    } catch (MatrixClientRequestException e) {
        return e.getError();
    }
}
 
Example #25
Source File: DistinctOpTest.java    From streamsupport with GNU General Public License v2.0 5 votes vote down vote up
public void testWithUnorderedInfiniteStream() {
    // These tests should short-circuit, otherwise will fail with a time-out
    // or an OOME

    // Note that since the streams are unordered and any element is requested
    // (a non-deterministic process) the only assertion that can be made is
    // that an element should be found

    Optional<Integer> oi = RefStreams.iterate(1, i -> i + 1).unordered().parallel().distinct().findAny();
    assertTrue(oi.isPresent());

    oi = ThreadLocalRandom.current().ints().boxed().parallel().distinct().findAny();
    assertTrue(oi.isPresent());
}
 
Example #26
Source File: DefaultMethodStreams.java    From streamsupport with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Optional<T> min(Comparator<? super T> comparator) {
    return s.min(comparator);
}
 
Example #27
Source File: ObservationListViewModel.java    From ground-android with Apache License 2.0 4 votes vote down vote up
public ObservationListRequest(Project project, String featureId, Optional<String> formId) {
  this.project = project;
  this.featureId = featureId;
  this.formId = formId;
}
 
Example #28
Source File: ReferencePipeline.java    From streamsupport with GNU General Public License v2.0 4 votes vote down vote up
@Override
public final Optional<P_OUT> reduce(BinaryOperator<P_OUT> accumulator) {
    return evaluate(ReduceOps.makeRef(accumulator));
}
 
Example #29
Source File: MatrixJsonEventFactory.java    From matrix-java-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
public static _MatrixEvent get(JsonObject obj) {
    String type = obj.get("type").getAsString();

    if ("m.room.member".contentEquals(type)) {
        return new MatrixJsonRoomMembershipEvent(obj);
    } else if ("m.room.power_levels".contentEquals(type)) {
        return new MatrixJsonRoomPowerLevelsEvent(obj);
    } else if ("m.room.avatar".contentEquals(type)) {
        return new MatrixJsonRoomAvatarEvent(obj);
    } else if ("m.room.name".contentEquals(type)) {
        return new MatrixJsonRoomNameEvent(obj);
    } else if ("m.room.topic".contentEquals(type)) {
        return new MatrixJsonRoomTopicEvent(obj);
    } else if ("m.room.aliases".contentEquals(type)) {
        return new MatrixJsonRoomAliasesEvent(obj);
    } else if (_RoomCanonicalAliasEvent.Type.contentEquals(type)) {
        return new MatrixJsonRoomCanonicalAliasEvent(obj);
    } else if ("m.room.message".contentEquals(type)) {
        return new MatrixJsonRoomMessageEvent(obj);
    } else if ("m.receipt".contentEquals(type)) {
        return new MatrixJsonReadReceiptEvent(obj);
    } else if ("m.room.history_visibility".contentEquals(type)) {
        return new MatrixJsonRoomHistoryVisibilityEvent(obj);
    } else if (_TagsEvent.Type.contentEquals(type)) {
        return new MatrixJsonRoomTagsEvent(obj);
    } else if (_DirectEvent.Type.contentEquals(type)) {
        return new MatrixJsonDirectEvent(obj);
    } else {
        Optional<String> timestamp = EventKey.Timestamp.findString(obj);
        Optional<String> sender = EventKey.Sender.findString(obj);

        if (!timestamp.isPresent() || !sender.isPresent()) {
            return new MatrixJsonEphemeralEvent(obj);
        } else {
            Optional<String> rId = EventKey.RoomId.findString(obj);
            if (rId.isPresent()) {
                return new MatrixJsonRoomEvent(obj);
            }

            return new MatrixJsonPersistentEvent(obj);
        }
    }
}
 
Example #30
Source File: MapContainerViewModel.java    From ground-android with Apache License 2.0 4 votes vote down vote up
public Optional<Float> getMinZoomLevel() {
  return minZoomLevel;
}