Example usage for java.util Optional of

List of usage examples for java.util Optional of

Introduction

In this page you can find the example usage for java.util Optional of.

Prototype

public static <T> Optional<T> of(T value) 

Source Link

Document

Returns an Optional describing the given non- null value.

Usage

From source file:com.uber.hoodie.common.HoodieJsonPayload.java

@Override
public Optional<IndexedRecord> getInsertValue(Schema schema) throws IOException {
    MercifulJsonConverter jsonConverter = new MercifulJsonConverter(schema);
    return Optional.of(jsonConverter.convert(getJsonData()));
}

From source file:org.openwms.tms.ChangeTUDocumentation.java

public @Test void testTUChange() throws Exception {
    // setup .../*  w  ww  .j  a  v  a 2  s. co  m*/
    CreateTransportOrderVO vo = createTO();
    postTOAndValidate(vo, NOTLOGGED);
    vo.setBarcode(KNOWN);
    given(commonGateway.getTransportUnit(KNOWN))
            .willReturn(Optional.of(new TransportUnit(KNOWN, INIT_LOC, ERR_LOC_STRING)));

    // test ...
    mockMvc.perform(patch(TMSConstants.ROOT_ENTITIES).contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(vo))).andExpect(status().isNoContent())
            .andDo(document("to-patch-tu-change"));
}

From source file:com.formkiq.core.form.calc.GraphCalculatorNode.java

/**
 * constructor./*w  w w  . ja  v a2 s .  c  o  m*/
 * @param nodename {@link String}
 * @param calc {@link Calculator}
 * @param formField {@link FormJSONField}
 */
public GraphCalculatorNode(final String nodename, final Calculator calc, final FormJSONField formField) {
    this(nodename);
    this.calculator = Optional.of(calc);
    this.field = formField != null ? Optional.of(formField) : Optional.empty();
}

From source file:ch.algotrader.service.NativeMarketDataServiceImpl.java

protected final Optional<String> esperUnsubscribe(Security security) {

    String tickerId = (String) this.serverEngine.executeSingelObjectQuery(
            "select tickerId from TickWindow where securityId = " + security.getId(), "tickerId");
    if (tickerId != null) {
        this.serverEngine.executeQuery("delete from TickWindow where securityId = " + security.getId());
        return Optional.of(tickerId);
    } else {/*from  w w w  .j av  a  2  s. co m*/
        return Optional.empty();
    }

}

From source file:org.trustedanalytics.cloud.cc.api.manageusers.CcOrgUser.java

@JsonIgnore
public String getUsername() {
    Optional<CcOrgUser> user = Optional.of(this);
    return user.map(CcOrgUser::getEntity).map(CcOrgUserEntity::getUsername).orElse(null);
}

From source file:ru.mera.samples.infrastructure.aop.BeforeAfterLogAdvice.java

@AfterReturning("inImageRepositoryEndpoint()")
public void afterReturning(JoinPoint joinPoint) {
    final String[] principals = new String[1];
    Optional.of(SecurityContextHolder.getContext())
            .ifPresent(securityContext -> Optional.of(securityContext.getAuthentication())
                    .ifPresent(authentication -> Optional.of(authentication.getPrincipal())
                            .ifPresent(o -> principals[0] = o.toString())));
    logger.info("After method: " + joinPoint.getSignature().getName() + " by user " + principals);
}

From source file:jp.toastkid.script.runner.GroovyRunner.java

@Override
public Optional<String> run(final String script) {
    if (StringUtils.isEmpty(script)) {
        return Optional.empty();
    }//from w  ww  . j  av  a2  s  .c  o  m
    if (engine == null) {
        System.out.println("groovy null");
    }

    final StringBuilder result = new StringBuilder();

    try (final StringWriter writer = new StringWriter();) {
        if (engine != null) {
            final ScriptContext context = engine.getContext();
            context.setWriter(new PrintWriter(writer));
            context.setErrorWriter(new PrintWriter(writer));
        }
        final java.lang.Object run = engine.eval(script);
        result.append(writer.toString()).append(LINE_SEPARATOR);
        if (run != null) {
            result.append("return = ").append(run.toString());
        }
        writer.close();
    } catch (final CompilationFailedException | IOException | javax.script.ScriptException e) {
        e.printStackTrace();
        result.append("Occurred Exception.").append(LINE_SEPARATOR).append(e.getMessage());
    }
    return Optional.of(result.toString());
}

From source file:com.orange.ngsi2.model.ErrorTest.java

@Test
public void checkToString() {
    Error parseError = new Error("400", Optional.of("The incoming JSON payload cannot be parsed"),
            Optional.empty());//from  w  w  w  .  j  av  a2s. co  m
    assertEquals("error: 400 | description: The incoming JSON payload cannot be parsed | affectedItems: []",
            parseError.toString());
    parseError.setAffectedItems(Optional.of(Collections.singleton("entities")));
    assertEquals(
            "error: 400 | description: The incoming JSON payload cannot be parsed | affectedItems: [entities]",
            parseError.toString());
}

From source file:br.com.blackhubos.eventozero.updater.assets.uploader.Uploader.java

@SuppressWarnings("unchecked")
public static Optional<Uploader> parseJsonObject(JSONObject parse, MultiTypeFormatter formatter) {

    long id = Long.MIN_VALUE;
    String name = null;/*from  ww w . ja  v a  2 s .co m*/
    boolean admin = false;
    // Loop em todas entradas do JSON
    for (Map.Entry entries : (Set<Map.Entry>) parse.entrySet()) {

        Object key = entries.getKey();
        Object value = entries.getValue();
        String valueString = String.valueOf(value);
        /** Transforma o objeto em um {@link AssetUploaderInput) para usar com switch **/
        switch (AssetUploaderInput.parseObject(key)) {
        case ADMIN: {
            // Obtem o valor que indica se quem enviou era administrador
            if (formatter.canFormat(Boolean.class)) {
                Optional<Boolean> result = formatter.format(value, Boolean.class);
                if (result.isPresent())
                    admin = result.get();
            }
            break;
        }
        case ID: {
            // Obtm o ID do usurio
            id = Long.parseLong(valueString);
            break;
        }
        case LOGIN: {
            // Obtm o nome/login do usurio
            name = valueString;
            break;
        }

        default: {
            break;
        }
        }
    }
    if (id == Long.MIN_VALUE || name == null) {
        return Optional.empty();
    }
    return Optional.of(new Uploader(name, admin, id));
}

From source file:com.openthinks.webscheduler.controller.ProfileController.java

private Optional<User> getCurrentUser(WebAttributers was) {
    User currentUser = was.getSession(StaticDict.SESSION_ATTR_LOGIN_INFO);
    if (currentUser != null) {
        currentUser = securityService.getUsers().findById(currentUser.getId());
        return Optional.of(currentUser);
    }/* ww  w.  j ava2  s .  co m*/
    return Optional.empty();
}