@ApiOperation( value = "UnVote for LunchMenu.", notes = "Returns NO_CONTENT if unVoting was successful.") @ApiResponses( value = { @ApiResponse(code = 401, message = "Only authenticated access allowed."), @ApiResponse(code = 403, message = "Only user of ADMIN role can have access to it."), @ApiResponse(code = 404, message = "LunchMenu with such Id not found."), }) @RequestMapping(value = "/{id}/unvote", method = RequestMethod.POST) public Long unVote( @ApiParam(value = "ID of LunchMenu from DB", required = true) @PathVariable Long id, @ApiParam(value = "authentication ", hidden = true) Authentication authentication) { SpringUser springUser = (SpringUser) authentication.getPrincipal(); LOGGER.debug("Voting on LunchMenu (id={}) by {}", id, springUser.getUsername()); Optional<LunchMenu> menuSearch = lunchMenusService.getLunchMenuById(id, springUser.getRole()); menuSearch.orElseThrow( () -> new ExceptionLunchMenuNotFound(String.format("LunchMenu=%s not found.", id))); Optional<User> userSearch = usersService.getUserById(springUser.getId()); userSearch.orElseThrow( () -> new UsersController.ExceptionUserNotFound(String.format("User=%s not found.", id))); Long result = voteService.unVote(menuSearch.get(), userSearch.get()); return result; }
@Override public Person search(String login) { Optional<Person> person = persons.stream().findFirst().filter(p -> login.equals(p.getFirstName())); return person.orElseThrow( () -> new IllegalArgumentException("person with login :"******" not exists...")); }
public void playCard(Card card) { playerHand.validateHasCard(card); playerHand.remove(card); currentHand .orElseThrow(() -> new GameRuleException("Player is not participating in a hand!")) .playsCard(card, this); }
static void optionalTest() { // 不要这样,这与!=null没什么区别 Optional<String> stringOptional = Optional.of("alibaba"); if (stringOptional.isPresent()) { System.out.println(stringOptional.get().length()); } Optional<String> optionalValue = Optional.of("alibaba"); // 下面是推荐的常用操作 optionalValue.ifPresent(s -> System.out.println(s + " contains red")); // 增加到集合汇总 List<String> results = Lists.newArrayList(); optionalValue.ifPresent(results::add); // 增加到集合中,并返回操作结果 Optional<Boolean> added = optionalValue.map(results::add); // 无值的optional Optional<String> optionalString = Optional.empty(); // 不存在值,返回“No word” String result = optionalValue.orElse("No word"); // 没值,计算一个默认值 result = optionalString.orElseGet(() -> System.getProperty("user.dir")); // 无值,抛一个异常 try { result = optionalString.orElseThrow(NoSuchElementException::new); } catch (Throwable t) { t.getCause(); } }
@Override public RequestHandler getHandler(Class<? extends Request> request) throws HandlerNotFoundException { log.debug("getHandler for class: " + request.getName()); Optional<RequestHandler> maybeHandler = Optional.ofNullable(handlerMapping.get(request.getName()).getRequestHandlerInstance()); return maybeHandler.orElseThrow(() -> new HandlerNotFoundException(request)); }
private RemoteDeflectorResource getDeflectorResource() { final Node master = findMasterNode(); final Function<String, Optional<RemoteDeflectorResource>> remoteInterfaceProvider = createRemoteInterfaceProvider(RemoteDeflectorResource.class); final Optional<RemoteDeflectorResource> deflectorResource = remoteInterfaceProvider.apply(master.getNodeId()); return deflectorResource.orElseThrow( () -> new InternalServerErrorException("Unable to get remote deflector resource.")); }
public void tradingCards(List<Card> cards) { if (!trading) { throw new GameRuleException("Trading not allowed at this time."); } cards.stream().forEach(playerHand::validateHasCard); playerHand.removeAll(cards); trading = false; currentHand .orElseThrow(() -> new GameRuleException("Player is not participating in a hand!")) .tradesCard(this, cards); }
@Test public void _07_옵션_다루기() { final Optional<String> optional = words.stream().filter(w -> w.contains("red")).findFirst(); try { optional.ifPresent( v -> { throw new RuntimeException(); }); assert false; // 이 행은 실행되면 안됨. } catch (RuntimeException e) { } // 비어있는 경우는 실행되지 않음. Optional.empty() .ifPresent( v -> { throw new RuntimeException(); }); Set<String> results = new HashSet<>(); optional.ifPresent(results::add); assertThat(results.contains("tired"), is(true)); // 실행 결과를 받고 싶은 경우에는 map 사용. results = new HashSet<>(); Optional<Boolean> added = optional.map(results::add); assertThat(added, is(Optional.of(Boolean.TRUE))); // 대상이 빈경우에는 empty Optional 반환 Optional<Boolean> a = Optional.empty().map(v -> true); assertThat(a.isPresent(), is(false)); Optional<String> emptyOptional = Optional.empty(); // orElse로 기본값 지정 가능 String result = emptyOptional.orElse("기본값"); assertThat(result, is("기본값")); // 기본값 생성하는 코드 호출 가능 result = emptyOptional.orElseGet(() -> System.getProperty("user.dir")); assertThat(result, is(System.getProperty("user.dir"))); // 값이 없는 경우 예외 던지기 try { emptyOptional.orElseThrow(NoSuchElementException::new); assert false; } catch (NoSuchElementException e) { } }
public SocketHint<T> build() throws NoSuchElementException { if (!view.equals(View.NONE)) { initialValueSupplier.orElseThrow( () -> new NoSuchElementException( "A View other than `NONE` was supplied but not an initial value")); } return new SocketHint<>( this.type, identifier.orElseThrow( () -> new NoSuchElementException("The identifier was not supplied")), initialValueSupplier, view, domain); }
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { Optional<byte[]> data = getResourceAsBytes(name.replace('.', '/') + ".class"); byte[] bb = data.orElseThrow(() -> new ClassNotFoundException(name)); { int idx = name.lastIndexOf('.'); if (idx != -1) { String pkgname = name.substring(0, idx); try { definePackage(pkgname, null, null, null, null, null, null, null); } catch (IllegalArgumentException e) { // package was already defined by parallel thred, // swallow. } } } return defineClass(name, bb, 0, bb.length); }
@Override public void perform(InputSocket<?>[] inputs, OutputSocket<?>[] outputs, Optional<?> data) { final Mat[] dataArray = (Mat[]) data.orElseThrow(() -> new IllegalStateException("Data was not provided")); final Mat input = ((InputSocket<Mat>) inputs[0]).getValue().get(); final List<Number> channel1 = ((InputSocket<List<Number>>) inputs[1]).getValue().get(); final List<Number> channel2 = ((InputSocket<List<Number>>) inputs[2]).getValue().get(); final List<Number> channel3 = ((InputSocket<List<Number>>) inputs[3]).getValue().get(); final OutputSocket<Mat> outputSocket = (OutputSocket<Mat>) outputs[0]; final Mat output = outputSocket.getValue().get(); // Intentionally 1, 3, 2. This maps to the HLS open cv expects final Scalar lowScalar = new Scalar( channel1.get(0).doubleValue(), channel3.get(0).doubleValue(), channel2.get(0).doubleValue(), 0); final Scalar highScalar = new Scalar( channel1.get(1).doubleValue(), channel3.get(1).doubleValue(), channel2.get(1).doubleValue(), 0); final Mat low = reallocateMatIfInputSizeOrWidthChanged(dataArray, 0, lowScalar, input); final Mat high = reallocateMatIfInputSizeOrWidthChanged(dataArray, 1, highScalar, input); final Mat hls = dataArray[2]; try { cvtColor(input, hls, COLOR_BGR2HLS); inRange(hls, low, high, output); outputSocket.setValue(output); } catch (RuntimeException e) { logger.log(Level.WARNING, e.getMessage(), e); } }
/** * @param directoryWithUnpackedFiles Directory with unpacked files (should include BBIs and DBF) * @return Map of BBI files names to their corresponding verifications * @throws SQLException * @throws ClassNotFoundException * @throws FileNotFoundException * @implNote Uses sqlite to open DBF */ private Map<String, Map<String, String>> getVerificationMapFromUnpackedFiles( File directoryWithUnpackedFiles) throws SQLException, ClassNotFoundException, FileNotFoundException { Map<String, Map<String, String>> bbiFilesToVerification = new LinkedHashMap<>(); Map<String, String> verificationMap; Optional<File> foundDBFile = FileUtils.listFiles(directoryWithUnpackedFiles, dbfExtensions, true).stream().findFirst(); File dbFile = foundDBFile.orElseThrow(() -> new FileNotFoundException("DBF not found")); Class.forName("org.sqlite.JDBC"); try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile)) { Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("SELECT * FROM Results"); while (rs.next()) { verificationMap = new LinkedHashMap<>(); verificationMap.put(Constants.VERIFICATION_ID, rs.getString("Id_pc")); verificationMap.put(Constants.PROVIDER, rs.getString("Customer")); verificationMap.put(Constants.DATE, rs.getString("Date")); verificationMap.put(Constants.COUNTER_NUMBER, rs.getString("CounterNumber")); verificationMap.put(Constants.COUNTER_SIZE_AND_SYMBOL, rs.getString("Type")); verificationMap.put(Constants.YEAR, rs.getString("Year")); verificationMap.put(Constants.STAMP, rs.getString("Account")); verificationMap.put(Constants.LAST_NAME, rs.getString("Surname")); verificationMap.put(Constants.FIRST_NAME, rs.getString("Name")); verificationMap.put(Constants.MIDDLE_NAME, rs.getString("Middlename")); verificationMap.put(Constants.PHONE_NUMBER, rs.getString("TelNumber")); verificationMap.put(Constants.REGION, rs.getString("District")); verificationMap.put(Constants.CITY, rs.getString("City")); verificationMap.put(Constants.STREET, rs.getString("Street")); verificationMap.put(Constants.BUILDING, rs.getString("Building")); verificationMap.put(Constants.FLAT, rs.getString("Apartment")); bbiFilesToVerification.put(rs.getString("FileNumber"), verificationMap); } } return bbiFilesToVerification; }
public BitField getBitField() { return bitField.orElseThrow( () -> new IllegalStateException("Peer is not linked to any torrent yet")); }
private BillOfMaterials findbillOfMaterialsById(String id) { Optional<BillOfMaterials> result = repository.findOne(id); return result.orElseThrow(() -> new NotFoundException(id)); }
private Todo findTodoById(String id) { Optional<Todo> result = repository.findOne(id); return result.orElseThrow(() -> new TodoNotFoundException(id)); }
@Override public String getPage(Optional<FileItem[]> request) throws ResponseStatusNotice { String assignment = null; String course = null; String onyen = null; Path fileLoc = null; String ip = null; String uid = null; String firstName = null; String lastName = null; String pid = null; String year = null; String season = null; try { IConfigReader config = new ConfigReader("./config/config.properties"); String username = config.getString("database.username").orElseThrow(IllegalArgumentException::new); String password = config.getString("database.password").orElseThrow(IllegalArgumentException::new); String url = config.getString("database.url").orElseThrow(IllegalArgumentException::new); if (config.getBoolean("database.ssl", false).get()) { url += "?verifyServerCertificate=true&useSSL=true&requireSSL=true"; } try (IDatabaseReader dr = new DatabaseReader(username, password, "jdbc:" + url) {}) { String[] termParts = dr.readCurrentTerm(); year = termParts[0]; season = termParts[1]; } } catch (IOException | SQLException ex) { LOG.log(Level.SEVERE, null, ex); } FileItem[] args = request.orElseThrow( () -> { System.out.println("broken"); return new ResponseStatusNotice(HttpStatus.SC_BAD_REQUEST); }); for (FileItem arg : args) { switch (arg.getFieldName()) { case "assignment": assignment = arg.getString(); break; case "course": course = arg.getString(); break; case "onyen": onyen = arg.getString(); break; case "file": String name = arg.getName(); int lastDot = name.lastIndexOf('.'); String ext = lastDot < 0 ? "" : name.substring(lastDot); try { Path file = Files.createTempFile("grader-submission-", ext); try (BufferedOutputStream bos = new BufferedOutputStream( Files.newOutputStream(file, StandardOpenOption.TRUNCATE_EXISTING)); BufferedInputStream bis = new BufferedInputStream(arg.getInputStream())) { byte[] bytes = new byte[1024]; int available = bis.available(); while (available > 0) { if (available > 1024) { bis.read(bytes); bos.write(bytes, 0, 1024); } else { bytes = new byte[available]; bis.read(bytes); bos.write(bytes, 0, available); } available = bis.available(); } } fileLoc = file; } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); throw new ResponseStatusNotice(HttpStatus.SC_INTERNAL_SERVER_ERROR); } break; case "ip": ip = arg.getString(); break; case "uid": uid = arg.getString(); try { IConfigReader config = new ConfigReader("./config/config.properties"); String username = config.getString("database.username").orElseThrow(IllegalArgumentException::new); String password = config.getString("database.password").orElseThrow(IllegalArgumentException::new); String url = config.getString("database.url").orElseThrow(IllegalArgumentException::new); if (config.getBoolean("database.ssl", false).get()) { url += "?verifyServerCertificate=true&useSSL=true&requireSSL=true"; } try (IDatabaseReader dr = new DatabaseReader(username, password, "jdbc:" + url) {}) { String[] nameParts = dr.readNameForUID(uid); firstName = nameParts[0]; lastName = nameParts[1]; } } catch (IOException | SQLException ex) { LOG.log(Level.SEVERE, null, ex); } break; case "firstName": firstName = arg.getString(); break; case "lastName": lastName = arg.getString(); break; case "pid": pid = arg.getString(); break; case "year": year = arg.getString(); break; case "season": season = arg.getString(); break; } } int missing = 0; if (assignment == null) { missing += 1; } if (course == null) { missing += 2; } if (onyen == null) { missing += 4; } if (fileLoc == null) { missing += 8; } if (ip == null) { missing += 16; } if (uid == null) { missing += 32; } if (firstName == null) { missing += 64; } if (lastName == null) { missing += 128; } if (assignment == null || course == null || onyen == null || fileLoc == null || ip == null || uid == null || firstName == null || lastName == null) { LOG.log(Level.WARNING, "Missing argument. Code: {0}", missing); throw new ResponseStatusNotice(HttpStatus.SC_BAD_REQUEST); } String uuid = submit(assignment, course, onyen, fileLoc, ip, uid, firstName, lastName, pid, year, season); FileItem uuidItem = new URLEncodedPostFileItem("id", uuid, Charset.defaultCharset().name()); Optional<FileItem[]> retParam = Optional.of(new FileItem[] {uuidItem}); int sleepCount = 0; while (GradePageManager.getNumber(uuid).orElse(-2) == -1 && sleepCount < 10) { try { sleepCount++; Thread.sleep(50); } catch (InterruptedException ex) { LOG.log(Level.SEVERE, null, ex); sleepCount = 10; } } return GradePageManager.IN_PROGRESS_PAGE_GENERATOR.getPage(retParam); }
@Override public void deleteUser(String username) { Optional<User> userOptional = this.userRepository.findByUsername(username); User user = userOptional.orElseThrow( () -> new UsernameDoesNotExistException("Username " + username + " does not exist")); this.userRepository.delete(user); }