Beispiel #1
0
  @Override
  public void validateIfLocked(final ILockKey context, Optional<ILock> heldLock)
      throws LockException {

    Optional<ILock> stored =
        storage.read(storeProvider -> storeProvider.getLockStore().fetchLock(context));

    // The implementation below assumes the following use cases:
    // +-----------+-----------------+----------+
    // |   eq      |     held        | not held |
    // +-----------+-----------------+----------+
    // |stored     |(stored == held)?| invalid  |
    // +-----------+-----------------+----------+
    // |not stored |    invalid      |  valid   |
    // +-----------+-----------------+----------+
    if (!stored.equals(heldLock)) {
      if (stored.isPresent()) {
        throw new LockException(
            String.format(
                "Unable to perform operation for: %s. Use override/cancel option.",
                formatLockKey(context)));
      } else if (heldLock.isPresent()) {
        throw new LockException(
            String.format("Invalid operation context: %s", formatLockKey(context)));
      }
    }
  }
Beispiel #2
0
  public static PopupForm fromRequest(String uuid, HttpServletRequest request) {
    String descriptor = request.getParameter("descriptor");
    boolean isOpenCampaign = "open-campaign".equals(request.getParameter("open-campaign"));

    long startTime =
        "".equals(request.getParameter("start_time"))
            ? 0
            : parseTime(request.getParameter("start_time_selected_datetime"));
    long endTime =
        "".equals(request.getParameter("end_time"))
            ? 0
            : parseTime(request.getParameter("end_time_selected_datetime"));

    List<String> assignees = new ArrayList<String>();
    if (request.getParameter("distribution") != null) {
      for (String user : request.getParameter("distribution").split("[\r\n]+")) {
        if (!user.isEmpty()) {
          assignees.add(user);
        }
      }
    }

    Optional<DiskFileItem> templateItem = Optional.empty();
    DiskFileItem dfi = (DiskFileItem) request.getAttribute("template");
    if (dfi != null && dfi.getSize() > 0) {
      templateItem = Optional.of(dfi);
    }

    return new PopupForm(
        uuid, descriptor, startTime, endTime, isOpenCampaign, assignees, templateItem);
  }
Beispiel #3
0
 @Override
 public void clearLevelCache(String levelCacheName) {
   Optional<CachingLevel> cachingLevel =
       environment.cachingConfiguration().findLevelForLevelName(levelCacheName);
   if (!cachingLevel.isPresent()) {
     log.info("cachingLevel does not exist!");
     return;
   }
   if (!caches.containsKey(cachingLevel.get().name())) {
     log.info("no cache for this level existing!");
     return;
   }
   Optional<RetentionLevel> retentionLevel =
       environment.retentions().getLevelForName(levelCacheName);
   if (!retentionLevel.isPresent()) {
     log.info("no retentionLevel for this levelCache! something is seriously broken!");
     return;
   }
   if (!levelIsAccessLevel(retentionLevel.get())) {
     log.info("levelCache that is no accessLevelCache cannot be dropped!");
     return;
   }
   Optional<EvictionStrategy> evictionStrategy =
       findEvictionStrategyForAccessLevel(retentionLevel.get());
   if (!evictionStrategy.isPresent()) {
     log.info("no evictionStrategy found - there must be something wrong!");
     return;
   }
   List<String> metricsToClear = caches.get(levelCacheName).getMetrics();
   for (String metric : metricsToClear) {
     evictionStrategy.get().mBeanTriggeredEviction(metric);
   }
   log.info("cleared cache " + levelCacheName);
 }
 private Optional<List<String>> loadPartitionNamesByParts(PartitionFilter partitionFilter)
     throws Exception {
   try {
     return retry()
         .stopOn(NoSuchObjectException.class)
         .stopOnIllegalExceptions()
         .run(
             "getPartitionNamesByParts",
             stats
                 .getGetPartitionNamesPs()
                 .wrap(
                     () -> {
                       try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) {
                         return Optional.of(
                             client.getPartitionNamesFiltered(
                                 partitionFilter.getHiveTableName().getDatabaseName(),
                                 partitionFilter.getHiveTableName().getTableName(),
                                 partitionFilter.getParts()));
                       }
                     }));
   } catch (NoSuchObjectException e) {
     return Optional.empty();
   } catch (TException e) {
     throw new PrestoException(HIVE_METASTORE_ERROR, e);
   }
 }
  public Optional<String> toImageBlock(List<File> dropFiles) {

    if (!current.currentPath().isPresent()) asciiDocController.saveDoc();

    Path currentPath = current.currentPath().map(Path::getParent).get();
    IOHelper.createDirectories(currentPath.resolve("images"));
    List<Path> paths =
        dropFiles
            .stream()
            .map(File::toPath)
            .filter(pathResolver::isImage)
            .collect(Collectors.toList());

    List<String> buffer = new LinkedList<>();

    for (Path path : paths) {
      Path targetImage = currentPath.resolve("images").resolve(path.getFileName());
      if (!path.equals(targetImage)) IOHelper.copy(path, targetImage);
      buffer.add(String.format("image::images/%s[]", path.getFileName()));
    }

    if (buffer.size() > 0) return Optional.of(String.join("\n", buffer));

    return Optional.empty();
  }
Beispiel #6
0
  private Optional<ResolvedField> resolveField(Expression node, QualifiedName name, boolean local) {
    List<Field> matches = relation.resolveFields(name);
    if (matches.size() > 1) {
      throwAmbiguousAttributeException(node, name);
    }

    if (matches.isEmpty()) {
      if (isColumnReference(name, relation)) {
        return Optional.empty();
      }
      Scope boundary = this;
      while (!boundary.queryBoundary) {
        if (boundary.parent.isPresent()) {
          boundary = boundary.parent.get();
        } else {
          return Optional.empty();
        }
      }
      if (boundary.parent.isPresent()) {
        // jump over the query boundary
        return boundary.parent.get().resolveField(node, name, false);
      }
      return Optional.empty();
    } else {
      return Optional.of(asResolvedField(getOnlyElement(matches), local));
    }
  }
Beispiel #7
0
  @Override
  protected void runChild(Interaction interaction, RunNotifier notifier) {
    final Description description = describeChild(interaction);
    notifier.fireTestStarted(description);

    if (interaction.providerState().isDefined()) {
      final Optional<FrameworkMethod> initializationMethod =
          findProvderStateInitializationMethod(interaction.providerState().get());
      if (initializationMethod.isPresent()) {
        try {
          invokeMethod(initializationMethod.get());
          testPact(interaction);
          notifier.fireTestFinished(description);
          return;
        } catch (Exception ex) {
          notifier.fireTestFailure(new Failure(description, ex));
          return;
        }
      } else {
        notifier.fireTestIgnored(description);
        return;
      }
    }
    notifier.fireTestIgnored(description);
  }
Beispiel #8
0
 public void route(String url, Map<String, String> postdata, HttpServletResponse response)
     throws IOException {
   try {
     this.actions
         .stream()
         .filter(action -> action.url.equals(url))
         .findAny()
         .orElseThrow(() -> new UrlNotMappedToActionException(url))
         .performAction(postdata, controllerFactory)
         .createResult(this, response);
   } catch (Exception e) {
     try {
       if (defaultErrorAction.isPresent()) {
         final ActionResult actionResult =
             defaultErrorAction.get().performAction(e, url, postdata, controllerFactory);
         actionResult.createResult(this, response);
       } else {
         // Default to printing the full exception
         new PrintFullExceptionView(e).createResult(this, response);
       }
     } catch (Exception e2) {
       // If we can't print it to the response, then at least print it to std.err
       e2.printStackTrace();
       throw new RuntimeException(e2);
     }
   }
 }
  @Override
  @SuppressWarnings("unchecked")
  public <T> T getBean(Class<T> clazz) {
    Object bean = beans.get(clazz);
    if (bean != null) {
      return (T) bean;
    }

    BeanDefinition beanDefinition = beanDefinitions.get(clazz);
    if (beanDefinition != null && beanDefinition instanceof AnnotatedBeanDefinition) {
      Optional<Object> optionalBean = createAnnotatedBean(beanDefinition);
      optionalBean.ifPresent(b -> beans.put(clazz, b));
      initialize(bean, clazz);
      return (T) optionalBean.orElse(null);
    }

    Optional<Class<?>> concreteClazz = BeanFactoryUtils.findConcreteClass(clazz, getBeanClasses());
    if (!concreteClazz.isPresent()) {
      return null;
    }

    beanDefinition = beanDefinitions.get(concreteClazz.get());
    bean = inject(beanDefinition);
    beans.put(concreteClazz.get(), bean);
    initialize(bean, concreteClazz.get());
    return (T) bean;
  }
Beispiel #10
0
  /**
   * Helper function to find string between certain other strings.
   *
   * @param content Content for search
   * @param start String marking start point
   * @param end String marking end point
   * @return The string between, or empty Optional
   */
  public static Optional<String> findBetween(String content, String start, String end) {
    int pos1 = content.indexOf(start) + start.length();
    int pos2 = content.indexOf(end, pos1);

    if (pos1 == -1 || pos2 == -1) return Optional.empty();
    return Optional.ofNullable(content.substring(pos1, pos2));
  }
Beispiel #11
0
  @Test
  public void subTitleTest() throws Exception {
    try (InputStream is =
        GvkParserTest.class.getResourceAsStream("gvk_artificial_subtitle_test.xml")) {
      GvkParser parser = new GvkParser();
      List<BibEntry> entries = parser.parseEntries(is);
      Assert.assertNotNull(entries);
      Assert.assertEquals(5, entries.size());

      BibEntry entry = entries.get(0);
      Assert.assertEquals(Optional.empty(), entry.getField("subtitle"));

      entry = entries.get(1);
      Assert.assertEquals(Optional.of("C"), entry.getField("subtitle"));

      entry = entries.get(2);
      Assert.assertEquals(Optional.of("Word"), entry.getField("subtitle"));

      entry = entries.get(3);
      Assert.assertEquals(Optional.of("Word1 word2"), entry.getField("subtitle"));

      entry = entries.get(4);
      Assert.assertEquals(Optional.of("Word1 word2"), entry.getField("subtitle"));
    }
  }
 public void test_migratedFrom() throws Exception {
   assertTrue(
       OptionalThing.migratedFrom(
               Optional.of("sea"),
               () -> {
                 throw new IllegalStateException();
               })
           .isPresent());
   assertFalse(
       OptionalThing.migratedFrom(
               Optional.empty(),
               () -> {
                 throw new IllegalStateException();
               })
           .isPresent());
   try {
     OptionalThing.migratedFrom(
             Optional.empty(),
             () -> {
               throw new IllegalStateException("land");
             })
         .get();
     fail();
   } catch (IllegalStateException e) {
     String message = e.getMessage();
     log(message);
     assertContains(message, "land");
   }
 }
  private void addToSnakList(final Optional<Snak> optionalSnak, final List<Snak> snakList) {

    if (optionalSnak.isPresent()) {

      snakList.add(optionalSnak.get());
    }
  }
  private Optional<List<Snak>> processGDMQualifiedAttributes(final Statement statement) {

    final List<Snak> snakList = new ArrayList<>();

    final Optional<Snak> optionalConfidence =
        processGDMQualifiedAttribute(
            CONFIDENCE_QUALIFIED_ATTRIBUTE_IDENTIFIER, statement.getConfidence());
    final Optional<Snak> optionalEvidence =
        processGDMQualifiedAttribute(
            EVIDENCE_QUALIFIED_ATTRIBUTE_IDENTIFIER, statement.getEvidence());
    final Optional<Snak> optionalOrder =
        processGDMQualifiedAttribute(ORDER_QUALIFIED_ATTRIBUTE_IDENTIFIER, statement.getOrder());

    // D:SWARM statement uuid
    final Optional<Snak> optionalUUID =
        processGDMQualifiedAttribute(
            STATEMENT_UUID_QUALIFIED_ATTRIBUTE_IDENTIFIER, statement.getUUID());

    addToSnakList(optionalConfidence, snakList);
    addToSnakList(optionalEvidence, snakList);
    addToSnakList(optionalOrder, snakList);
    addToSnakList(optionalUUID, snakList);

    if (snakList.isEmpty()) {

      return Optional.empty();
    }

    return Optional.of(snakList);
  }
  private boolean setMetadataCdaCh(DocumentMetadataCh metaData, CdaChVacd document) {

    metaData.addAuthor(document.getAuthor());

    metaData.setMimeType(MimeType.XML_TEXT);
    Optional<Identificator> patId = getMeineImpfungenPatientId(document.getPatient());
    if (patId.isPresent()) {
      metaData.setDestinationPatientId(patId.get());
      metaData.setSourcePatientId(patId.get());
    } else {
      return false;
    }

    metaData.setCodedLanguage(LanguageCode.DEUTSCH);

    metaData.setTypeCode(TypeCode.ELEKTRONISCHER_IMPFAUSWEIS);
    metaData.setFormatCode(FormatCode.EIMPFDOSSIER);
    metaData.setClassCode(ClassCode.ALERTS);

    metaData.setHealthcareFacilityTypeCode(
        HealthcareFacilityTypeCode.AMBULANTE_EINRICHTUNG_INKL_AMBULATORIUM);
    metaData.setPracticeSettingCode(PracticeSettingCode.ALLERGOLOGIE);
    metaData.addConfidentialityCode(ConfidentialityCode.ADMINISTRATIVE_DATEN);
    return true;
  }
Beispiel #16
0
 private void assertCommonSuperType(Type firstType, Type secondType, Type expected) {
   TypeRegistry typeManager = new TypeRegistry();
   assertEquals(
       typeManager.getCommonSuperType(firstType, secondType), Optional.ofNullable(expected));
   assertEquals(
       typeManager.getCommonSuperType(secondType, firstType), Optional.ofNullable(expected));
 }
  @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();
                        })));
  }
  public static Optional<List<FixMessage>> toFixMessage(String line) {
    try {
      FixType fixType = resolveFixType(line);

      List<String> messages = extractMessageFromLine(line, fixType);
      if (messages.isEmpty()) {
        return Optional.empty();
      }

      String delimiter = getDelimiter(messages.get(0));
      List<FixMessage> fixMessages = new ArrayList<FixMessage>();

      for (String message : messages) {
        if (!message.isEmpty()) {
          FixMessage fixMessage = new FixMessage(fixType);
          fillFixMessage(message, delimiter, fixMessage);
          fixMessages.add(fixMessage);
        }
      }

      return Optional.of(fixMessages);
    } catch (IllegalArgumentException e) {
      return Optional.empty();
    }
  }
  public ASTUnannReferenceType deepClone(ASTUnannReferenceType result) {

    /* generated by template ast.ErrorIfNull*/
    Log.errorIfNull(result, "0xA7006_806 Parameter 'result' must not be null.");

    /* generated by template ast.additionalmethods.DeepCloneWithParameters*/

    super.deepClone(result);

    result.unannClassOrInterfaceType =
        this.unannClassOrInterfaceType.isPresent()
            ? Optional.ofNullable(
                (java8._ast.ASTUnannClassOrInterfaceType)
                    this.unannClassOrInterfaceType.get().deepClone())
            : Optional.empty();
    result.unannTypeVariable =
        this.unannTypeVariable.isPresent()
            ? Optional.ofNullable(
                (java8._ast.ASTUnannTypeVariable) this.unannTypeVariable.get().deepClone())
            : Optional.empty();
    result.unannArrayType =
        this.unannArrayType.isPresent()
            ? Optional.ofNullable(
                (java8._ast.ASTUnannArrayType) this.unannArrayType.get().deepClone())
            : Optional.empty();
    result.symbol =
        this.symbol.isPresent()
            ? Optional.ofNullable((Symbol) this.symbol.get())
            : Optional.empty();
    result.enclosingScope =
        this.enclosingScope.isPresent()
            ? Optional.ofNullable((Scope) this.enclosingScope.get())
            : Optional.empty();
    return result;
  }
Beispiel #20
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));
 }
 private Optional<Table> loadTable(HiveTableName hiveTableName) throws Exception {
   try {
     return retry()
         .stopOn(NoSuchObjectException.class, HiveViewNotSupportedException.class)
         .stopOnIllegalExceptions()
         .run(
             "getTable",
             stats
                 .getGetTable()
                 .wrap(
                     () -> {
                       try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) {
                         Table table =
                             client.getTable(
                                 hiveTableName.getDatabaseName(), hiveTableName.getTableName());
                         if (table.getTableType().equals(TableType.VIRTUAL_VIEW.name())
                             && (!isPrestoView(table))) {
                           throw new HiveViewNotSupportedException(
                               new SchemaTableName(
                                   hiveTableName.getDatabaseName(), hiveTableName.getTableName()));
                         }
                         return Optional.of(table);
                       }
                     }));
   } catch (NoSuchObjectException e) {
     return Optional.empty();
   } catch (TException e) {
     throw new PrestoException(HIVE_METASTORE_ERROR, e);
   }
 }
  @FXML
  private void lvListenerGetEmployeeInfo(MouseEvent event) {
    try {
      tabPayCheck.setDisable(true);
      clearTextFields();

      String[] a = lvEmployees.getSelectionModel().getSelectedItem().split("-");
      tfInfoId.setText(a[1].trim());

      final int ID = Integer.parseInt(tfInfoId.getText());

      tfInfoName.setText(Environment.getEmployeeStrInfo(ID, "name"));
      tfInfoPos.setText(Environment.getEmployeeStrInfo(ID, "position"));
      tfInfoStreet.setText(Environment.getEmployeeStrInfo(ID, "street"));
      tfInfoCSZ.setText(Environment.getCityStateZip(ID));
      tfInfoPayRate.setText(
          String.format("%.2f", Double.parseDouble(Environment.getEmployeeStrInfo(ID, "payRate"))));

    } catch (Exception e) {
      Alert alert;

      alert = new Alert(AlertType.CONFIRMATION);
      alert.setTitle("Error Message");
      alert.setHeaderText("Whoops you did not select an Employee.");
      alert.setContentText("Try again.");
      Optional<ButtonType> result = alert.showAndWait();
      if (result.get() == ButtonType.OK) {
        // ... user chose OK
      } else {
        // ... user chose CANCEL or closed the dialog
      }
    }
  }
 private Optional<Partition> loadPartitionByName(HivePartitionName partitionName)
     throws Exception {
   requireNonNull(partitionName, "partitionName is null");
   try {
     return retry()
         .stopOn(NoSuchObjectException.class)
         .stopOnIllegalExceptions()
         .run(
             "getPartitionsByNames",
             stats
                 .getGetPartitionByName()
                 .wrap(
                     () -> {
                       try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) {
                         return Optional.of(
                             client.getPartitionByName(
                                 partitionName.getHiveTableName().getDatabaseName(),
                                 partitionName.getHiveTableName().getTableName(),
                                 partitionName.getPartitionName()));
                       }
                     }));
   } catch (NoSuchObjectException e) {
     return Optional.empty();
   } catch (TException e) {
     throw new PrestoException(HIVE_METASTORE_ERROR, e);
   }
 }
  @Override
  protected void doExecute(final Collection<Item<Element>> itemCollection)
      throws StageProcessingException {
    log.info(
        "Filtering {} items on allowed organisationIds from authentication request",
        itemCollection.size());

    final Optional<OrganisationUserDetails> userDetails =
        SecurityContextHelper.getOrganisationUserDetails();

    if (userDetails.isPresent() == false) {
      log.error("FATAL: No UserDetails in Authentication Context, all items filtered");
      itemCollection.clear();
    }
    if (userDetails.get().getRelyingOrganisationId() == null) {
      log.error("FATAL: No Relying Organisation Id in Authentication Context, all items filtered");
      itemCollection.clear();
    }

    final Collection<Item<Element>> filteredItems =
        filter.filterElementMembers(itemCollection, userDetails.get().getRelyingOrganisationId());

    itemCollection.clear();
    itemCollection.addAll(filteredItems);
  }
Beispiel #25
0
 @Test
 public void testOptional() {
   Optional<String> fullName = Optional.ofNullable(null);
   Assert.assertEquals("Optional.empty", fullName.toString());
   Assert.assertEquals("[none]", fullName.orElseGet(() -> "[none]"));
   Assert.assertEquals("[none2]", fullName.orElse("[none2]"));
 }
Beispiel #26
0
 private static Optional<Object> getParsedStatement(String statement) {
   try {
     return Optional.of((Object) SQL_PARSER.createStatement(statement));
   } catch (ParsingException e) {
     return Optional.empty();
   }
 }
Beispiel #27
0
 private Optional<EvictionStrategy> findEvictionStrategyForAccessLevel(
     RetentionLevel accessLevel) {
   if (evictionStrategyMap.containsKey(accessLevel.name())) {
     return Optional.of(evictionStrategyMap.get(accessLevel.name()));
   }
   return Optional.empty();
 }
 @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"));
 }
Beispiel #29
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));
  }
Beispiel #30
0
  @Override
  public ILock acquireLock(final ILockKey lockKey, final String user) throws LockException {
    return storage.write(
        storeProvider -> {
          LockStore.Mutable lockStore = storeProvider.getLockStore();
          Optional<ILock> existingLock = lockStore.fetchLock(lockKey);

          if (existingLock.isPresent()) {
            throw new LockException(
                String.format(
                    "Operation for: %s is already in progress. Started at: %s. Current owner: %s.",
                    formatLockKey(lockKey),
                    new Date(existingLock.get().getTimestampMs()).toString(),
                    existingLock.get().getUser()));
          }

          ILock lock =
              ILock.build(
                  new Lock()
                      .setKey(lockKey.newBuilder())
                      .setToken(tokenGenerator.createNew().toString())
                      .setTimestampMs(clock.nowMillis())
                      .setUser(user));

          lockStore.saveLock(lock);
          return lock;
        });
  }