Java Code Examples for java8.util.Optional#of()

The following examples show how to use java8.util.Optional#of() . 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: FieldConverter.java    From ground-android with Apache License 2.0 6 votes vote down vote up
static Optional<Field> toField(ElementNestedObject em) {
  Field.Builder field = Field.newBuilder();
  switch (toEnum(Field.Type.class, em.getType())) {
    case TEXT:
      field.setType(Type.TEXT);
      break;
    case MULTIPLE_CHOICE:
      field.setType(Type.MULTIPLE_CHOICE);
      field.setMultipleChoice(MultipleChoiceConverter.toMultipleChoice(em));
      break;
    case PHOTO:
      field.setType(Type.PHOTO);
      break;
    default:
      return Optional.empty();
  }
  field.setRequired(em.getRequired() != null && em.getRequired());
  field.setId(em.getId());
  field.setLabel(getLocalizedMessage(em.getLabels()));
  return Optional.of(field.build());
}
 
Example 2
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 3
Source File: GuiTaskExecutor.java    From settlers-remake with MIT License 5 votes vote down vote up
private Optional<ILogicMovable> removeMovableThatCanMoveTo(List<ILogicMovable> movables, int x, int y) {
	for (Iterator<ILogicMovable> iterator = movables.iterator(); iterator.hasNext(); ) {
		ILogicMovable movable = iterator.next();
		if (canMoveTo(movable, x, y)) {
			iterator.remove();
			return Optional.of(movable);
		}
	}
	return Optional.empty();
}
 
Example 4
Source File: TradingBuilding.java    From settlers-remake with MIT License 5 votes vote down vote up
@Override
public Optional<MaterialTypeWithCount> tryToTakeMaterial(int maxAmount) {
	if (!isTargetSet() || getPriority() == EPriority.STOPPED) { // if no target is set, or work is stopped don't give materials
		return Optional.empty();
	}

	List<? extends IRequestStack> potentialStacks = stream(getStacks()).filter(IRequestStack::hasMaterial).collect(Collectors.toList());

	if (potentialStacks.isEmpty()) {
		return Optional.empty();
	}

	EMaterialType resultMaterialType = potentialStacks.get(0).getMaterialType();
	int resultCount = 0;

	for (IRequestStack stack : potentialStacks) {
		if (stack.getMaterialType() != resultMaterialType) {
			continue;
		}

		while (resultCount < maxAmount && stack.pop()) {
			resultCount++;
		}

		if (resultCount >= maxAmount) {
			break;
		}
	}

	return Optional.of(new MaterialTypeWithCount(resultMaterialType, resultCount));
}
 
Example 5
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 6
Source File: WellKnownAutoDiscoverySettings.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
private Optional<URL> getUrl(String url) {
    try {
        return Optional.of(new URL(url));
    } catch (MalformedURLException e) {
        log.warn("Ignoring invalid Base URL entry in well-known: {} - {}", url, e.getMessage());
        return Optional.empty();
    }
}
 
Example 7
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 8
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<JsonObject> getState(String type, String key) {
    URL path = getClientPath("rooms", roomId, "state", type, key);

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

    return Optional.of(GsonUtil.parseObj(body));
}
 
Example 9
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<JsonObject> getState(String type) {
    URL path = getClientPath("rooms", getAddress(), "state", type);

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

    return Optional.of(GsonUtil.parseObj(body));
}
 
Example 10
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 11
Source File: MultipleChoiceResponse.java    From ground-android with Apache License 2.0 5 votes vote down vote up
public static Optional<Response> fromList(List<String> codes) {
  if (codes.isEmpty()) {
    return Optional.empty();
  } else {
    return Optional.of(new MultipleChoiceResponse(codes));
  }
}
 
Example 12
Source File: MultipleChoice.java    From ground-android with Apache License 2.0 5 votes vote down vote up
public Optional<Integer> getIndex(String code) {
  for (int i = 0; i < getOptions().size(); i++) {
    if (getOptions().get(i).getCode().equals(code)) {
      return Optional.of(i);
    }
  }
  return Optional.empty();
}
 
Example 13
Source File: AbstractFieldViewModel.java    From ground-android with Apache License 2.0 4 votes vote down vote up
private Optional<String> validate(Field field, Optional<Response> response) {
  if (field.isRequired() && (response == null || response.isEmpty())) {
    return Optional.of(resources.getString(R.string.required_field));
  }
  return Optional.empty();
}
 
Example 14
Source File: MapContainerViewModel.java    From ground-android with Apache License 2.0 4 votes vote down vote up
private static CameraUpdate panAndZoom(Point center) {
  return new CameraUpdate(center, Optional.of(DEFAULT_ZOOM_LEVEL));
}
 
Example 15
Source File: FindOps.java    From streamsupport with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Optional<T> get() {
    return hasValue ? Optional.of(value) : null;
}
 
Example 16
Source File: Basic.java    From streamsupport with GNU General Public License v2.0 4 votes vote down vote up
@Test(groups = "unit")
public void testPresent() {
    Optional<Boolean> empty = Optional.empty();
    Optional<String> presentEmptyString = Optional.of("");
    Optional<Boolean> present = Optional.of(Boolean.TRUE);

    // present
    assertTrue(present.equals(present));
    assertTrue(present.equals(Optional.of(Boolean.TRUE)));
    assertTrue(!present.equals(empty));
    assertTrue(Boolean.TRUE.hashCode() == present.hashCode());
    assertTrue(!present.toString().isEmpty());
    assertTrue(!present.toString().equals(presentEmptyString.toString()));
    assertTrue(-1 != present.toString().indexOf(Boolean.TRUE.toString()));
    assertSame(Boolean.TRUE, present.get());
    try {
        present.ifPresent(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean v) {
                throw new ObscureException();
            }
        });
        fail();
    } catch(ObscureException expected) {

    }
    assertSame(Boolean.TRUE, present.orElse(null));
    assertSame(Boolean.TRUE, present.orElse(Boolean.FALSE));
    assertSame(Boolean.TRUE, present.orElseGet(null));
    assertSame(Boolean.TRUE, present.orElseGet(new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            return null;
        }
    }));
    assertSame(Boolean.TRUE, present.orElseGet(new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            return Boolean.FALSE;
        }
    }));
    assertSame(Boolean.TRUE, present.<RuntimeException>orElseThrow( null));
    assertSame(Boolean.TRUE, present.<RuntimeException>orElseThrow(new Supplier<RuntimeException>() {
        @Override
        public RuntimeException get() {
            return new ObscureException();
        }
    }));
}
 
Example 17
Source File: TextResponse.java    From ground-android with Apache License 2.0 4 votes vote down vote up
public static Optional<Response> fromString(String text) {
  return text.isEmpty() ? Optional.empty() : Optional.of(new TextResponse(text));
}
 
Example 18
Source File: GeoJsonTile.java    From ground-android with Apache License 2.0 4 votes vote down vote up
public Optional<String> getId() {
  String s = json.optString(ID_KEY);
  return s.isEmpty() ? Optional.empty() : Optional.of(s);
}