public Response deleteQueue(String queueName, Boolean ifUnused, Boolean ifEmpty) { if (Objects.isNull(ifUnused)) { ifUnused = true; } if (Objects.isNull(ifEmpty)) { ifEmpty = true; } try { if (broker.deleteQueue(queueName, ifUnused, ifEmpty)) { return Response.ok().build(); } else { throw new NotFoundException("Queue " + queueName + " doesn't exist."); } } catch (BrokerException e) { throw new BadRequestException(e.getMessage(), e); } }
@POST @Path("/meeting") @Produces(APPLICATION_JSON) @Consumes(APPLICATION_JSON) public Reservation make(Reservation reservation) { if (reservation.getId() != null) throw new BadRequestException(MessageFormat.format(ERROR_RESERVATION_IS_EXISTS_FMT, reservation.getId())); Set<Reservation> alreadyMadeReservations = reservationDao.getReservations( reservation.getVenue(), reservation.getDate(), reservation.getStartTime(), reservation.getDuration()); if (alreadyMadeReservations != null && !alreadyMadeReservations.isEmpty()) throw new BadRequestException(MessageFormat.format(ERROR_RESERVATION_CONFLICT_FMT, reservation.getVenue())); return reservationDao.createNew(reservation); }
/** * Updates an existing content element in a comb of a user * @param userId of the user to update the comb element * @param contentId of the element in the comb of the user * @param item Data to change * @param con Connection to use - is injected automatically * @return the updated {@link CombItemModel} */ @PUT public Response updateCombItem(@PathParam("userId") final long userId, @PathParam("contentId") final long contentId, final CombItemModel item, @Context final Connection con) { if(userId != item.getUserId()) { throw new BadRequestException("Different userIds."); } if(contentId != item.getContentId()) { throw new BadRequestException("Different contentIds."); } getAccessChecker().checkLoggedInUser(userId); new CombItemDao(con).updateCombItem(item); return ok(item); }
@Test(expected = BadRequestException.class) public void testFormFailsIfRequiredBooleanIsNotBoolean() { Builder<Map<String, Object>> builder = new Builder<>(emptyList()); Form<Map<String, Object>> form = builder.title( __ -> "title" ).description( __ -> "description" ).constructor( HashMap::new ).addRequiredBoolean( "long1", (map, string) -> map.put("l1", string) ).build(); form.get(_body); }
private List<Triple> updateGraph(final Resource res, final IRI graphName) { final List<Triple> triples; // Update existing graph try (final TrellisGraph graph = TrellisGraph.createGraph()) { try (final Stream<? extends Triple> stream = res.stream(graphName)) { stream.forEachOrdered(graph::add); } ioService.update(graph.asGraph(), sparqlUpdate, TRELLIS_PREFIX + req.getPath() + (ACL.equals(req.getExt()) ? "?ext=acl" : "")); triples = graph.stream().collect(toList()); } catch (final RuntimeTrellisException ex) { LOGGER.warn(ex.getMessage()); throw new BadRequestException("Invalid RDF: " + ex.getMessage()); } return triples; }
@Test public void makePost_checkSOAPRequestErrorIsThrownWhenNotValidXML() throws Exception { when(webResourceBuilder.post(any(Entity.class))).thenReturn(response); when(response.readEntity(Document.class)).thenThrow(new BadRequestException()); when(response.getStatus()).thenReturn(200); Element matchingServiceRequest = XmlUtils.convertToElement("<someElement/>"); URI matchingServiceUri = new URI("http://heyyeyaaeyaaaeyaeyaa.com/abc1"); try { soapRequestClient.makeSoapRequest(matchingServiceRequest, matchingServiceUri); fail("Exception should have been thrown"); } catch(SOAPRequestError e) { } finally { verify(response).readEntity(Document.class); } }
/** * Filter streams/channels by game and by language. * Passes the JSON response to a Java object for easier use. * * @param game the game to get the channels for * @param language filter all channels by language * @return a list of the channels currently streaming for a given game + language * @throws IOException */ public Set<String> getStreamsByGame(final String game, final String language) throws IOException { /* TODO: maybe handle the case for "all" languages TODO: make this run in its own thread. See java.util.concurrency TODO: organize the API better. This function is weak. */ StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(STREAM_ENDPOINT) .append(QUESTION_MARK) .append(GAME_PARAM) .append(EQUALS) .append(game); if (language != null) { urlBuilder.append(AMPERSAND) .append(LANG_PARAM) .append(EQUALS) .append(language); } String urlString = urlBuilder.toString(); URL url = new URL(urlString); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty(CLIENT_ID_HEADER, clientId); if (con.getResponseCode() != Constants.RESPONSE_OK) { throw new BadRequestException(BAD_CLIENT_ID + clientId); } channels = mapper.readValue(con.getInputStream(), ChannelContainer.class); return channels.getChannels(); }
@Override public MultipartBean startMultipart(String uuid, String filepath, Boolean uploads) { if( uploads == null ) { throw new BadRequestException("Must use PUT for uploading files"); } StagingFile stagingFile = getStagingFile(uuid); String uploadId = UUID.randomUUID().toString(); String folderPath = "multipart/" + uploadId; ensureMultipartDir(stagingFile); try { fileSystemService.mkdir(stagingFile, folderPath); return new MultipartBean(uploadId); } catch( Exception e ) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } }
@Override public Object readFrom( final Class<Object> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException { try { return objectMapper.readValue(entityStream, type); } catch (final JsonProcessingException ex) { throw new BadRequestException(ex.getMessage(), ex); } }
/** * Logs in the user with email address and password. * Returns the user on success. * * @param email The user's email address. * @param password The user's plain text password. * @return the user details. */ public NewCookie login(final String email, final String password) { final SecurityUser candidate = dao.findUserByEmail(userClass, email); if (candidate == null) { throw new BadRequestException("notfound"); } if (candidate.getPasswordHash() == null) { throw new BadRequestException("invalid"); } if (!BCrypt.checkpw(password, candidate.getPasswordHash())) { throw new BadRequestException("incorrect"); } return loginAs(candidate); }
/** * Changes the current user's password. * * @param oldPassword The old password. * @param newPassword The new password. * @param confirmNewPassword The confirmed new password. */ public void changePassword(final String oldPassword, final String newPassword, final String confirmNewPassword) { requireLogin(); if (user.getPasswordHash() == null) { throw new BadRequestException("unset"); } if (!BCrypt.checkpw(oldPassword, user.getPasswordHash())) { throw new BadRequestException("incorrect"); } if (!newPassword.equals(confirmNewPassword)) { throw new BadRequestException("mismatch"); } if (newPassword.length() < MINIMUM_PASSWORD_LENGTH) { throw new BadRequestException("short"); } user.setPassword(newPassword); dao.update(user); }
@Test(expected = BadRequestException.class) public void testFormFailsIfRequiredDoubleIsNotDouble() { Builder<Map<String, Object>> builder = new Builder<>(emptyList()); Form<Map<String, Object>> form = builder.title( __ -> "title" ).description( __ -> "description" ).constructor( HashMap::new ).addRequiredDouble( "long1", (map, string) -> map.put("l1", string) ).build(); form.get(_body); }
@Test(expected = BadRequestException.class) public void testInvalidSessionToken() { final User user = new User(); final UserSession session = new UserSession(); session.setUser(user); final String cookie = session.getId().toString(); final SecurityDao dao = mock(SecurityDao.class); when(dao.read(eq(UserSession.class), eq(session.getId()))).thenReturn(session); when(dao.read(eq(User.class), eq(user.getId()))).thenReturn(user); final Configuration config = mock(Configuration.class); when(config.getProperty(eq(MinijaxProperties.SECURITY_USER_CLASS))).thenReturn(User.class); final Security<User> security = new Security<>(dao, config, null, cookie); security.validateSession("not-the-right-token"); }
@Test(expected = BadRequestException.class) public void testFormFailsIfRequiredIsNotPresent() { Builder<Map<String, Object>> builder = new Builder<>(emptyList()); Form<Map<String, Object>> form = builder.title( __ -> "title" ).description( __ -> "description" ).constructor( HashMap::new ).addRequiredString( "string1", (map, string) -> map.put("s1", string) ).addRequiredString( "string3", (map, string) -> map.put("s2", string) ).build(); form.get(_body); }
private void readForm() { final MediaType contentType = getMediaType(); if (contentType == null) { return; } try { if (contentType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) { form = new MinijaxUrlEncodedForm(IOUtils.toString(getEntityStream(), StandardCharsets.UTF_8)); } else if (contentType.isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)) { form = new MinijaxMultipartForm(request.getParts()); } else { throw new BadRequestException("Unsupported content type (" + contentType + ")"); } } catch (final IOException | ServletException ex) { throw new WebApplicationException(ex.getMessage(), ex); } }
private static void verifyPathParamsMatchBody(String bucketIdParam, String flowIdParam, VersionedFlowSnapshot flowSnapshot) throws BadRequestException { if (StringUtils.isBlank(bucketIdParam)) { throw new BadRequestException("Bucket id path parameter cannot be blank"); } if (StringUtils.isBlank(flowIdParam)) { throw new BadRequestException("Flow id path parameter cannot be blank"); } if (flowSnapshot == null) { throw new BadRequestException("VersionedFlowSnapshot cannot be null in body"); } final VersionedFlowSnapshotMetadata metadata = flowSnapshot.getSnapshotMetadata(); if (metadata != null && metadata.getBucketIdentifier() != null && !bucketIdParam.equals(metadata.getBucketIdentifier())) { throw new BadRequestException("Bucket id in path param must match bucket id in body"); } if (metadata != null && metadata.getFlowIdentifier() != null && !flowIdParam.equals(metadata.getFlowIdentifier())) { throw new BadRequestException("Flow id in path param must match flow id in body"); } }
@Test(expected = BadRequestException.class) public void testFormFailsIfOptionalStringIsNotString() { Builder<Map<String, Object>> builder = new Builder<>(emptyList()); Form<Map<String, Object>> form = builder.title( __ -> "title" ).description( __ -> "description" ).constructor( HashMap::new ).addOptionalString( "long1", (map, string) -> map.put("l1", string) ).build(); form.get(_body); }
@PUT @Path("/{connectorType}/config/validate") public ConfigInfos validateConfigs( final @PathParam("connectorType") String connType, final Map<String, String> connectorConfig ) throws Throwable { String includedConnType = connectorConfig.get(ConnectorConfig.CONNECTOR_CLASS_CONFIG); if (includedConnType != null && !normalizedPluginName(includedConnType).endsWith(normalizedPluginName(connType))) { throw new BadRequestException( "Included connector type " + includedConnType + " does not match request type " + connType ); } return herder.validateConnectorConfig(connectorConfig); }
@POST @Path("/") public Response createConnector(final @QueryParam("forward") Boolean forward, final CreateConnectorRequest createRequest) throws Throwable { String name = createRequest.name(); if (name.contains("/")) { throw new BadRequestException("connector name should not contain '/'"); } Map<String, String> configs = createRequest.config(); if (!configs.containsKey(ConnectorConfig.NAME_CONFIG)) configs.put(ConnectorConfig.NAME_CONFIG, name); FutureCallback<Herder.Created<ConnectorInfo>> cb = new FutureCallback<>(); herder.putConnectorConfig(name, configs, false, cb); Herder.Created<ConnectorInfo> info = completeOrForwardRequest(cb, "/connectors", "POST", createRequest, new TypeReference<ConnectorInfo>() { }, new CreatedConnectorInfoTranslator(), forward); return Response.created(URI.create("/connectors/" + name)).entity(info.result()).build(); }
@PUT @Path("/{connector}/config") public Response putConnectorConfig(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward, final Map<String, String> connectorConfig) throws Throwable { FutureCallback<Herder.Created<ConnectorInfo>> cb = new FutureCallback<>(); String includedName = connectorConfig.get(ConnectorConfig.NAME_CONFIG); if (includedName != null) { if (!includedName.equals(connector)) throw new BadRequestException("Connector name configuration (" + includedName + ") doesn't match connector name in the URL (" + connector + ")"); } else { connectorConfig.put(ConnectorConfig.NAME_CONFIG, connector); } herder.putConnectorConfig(connector, connectorConfig, true, cb); Herder.Created<ConnectorInfo> createdInfo = completeOrForwardRequest(cb, "/connectors/" + connector + "/config", "PUT", connectorConfig, new TypeReference<ConnectorInfo>() { }, new CreatedConnectorInfoTranslator(), forward); Response.ResponseBuilder response; if (createdInfo.created()) response = Response.created(URI.create("/connectors/" + connector)); else response = Response.ok(); return response.entity(createdInfo.result()).build(); }
/** * Tests adding of a null device key using POST via JSON stream. */ @Test public void testPostNullDeviceKey() { replay(mockDeviceKeyAdminService); WebTarget wt = target(); try { wt.path("keys").request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(null), String.class); fail("POST of null device key did not throw an exception"); } catch (BadRequestException ex) { assertThat(ex.getMessage(), containsString("HTTP 400 Bad Request")); } verify(mockDeviceKeyAdminService); }
/** * Tests adding of a null virtual network using POST via JSON stream. */ @Test public void testPostVirtualNetworkNullTenantId() { replay(mockVnetAdminService); WebTarget wt = target(); try { wt.path("vnets") .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(null), String.class); fail("POST of null virtual network did not throw an exception"); } catch (BadRequestException ex) { assertThat(ex.getMessage(), containsString("HTTP 400 Bad Request")); } verify(mockVnetAdminService); }
/** * Tests adding of a null virtual port using POST via JSON stream. */ @Test public void testPostVirtualPortNullJsonStream() { NetworkId networkId = networkId3; DeviceId deviceId = devId2; replay(mockVnetAdminService); WebTarget wt = target(); try { String reqLocation = "vnets/" + networkId.toString() + "/devices/" + deviceId.toString() + "/ports"; wt.path(reqLocation) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(null), String.class); fail("POST of null virtual port did not throw an exception"); } catch (BadRequestException ex) { assertThat(ex.getMessage(), containsString("HTTP 400 Bad Request")); } verify(mockVnetAdminService); }
/** * Tests adding of a null virtual link using POST via JSON stream. */ @Test public void testPostVirtualLinkNullJsonStream() { NetworkId networkId = networkId3; replay(mockVnetAdminService); WebTarget wt = target(); try { String reqLocation = "vnets/" + networkId.toString() + "/links"; wt.path(reqLocation) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(null), String.class); fail("POST of null virtual link did not throw an exception"); } catch (BadRequestException ex) { assertThat(ex.getMessage(), containsString("HTTP 400 Bad Request")); } verify(mockVnetAdminService); }
@Override public Map<String, Object> readFrom( Class<Map<String, Object>> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException { Gson gson = new Gson(); Try<Map<String, Object>> mapTry = Try.fromFallibleWithResources( () -> new InputStreamReader(entityStream, "UTF-8"), streamReader -> gson.fromJson(streamReader, genericType)); return mapTry.orElseThrow( () -> new BadRequestException("Body is not a valid JSON")); }
private DLFolder _addDLFolder(Long groupId, FolderForm folderForm) { long parentFolderId = 0; Try<DLFolder> dlFolderTry = Try.fromFallible( () -> _dlFolderService.getFolder( groupId, parentFolderId, folderForm.getName())); if (dlFolderTry.isSuccess()) { throw new BadRequestException( "A folder with that name already exists"); } dlFolderTry = Try.fromFallible( () -> _dlFolderService.addFolder( groupId, groupId, false, parentFolderId, folderForm.getName(), folderForm.getDescription(), new ServiceContext())); return dlFolderTry.getUnchecked(); }
public SimpleUser create(UpdateUser user, List<String> permissions) { if (user.getLogin() == null || user.getPassword() == null) { throw new BadRequestException("login and password cannot be null"); } // check if the current login already exist if (this.exists(user.getLogin())) { throw new EntityExistsException("user with login : " + user.getLogin() + " already exists"); } // remove unknown permission List<String> filteredPermissions = permissions.stream().filter(Permission::isValid).collect(Collectors.toList()); //generate entity, hash and salt the password UserEntity entity = new UserEntity(user, filteredPermissions); return new SimpleUser(super.create(entity)); }
@Test(expected = BadRequestException.class) public void testFormFailsIfRequiredLongIsNotLong() { Builder<Map<String, Object>> builder = new Builder<>(emptyList()); Form<Map<String, Object>> form = builder.title( __ -> "title" ).description( __ -> "description" ).constructor( HashMap::new ).addRequiredLong( "string1", (map, string) -> map.put("s1", string) ).build(); form.get(_body); }
@Test(expected = BadRequestException.class) public void testFormFailsIfOptionalBooleanIsNotBoolean() { Builder<Map<String, Object>> builder = new Builder<>(emptyList()); Form<Map<String, Object>> form = builder.title( __ -> "title" ).description( __ -> "description" ).constructor( HashMap::new ).addOptionalBoolean( "long1", (map, string) -> map.put("l1", string) ).build(); form.get(_body); }
@Test(expected = BadRequestException.class) public void testFormFailsIfOptionalDateIsNotDate() { Builder<Map<String, Object>> builder = new Builder<>(emptyList()); Form<Map<String, Object>> form = builder.title( __ -> "title" ).description( __ -> "description" ).constructor( HashMap::new ).addOptionalDate( "long1", (map, string) -> map.put("l1", string) ).build(); form.get(_body); }
@Test(expected = BadRequestException.class) public void testFormFailsIfOptionalDoubleIsNotDouble() { Builder<Map<String, Object>> builder = new Builder<>(emptyList()); Form<Map<String, Object>> form = builder.title( __ -> "title" ).description( __ -> "description" ).constructor( HashMap::new ).addOptionalDouble( "long1", (map, string) -> map.put("l1", string) ).build(); form.get(_body); }
@Test(expected = BadRequestException.class) public void testFormFailsIfOptionalLongIsNotLong() { Builder<Map<String, Object>> builder = new Builder<>(emptyList()); Form<Map<String, Object>> form = builder.title( __ -> "title" ).description( __ -> "description" ).constructor( HashMap::new ).addOptionalLong( "string1", (map, string) -> map.put("s1", string) ).build(); form.get(_body); }
@GET @Path("/{name}.json") @Produces(APPLICATION_JSON) public PluginConfigWrapper getStoragePluginJSON(@PathParam("name") String name) { try { StoragePlugin plugin = pluginConfiguration.getPlugin(name); if (plugin != null) { return new PluginConfigWrapper(name, plugin.getConfig()); } } catch (Exception e) { throw new BadRequestException("Failure while trying to access storage config: " + name, e); } return new PluginConfigWrapper(name, null); }
@Test public void testBadDigest2() { final File entity = new File(getClass().getResource("/simpleData.txt").getFile()); when(mockRequest.getContentType()).thenReturn("text/plain"); when(mockRequest.getDigest()).thenReturn(new Digest("foo", "blahblah")); final PostHandler postHandler = new PostHandler(mockRequest, "newresource", entity, mockResourceService, mockIoService, mockBinaryService, null); assertThrows(BadRequestException.class, postHandler::createResource); }
private static void verifyPathParamsMatchBody(String bucketIdParam, BucketItem bodyBucketItem) throws BadRequestException { if (StringUtils.isBlank(bucketIdParam)) { throw new BadRequestException("Bucket id path parameter cannot be blank"); } if (bodyBucketItem == null) { throw new BadRequestException("Object in body cannot be null"); } if (bodyBucketItem.getBucketIdentifier() != null && !bucketIdParam.equals(bodyBucketItem.getBucketIdentifier())) { throw new BadRequestException("Bucket id in path param must match bucket id in body"); } }
/** * Wrap the supplied element in a SOAP wrapper and post to the specified end-point * * @return Response from the remote server * @throws SOAPRequestError if the remote server returns a non-200 status code * @throws ResponseProcessingException in case processing of a received HTTP response fails (e.g. in a filter * or during conversion of the response entity data to an instance * of a particular Java type). * @throws ProcessingException in case the request processing or subsequent I/O operation fails. */ protected SoapResponse makePost(URI uri, Element requestElement) throws SOAPRequestError { LOG.info(format("Making SOAP request to: {0}", uri)); Document requestDocument = soapMessageManager.wrapWithSoapEnvelope(requestElement); WebTarget target = client.target(uri); final Invocation.Builder request = target.request(); final Response response = request.post(Entity.entity(requestDocument, MediaType.TEXT_XML_TYPE)); try { if (response.getStatus() != 200) { LOG.warn(format("Unexpected status code ({0}) when contacting ({1}))", response.getStatus(), uri)); // let the calling code handle this issue appropriately throw new SOAPRequestError(response); } else { try { return giveMeMySoap(response); } catch(BadRequestException e) { LOG.warn(format("Couldn't parse SOAP response when contacting ({0}))", uri), e); throw new SOAPRequestError(response, e); } } } finally { // Ensure that response's input stream has been closed. This may not happen automatically in some cases // (e.g. the response body is never read from). try { response.close(); } catch (ProcessingException f) { LOG.warn("Problem closing Jersey connection.", f); } } }
@Override public Response toResponse(BadRequestException exception) { LOGGER.debug("Bad request.", exception); Map<String, Object> errorResponse = new HashMap<>(); errorResponse.put("message", exception.getMessage()); return Response.status(Response.Status.BAD_REQUEST) .entity(errorResponse) .type(MediaType.APPLICATION_JSON_TYPE) .build(); }
@Override public void filter(ContainerRequestContext request) throws IOException { String origin = request.getHeaderString(ORIGIN_HEADER_FIELD); if (origin != null) { if (!originFilter.isOriginAllowed(origin)) { throw new BadRequestException("The origin ist not set accordingly"); } } }
private void send(Collection<Trace> traces) { try { apmApi.reportTraces(traces); } catch (NotFoundException | NotSupportedException cee) { // 404, 415 if (apmApi instanceof ApmApi0_3) { log.info("falling back to json"); fallbackTo0_2(); send(traces); } } catch (BadRequestException bre) { log.error("{}: {}", bre.getMessage(), traces); } }
@ApiOperation(value = "throws an client exception") @GET @Path("/bad") public Response badClient() { final JsonElement entity = jsonOps.toJsonElement("{\"error\":\"client bad\"}"); throw new BadRequestException("who's bad", Response.status(Status.BAD_REQUEST).entity(entity).build()); }