Exemple #1
0
  public FManager() {

    loaded =
        Collections.synchronizedSet(
            new HashSet<File>() {
              @Override
              public boolean add(File e) {
                synchronized (loadedObserver) {
                  loadedObserver.setChanged();
                  loadedObserver.notifyObservers(e);
                }
                return super.add(e);
              }
            });
    pending = Collections.synchronizedSet(new HashSet<>());
    filterChange = new InvokeObservable(this);
    loadedObserver = new InvokeObservable(this);
    activityObserver = new InvokeObservable(this);
    autoLoad = true;
    verbose = true;
    activity = IDLE;
    stdErr = Optional.empty();
    stdOut = Optional.empty();
    FPC fpcObject = null;
    try {
      fpcObject = new FPC(DataDetails.class);
      fpcObject.onFilterChange(this::setActiveFilter);
    } catch (Exception ex) {
      Logger.getLogger(FManager.class.getName()).log(Level.SEVERE, null, ex);
    }
    fpc = fpcObject;
    checkProperties();
  }
 @RequestMapping(value = "/events/check", method = POST)
 public ValidationResult validateEvent(
     @RequestBody EventModification eventModification, Errors errors) {
   ValidationResult base =
       validateEventHeader(Optional.<Event>empty(), eventModification, errors)
           .or(validateEventPrices(Optional.<Event>empty(), eventModification, errors))
           .or(
               eventModification
                   .getAdditionalServices()
                   .stream()
                   .map(as -> validateAdditionalService(as, eventModification, errors))
                   .reduce(ValidationResult::or)
                   .orElse(ValidationResult.success()));
   AtomicInteger counter = new AtomicInteger();
   return base.or(
           eventModification
               .getTicketCategories()
               .stream()
               .map(
                   c ->
                       validateCategory(
                           c, errors, "ticketCategories[" + counter.getAndIncrement() + "]."))
               .reduce(ValidationResult::or)
               .orElse(ValidationResult.success()))
       .or(validateAdditionalTicketFields(eventModification.getTicketFields(), errors));
 }
  @Override
  public List<Catalog> fineEpisodesBySeriesAndSeason(int id, int season) {
    Optional<Catalog> series = findBySeriesId(id);
    List<Catalog> episodes = getSeriesEpisodes(series.get(), season);

    return episodes;
  }
Exemple #4
0
 public static Container setup() throws IOException {
   Properties properties = new Properties();
   File revProps = new File("revenj.properties");
   if (revProps.exists() && revProps.isFile()) {
     properties.load(new FileReader(revProps));
   } else {
     String location = System.getProperty("revenj.properties");
     if (location != null) {
       revProps = new File(location);
       if (revProps.exists() && revProps.isFile()) {
         properties.load(new FileReader(revProps));
       } else {
         throw new IOException(
             "Unable to find revenj.properties in alternative location. Searching in: "
                 + revProps.getAbsolutePath());
       }
     } else {
       throw new IOException(
           "Unable to find revenj.properties. Searching in: " + revProps.getAbsolutePath());
     }
   }
   String plugins = properties.getProperty("revenj.pluginsPath");
   File pluginsPath = null;
   if (plugins != null) {
     File pp = new File(plugins);
     pluginsPath = pp.isDirectory() ? pp : null;
   }
   return setup(
       dataSource(properties),
       properties,
       Optional.ofNullable(pluginsPath),
       Optional.ofNullable(Thread.currentThread().getContextClassLoader()));
 }
  @Test
  @Transactional
  public void testRegisterAdminIsIgnored() throws Exception {
    UserDTO u =
        new UserDTO(
            "badguy", // login
            "password", // password
            "Bad", // firstName
            "Guy", // lastName
            "*****@*****.**", // e-mail
            true, // activated
            "en", // langKey
            new HashSet<>(
                Arrays.asList(
                    AuthoritiesConstants.ADMIN)) // <-- only admin should be able to do that
            );

    restMvc
        .perform(
            post("/api/register")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(u)))
        .andExpect(status().isCreated());

    Optional<User> userDup = userRepository.findOneByLogin("badguy");
    assertThat(userDup.isPresent()).isTrue();
    assertThat(userDup.get().getAuthorities())
        .hasSize(1)
        .containsExactly(authorityRepository.findOne(AuthoritiesConstants.USER));
  }
Exemple #6
0
 public Optional<Response> get(Optional<Request> request) {
   if (!valid) {
     Logger.error("CANNOT GET! NO VALID CONNECTION");
     return Optional.empty();
   }
   Response response = new Response();
   if (request.isPresent()) {
     Request r = request.get();
     response.key = r.key;
     response.table = r.table;
     try {
       final Table htable = connection.getTable(TableName.valueOf(r.table));
       Result result = htable.get(new Get(r.key));
       if (result == null || result.isEmpty()) {
         return Optional.empty();
       }
       r.columns.forEach(
           c ->
               response.columns.add(
                   new Request.Column(
                       c.family,
                       c.qualifier,
                       result.getValue(c.family.getBytes(), c.qualifier.getBytes()))));
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return Optional.of(response);
 }
  public RefsModel(
      @NotNull Map<VirtualFile, CompressedRefs> refs,
      @NotNull Set<Integer> heads,
      @NotNull VcsLogStorage hashMap,
      @NotNull Map<VirtualFile, VcsLogProvider> providers) {
    myRefs = refs;
    myHashMap = hashMap;

    myBestRefForHead = new TIntObjectHashMap<>();
    myRootForHead = new TIntObjectHashMap<>();
    for (int head : heads) {
      CommitId commitId = myHashMap.getCommitId(head);
      if (commitId != null) {
        VirtualFile root = commitId.getRoot();
        myRootForHead.put(head, root);
        Optional<VcsRef> bestRef =
            myRefs
                .get(root)
                .refsToCommit(head)
                .stream()
                .min(providers.get(root).getReferenceManager().getBranchLayoutComparator());
        if (bestRef.isPresent()) {
          myBestRefForHead.put(head, bestRef.get());
        } else {
          LOG.warn("No references at head " + commitId);
        }
      }
    }
  }
Exemple #8
0
 /** POST /account -> update the current user information. */
 @RequestMapping(
     value = "/account",
     method = RequestMethod.POST,
     produces = MediaType.APPLICATION_JSON_VALUE)
 @Timed
 public ResponseEntity<String> saveAccount(@RequestBody UserDTO userDTO) {
   Optional<User> existingUser = userRepository.findOneByEmail(userDTO.getEmail());
   if (existingUser.isPresent()
       && (!existingUser.get().getLogin().equalsIgnoreCase(userDTO.getLogin()))) {
     return ResponseEntity.badRequest()
         .headers(
             HeaderUtil.createFailureAlert(
                 "user-management", "emailexists", "Email already in use"))
         .body(null);
   }
   return userRepository
       .findOneByLogin(SecurityUtils.getCurrentUser().getUsername())
       .map(
           u -> {
             userService.updateUserInformation(
                 userDTO.getFirstName(),
                 userDTO.getLastName(),
                 userDTO.getEmail(),
                 userDTO.getLangKey());
             return new ResponseEntity<String>(HttpStatus.OK);
           })
       .orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
 }
Exemple #9
0
  @Override
  public Optional<Suggestion> requestPlayerSuggestion(Player player, Room room) {
    char userWantsToMakeSuggestion = '\0';

    while (userWantsToMakeSuggestion != 'Y' && userWantsToMakeSuggestion != 'N') {
      this.out.println("Do you want to make an suggestion (Y/N)?");
      this.out.println("Your cards are: " + player.cards);
      userWantsToMakeSuggestion = this.scanner.next().charAt(0);
    }

    if (userWantsToMakeSuggestion == 'Y') {
      this.out.printf("You suggest it was done in the %s, by: \n", room);

      Stream<String> suspects =
          Arrays.stream(CluedoCharacter.values()).map(CluedoCharacter::toString);
      CluedoCharacter suspect = CluedoCharacter.values()[this.selectOptionFromList(suspects)];

      this.out.println("with the ");

      Stream<String> weapons = Arrays.stream(Weapon.values()).map(Weapon::toString);
      Weapon weapon = Weapon.values()[this.selectOptionFromList(weapons)];

      return Optional.of(new Suggestion(suspect, weapon, room));

    } else {
      return Optional.empty();
    }
  }
  /**
   * Returns the target types that need to have conversion. The types contain first as many
   * constructor parameter types as we have and then the types of properties of object as given by
   * names of result-set.
   */
  @NotNull
  private static Optional<List<Type>> findTargetTypes(
      @NotNull Constructor<?> ctor, @NotNull List<String> resultSetColumns) {
    List<Type> constructorParameterTypes = asList(ctor.getGenericParameterTypes());

    int constructorParameterCount = constructorParameterTypes.size();

    if (constructorParameterCount > resultSetColumns.size()) {
      // We don't have enough columns in ResultSet to instantiate this constructor, discard it.
      return Optional.empty();

    } else if (constructorParameterCount == resultSetColumns.size()) {
      // We have exactly enough column in ResultSet. Use the constructor as it is.
      return Optional.of(constructorParameterTypes);

    } else {
      // Get the types of remaining properties
      ArrayList<Type> result = new ArrayList<>(resultSetColumns.size());
      result.addAll(constructorParameterTypes);

      List<String> propertyNames =
          resultSetColumns.subList(constructorParameterCount, resultSetColumns.size());
      for (String name : propertyNames) {
        Type type = PropertyAccessor.findPropertyType(ctor.getDeclaringClass(), name).orElse(null);
        if (type != null) result.add(type);
        else return Optional.empty();
      }

      return Optional.of(result);
    }
  }
  @Override
  protected boolean specificValidate(SymbolResolver resolver, ErrorCollector errorCollector) {
    if (baseType.isPresent()) {
      if (!baseType.get().isReferenceTypeUsage()
          || !baseType.get().asReferenceTypeUsage().isClass(resolver)) {
        errorCollector.recordSemanticError(
            baseType.get().getPosition(), "Only classes can be extended");
        return false;
      }
    }

    for (TypeUsageNode typeUsage : interfaces) {
      if (!typeUsage.isReferenceTypeUsage()
          || !typeUsage.asReferenceTypeUsage().isInterface(resolver)) {
        errorCollector.recordSemanticError(
            typeUsage.getPosition(), "Only interfaces can be implemented");
        return false;
      }
    }

    if (getExplicitConstructors().size() > 1) {
      for (TurinTypeContructorDefinitionNode contructorDefinition : getExplicitConstructors()) {
        errorCollector.recordSemanticError(
            contructorDefinition.getPosition(), "At most one explicit constructor can be defined");
      }
      return false;
    }

    return super.specificValidate(resolver, errorCollector);
  }
Exemple #12
0
  @Override
  public Board.Path requestPlayerMove(
      Player player, Board board, Set<Location<Integer>> blockedLocations, int distance) {
    this.out.printf("Enter a move of length %d.\n", distance);
    this.out.printf(
        "Moves are in the format UDLR, where such a move would mean go up, then down, then left, then right.\n\n");

    List<Direction> moveSequence = new ArrayList<>();

    String charSequence = this.scanner.next();

    if (charSequence.length() != distance) {
      return this.requestPlayerMove(player, board, blockedLocations, distance);
    }

    for (int i = 0; i < charSequence.length(); i++) {
      char c = charSequence.charAt(i);
      Direction dir = Direction.fromCharacter(c);
      if (dir == null) {
        return this.requestPlayerMove(player, board, blockedLocations, distance);
      }
      moveSequence.add(dir);
    }

    Optional<Board.Path> path =
        board.directionsToPath(player.location(), moveSequence, blockedLocations);

    return path.isPresent()
        ? path.get()
        : this.requestPlayerMove(player, board, blockedLocations, distance);
  }
  void renameTrack() {
    if (interfaceDisabled) return;
    Playlist p = getSelectedPlaylist();
    if (p == null) return;
    Track t = getSelectedTrack();
    if (t == null) return;

    TextInputDialog dialog = new TextInputDialog(t.getTitle());
    dialog.setTitle(res.getString("rename_track"));
    dialog.setHeaderText(res.getString("rename_track"));
    dialog.setContentText(res.getString("enter_new_title"));
    dialog.getDialogPane().getStylesheets().add("/styles/dialogs.css");
    ((Stage) dialog.getDialogPane().getScene().getWindow()).getIcons().addAll(logoImages);
    Optional<String> result = dialog.showAndWait();
    result.ifPresent(
        title -> {
          if (StringUtils.isEmpty(title)) {
            return;
          }
          Cache.renameTrack(t, p, title);
          Platform.runLater(
              () -> {
                loadSelectedPlaylist();
              });
        });
  }
 private Optional<MediaType> getContentType(HttpServletRequest request) {
   String contentType = request.getContentType();
   if (contentType != null) {
     return Optional.of(MediaType.parseMediaType(contentType));
   }
   return Optional.empty();
 }
  /** Unit tests */
  public static void main(String[] args) {
    final Tree targetTree =
        tree(
            1,
            tree(
                2,
                tree(3, tree(4), tree(3, tree(4), tree(5))),
                tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree()))),
            tree(12));

    System.out.println("    Test Pattern");
    checkPattern(targetTree, tree(), Optional.of(targetTree));

    checkPattern(targetTree, tree(9), Optional.of(tree(9)));
    checkPattern(targetTree, tree(12), Optional.of(tree(12)));
    checkPattern(targetTree, tree(13), Optional.empty());
    checkPattern(targetTree, tree(1), Optional.of(targetTree));

    checkPattern(targetTree, tree(2, tree(3), tree(5)), Optional.of(targetTree.left()));
    checkPattern(
        targetTree, tree(3, tree(4), tree(5)), Optional.of(targetTree.left().left().right()));
    checkPattern(
        targetTree, tree(6, tree(), tree(8)), Optional.of(targetTree.left().right().left()));
    checkPattern(targetTree, tree(6, tree(), tree(7)), Optional.empty());

    checkPattern(
        targetTree,
        tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree())),
        Optional.of(targetTree.left().right()));
  }
  /** @return True if the backup location was created successfully */
  private boolean handleBackupLocation() {

    try {
      // Locate the installation directory
      File applicationDataDirectory = InstallationManager.getOrCreateApplicationDataDirectory();

      log.debug("Cloud backup...");
      File cloudBackupLocation = null;
      if (Configurations.currentConfiguration != null) {
        String cloudBackupLocationString =
            Configurations.currentConfiguration.getAppearance().getCloudBackupLocation();
        if (cloudBackupLocationString != null && !"".equals(cloudBackupLocationString)) {
          cloudBackupLocation = new File(cloudBackupLocationString);
        }
      }

      log.debug("Backup manager...");
      // Initialise backup (must be before Bitcoin network starts and on the main thread)
      BackupManager.INSTANCE.initialise(
          applicationDataDirectory,
          cloudBackupLocation == null ? Optional.<File>absent() : Optional.of(cloudBackupLocation));

      return true;

    } catch (Exception e) {
      log.error("Failed to create backup location.", e);
    }

    // Must have failed to be here
    return false;
  }
  @Override
  public void unpublish(String id, Handler<AsyncResult<Void>> resultHandler) {
    Objects.requireNonNull(id);
    if (resultHandler == null) {
      resultHandler = (v) -> {};
    }
    Handler<AsyncResult<Void>> handler = resultHandler;

    acquireLock(
        resultHandler,
        lock ->
            getRegistry(
                lock,
                handler,
                map ->
                    vertx.<Void>executeBlocking(
                        future -> {
                          Optional<JsonObject> match =
                              map.values()
                                  .stream()
                                  .filter(reg -> reg.getString("service.id").equals(id))
                                  .findFirst();
                          if (match.isPresent()) {
                            map.remove(match.get().getString("service.address"));
                            future.complete();
                          } else {
                            future.fail("Service registration not found");
                          }
                        },
                        result -> {
                          handler.handle(result);
                          lock.release();
                        })));
  }
Exemple #18
0
  @RequestMapping(
      value = "/api/broadcast",
      method = RequestMethod.POST,
      produces = "application/json")
  public List<BroadcastGroup> broadcastMessage(
      @RequestParam("name") String name,
      @RequestParam("set") Integer setId,
      @RequestParam("message") String message) {
    BroadcastGroup group = broadcastRepository.findOne(name);
    if (group != null) {
      Optional<BroadcastSet> setOptional =
          group.getBroadcastSets().stream().filter(set -> set.getId() == setId).findFirst();
      if (setOptional.isPresent()) {
        BroadcastSet set = setOptional.get();
        set.getMessages().add(new BroadcastMessage(message, new Date()));
        broadcastRepository.save(group);
        executorService.execute(
            () -> {
              set.getUsers()
                  .forEach(
                      userId -> {
                        SlackUser user = session.findUserById(userId);
                        session.sendMessageToUser(user, message, null);
                      });
            });
      } else {
        log.error("Can't find set with id {}", setId);
      }

    } else {
      log.error("Can't find group with name {}", name);
    }
    return broadcastRepository.findAll();
  }
Exemple #19
0
  private Map<String, Function> getByAssignable(
      Map<String, Map<String, Function>> cache,
      Map<Class, Map<String, Map<String, Function>>> rawMap,
      Class clazz,
      String name) {

    Set<Class> classes = rawMap.keySet();
    Optional<Class> candidate =
        classes.stream().findFirst().filter(it -> it.isAssignableFrom(clazz));

    if (candidate.isPresent()) {
      Class candidateClass = candidate.get();
      Map<String, Map<String, Function>> namedFunctionMap = rawMap.get(candidateClass);

      Map<String, Function> functionMap = namedFunctionMap.get(name);
      if (functionMap != null) {
        String key = clazz + "#" + name;
        cache.put(key, functionMap);

        return functionMap;
      }
    }

    return null;
  }
  /**
   * Perform one setter operation with the provided value.
   *
   * @param instance Instance of class under test to operate on.
   * @param property Property being tested
   * @param field Field being tested
   * @param testVal Test value to use.
   * @return Optional that will contain an error message if the test failed, otherwise empty.
   * @throws InvocationTargetException
   * @throws IllegalAccessException
   */
  private Optional<String> testSetterWithVal(
      T instance, PropertyDescriptor property, Field field, Object testVal)
      throws InvocationTargetException, IllegalAccessException {

    Objects.requireNonNull(instance, "Instance of target class required.");
    boolean status = true;
    property.getWriteMethod().invoke(instance, testVal);

    Object expected, actual;
    if (property.getPropertyType().isPrimitive()) {
      expected = String.valueOf(testVal);
      actual = String.valueOf(field.get(instance));
      status = expected.equals(actual);
    } else {

      expected = testVal;
      actual = field.get(instance);

      if (expected == null) {
        status = actual == null;
      } else {
        status = expected.equals(actual);
      }
    }
    if (status == false) {
      return Optional.of(
          String.format(
              "Failed during setter test: %s.  Expected: %s  Actual: %s",
              property.getWriteMethod(), expected, actual));
    }
    return Optional.empty();
  }
  /**
   * PUT /users : Updates an existing User.
   *
   * @param managedUserVM the user to update
   * @return the ResponseEntity with status 200 (OK) and with body the updated user, or with status
   *     400 (Bad Request) if the login or email is already in use, or with status 500 (Internal
   *     Server Error) if the user couldn't be updated
   */
  @PutMapping("/users")
  @Timed
  @Secured(AuthoritiesConstants.ADMIN)
  public ResponseEntity<ManagedUserVM> updateUser(@RequestBody ManagedUserVM managedUserVM) {
    log.debug("REST request to update User : {}", managedUserVM);
    Optional<User> existingUser = userRepository.findOneByEmail(managedUserVM.getEmail());
    if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) {
      return ResponseEntity.badRequest()
          .headers(
              HeaderUtil.createFailureAlert(
                  "userManagement", "emailexists", "E-mail already in use"))
          .body(null);
    }
    existingUser = userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase());
    if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) {
      return ResponseEntity.badRequest()
          .headers(
              HeaderUtil.createFailureAlert("userManagement", "userexists", "Login already in use"))
          .body(null);
    }
    userService.updateUser(
        managedUserVM.getId(),
        managedUserVM.getLogin(),
        managedUserVM.getFirstName(),
        managedUserVM.getLastName(),
        managedUserVM.getEmail(),
        managedUserVM.isActivated(),
        managedUserVM.getLangKey(),
        managedUserVM.getAuthorities());

    return ResponseEntity.ok()
        .headers(HeaderUtil.createAlert("userManagement.updated", managedUserVM.getLogin()))
        .body(new ManagedUserVM(userService.getUserWithAuthorities(managedUserVM.getId())));
  }
 @Override
 @Transactional
 public UserDetails loadUserByUsername(final String login) {
   log.debug("Authenticating {}", login);
   String lowercaseLogin = login.toLowerCase();
   Optional<User> userFromDatabase = userRepository.findOneByLogin(lowercaseLogin);
   return userFromDatabase
       .map(
           user -> {
             if (!user.getActivated()) {
               throw new UserNotActivatedException(
                   "User " + lowercaseLogin + " was not activated");
             }
             List<GrantedAuthority> grantedAuthorities =
                 user.getAuthorities()
                     .stream()
                     .map(authority -> new SimpleGrantedAuthority(authority.getName()))
                     .collect(Collectors.toList());
             return new org.springframework.security.core.userdetails.User(
                 lowercaseLogin, user.getPassword(), grantedAuthorities);
           })
       .orElseThrow(
           () ->
               new UsernameNotFoundException(
                   "User " + lowercaseLogin + " was not found in the " + "database"));
 }
 private static Optional<PredictionBatch> asOptional(PredictionBatch pb) {
   if (pb == null || pb.predictions.isEmpty()) {
     return Optional.empty();
   } else {
     return Optional.of(pb);
   }
 }
  @Override
  public void validate(
      final String key,
      final long totalOccurrences,
      final double percentContaining,
      final String... types) {
    final Optional<VarietyEntry> first =
        entries.stream().filter(entry -> entry.getKey().equals(key)).findFirst();
    if (!first.isPresent()) {
      Assert.fail("Entry with key '" + key + "' not found in variety results");
    }

    final VarietyEntry varietyEntry = first.get();
    Assert.assertEquals(
        "Failed to verify types of key " + key,
        new HashSet<>(Arrays.asList(types)),
        varietyEntry.getTypes());
    Assert.assertEquals(
        "Failed to verify total occurrences of key " + key,
        totalOccurrences,
        varietyEntry.getTotalOccurrences());
    Assert.assertEquals(
        "Failed to verify percents of key " + key,
        percentContaining,
        varietyEntry.getPercentContaining(),
        1e-15); // TODO: precision?
  }
  @Test
  public void _03_filter() {
    Stream<String> longWords = words.stream().filter(w -> w.length() > 12);

    Optional<String> first = longWords.findFirst();
    assertThat(first.isPresent(), is(true));
    assertThat(first.get(), is("conversations"));
  }
Exemple #26
0
 @Override
 public Card deal() {
   Optional<Card> nextCard = cards.stream().findFirst();
   if (nextCard.isPresent()) {
     cards.remove(nextCard.get());
   }
   return nextCard.get();
 }
    private Optional<String> getNameToken(int i) {

      if (i >= 0 && i < names.size()) {
        return Optional.ofNullable(names.get(i));
      }

      return Optional.empty();
    }
 public void setCapability(int engineNumber, double capability) {
   Optional<HostCapability> c1 =
       (capabilitySet.stream().filter((c) -> c.geteNum() == engineNumber).findFirst());
   if (c1.isPresent()) {
     c1.get().setCapability(capability);
   }
   capabilitySet.add(new HostCapability(this, engineNumber));
 }
Exemple #29
0
 public Optional<Put> getPut() {
   if (valid()) {
     Put p = new Put(key);
     columns.forEach(c -> p.addColumn(c.family.getBytes(), c.qualifier.getBytes(), c.value));
     return Optional.of(p);
   }
   return Optional.empty();
 }
Exemple #30
0
 @Test
 public void singleNullValue() {
   when(cursor.getCount()).thenReturn(1);
   when(cursor.moveToFirst()).thenReturn(true);
   Fetcher fetcher = Fetcher.of(cursor);
   Optional<String> result = fetcher.toValue(Converter.STRING);
   assertFalse("We should not have a value", result.isPresent());
 }