@Test
  public void testCreateDoStuffAndCommitTransaction() throws IOException {
    /* create a tx */
    final String txLocation = createTransaction();
    /* create a new object inside the tx */
    final String objectInTxCommit = getRandomUniqueId();
    final HttpPost postNew = new HttpPost(txLocation);
    postNew.addHeader("Slug", objectInTxCommit);
    assertEquals(CREATED.getStatusCode(), getStatus(postNew));

    /* fetch the created tx from the endpoint */
    try (CloseableDataset dataset = getDataset(new HttpGet(txLocation + "/" + objectInTxCommit))) {
      assertTrue(
          dataset
              .asDatasetGraph()
              .contains(ANY, createURI(txLocation + "/" + objectInTxCommit), ANY, ANY));
    }
    /* fetch the object-in-tx outside of the tx */
    assertEquals(
        "Expected to not find our object within the scope of the transaction",
        NOT_FOUND.getStatusCode(),
        getStatus(new HttpGet(serverAddress + objectInTxCommit)));
    /* and commit */
    assertEquals(
        NO_CONTENT.getStatusCode(), getStatus(new HttpPost(txLocation + "/fcr:tx/fcr:commit")));

    /* fetch the object-in-tx outside of the tx after it has been committed */
    try (CloseableDataset dataset = getDataset(new HttpGet(serverAddress + objectInTxCommit))) {
      assertTrue(
          "Expected to  find our object after the transaction was committed",
          dataset
              .asDatasetGraph()
              .contains(ANY, createURI(serverAddress + objectInTxCommit), ANY, ANY));
    }
  }
  @Test
  public void testCreateDoStuffAndRollbackTransaction() throws IOException {
    /* create a tx */
    final HttpPost createTx = new HttpPost(serverAddress + "fcr:tx");

    final String txLocation;
    try (final CloseableHttpResponse response = execute(createTx)) {
      assertEquals(CREATED.getStatusCode(), getStatus(response));
      txLocation = getLocation(response);
    }

    /* create a new object inside the tx */
    final HttpPost postNew = new HttpPost(txLocation);
    final String id = getRandomUniqueId();
    postNew.addHeader("Slug", id);
    try (CloseableHttpResponse resp = execute(postNew)) {
      assertEquals(CREATED.getStatusCode(), getStatus(resp));
    }
    /* fetch the created tx from the endpoint */
    try (final CloseableDataset dataset = getDataset(new HttpGet(txLocation + "/" + id))) {
      assertTrue(
          dataset.asDatasetGraph().contains(ANY, createURI(txLocation + "/" + id), ANY, ANY));
    }
    /* fetch the created tx from the endpoint */
    assertEquals(
        "Expected to not find our object within the scope of the transaction",
        NOT_FOUND.getStatusCode(),
        getStatus(new HttpGet(serverAddress + "/" + id)));

    /* and rollback */
    assertEquals(
        NO_CONTENT.getStatusCode(), getStatus(new HttpPost(txLocation + "/fcr:tx/fcr:rollback")));
  }
  /**
   * Updates device class' equipment. None of following parameters are mandatory. Parameters, if
   * left unspecified, remains unchanged, instead setting parameter to null will null corresponding
   * value. In following JSON
   *
   * <p>name Equipment display name. code Equipment code. It's used to reference particular
   * equipment and it should be unique within a device class. type Equipment type. An arbitrary
   * string representing equipment capabilities. data Equipment data, a JSON object with an
   * arbitrary structure.
   *
   * <p><code>
   * {
   * "name": "equipment name",
   * "code": "equipment_code",
   * "type": "equipment_type",
   * "data": {/ * json object* /}
   * }
   * </code>
   *
   * @param classId id of class
   * @param eqId equipment id
   * @param equipmentUpdate Json object
   * @return empty response with status 201 in case of success, empty response with status 404, if
   *     there's no such record
   */
  @PUT
  @Path("/{id}")
  @Consumes(MediaType.APPLICATION_JSON)
  public Response updateEquipment(
      @PathParam(DEVICE_CLASS_ID) long classId,
      @PathParam(ID) long eqId,
      @JsonPolicyApply(JsonPolicyDef.Policy.EQUIPMENT_PUBLISHED) EquipmentUpdate equipmentUpdate) {

    logger.debug("Update device class's equipment requested");

    if (!equipmentService.update(equipmentUpdate, eqId, classId)) {
      logger.debug(
          "Unable to update equipment. Equipment with id = {} for device class with id = {} not found",
          eqId,
          classId);
      return ResponseFactory.response(
          NOT_FOUND,
          new ErrorResponse(
              NOT_FOUND.getStatusCode(),
              String.format(Messages.EQUIPMENT_NOT_FOUND, eqId, classId)));
    }

    logger.debug("Update device class's equipment finished successfully");

    return ResponseFactory.response(NO_CONTENT);
  }
 /**
  * Allows user access to given network
  *
  * @param userId id of user
  * @param networkId id of network
  */
 @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
 public void assignNetwork(@NotNull long userId, @NotNull long networkId) {
   User existingUser = userDAO.findById(userId);
   if (existingUser == null) {
     throw new HiveException(
         String.format(Messages.USER_NOT_FOUND, userId), NOT_FOUND.getStatusCode());
   }
   Network existingNetwork = networkDAO.getByIdWithUsers(networkId);
   if (existingNetwork == null) {
     throw new HiveException(
         String.format(Messages.NETWORK_NOT_FOUND, networkId), NOT_FOUND.getStatusCode());
   }
   Set<User> usersSet = existingNetwork.getUsers();
   usersSet.add(existingUser);
   existingNetwork.setUsers(usersSet);
   networkDAO.merge(existingNetwork);
 }
 @Test
 public void testGetNonExistingObject() throws IOException {
   final String txLocation = createTransaction();
   final String newObjectLocation = txLocation + "/idontexist";
   assertEquals(
       "Status should be NOT FOUND",
       NOT_FOUND.getStatusCode(),
       getStatus(new HttpGet(newObjectLocation)));
 }
 public Network update(@NotNull Long networkId, NetworkUpdate networkUpdate) {
   Network existing = getById(networkId);
   if (existing == null) {
     throw new HiveException(
         String.format(Messages.NETWORK_NOT_FOUND, networkId), NOT_FOUND.getStatusCode());
   }
   if (networkUpdate.getKey() != null) {
     existing.setKey(networkUpdate.getKey().getValue());
   }
   if (networkUpdate.getName() != null) {
     existing.setName(networkUpdate.getName().getValue());
   }
   if (networkUpdate.getDescription() != null) {
     existing.setDescription(networkUpdate.getDescription().getValue());
   }
   return existing;
 }
  /**
   * Gets current state of device equipment. <code>
   * [
   * {
   * "id":1,
   * "timestamp": "1970-01-01 00:00:00.0",
   * "parameters":{/ *custom json object* /}
   * },
   * {
   * "id":2,
   * "timestamp": "1970-01-01 00:00:00.0",
   * "parameters":{/ *custom json object* /}
   * }
   * ]
   * <p/>
   * </code>
   *
   * @param classId device class id
   * @param eqId equipment id
   */
  @GET
  @Path("/{id}")
  public Response getEquipment(@PathParam(DEVICE_CLASS_ID) long classId, @PathParam(ID) long eqId) {

    logger.debug("Device class's equipment get requested");
    Equipment result = equipmentService.getByDeviceClass(classId, eqId);

    if (result == null) {
      logger.debug("No equipment with id = {} for device class with id = {} found", eqId, classId);
      return ResponseFactory.response(
          NOT_FOUND,
          new ErrorResponse(
              NOT_FOUND.getStatusCode(),
              String.format(Messages.EQUIPMENT_NOT_FOUND, eqId, classId)));
    }
    logger.debug("Device class's equipment get proceed successfully");

    return ResponseFactory.response(OK, result, EQUIPMENT_PUBLISHED);
  }
  @Test
  public void testDropTableTable() {
    try {
      metadata.dropTable(SESSION, tableHandle);
      fail("expected exception");
    } catch (PrestoException e) {
      assertEquals(e.getErrorCode(), PERMISSION_DENIED.toErrorCode());
    }

    JdbcMetadataConfig config = new JdbcMetadataConfig().setAllowDropTable(true);
    metadata =
        new JdbcMetadata(new JdbcConnectorId(CONNECTOR_ID), database.getJdbcClient(), config);
    metadata.dropTable(SESSION, tableHandle);

    try {
      metadata.getTableMetadata(SESSION, tableHandle);
      fail("expected exception");
    } catch (PrestoException e) {
      assertEquals(e.getErrorCode(), NOT_FOUND.toErrorCode());
    }
  }
  @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
  public User updateUser(@NotNull Long id, UserUpdate userToUpdate) {
    User existing = userDAO.findById(id);

    if (existing == null) {
      throw new HiveException(
          String.format(Messages.USER_NOT_FOUND, id), NOT_FOUND.getStatusCode());
    }
    if (userToUpdate == null) {
      return existing;
    }
    if (userToUpdate.getLogin() != null) {
      String newLogin = StringUtils.trim(userToUpdate.getLogin().getValue());
      User withSuchLogin = userDAO.findByLogin(newLogin);
      if (withSuchLogin != null && !withSuchLogin.getId().equals(id)) {
        throw new HiveException(Messages.DUPLICATE_LOGIN, FORBIDDEN.getStatusCode());
      }
      existing.setLogin(newLogin);
    }
    if (userToUpdate.getPassword() != null) {
      if (StringUtils.isEmpty(userToUpdate.getPassword().getValue())) {
        throw new HiveException(Messages.PASSWORD_REQUIRED, BAD_REQUEST.getStatusCode());
      }
      String salt = passwordService.generateSalt();
      String hash = passwordService.hashPassword(userToUpdate.getPassword().getValue(), salt);
      existing.setPasswordSalt(salt);
      existing.setPasswordHash(hash);
    }
    if (userToUpdate.getRole() != null) {
      existing.setRole(userToUpdate.getRoleEnum());
    }
    if (userToUpdate.getStatus() != null) {
      existing.setStatus(userToUpdate.getStatusEnum());
    }

    hiveValidator.validate(existing);
    return userDAO.update(existing);
  }
  @GET
  @Produces("application/json")
  public EntityList<Record> get(
      @PathParam("id") String id,
      @DefaultValue("1") @QueryParam("start-index") Long startIndex,
      @DefaultValue("10") @QueryParam("max-results") Long maxResults,
      @Context UriInfo uriInfo) {

    List<QName> fieldQNames = ResourceClassUtil.parseFieldList(uriInfo);

    RecordId recordId = repository.getIdGenerator().fromString(id);
    List<Record> records;
    try {
      records =
          repository.readVersions(recordId, startIndex, startIndex + maxResults - 1, fieldQNames);
      return EntityList.create(records, uriInfo);
    } catch (RecordNotFoundException e) {
      throw new ResourceException(e, NOT_FOUND.getStatusCode());
    } catch (Exception e) {
      throw new ResourceException(
          "Error loading record versions.", e, INTERNAL_SERVER_ERROR.getStatusCode());
    }
  }