@GET @Path("{planId}") @Produces({ MediaType.TEXT_HTML }) public Response getPlanAsHtml( @PathParam("serviceProviderId") final String serviceProviderId, @PathParam("planId") final String planId ) throws ServletException, IOException, URISyntaxException { // Start of user code getPlanAsHtml_init // End of user code final Plan aPlan = PlannerReasonerManager.getPlan(httpServletRequest, serviceProviderId, planId); if (aPlan != null) { httpServletRequest.setAttribute("aPlan", aPlan); // Start of user code getPlanAsHtml_setAttributes // End of user code RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/se/ericsson/cf/scott/sandbox/plan.jsp"); rd.forward(httpServletRequest,httpServletResponse); } throw new WebApplicationException(Status.NOT_FOUND); }
@Override public void writeTo(Model t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Lang lang = null; if(mediaType.equals(KRFormat.N3_TYPE)) lang = Lang.N3; else if(mediaType.equals(KRFormat.N_TRIPLE_TYPE)) lang = Lang.NTRIPLES; else if(mediaType.equals(KRFormat.RDF_JSON_TYPE)) lang = Lang.RDFJSON; else if(mediaType.equals(new MediaType("application", "json-ld"))) lang = Lang.JSONLD; else lang = Lang.TURTLE; RDFDataMgr.write(entityStream, t, lang); }
@GET @Path("places/{placeId}") @Produces({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON}) public Place getPlace( @PathParam("serviceProviderId") final String serviceProviderId, @PathParam("placeId") final String placeId ) throws IOException, ServletException, URISyntaxException { // Start of user code getResource_init // End of user code final Place aPlace = WarehouseControllerManager.getPlace(httpServletRequest, serviceProviderId, placeId); if (aPlace != null) { // Start of user code getPlace // End of user code httpServletResponse.addHeader(WarehouseControllerConstants.HDR_OSLC_VERSION, WarehouseControllerConstants.OSLC_VERSION_V2); return aPlace; } throw new WebApplicationException(Status.NOT_FOUND); }
@Test public void testGetJobTasksAcls() { HttpServletRequest hsr = mock(HttpServletRequest.class); when(hsr.getRemoteUser()).thenReturn(ENEMY_USER); try { hsWebServices.getJobTasks(hsr, jobIdStr, "m"); fail("enemy can access job"); } catch (WebApplicationException e) { assertEquals(Status.UNAUTHORIZED, Status.fromStatusCode(e.getResponse().getStatus())); } when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER); hsWebServices.getJobTasks(hsr, jobIdStr, "m"); }
@SuppressWarnings("boxing") private MultivaluedMap<String, String> testVersionFilter(String version) throws WebApplicationException, NoSuchMethodException { ResourceInfo resourceInfo = mock(ResourceInfo.class); ContainerRequestContext request = mock(ContainerRequestContext.class); UriInfo uriInfo = mock(UriInfo.class); when(request.getUriInfo()).thenReturn(uriInfo); Method method = SinceClass.class.getMethod("dummy"); MultivaluedMap<String, String> prop = new MultivaluedHashMap<>(); prop.putSingle(CommonParams.PARAM_VERSION, version); when(uriInfo.getPathParameters()).thenReturn(prop); VersionFilter filter = spy(new VersionFilter()); when(filter.getResourceInfo()).thenReturn(resourceInfo); when(resourceInfo.getResourceMethod()).thenReturn(method); filter.filter(request); return prop; }
@Override public Response update(UUID id, User user) { try { final Optional<User> internalUser = this.service.read(id); if (internalUser.isPresent()) { if (!internalUser.get().getId().equals(id)) { mapper.toResponse(new WebApplicationException(new IllegalArgumentException("Invalid unique id"), Response.status(Response.Status.INTERNAL_SERVER_ERROR).build())); } else { return Response.status(Response.Status.OK).entity(this.service.save(user)).build(); } } else { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.status(Response.Status.CREATED).entity(this.service.save(user)).build(); } catch (Exception e) { log.error(e.getMessage(), e); return mapper.toResponse(new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR).build())); } }
@Test public void testGetJobCountersAcls() { HttpServletRequest hsr = mock(HttpServletRequest.class); when(hsr.getRemoteUser()).thenReturn(ENEMY_USER); try { hsWebServices.getJobCounters(hsr, jobIdStr); fail("enemy can access job"); } catch (WebApplicationException e) { assertEquals(Status.UNAUTHORIZED, Status.fromStatusCode(e.getResponse().getStatus())); } when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER); hsWebServices.getJobCounters(hsr, jobIdStr); }
@Override public TestCaseResult runTestCase(String serviceName, String testName, String mode) { MDC.put(APP_NAME, RedirectorConstants.Logging.APP_NAME_PREFIX + serviceName); TestMode testMode = TestMode.valueOf(mode.toUpperCase()); RedirectorTestCase testCase = getTestCase(serviceName, testName); if (testCase == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); // test case not found } IRedirectorEnvLoader envLoader = getZookeeperRedirectorEnvLoader(serviceName, testMode); SelectServer flavorRules = envLoader.getFlavorRules(); URLRules urlRules = envLoader.getUrlRules(); Whitelisted whitelisted = envLoader.getWhitelists(); NamespacedListRepository namespacedLists = new SimpleNamespacedListsHolder(envLoader.getNamespacedListsBatch()); IRedirectorEngine engine = redirectorEngineFactory.newRedirectorEngine( serviceName, flavorRules, urlRules, whitelisted, namespacedLists, envLoader.getStacks(), new RedirectorEngine.SessionLog()); Context context = TestSuiteUtils.getRedirectorContext(testCase); InstanceInfo instanceInfo = engine.redirect(context.asMap()); TestSuiteResponse actual = TestSuiteUtils.getRedirectorResponse(instanceInfo); TestCaseResult testCaseResult = new TestCaseResult(); testCaseResult.setStatus(TestCaseResult.Status.fromTestCase(testCase.getExpected(), actual)); testCaseResult.setActual(actual); testCaseResult.setLogs(AutoTestRunner.getSessionLogs(context, engine)); MDC.remove(APP_NAME); return testCaseResult; }
public OperationResult deleteUrlRule(String appName, String ruleId, ApplicationStatusMode mode) { final OperationContextHolder.OperationContext currentContext = OperationContextHolder.getCurrentContext(); IfExpression current = currentContext.getUrlRule(ruleId); PendingChangesStatus pendingChangesStatus = currentContext.getPendingChangesStatus(); // check for existing rule if (current == null && !(pendingChangesStatus != null && getUrlRules(pendingChangesStatus).containsKey(ruleId))) { throw new WebApplicationException(Response.Status.NOT_FOUND); // rule not found } if (current != null) { return pendingUrlRuleWriteService.save(appName, ruleId, null, current, mode); } else { // if admin added rule and decided to remove it right away it's the same as cancel pending addition return pendingUrlRuleWriteService.cancel(appName, ruleId, mode); } }
public static ServiceProvider getServiceProvider(HttpServletRequest httpServletRequest, final String serviceProviderId) { ServiceProvider serviceProvider; synchronized(serviceProviders) { String identifier = serviceProviderIdentifier(serviceProviderId); serviceProvider = serviceProviders.get(identifier); //One retry refreshing the service providers if (serviceProvider == null) { getServiceProviders(httpServletRequest); serviceProvider = serviceProviders.get(identifier); } } if (serviceProvider != null) { return serviceProvider; } throw new WebApplicationException(Status.NOT_FOUND); }
@Test public void testValidationNegativeSuspend() throws Exception { DefinitionRepresentation trigger = new DefinitionRepresentation(); trigger.setAction("SUBSCRIBE_TO_SERVICE"); trigger.setTargetURL("<http://"); trigger.setDescription("abc"); trigger.setType("REST_SERVICE"); trigger.setAction("SUBSCRIBE_TO_SERVICE"); try { trigger.validateContent(); fail(); } catch (WebApplicationException e) { assertEquals(Status.BAD_REQUEST.getStatusCode(), e.getResponse() .getStatus()); } }
/** * Verifies that the user's authorization. * * @param username The username of the user. * @param authorization The authorization of the user. * @throws IllegalArgumentException When the format of Authorization is unexpected. * @throws WebApplicationException When UNAUTHORIZED. */ public static void verify(String username, String authorization) { final String accessToken; if (authorization.startsWith("token")) { accessToken = authorization.split(" ")[1]; } else { throw new IllegalArgumentException("The format of Authorization is unexpected."); } Document user = MongoDBs.users().find(eq(User.USERNAME, username)).limit(1).first(); if (user == null) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } Document auth = user.get(User.AUTHORIZATION, Document.class); if (Objects.equals(auth.getString(Authorization.ACCESS_TOKEN), accessToken)) { Log.i(TAG, "Verified successfully."); } else { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } }
public ZNodeResource(@DefaultValue("") @QueryParam("session") String session, @Context UriInfo ui, @Context HttpServletRequest request ) throws IOException { String contextPath = request.getContextPath(); if (contextPath.equals("")) { contextPath = "/"; } if (session.equals("")) { session = null; } else if (!ZooKeeperService.isConnected(contextPath, session)) { throw new WebApplicationException(Response.status( Response.Status.UNAUTHORIZED).build()); } zk = ZooKeeperService.getClient(contextPath, session); }
@Override public Response toResponse(WebApplicationException exception) { log.error("Exception happened in RedirectorWebService", exception); int exceptionStatusCode = exception.getResponse().getStatus(); String exceptionMessage = exception.getMessage(); if (exceptionMessage == null) { Response.Status exceptionStatus = Response.Status.fromStatusCode(exceptionStatusCode); exceptionMessage = (exceptionStatus != null) ? exceptionStatus.getReasonPhrase() : String.format("Exception has been thrown with Status Code : %s", exceptionStatusCode); } return Response.status(exceptionStatusCode) .entity(exceptionMessage) .type(MediaType.TEXT_PLAIN) .build(); }
public NamespaceChangesStatus approve(String serviceName, NamespacedList namespacedList) { NamespaceChangesStatus namespaceChangesStatus = getNamespaceChangesStatus(serviceName); errorList = null; if (namespaceChangesStatus != null && namespaceChangesStatus.getNamespaceChanges() != null && namespacedList != null) { Map<NamespacedList, ActionType> removedNamespacesChangesMap = namespaceChangesStatus.getNamespaceChanges().entrySet().stream() .filter(filterToSaveAlone(namespacedList)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); namespaceChangesStatus.setNamespaceChanges(removedNamespacesChangesMap); save(serviceName, namespaceChangesStatus); } if (errorList != null) { throw new WebApplicationException(FAILED_TO_SAVE_NAMESPACE_DUE_TO_VALIDATION_ERROR, Response.status(Response.Status.BAD_REQUEST).entity(new ErrorMessage(FAILED_TO_SAVE_NAMESPACE_DUE_TO_VALIDATION_ERROR)).build()); } return namespaceChangesStatus; }
@Test(expected = WebApplicationException.class) public void testMappingException() throws Exception { final ObjectMapper om = mock(ObjectMapper.class); when(om.writeValueAsString(any())).thenThrow(new JsonProcessingException("ignore me") { private static final long serialVersionUID = 1L; @Override public StackTraceElement[] getStackTrace() { return new StackTraceElement[] {}; } }); uut = new FactsTransactionsResource(mock(FactStore.class), om); final FactTransactionJson tx = new FactTransactionJson(); tx.facts(Arrays.asList(new FactJson().payload(TextNode.valueOf("buh")))); uut.newTransaction(tx); }
@Test public void testGetSingleTaskCountersAcls() { HttpServletRequest hsr = mock(HttpServletRequest.class); when(hsr.getRemoteUser()).thenReturn(ENEMY_USER); try { hsWebServices.getSingleTaskCounters(hsr, this.jobIdStr, this.taskIdStr); fail("enemy can access job"); } catch (WebApplicationException e) { assertEquals(Status.UNAUTHORIZED, Status.fromStatusCode(e.getResponse().getStatus())); } when(hsr.getRemoteUser()).thenReturn(FRIENDLY_USER); hsWebServices.getSingleTaskCounters(hsr, this.jobIdStr, this.taskIdStr); }
@GET @Path("download") @Consumes(MediaType.APPLICATION_JSON) public Response downloadData(@PathParam("jobId") JobId jobId) throws IOException, JobResourceNotFoundException, JobNotFoundException { final Job job = jobsService.getJob(jobId); final JobInfo jobInfo = job.getJobAttempt().getInfo(); if (jobInfo.getQueryType() == QueryType.UI_EXPORT) { final DownloadDataResponse downloadDataResponse = datasetService.downloadData(jobInfo.getDownloadInfo(), securityContext.getUserPrincipal().getName()); final StreamingOutput streamingOutput = new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { IOUtils.copyBytes(downloadDataResponse.getInput(), output, 4096, true); } }; return Response.ok(streamingOutput, MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", "attachment; filename=\"" + downloadDataResponse.getFileName() + "\"").build(); } else { throw new JobResourceNotFoundException(jobId, format("Job %s has no data that can not be downloaded, invalid type %s", jobId, jobInfo.getQueryType())); } }
private BatchChange approveUrlParams(ITransactionalDAO.ITransaction transaction, PendingChangesStatus pendingChangesStatus, String appName, ApplicationStatusMode mode) { BatchChange result = new BatchChange(); for (Map.Entry<String, PendingChange> changeEntry : pendingChangesStatus.getUrlParams().entrySet()) { String serverName = changeEntry.getKey(); PendingChange change = pendingChangesStatus.getUrlParams().get(serverName); addRuleToResult(result, change); if (mode == ApplicationStatusMode.ONLINE) { try { transaction.<UrlRule>operationByActionType((UrlRule) change.getChangedExpression(), EntityType.URL_PARAMS, appName, serverName, change.getChangeType()); } catch (SerializerException e) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity(new ErrorMessage(e.getMessage())).build()); } } } return result; }
@Override public CharmAttachmentMeta readFrom(Class<CharmAttachmentMeta> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { try { JAXBContext context = JAXBContext.newInstance(CharmAttachmentMeta.class); Unmarshaller attachmentUnmarshaller = context.createUnmarshaller(); return (CharmAttachmentMeta) attachmentUnmarshaller.unmarshal(entityStream); } catch (JAXBException e) { throw new ProcessingException("Error deserializing Attachment"); } }
@Test public void testVersionFilterSinceNegative() throws NoSuchMethodException { String version = "v-1"; try { testVersionFilter(version ); fail(); } catch (WebApplicationException e) { assertEquals(Status.NOT_FOUND.getStatusCode(), e.getResponse().getStatus()); } }
private void validate(String serviceName, IfExpression rule) { try { ModelValidationFacade.validateFlavorRule(rule, OperationContextHolder.getCurrentContext(), getEntityType()); } catch (ExpressionValidationException e) { String error = String.format("Failed to save rule '%s' for %s application due to validation error(s). %s", rule.getId(), serviceName, e.getMessage()); throw new WebApplicationException(error, e, Response.status(Response.Status.BAD_REQUEST).entity(e.getErrors()).build()); } }
PendingChangesServiceUrlRulesSteps getUrlRuleAndVerifyResponseIsRuleNotFound() { try { apiFacade.getUrlRuleByIdForService(serviceName, urlRule.getId()); Assert.fail(); } catch (WebApplicationException exception) { Assert.assertEquals(exception.getResponse().getStatus(), Response.Status.NOT_FOUND.getStatusCode()); } return this; }
private static void throwNotFound(String path, UriInfo ui) throws WebApplicationException { throw new WebApplicationException(Response.status( Response.Status.NOT_FOUND).entity( new ZError(ui.getRequestUri().toString(), path + " not found")) .build()); }
@PUT @Produces( { MediaType.APPLICATION_JSON, "application/javascript", MediaType.APPLICATION_XML }) @Consumes(MediaType.APPLICATION_OCTET_STREAM) public Response setZNode( @PathParam("path") String path, @QueryParam("callback") String callback, @DefaultValue("-1") @QueryParam("version") String versionParam, @DefaultValue("base64") @QueryParam("dataformat") String dataformat, @DefaultValue("false") @QueryParam("null") String setNull, @Context UriInfo ui, byte[] data) throws InterruptedException, KeeperException { ensurePathNotNull(path); int version; try { version = Integer.parseInt(versionParam); } catch (NumberFormatException e) { throw new WebApplicationException(Response.status( Response.Status.BAD_REQUEST).entity( new ZError(ui.getRequestUri().toString(), path + " bad version " + versionParam)).build()); } if (setNull.equals("true")) { data = null; } Stat stat = zk.setData(path, data, version); ZStat zstat = new ZStat(path, ui.getAbsolutePath().toString(), null, null, stat.getCzxid(), stat.getMzxid(), stat.getCtime(), stat .getMtime(), stat.getVersion(), stat.getCversion(), stat.getAversion(), stat.getEphemeralOwner(), stat .getDataLength(), stat.getNumChildren(), stat .getPzxid()); return Response.status(Response.Status.OK).entity( new JSONWithPadding(zstat, callback)).build(); }
/** * Return a list of domains of the given owner. */ @GET @Path("/domain") @Produces({ MediaType.APPLICATION_JSON /* , MediaType.APPLICATION_XML */}) public TimelineDomains getDomains( @Context HttpServletRequest req, @Context HttpServletResponse res, @QueryParam("owner") String owner) { init(res); owner = parseStr(owner); UserGroupInformation callerUGI = getUser(req); if (owner == null || owner.length() == 0) { if (callerUGI == null) { throw new BadRequestException("Domain owner is not specified."); } else { // By default it's going to list the caller's domains owner = callerUGI.getShortUserName(); } } try { return timelineDataManager.getDomains(owner, callerUGI); } catch (Exception e) { LOG.error("Error getting domains", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
private void validateCommand(String commandName) { if (commandMap.get(commandName) == null) { String message = "No such command '" + commandName + "'. Supported commmands are '" + String.join("', '", commandMap.keySet()) + "'"; throw new WebApplicationException(message, Status.NOT_FOUND); } }
@Test public void testUnauthorized() throws IOException { final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(); headers.add(HttpHeaders.AUTHORIZATION, "Bearer blahblahblah"); when(mockContext.getHeaders()).thenReturn(headers); final AuthFilter<String, Principal> filter = new AnonymousAuthFilter.Builder() .setAuthenticator(new AnonymousAuthenticator()).buildAuthFilter(); assertThrows(WebApplicationException.class, () -> filter.filter(mockContext)); }
public Response modifyProfile(UserDTO userDTO){ if (userDTO == null){ throw new WebApplicationException(UserErrorMessage.MODIFY_USER_FAIL_NO_USER_INFO, Response.Status.BAD_REQUEST); } validateDisplayNameAndAvatarUrl(userDTO); User user = getUser(userDTO.getUserID()); user.setDisplayName(user.getDisplayName()); user.setAvatarUrl(user.getAvatarUrl()); userDAO.save(user); return Response.status(Response.Status.OK).entity(getUserProfileResponse(user)).build(); }
@Test public void GroupNameIsTooLongTest() { GroupCreateRequest request = new GroupCreateRequest( "verrylongfifdsfdsfsdffdsfssafastnameamefdsafdsafsdfddfdddddsssssssssfsdfsfsdfsfsdfsdfsdffdsfsfsfsf", validPermissions, validRoles ); exception.expect(WebApplicationException.class); exception.expectMessage(GroupErrorMessages.GROUP_NAME_INVALID); controller.createPublicGroup(request); }
@Override public Response readById(UUID id) { try { final Optional<User> internalUser = this.service.read(id); if (internalUser.isPresent()) { return Response.status(Response.Status.OK).entity(internalUser.get()).build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (Exception e) { log.error(e.getMessage(), e); return mapper.toResponse(new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR).build())); } }
/** * Renew a session * * @param sessionId the existing session ID * @param tokenString a current valid Fernet token * @return a new Fernet token with the updated session state embedded */ @PUT @Path("/api/sessions/{sessionId}/renewal") public String renew(@PathParam("sessionId") final String sessionId, final String tokenString, @Context final HttpServletResponse servletResponse) { final Token inputToken = Token.fromString(tokenString); final Session session = inputToken.validateAndDecrypt(key, validator); if (!Objects.equals(sessionId, session.getSessionId())) { throw new BadRequestException("SessionID mismatch."); } final Instant lastRenewed = Instant.ofEpochSecond(session.getLastRenewalTime()); if (session.hasLastRenewalTime() && lastRenewed.isAfter(Instant.now().minus(Duration.ofMinutes(1)))) { // prevent denial-of-service // if token was renewed less than a minute ago, tell the client to back off servletResponse.addHeader("Retry-After", "60"); // Too Many Requests: https://tools.ietf.org/html/rfc6585#section-4 throw new WebApplicationException("Try again in a minute", 429); } // The token and session are valid, now update the session final Builder builder = Session.newBuilder(session); builder.setRenewalCount(session.getRenewalCount() + 1); builder.setLastRenewalTime(Instant.now().getEpochSecond()); final Session updatedSession = builder.build(); // store the updated session in a new Fernet token final Token retval = Token.generate(random, key, updatedSession.toByteArray()); return retval.serialise(); }
@Test(expected = WebApplicationException.class) public void testFetchJobSummariesThrowsExceptionIfSpecifiedPageIndexIsNegative() throws IOException { final List<JobDetails> jobSummaries = generateRandomJobDetails(); final JobDAO jobDAO = mockJobDAOThatReturns(jobSummaries); final JobResource jobResource = resourceThatUses(jobDAO); jobResource.getJobs( TestHelpers.generateSecureSecurityContext(), Optional.of(-1), // Should cause exception Optional.empty(), Optional.empty()); }
private void ensureMultipartDir(StagingFile handle) { try { if( !fileSystemService.fileExists(handle, "multipart") ) { fileSystemService.mkdir(handle, "multipart"); } } catch( Exception e ) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } }
public Response getMtaFiles(SecurityContext securityContext, String spaceGuid) { try { List<FileEntry> entries = fileService.listFiles(spaceGuid, null); List<FileMetadata> files = entries.stream().map(entry -> parseFileEntry(entry)).collect(Collectors.toList()); return Response.ok().entity(files).build(); } catch (FileStorageException e) { throw new WebApplicationException(e, Response.status(Status.INTERNAL_SERVER_ERROR).build()); } }
@Test public void testVersionFilterUntilNegative() throws NoSuchMethodException { String version = "v3"; try { testVersionFilter(version); fail(); } catch (WebApplicationException e) { assertEquals(Status.NOT_FOUND.getStatusCode(), e.getResponse().getStatus()); } }
@Override public void writeTo(final Object object, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException { try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8)) { GsonFactory.getGson().toJson(object, type.equals(genericType) ? type : genericType, writer); } catch (final IOException ex) { throw new RestfulException(ex); } }