Esempio n. 1
1
  @SuppressWarnings("unchecked")
  public ResidentConverter(List<ObjectConverter.ColumnInfo> allColumns) throws java.io.IOException {
    Optional<ObjectConverter.ColumnInfo> column;

    final java.util.List<ObjectConverter.ColumnInfo> columns =
        allColumns
            .stream()
            .filter(
                it ->
                    "mixinReference".equals(it.typeSchema) && "Resident_entity".equals(it.typeName))
            .collect(Collectors.toList());
    columnCount = columns.size();

    readers = new ObjectConverter.Reader[columnCount];
    for (int i = 0; i < readers.length; i++) {
      readers[i] = (instance, rdr, ctx) -> StringConverter.skip(rdr, ctx);
    }

    final java.util.List<ObjectConverter.ColumnInfo> columnsExtended =
        allColumns
            .stream()
            .filter(
                it ->
                    "mixinReference".equals(it.typeSchema)
                        && "-ngs_Resident_type-".equals(it.typeName))
            .collect(Collectors.toList());
    columnCountExtended = columnsExtended.size();

    readersExtended = new ObjectConverter.Reader[columnCountExtended];
    for (int i = 0; i < readersExtended.length; i++) {
      readersExtended[i] = (instance, rdr, ctx) -> StringConverter.skip(rdr, ctx);
    }

    column = columns.stream().filter(it -> "id".equals(it.columnName)).findAny();
    if (!column.isPresent())
      throw new java.io.IOException(
          "Unable to find 'id' column in mixinReference Resident_entity. Check if DB is in sync");
    __index___id = (int) column.get().order - 1;

    column = columnsExtended.stream().filter(it -> "id".equals(it.columnName)).findAny();
    if (!column.isPresent())
      throw new java.io.IOException(
          "Unable to find 'id' column in mixinReference Resident. Check if DB is in sync");
    __index__extended_id = (int) column.get().order - 1;

    column = columns.stream().filter(it -> "birth".equals(it.columnName)).findAny();
    if (!column.isPresent())
      throw new java.io.IOException(
          "Unable to find 'birth' column in mixinReference Resident_entity. Check if DB is in sync");
    __index___birth = (int) column.get().order - 1;

    column = columnsExtended.stream().filter(it -> "birth".equals(it.columnName)).findAny();
    if (!column.isPresent())
      throw new java.io.IOException(
          "Unable to find 'birth' column in mixinReference Resident. Check if DB is in sync");
    __index__extended_birth = (int) column.get().order - 1;
  }
  @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);
  }
Esempio n. 3
0
 public static Container setup(
     DataSource dataSource,
     Properties properties,
     Optional<File> pluginsPath,
     Optional<ClassLoader> classLoader)
     throws IOException {
   ClassLoader loader;
   if (pluginsPath.isPresent()) {
     File[] jars = pluginsPath.get().listFiles(f -> f.getPath().toLowerCase().endsWith(".jar"));
     List<URL> urls = new ArrayList<>(jars.length);
     for (File j : jars) {
       try {
         urls.add(j.toURI().toURL());
       } catch (MalformedURLException ex) {
         throw new IOException(ex);
       }
     }
     loader =
         classLoader.isPresent()
             ? new URLClassLoader(urls.toArray(new URL[urls.size()]), classLoader.get())
             : new URLClassLoader(urls.toArray(new URL[urls.size()]));
   } else if (classLoader.isPresent()) {
     loader = classLoader.get();
   } else {
     loader = Thread.currentThread().getContextClassLoader();
   }
   ServiceLoader<SystemAspect> aspects = ServiceLoader.load(SystemAspect.class, loader);
   return setup(dataSource, properties, Optional.of(loader), aspects.iterator());
 }
Esempio n. 4
0
 public Optional<byte[]> get(
     Optional<String> table,
     Optional<String> family,
     Optional<String> qualifier,
     Optional<String> key) {
   if (!valid) {
     Logger.error("CANNOT GET! NO VALID CONNECTION");
     return Optional.empty();
   }
   if (table.isPresent()
       && family.isPresent()
       && qualifier.isPresent()
       && key.isPresent()
       && !key.get().isEmpty()) {
     try {
       final Table htable = connection.getTable(TableName.valueOf(table.get()));
       Result result = htable.get(new Get(key.get().getBytes("UTF8")));
       return Optional.ofNullable(
           result.getValue(family.get().getBytes("UTF8"), qualifier.get().getBytes("UTF8")));
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   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())));
  }
Esempio n. 6
0
 @Override
 public Card deal() {
   Optional<Card> nextCard = cards.stream().findFirst();
   if (nextCard.isPresent()) {
     cards.remove(nextCard.get());
   }
   return nextCard.get();
 }
  /**
   * Create a Trezor hard wallet from a backup summary, decrypting it with a password created from
   * the Trezor supplied entropy
   */
  private boolean createTrezorHardWallet() {

    // Get the model that contains the selected wallet backup to use
    SelectBackupSummaryModel selectedBackupSummaryModel =
        getWizardModel().getSelectBackupSummaryModel();

    if (selectedBackupSummaryModel == null
        || selectedBackupSummaryModel.getValue() == null
        || selectedBackupSummaryModel.getValue().getFile() == null) {
      log.debug("No wallet backup to use from the model");
      return false;
    }

    log.debug(
        "Loading hard wallet backup '" + selectedBackupSummaryModel.getValue().getFile() + "'");
    try {
      // For Trezor hard wallets the backups are encrypted with the entropy derived password
      String walletPassword = null;
      Optional<HardwareWalletService> hardwareWalletService =
          CoreServices.getOrCreateHardwareWalletService();
      if (hardwareWalletService.isPresent()
          && hardwareWalletService.get().getContext().getEntropy().isPresent()) {
        walletPassword =
            Hex.toHexString(hardwareWalletService.get().getContext().getEntropy().get());
      }

      // Check there is a wallet password - if not then cannot decrypt backup
      if (walletPassword == null) {
        log.debug(
            "Cannot work out the password to decrypt the backup - there is no entropy from the Trezor");
        return false;
      }
      KeyParameter backupAESKey =
          AESUtils.createAESKey(
              walletPassword.getBytes(Charsets.UTF_8), WalletManager.scryptSalt());

      WalletId loadedWalletId =
          BackupManager.INSTANCE.loadZipBackup(
              selectedBackupSummaryModel.getValue().getFile(), backupAESKey);

      // Attempt to open the wallet
      final Optional<WalletSummary> walletSummaryOptional =
          WalletManager.INSTANCE.openWalletFromWalletId(
              InstallationManager.getOrCreateApplicationDataDirectory(),
              loadedWalletId,
              walletPassword);

      // If the wallet is present then it was opened successfully
      return walletSummaryOptional.isPresent();

    } catch (Exception e) {
      log.error("Failed to restore Trezor hard wallet.", e);
    }

    // Must have failed to be here
    return false;
  }
 @Test
 public void testDataExtractor() throws Exception {
   BasicSampleExtractor extractor = new BasicSampleExtractor();
   Optional<SampleData> sampleData = extractor.extractSample(new JsonObject(buildMessage()));
   assertTrue(sampleData.isPresent());
   assertEquals(sampleData.get().getPublishId(), "norbert");
   assertEquals(sampleData.get().getTime(), NOW);
   assertEquals(sampleData.get().getMedian(), 10.5);
   assertTrue(sampleData.get().getReadings().length > 0);
 }
Esempio n. 9
0
 @Override
 public void configure(String cfgString, MessageEvent event, ServerConfig cfg) {
   if (cfgString == null) {
     Optional<String> chans =
         event
             .getGuild()
             .getTextChannels()
             .stream()
             .filter(c -> availableChats.contains(c.getId()))
             .map(Channel::getName)
             .reduce((s1, s2) -> s1 + ", " + s2);
     MessageUtil.reply(
         event,
         cfg,
         "Use addChannel/removeChannel CHANNELNAME to add/remove channels to whitelist"
             + "\nCurrent channels: "
             + (chans.isPresent() ? chans.get() : "All"));
     return;
   }
   String[] split = cfgString.toLowerCase().split("\\s+", 2);
   if (split.length != 2) {
     MessageUtil.reply(event, cfg, "Invalid Syntax");
   } else {
     Optional<TextChannel> chan =
         event
             .getGuild()
             .getTextChannels()
             .stream()
             .filter(c -> c.getName().toLowerCase().equals(split[1]))
             .findAny();
     if (split[0].equals("addchannel")) {
       if (chan.isPresent()) {
         availableChats.add(chan.get().getId());
         updateConfig();
         cfg.save();
         MessageUtil.reply(event, cfg, "Channel added");
       } else {
         MessageUtil.reply(event, cfg, "Channel not found!");
       }
     } else if (split[0].equals("removechannel")) {
       if (chan.isPresent()) {
         availableChats.remove(chan.get().getId());
         updateConfig();
         cfg.save();
         MessageUtil.reply(event, cfg, "Channel removed");
       } else {
         MessageUtil.reply(event, cfg, "Channel not found!");
       }
     } else {
       MessageUtil.reply(event, cfg, "Invalid Syntax");
     }
   }
 }
Esempio n. 10
0
  @Override
  public OntrackSVNRevisionInfo getOntrackRevisionInfo(SVNRepository repository, long revision) {

    // Gets information about the revision
    SVNRevisionInfo basicInfo = svnService.getRevisionInfo(repository, revision);
    SVNChangeLogRevision changeLogRevision =
        svnService.createChangeLogRevision(repository, basicInfo);

    // Gets the first copy event on this path after this revision
    SVNLocation firstCopy = svnService.getFirstCopyAfter(repository, basicInfo.toLocation());

    // Data to collect
    Collection<BuildView> buildViews = new ArrayList<>();
    Collection<BranchStatusView> branchStatusViews = new ArrayList<>();
    // Loops over all authorised branches
    for (Project project : structureService.getProjectList()) {
      // Filter on SVN configuration: must be present and equal to the one the revision info is
      // looked into
      Property<SVNProjectConfigurationProperty> projectSvnConfig =
          propertyService.getProperty(project, SVNProjectConfigurationPropertyType.class);
      if (!projectSvnConfig.isEmpty()
          && repository
              .getConfiguration()
              .getName()
              .equals(projectSvnConfig.getValue().getConfiguration().getName())) {
        for (Branch branch : structureService.getBranchesForProject(project.getId())) {
          // Filter on branch type
          // Filter on SVN configuration: must be present
          if (branch.getType() != BranchType.TEMPLATE_DEFINITION
              && propertyService.hasProperty(branch, SVNBranchConfigurationPropertyType.class)) {
            // Identifies a possible build given the path/revision and the first copy
            Optional<Build> build = lookupBuild(basicInfo.toLocation(), firstCopy, branch);
            // Build found
            if (build.isPresent()) {
              // Gets the build view
              BuildView buildView = structureService.getBuildView(build.get());
              // Adds it to the list
              buildViews.add(buildView);
              // Collects the promotions for the branch
              branchStatusViews.add(structureService.getEarliestPromotionsAfterBuild(build.get()));
            }
          }
        }
      }
    }

    // OK
    return new OntrackSVNRevisionInfo(
        repository.getConfiguration(), changeLogRevision, buildViews, branchStatusViews);
  }
Esempio n. 11
0
  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();
    }
  }
Esempio n. 12
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;
  }
Esempio n. 13
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);
  }
Esempio n. 14
0
  @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));
  }
Esempio n. 15
0
  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);
        }
      }
    }
  }
Esempio n. 16
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));
 }
  @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();
                        })));
  }
Esempio n. 18
0
  @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?
  }
Esempio n. 19
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();
  }
Esempio n. 20
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);
 }
  @Override
  public List<Catalog> fineEpisodesBySeriesAndSeason(int id, int season) {
    Optional<Catalog> series = findBySeriesId(id);
    List<Catalog> episodes = getSeriesEpisodes(series.get(), season);

    return episodes;
  }
 /**
  * PUT /users : Updates an existing User.
  *
  * @param managedUserDTO 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 couldnt be updated
  */
 @RequestMapping(
     value = "/users",
     method = RequestMethod.PUT,
     produces = MediaType.APPLICATION_JSON_VALUE)
 @Timed
 @Transactional
 @Secured(AuthoritiesConstants.ADMIN)
 public ResponseEntity<ManagedUserDTO> updateUser(@RequestBody ManagedUserDTO managedUserDTO) {
   log.debug("REST request to update User : {}", managedUserDTO);
   Optional<User> existingUser = userRepository.findOneByEmail(managedUserDTO.getEmail());
   if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserDTO.getId()))) {
     return ResponseEntity.badRequest()
         .headers(
             HeaderUtil.createFailureAlert(
                 "userManagement", "emailexists", "E-mail already in use"))
         .body(null);
   }
   existingUser = userRepository.findOneByLogin(managedUserDTO.getLogin().toLowerCase());
   if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserDTO.getId()))) {
     return ResponseEntity.badRequest()
         .headers(
             HeaderUtil.createFailureAlert("userManagement", "userexists", "Login already in use"))
         .body(null);
   }
   return userRepository
       .findOneById(managedUserDTO.getId())
       .map(
           user -> {
             user.setLogin(managedUserDTO.getLogin());
             user.setFirstName(managedUserDTO.getFirstName());
             user.setLastName(managedUserDTO.getLastName());
             user.setEmail(managedUserDTO.getEmail());
             user.setActivated(managedUserDTO.isActivated());
             user.setLangKey(managedUserDTO.getLangKey());
             Set<Authority> authorities = user.getAuthorities();
             authorities.clear();
             managedUserDTO
                 .getAuthorities()
                 .stream()
                 .forEach(authority -> authorities.add(authorityRepository.findOne(authority)));
             return ResponseEntity.ok()
                 .headers(
                     HeaderUtil.createAlert("userManagement.updated", managedUserDTO.getLogin()))
                 .body(new ManagedUserDTO(userRepository.findOne(managedUserDTO.getId())));
           })
       .orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
 }
Esempio n. 23
0
  @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"));
  }
Esempio n. 24
0
 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));
 }
 @Override
 public EmployeeDTO getEmployeeById(long id) {
   Optional<Employee> employee = Optional.ofNullable(employeeRepository.findOne(id));
   if (employee.isPresent()) {
     return mapEmployeeToEmployeeDtoObject(employee.get());
   } else {
     throw new IllegalArgumentException("there is no employee found with id " + id);
   }
 }
Esempio n. 26
0
  /**
   * Tests that replaceIssueAssigneeOnServer finds issue with the right id and successfully modify
   * the issue's assignee
   */
  @Test
  public void replaceIssueAssignee_successful() {
    String repoId = "testowner/testrepo";
    String originalAssignee = "user1";
    String newAssignee = "user2";

    TurboIssue issue1 = LogicTests.createIssueWithAssignee(1, originalAssignee);
    TurboIssue issue2 = LogicTests.createIssueWithAssignee(2, originalAssignee);
    TurboIssue issue3 = LogicTests.createIssueWithAssignee(3, originalAssignee);
    List<TurboIssue> issues = Arrays.asList(issue3, issue2, issue1);

    Model model =
        new Model(repoId, issues, new ArrayList<>(), new ArrayList<>(), new ArrayList<>());
    Optional<TurboIssue> result =
        model.replaceIssueAssignee(issue1.getId(), Optional.of(newAssignee));
    assertEquals(1, result.get().getId());
    assertEquals(newAssignee, result.get().getAssignee().get());
  }
Esempio n. 27
0
  public void exit() {
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Quit?");
    alert.setHeaderText("You've selected to quit this program.");
    alert.setContentText("Are you sure you want to quit?");

    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.OK) System.exit(0);
  }
Esempio n. 28
0
 @Test
 public void _06_단순리덕션() {
   Optional<String> largest = words.stream().max(String::compareToIgnoreCase);
   if (largest.isPresent()) {
     System.out.println("큰값: " + largest.get());
   } else {
     System.out.println("Empty~");
   }
 }
Esempio n. 29
0
 public double getCapability(int engineNumber) {
   Optional<HostCapability> c1 =
       (capabilitySet.stream().filter((c) -> c.geteNum() == engineNumber).findFirst());
   if (c1.isPresent()) {
     return c1.get().getCapability();
   }
   capabilitySet.add(new HostCapability(this, engineNumber));
   return 0;
 }
 @Override
 public EmployeeDTO getEmployeeDtoByEmail(String email) {
   Optional<Employee> employee = employeeRepository.findOneByEmail(email);
   if (employee.isPresent()) {
     return mapEmployeeToEmployeeDtoObject(employee.get());
   } else {
     throw new IllegalArgumentException(
         "there is no employee found with email ' " + email + " '.");
   }
 }