@Override
 public void updateCommand(String deviceId, DeviceCommand command) throws HiveException {
   if (command == null) {
     throw new HiveClientException("Command cannot be null!", BAD_REQUEST.getStatusCode());
   }
   if (command.getId() == null) {
     throw new HiveClientException("Command id cannot be null!", BAD_REQUEST.getStatusCode());
   }
   logger.debug(
       "DeviceCommand: update requested for device id {] and command: id {},  flags {}, status {}, "
           + " result {}",
       deviceId,
       command.getId(),
       command.getFlags(),
       command.getStatus(),
       command.getResult());
   JsonObject request = new JsonObject();
   request.addProperty("action", "command/update");
   request.addProperty("deviceGuid", deviceId);
   request.addProperty("commandId", command.getId());
   Gson gson = GsonFactory.createGson(COMMAND_UPDATE_FROM_DEVICE);
   request.add("command", gson.toJsonTree(command));
   websocketAgent.getWebsocketConnector().sendMessage(request);
   logger.debug(
       "DeviceCommand: update request proceed successfully for device id {] and command: id {},  "
           + "flags {}, status {}, result {}",
       deviceId,
       command.getId(),
       command.getFlags(),
       command.getStatus(),
       command.getResult());
 }
예제 #2
0
  @Test
  public void noHostHeaderOn11Request() throws Exception {
    final AtomicReference<RequestHandler> requestHandlerRef = new AtomicReference<>();
    when(mockHttpListenerConfig.addRequestHandler(
            any(ListenerRequestMatcher.class), any(RequestHandler.class)))
        .then(
            new Answer<RequestHandlerManager>() {
              @Override
              public RequestHandlerManager answer(InvocationOnMock invocation) throws Throwable {
                requestHandlerRef.set((RequestHandler) invocation.getArguments()[1]);
                return null;
              }
            });
    usePath("/");

    HttpRequest request = buildGetRootRequest(HTTP_1_1);
    HttpRequestContext requestContext = buildRequestContext(request);

    HttpResponseReadyCallback responseCallback = mock(HttpResponseReadyCallback.class);
    requestHandlerRef.get().handleRequest(requestContext, responseCallback);
    assertResponse(
        responseCallback,
        BAD_REQUEST.getStatusCode(),
        BAD_REQUEST.getReasonPhrase(),
        "Missing 'host' header");
  }
 @Test
 public void test400WithInvalidKeyPairGroupDuplicateIllegalStateException() {
   assertCodeMakes(
       GET,
       URI.create("https://amazonaws.com/foo"),
       BAD_REQUEST.getStatusCode(),
       BAD_REQUEST.getReasonPhrase(),
       "application/unknown",
       "<Error><Code>InvalidKeyPair.Duplicate</Code></Error>",
       IllegalStateException.class);
 }
 @Test
 public void test400WithTextPlainIllegalArgumentException() {
   assertCodeMakes(
       GET,
       URI.create("https://amazonaws.com/foo"),
       BAD_REQUEST.getStatusCode(),
       BAD_REQUEST.getReasonPhrase(),
       TEXT_PLAIN,
       "Failure: 400 Bad Request\nFailed to bind the following fields\nMonitoring.Enabled = true\n\n\n",
       IllegalArgumentException.class);
 }
  @TransactionAttribute(TransactionAttributeType.SUPPORTS)
  public Network createOrVeriryNetwork(NullableWrapper<Network> network) {
    Network stored;
    // case network is not defined
    if (network == null || network.getValue() == null) {
      return null;
    }
    Network update = network.getValue();

    if (update.getId() != null) {
      stored = networkDAO.getById(update.getId());
    } else {
      stored = networkDAO.findByName(update.getName());
    }

    if (stored != null) {
      if (stored.getKey() != null) {
        if (!stored.getKey().equals(update.getKey())) {
          throw new HiveException(Messages.INVALID_NETWORK_KEY, FORBIDDEN.getStatusCode());
        }
      }
    } else {
      if (update.getId() != null) {
        throw new HiveException(Messages.INVALID_REQUEST_PARAMETERS, BAD_REQUEST.getStatusCode());
      }
      stored = networkDAO.createNetwork(update);
    }
    assert (stored != null);
    return stored;
  }
  @Test
  public void nonOkResponse() throws IOException {
    this.snippet.expectHttpResponse("non-ok-response").withContents(httpResponse(BAD_REQUEST));

    MockHttpServletResponse response = new MockHttpServletResponse();
    response.setStatus(BAD_REQUEST.value());
    documentHttpResponse("non-ok-response").handle(result(response));
  }
 @Override
 public Timestamp fromString(String value) {
   try {
     return TimestampAdapter.parseTimestamp(value);
   } catch (IllegalArgumentException | UnsupportedOperationException e) {
     throw new HiveException(Messages.UNPARSEABLE_TIMESTAMP, e, BAD_REQUEST.getStatusCode());
   }
 }
 @Test
 public void test400WithSecurityGroupNotFoundForProjectSetsResourceNotFoundException() {
   assertCodeMakes(
       GET,
       URI.create("https://amazonaws.com/foo"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<Error><Code>SecurityGroupNotFoundForProject</Code></Error>",
       ResourceNotFoundException.class);
 }
 @Test
 public void test400WithIncorrectStateSetsIllegalStateException() {
   assertCodeMakes(
       GET,
       URI.create("https://amazonaws.com/foo"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<Error><Code>IncorrectState</Code></Error>",
       IllegalStateException.class);
 }
 @Test
 public void test400WithUnsupportedCodeMakesUnsupportedOperationException() {
   assertCodeMakes(
       POST,
       URI.create("https://ec2.us-west-1.amazonaws.com/"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<Error><Code>UnsupportedOperation</Code></Error>",
       UnsupportedOperationException.class);
 }
 @Test
 public void test400WithAuthFailureSetsAuthorizationException() {
   assertCodeMakes(
       GET,
       URI.create("https://amazonaws.com/foo"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<Error><Code>AuthFailure</Code></Error>",
       AuthorizationException.class);
 }
 public Network create(Network newNetwork) {
   if (newNetwork.getId() != null) {
     throw new HiveException(Messages.ID_NOT_ALLOWED, BAD_REQUEST.getStatusCode());
   }
   Network existing = networkDAO.findByName(newNetwork.getName());
   if (existing != null) {
     throw new HiveException(Messages.DUPLICATE_NETWORK, FORBIDDEN.getStatusCode());
   }
   return networkDAO.createNetwork(newNetwork);
 }
 @Test
 public void test400WithGroupAlreadyExistsEucalyptusIllegalStateException() {
   assertCodeMakes(
       GET,
       URI.create("https://amazonaws.com/foo"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<?xml version=\"1.0\"?><Response><Errors><Error><Code>Groups</Code><Message>\nError adding network group: group named jclouds#eucrun#Eucalyptus already exists\nError adding network group: group named jclouds#eucrun#Eucalyptus already exists</Message></Error></Errors><RequestID>e0133975-3bc5-456d-9753-1d61b27e07e9</RequestID></Response>",
       IllegalStateException.class);
 }
 @Test
 public void test400WithCloudBridgeNotFoundSetsResourceNotFoundException() {
   assertCodeMakes(
       POST,
       URI.create("https://api.greenqloud.com/"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<Error><Code>Client.InvalidInstanceID.NotFound</Code></Error>",
       ResourceNotFoundException.class);
 }
 @Test
 public void test400WithUnknownSetsResourceNotFoundException() {
   assertCodeMakes(
       GET,
       URI.create("https://amazonaws.com/foo"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<Error><Code>InvalidPlacementGroup.Unknown</Code></Error>",
       ResourceNotFoundException.class);
 }
 @Test
 public void test400WithAddressLimitExceededCodeMakesInsufficientResourcesException() {
   assertCodeMakes(
       POST,
       URI.create("https://ec2.us-east-1.amazonaws.com/"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<Response><Errors><Error><Code>AddressLimitExceeded</Code><Message>Too many addresses allocated</Message></Error></Errors><RequestID>c14f531a-cc35-4b48-8149-2655c7e6dc76</RequestID></Response>",
       InsufficientResourcesException.class);
 }
 @Test
 public void test400WithTooManyBucketsCodeMakesInsufficientResourcesException() {
   assertCodeMakes(
       POST,
       URI.create("https://ec2.us-east-1.amazonaws.com/"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<Response><Errors><Error><Code>TooManyBuckets</Code><Message>You have attempted to create more buckets than allowed</Message></Error></Errors><RequestID>c14f531a-cc35-4b48-8149-2655c7e6dc76</RequestID></Response>",
       InsufficientResourcesException.class);
 }
 @Test
 public void test400WithLoadBalancerNotFoundSetsResourceNotFoundException() {
   assertCodeMakes(
       GET,
       URI.create("https://amazonaws.com/foo"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<Error><Code>LoadBalancerNotFound</Code></Error>",
       ResourceNotFoundException.class);
 }
 @Test
 public void test400WithCloudBridgeAuthFailureSetsAuthorizationException() {
   assertCodeMakes(
       POST,
       URI.create("https://api.greenqloud.com/"),
       BAD_REQUEST.getStatusCode(),
       "",
       "<Error><Code>Client.AuthFailure</Code></Error>",
       AuthorizationException.class);
 }
 @Test
 public void test400WithInvalidIdIllegalArgumentException() {
   assertCodeMakes(
       POST,
       URI.create("https://ec2.us-east-1.amazonaws.com"),
       BAD_REQUEST.getStatusCode(),
       "HTTP/1.1 400",
       "",
       "Invalid id: \"asdaasdsa\" (expecting \"ami-...\")",
       IllegalArgumentException.class);
 }
 @Test
 public void test400WithInUseSetsIllegalStateException() {
   assertCodeMakes(
       GET,
       URI.create("https://amazonaws.com/foo"),
       BAD_REQUEST.getStatusCode(),
       "",
       TEXT_PLAIN,
       "The placement group 'jclouds#adriancoleec2cccluster#us-east-1' is in use and may not be deleted.",
       IllegalStateException.class);
 }
예제 #22
0
  @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
  public User createUser(@NotNull User user, String password) {
    if (user.getId() != null) {
      throw new HiveException(Messages.ID_NOT_ALLOWED, BAD_REQUEST.getStatusCode());
    }
    user.setLogin(StringUtils.trim(user.getLogin()));
    User existing = userDAO.findByLogin(user.getLogin());
    if (existing != null) {
      throw new HiveException(Messages.DUPLICATE_LOGIN, FORBIDDEN.getStatusCode());
    }
    if (StringUtils.isEmpty(password)) {
      throw new HiveException(Messages.PASSWORD_REQUIRED, BAD_REQUEST.getStatusCode());
    }
    String salt = passwordService.generateSalt();
    String hash = passwordService.hashPassword(password, salt);
    user.setPasswordSalt(salt);
    user.setPasswordHash(hash);
    user.setLoginAttempts(Constants.INITIAL_LOGIN_ATTEMPTS);

    hiveValidator.validate(user);
    return userDAO.create(user);
  }
  @Override
  public DeviceCommand insertCommand(
      String guid, DeviceCommand command, HiveMessageHandler<DeviceCommand> commandUpdatesHandler)
      throws HiveException {
    if (command == null) {
      throw new HiveClientException("Command cannot be null!", BAD_REQUEST.getStatusCode());
    }
    logger.debug(
        "DeviceCommand: insert requested for device id {] and command: command {}, parameters {}, "
            + "lifetime {}, flags {}",
        guid,
        command.getCommand(),
        command.getParameters(),
        command.getLifetime(),
        command.getFlags());

    JsonObject request = new JsonObject();
    request.addProperty("action", "command/insert");
    request.addProperty("deviceGuid", guid);
    Gson gson = GsonFactory.createGson(COMMAND_FROM_CLIENT);
    request.add("command", gson.toJsonTree(command));
    DeviceCommand toReturn =
        websocketAgent
            .getWebsocketConnector()
            .sendMessage(request, "command", DeviceCommand.class, COMMAND_TO_CLIENT);
    if (commandUpdatesHandler != null) {
      websocketAgent.addCommandUpdateSubscription(toReturn.getId(), guid, commandUpdatesHandler);
    }
    logger.debug(
        "DeviceCommand: insert request proceed successfully for device id {] and command: command {}, "
            + "parameters {}, lifetime {}, flags {}. Result command id {}, timestamp {}, userId {}",
        guid,
        command.getCommand(),
        command.getParameters(),
        command.getLifetime(),
        command.getFlags(),
        toReturn.getId(),
        toReturn.getTimestamp(),
        toReturn.getUserId());
    return toReturn;
  }
예제 #24
0
  @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);
  }
  @TransactionAttribute(TransactionAttributeType.SUPPORTS)
  public Network createOrUpdateNetworkByUser(NullableWrapper<Network> network, User user) {
    Network stored;

    // case network is not defined
    if (network == null || network.getValue() == null) {
      return null;
    }

    Network update = network.getValue();

    if (update.getId() != null) {
      stored = networkDAO.getWithDevicesAndDeviceClasses(update.getId());
    } else {
      stored = networkDAO.findByName(update.getName());
    }

    if (stored != null) {
      if (stored.getKey() != null) {
        if (!stored.getKey().equals(update.getKey())) {
          throw new HiveException(Messages.INVALID_NETWORK_KEY, FORBIDDEN.getStatusCode());
        }
      }
      if (!userService.hasAccessToNetwork(user, stored)) {
        throw new HiveException(Messages.NO_ACCESS_TO_NETWORK, FORBIDDEN.getStatusCode());
      }
    } else if (user.isAdmin()) {
      if (update.getId() != null) {
        throw new HiveException(Messages.INVALID_REQUEST_PARAMETERS, BAD_REQUEST.getStatusCode());
      }
      stored = networkDAO.createNetwork(update);

    } else {
      throw new HiveException(Messages.NETWORK_CREATION_NOT_ALLOWED, FORBIDDEN.getStatusCode());
    }
    return stored;
  }
예제 #26
0
  @Test
  public void signIn_shouldReturnBadRequestStatusCode_ifNullParameters() throws Exception {
    HttpRequest signInRequest = signInRequest("", "");

    assertThat(signInRequest.code()).isEqualTo(BAD_REQUEST.getStatusCode());
  }
예제 #27
0
 @Test
 public void signUpWithEmptyFormData_shouldFail() throws Exception {
   HttpRequest signUpRequest = signUpRequest("", "");
   assertThat(signUpRequest.code()).isEqualTo(BAD_REQUEST.getStatusCode());
 }
 @ExceptionHandler({IllegalArgumentException.class})
 public void invalidArguments(HttpServletResponse res) throws IOException {
   res.sendError(BAD_REQUEST.value());
 }
 @ExceptionHandler({MethodArgumentTypeMismatchException.class})
 public void badArguments(HttpServletResponse res, MethodArgumentTypeMismatchException e)
     throws IOException {
   res.sendError(BAD_REQUEST.value(), String.format(MSG_TEMPLATE, e.getName(), e.getValue()));
 }