Example usage for java.util Optional get

List of usage examples for java.util Optional get

Introduction

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

Prototype

public T get() 

Source Link

Document

If a value is present, returns the value, otherwise throws NoSuchElementException .

Usage

From source file:org.openmhealth.shim.withings.mapper.WithingsBodyHeightDataPointMapper.java

@Override
public Optional<Measure.Builder<BodyHeight, ?>> newMeasureBuilder(JsonNode measuresNode) {

    Optional<BigDecimal> value = getValueForMeasureType(measuresNode, BODY_HEIGHT);

    if (!value.isPresent()) {
        return empty();
    }/* w ww  .java  2s.c o  m*/

    return Optional.of(new BodyHeight.Builder(new LengthUnitValue(METER, value.get())));
}

From source file:com.github.blindpirate.gogradle.task.go.test.PlainGoTestResultExtractor.java

private List<Pair<Integer, String>> extractStartIndiceAndTestMethodNames(List<String> stdout) {
    List<Pair<Integer, String>> ret = new ArrayList<>();

    for (int i = 0; i < stdout.size(); ++i) {
        Optional<String> testName = getRootTestNameFromLine(stdout.get(i));
        if (testName.isPresent()) {
            ret.add(Pair.of(i, testName.get()));
        }//from   w ww  . j a  va 2s .  com
    }
    return ret;
}

From source file:org.openmhealth.shim.withings.mapper.WithingsBodyWeightDataPointMapper.java

@Override
public Optional<Measure.Builder<BodyWeight, ?>> newMeasureBuilder(JsonNode measuresNode) {

    Optional<BigDecimal> value = getValueForMeasureType(measuresNode, BODY_WEIGHT);

    if (!value.isPresent()) {
        return empty();
    }//from   w w  w . j ava  2s . c  o m

    return Optional.of(new BodyWeight.Builder(new MassUnitValue(KILOGRAM, value.get())));
}

From source file:inflor.core.plots.HistogramPlot.java

@Override
public JFreeChart createChart(FCSFrame dataFrame, TransformSet transforms) {

    Optional<FCSDimension> domainDimension = FCSUtilities.findCompatibleDimension(dataFrame,
            spec.getDomainAxisName());//from  www  . ja v  a2  s . com

    AbstractTransform transform = transforms.get(domainDimension.get().getShortName());
    double[] transformedData = transform.transform(domainDimension.get().getData());

    Histogram1D hist = new Histogram1D(transformedData, transform.getMinTranformedValue(),
            transform.getMaxTransformedValue(), ChartingDefaults.BIN_COUNT);

    DefaultXYDataset dataset = new DefaultXYDataset();
    dataset.addSeries(dataFrame.getDisplayName(), hist.getData());

    ValueAxis domainAxis = PlotUtils.createAxis(domainDimension.get().getDisplayName(), transform);
    ValueAxis rangeAxis = new NumberAxis(spec.getRangeAxisName());
    FillType fillType = FillType.TO_ZERO;
    XYItemRenderer renderer = new XYSplineRenderer(1, fillType);
    renderer.setSeriesShape(0, ShapeUtilities.createDiamond(Float.MIN_VALUE));// Make the points
                                                                              // invisible
    XYPlot plot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);
    return new JFreeChart(plot);
}

From source file:com.openshift.internal.restclient.model.image.ImageStreamImport.java

@Override
public String getImageJsonFor(String tag) {
    ModelNode images = get(STATUS_IMAGES);
    if (images.isDefined() && StringUtils.isNotBlank(tag)) {
        Optional<ModelNode> node = images.asList().stream().filter(n -> tag.equals(asString(n, TAG)))
                .findFirst();/*  w ww  .j  a v a  2 s . co m*/
        if (node.isPresent()) {
            return node.get().toJSONString(true);
        }
    }
    return null;
}

From source file:mtsar.resources.TaskResource.java

@GET
@Path("{task}/answer")
public AnswerAggregation getTaskAnswer(@PathParam("task") Integer id) {
    final Task task = fetchTask(id);
    final Optional<AnswerAggregation> aggregation = stage.getAnswerAggregator().aggregate(task);
    return aggregation.isPresent() ? aggregation.get() : null;
}

From source file:com.linksinnovation.elearning.controller.api.WishlistController.java

@RequestMapping(method = RequestMethod.POST)
public boolean add(@RequestBody Map<String, Object> params, @AuthenticationPrincipal String username) {
    UserDetails userDetails = userDetailsRepository.findOne(username.toUpperCase());
    Course course = courseRepositroy.findOne(new Long(params.get("id").toString()));
    Optional<Wishlist> optional = wishlistRepository.findByUserAndCourse(userDetails, course);
    Wishlist wishlist;//ww  w. j a  v a  2s  .c  o m
    if (optional.isPresent()) {
        wishlistRepository.delete(optional.get());
    } else {
        wishlist = new Wishlist();
        wishlist.setUser(userDetails);
        wishlist.setCourse(course);
        wishlistRepository.save(wishlist);
    }

    return true;
}

From source file:io.soabase.web.filters.LanguageFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        AtomicReference<String> fixedQueryString = new AtomicReference<>();
        String queryStringCode = getFromQueryString(httpRequest.getQueryString(), fixedQueryString);
        String expectedLanguageCode = MoreObjects.firstNonNull(queryStringCode,
                getLanguageCode(null, getCookie(httpRequest)));
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        Optional<String> foundCookie = getCookie(httpRequest);
        if (!foundCookie.isPresent() || !foundCookie.get().equals(expectedLanguageCode)) {
            Cookie cookie = new Cookie(cookieName, expectedLanguageCode);
            httpResponse.addCookie(cookie);
        }//from   w ww  .  j ava2s. c o m

        if (queryStringCode != null) {
            StringBuffer redirectUrl = httpRequest.getRequestURL();
            if (!fixedQueryString.get().isEmpty()) {
                redirectUrl.append("?").append(fixedQueryString.get());
            }
            ((HttpServletResponse) response).sendRedirect(redirectUrl.toString());
            return;
        }
    }
    chain.doFilter(request, response);
}

From source file:com.devicehive.service.OAuthTokenService.java

@Transactional(propagation = Propagation.REQUIRED)
public JwtTokenVO authenticate(@NotNull UserVO user) {
    UserWithNetworkVO userWithNetwork = userService.findUserWithNetworks(user.getId());
    userService.refreshUserLoginData(user);

    Set<String> networkIds = new HashSet<>();
    Set<String> deviceGuids = new HashSet<>();
    userWithNetwork.getNetworks().stream().forEach(network -> {
        networkIds.add(network.getId().toString());
        Optional<NetworkWithUsersAndDevicesVO> networkWithDevices = networkDao.findWithUsers(network.getId());
        if (networkWithDevices.isPresent()) {
            networkWithDevices.get().getDevices().stream().forEach(device -> {
                deviceGuids.add(device.getGuid());
            });//from   w  ww. j a  va 2  s . co m
        }
    });

    JwtTokenVO tokenVO = new JwtTokenVO();
    JwtPayload payload = JwtPayload.newBuilder().withUserId(userWithNetwork.getId())
            .withActions(new HashSet<>(Arrays.asList(AvailableActions.getClientActions())))
            .withNetworkIds(networkIds).withDeviceGuids(deviceGuids).buildPayload();

    tokenVO.setAccessToken(tokenService.generateJwtAccessToken(payload));
    return tokenVO;
}

From source file:com.teradata.benchto.service.EnvironmentService.java

@Transactional(readOnly = true)
public Environment findEnvironment(String name) {
    Optional<Environment> environment = tryFindEnvironment(name);
    if (!environment.isPresent()) {
        throw new IllegalArgumentException("Could not find environment " + name);
    }/*from   w  w  w  .  j av a  2s  .  c  o m*/
    return environment.get();
}