List of usage examples for java.util Optional orElseThrow
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X
From source file:it.unibo.alchemist.model.implementations.environments.OSMEnvironment.java
private void initAll(final String fileName) throws IOException { Objects.requireNonNull(fileName, "define the file with the map: " + fileName); final Optional<URL> file = Optional.of(new File(fileName)).filter(File::exists).map(File::toURI) .map(Unchecked.function(URI::toURL)); final URL resource = Optional.ofNullable(OSMEnvironment.class.getResource(fileName)) .orElseGet(Unchecked.supplier(() -> file.orElseThrow( () -> new FileNotFoundException("No file or resource with name " + fileName)))); final String dir = initDir(resource).intern(); final File workdir = new File(dir); mkdirsIfNeeded(workdir);/*from w w w .j a va 2s.c o m*/ final File mapFile = new File(dir + SLASH + MAPNAME); try (RandomAccessFile fileAccess = new RandomAccessFile(workdir + SLASH + "lock", "rw")) { try (FileLock lock = fileAccess.getChannel().lock()) { if (!mapFile.exists()) { Files.copy(resource.openStream(), mapFile.toPath()); } } } navigators = new EnumMap<>(Vehicle.class); mapLock = new FastReadWriteLock(); final Optional<Exception> error = Arrays.stream(Vehicle.values()).parallel().<Optional<Exception>>map(v -> { try { final String internalWorkdir = workdir + SLASH + v; final File iwdf = new File(internalWorkdir); if (mkdirsIfNeeded(iwdf)) { final GraphHopperAPI gh = initNavigationSystem(mapFile, internalWorkdir, v); mapLock.write(); navigators.put(v, gh); mapLock.release(); } return Optional.empty(); } catch (Exception e) { return Optional.of(e); } }).filter(Optional::isPresent).map(Optional::get).findFirst(); if (error.isPresent()) { throw new IllegalStateException("A error occurred during initialization.", error.get()); } }
From source file:alfio.controller.ReservationController.java
@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/re-send-email", method = RequestMethod.POST) public String reSendReservationConfirmationEmail(@PathVariable("eventName") String eventName, @PathVariable("reservationId") String reservationId, HttpServletRequest request) { Optional<Event> event = eventRepository.findOptionalByShortName(eventName); if (!event.isPresent()) { return "redirect:/"; }// w w w.j a v a 2s . com Optional<TicketReservation> ticketReservation = ticketReservationManager.findById(reservationId); if (!ticketReservation.isPresent()) { return "redirect:/event/" + eventName + "/"; } sendReservationCompleteEmail(request, event.get(), ticketReservation.orElseThrow(IllegalStateException::new)); return "redirect:/event/" + eventName + "/reservation/" + reservationId + "/success?confirmation-email-sent=true"; }
From source file:org.alfresco.permissions.dao.titan.TitanPermissionsDAO.java
@Override public void versionNode(String nodeId, Auths auths) { graph.tx().submit(new Function<Graph, Vertex>() { public Vertex apply(Graph g) { Optional<Vertex> head = graph.traversal().V().hasLabel("NODE").has("nid", nodeId) .has("latest", true).map(v -> { Vertex nodeVertex = v.get(); int nodeVersion = (Integer) nodeVertex.property("nv").value(); Properties properties = Properties.fromVertex(nodeVertex.properties()); Vertex newHead = addNodeImpl(g, nodeId, nodeVersion + 1, auths, properties, true); Edge edge = newHead.addEdge("EDGE", v.get()); edge.property("assocType", "version"); nodeVertex.property("latest", false); return newHead; }).tryNext();/*from w w w. ja va 2 s . com*/ return head.orElseThrow(() -> new IllegalArgumentException("Invalid node " + nodeId)); } }).exponentialBackoff(5); }
From source file:org.openwms.tms.routing.ActivitiMatrix.java
@Override public Action findBy(@NotNull String actionType, @NotNull Route route, LocationVO location, LocationGroupVO locationGroup) { // search explicitly... Optional<Action> prg = Optional.empty(); if (null != location) { // First explicitly search for the Location and Route prg = repository.findByRouteAndLocationKey(route, location.getCoordinate()); if (!prg.isPresent()) { // When Location is set but no Action exists, check by LocationGroup prg = findByLocationGroupByName(route, location.getLocationGroupName()); if (!prg.isPresent()) { // search the LocationGroup hierarchy the way up... prg = findByLocationGroup(route, locationGroup); if (!prg.isPresent()) { String message = String.format( "No Action found for Route [%s] on Location [%s] and LocationGroup [%s]", route.getRouteId(), location.getCoordinate(), location.getLocationGroupName()); LOGGER.info(message); throw new NoRouteException(message); }//from w w w. java 2 s . co m } } } // search for locgroup... if (!prg.isPresent()) { if (null == locationGroup) { String message = String.format( "No Action found for Route [%s] and Location [%s] without LocationGroup", route.getRouteId(), location); LOGGER.info(message); throw new NoRouteException(message); } prg = findByLocationGroup(route, locationGroup); } return prg.orElseThrow(() -> { String message = String.format("No Action found for Route [%s], Location [%s], LocationGroup [%s]", route.getRouteId(), location, locationGroup); LOGGER.info(message); return new NoRouteException(message); }); }
From source file:com.sothawo.taboo2.Taboo2UserService.java
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<User> optionalUser; synchronized (knownUsers) { optionalUser = Optional.ofNullable(knownUsers.get(username)); if (!optionalUser.isPresent()) { // reload the data from users file log.debug("loading user data"); knownUsers.clear();//from w ww . ja v a 2 s . c o m Optional.ofNullable(taboo2Configuration.getUsers()).ifPresent(filename -> { log.debug("user file: {}", filename); try { Files.lines(Paths.get(filename)).map(String::trim).filter(line -> !line.isEmpty()) .filter(line -> !line.startsWith("#")).forEach(line -> { String[] fields = line.split(":"); if (fields.length == 3) { String user = fields[0]; String hashedPassword = fields[1]; String[] roles = fields[2].split(","); if (roles.length < 1) { roles = new String[] { "undef" }; } List<GrantedAuthority> authorities = new ArrayList<>(); for (String role : roles) { authorities.add(new SimpleGrantedAuthority(role)); } knownUsers.put(user, new User(user, hashedPassword, authorities)); } }); log.debug("loaded {} user(s)", knownUsers.size()); } catch (IOException e) { log.debug("reading file", e); } }); // search again after reload optionalUser = Optional.ofNullable(knownUsers.get(username)); } } // need to return a copy as Spring security erases the password in the object after verification User user = optionalUser.orElseThrow(() -> new UsernameNotFoundException(username)); return new User(user.getUsername(), user.getPassword(), user.getAuthorities()); }
From source file:no.asgari.civilization.server.action.PlayerAction.java
/** * Choose a tech for player and store back in the pbf collection * * @param pbfId - The pbf id/*from w ww .j a v a 2s . co m*/ * @param techName - The tech * @param playerId - The id of player */ public GameLog chooseTech(String pbfId, String techName, String playerId) { Preconditions.checkNotNull(pbfId); Preconditions.checkNotNull(techName); PBF pbf = pbfCollection.findOneById(pbfId); if (!SecurityCheck.hasUserAccess(pbf, playerId)) { log.error("User with id " + playerId + " has no access to pbf " + pbf.getName()); throw new WebApplicationException(Response.Status.FORBIDDEN); } Optional<Tech> tech = pbf.getTechs().stream().filter(techToFind -> techToFind.getName().equals(techName)) .findFirst(); //if not static then this::cannotFindItem Tech chosenTech = tech.orElseThrow(PlayerAction::cannotFindItem); chosenTech.setHidden(true); chosenTech.setOwnerId(playerId); Playerhand playerhand = getPlayerhandByPlayerId(playerId, pbf); if (playerhand.getTechsChosen().contains(chosenTech)) { log.warn("Player with id " + playerId + " tried to add same tech as they had"); return null; } playerhand.getTechsChosen().add(chosenTech); pbfCollection.updateById(pbf.getId(), pbf); log.debug("Player " + playerId + " chose tech " + chosenTech.getName()); return super.createLog(chosenTech, pbfId, GameLog.LogType.TECH); }
From source file:no.asgari.civilization.server.action.PlayerAction.java
/** * Returns the remaining techs the player can choose from * * @param playerId - The player/* w w w . j a v a 2 s . c om*/ * @param pbfId - The PBF * @return */ public List<Tech> getRemaingTechsForPlayer(String playerId, String pbfId) { PBF pbf = pbfCollection.findOneById(pbfId); Optional<Playerhand> playerhandOptional = pbf.getPlayers().stream() .filter(p -> p.getPlayerId().equals(playerId)).findFirst(); Set<Tech> techsChosen = playerhandOptional.orElseThrow(PlayerAction::cannotFindPlayer).getTechsChosen(); Playerhand playerhand = playerhandOptional.get(); if (playerhand.getCivilization() != null && playerhand.getCivilization().getStartingTech() != null) { techsChosen.add(playerhandOptional.get().getCivilization().getStartingTech()); } List<Tech> techs = pbf.getTechs(); techs.removeAll(techsChosen); techs.sort(((o1, o2) -> Integer.valueOf(o1.getLevel()).compareTo(o2.getLevel()))); return techs; }
From source file:no.asgari.civilization.server.action.PlayerAction.java
public GameLog chooseSocialPolicy(String pbfId, String socialPolicyName, String playerId) { Preconditions.checkNotNull(pbfId);//from w ww . java2 s .com Preconditions.checkNotNull(socialPolicyName); PBF pbf = pbfCollection.findOneById(pbfId); if (!SecurityCheck.hasUserAccess(pbf, playerId)) { log.error("User with id " + playerId + " has no access to pbf " + pbf.getName()); throw new WebApplicationException(Response.Status.FORBIDDEN); } Optional<SocialPolicy> socialPolicyOptional = pbf.getSocialPolicies().stream() .filter(it -> it.getName().equals(socialPolicyName)).findFirst(); //if not static then this::cannotFindItem SocialPolicy socialPolicy = socialPolicyOptional.orElseThrow(PlayerAction::cannotFindItem); Playerhand playerhand = getPlayerhandByPlayerId(playerId, pbf); if (playerhand.getSocialPolicies().contains(socialPolicy)) { log.warn("Player with id " + playerId + " tried to add same social policy as they had"); return null; } if (playerhand.getSocialPolicies().stream() .anyMatch(sp -> sp.getName().equals(socialPolicy.getFlipside()))) { log.warn("Player with id " + playerId + " tried to add a social policy on same flipside"); throw new WebApplicationException(Response.Status.BAD_REQUEST); } SocialPolicy sp = new SocialPolicy(socialPolicyName); sp.setFlipside(socialPolicy.getFlipside()); sp.setOwnerId(playerId); sp.setHidden(true); playerhand.getSocialPolicies().add(sp); pbfCollection.updateById(pbf.getId(), pbf); log.debug("Player " + playerId + " chose social policy " + sp.getName()); return super.createLog(sp, pbfId, GameLog.LogType.SOCIAL_POLICY, playerId); }
From source file:nu.yona.server.subscriptions.service.UserService.java
public static String getPassword(Optional<String> password) { return password.orElseThrow(() -> new YonaException("Missing '" + Constants.PASSWORD_HEADER + "' header")); }
From source file:org.apache.hadoop.hive.kafka.TransactionalKafkaWriter.java
/** * Given a query workingDirectory as table_directory/hive_query_id/ will fetch the open transaction states. * Table directory is {@link org.apache.hadoop.hive.metastore.api.Table#getSd()#getLocation()}. * Hive Query ID is inferred from the JobConf see {@link KafkaStorageHandler#getQueryId()}. * * The path to a transaction state is as follow. * .../{@code queryWorkingDir}/{@code TRANSACTION_DIR}/{@code writerId}/{@code producerEpoch} * * The actual state is stored in the file {@code producerEpoch}. * The file contains a {@link Long} as internal producer Id and a {@link Short} as the producer epoch. * According to Kafka API, highest epoch corresponds to the active Producer, therefore if there is multiple * {@code producerEpoch} files will pick the maximum based on {@link Short::compareTo}. * * @param fs File system handler.//ww w. j a v a 2 s .c o m * @param queryWorkingDir Query working Directory, see: * {@link KafkaStorageHandler#getQueryWorkingDir(org.apache.hadoop.hive.metastore.api.Table)}. * @return Map of Transaction Ids to Pair of Kafka Producer internal ID (Long) and producer epoch (short) * @throws IOException if any of the IO operations fail. */ static Map<String, Pair<Long, Short>> getTransactionsState(FileSystem fs, Path queryWorkingDir) throws IOException { //list all current Dir final Path transactionWorkingDir = new Path(queryWorkingDir, TRANSACTION_DIR); final FileStatus[] files = fs.listStatus(transactionWorkingDir); final Set<FileStatus> transactionSet = Arrays.stream(files).filter(FileStatus::isDirectory) .collect(Collectors.toSet()); Set<Path> setOfTxPath = transactionSet.stream().map(FileStatus::getPath).collect(Collectors.toSet()); ImmutableMap.Builder<String, Pair<Long, Short>> builder = ImmutableMap.builder(); setOfTxPath.forEach(path -> { final String txId = path.getName(); try { FileStatus[] epochFiles = fs.listStatus(path); // List all the Epoch if any and select the max. // According to Kafka API recent venison of Producer with the same TxID will have greater epoch and same PID. Optional<Short> maxEpoch = Arrays.stream(epochFiles).filter(FileStatus::isFile) .map(fileStatus -> Short.valueOf(fileStatus.getPath().getName())).max(Short::compareTo); short epoch = maxEpoch.orElseThrow(() -> new RuntimeException( "Missing sub directory epoch from directory [" + path.toString() + "]")); Path openTxFileName = new Path(path, String.valueOf(epoch)); long internalId; try (FSDataInputStream inStream = fs.open(openTxFileName)) { internalId = inStream.readLong(); short fileEpoch = inStream.readShort(); if (epoch != fileEpoch) { throw new RuntimeException(String.format("Was expecting [%s] but got [%s] from path [%s]", epoch, fileEpoch, path.toString())); } } catch (IOException e) { throw new RuntimeException(e); } builder.put(txId, Pair.of(internalId, epoch)); } catch (IOException e) { throw new RuntimeException(e); } }); return builder.build(); }