target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test(expected = APIAccessDeniedException.class) public void testGetDelegationsNoEdOrg() throws Exception { securityContextInjector.setLeaAdminContext(); resource.getDelegations(); }
@GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); }
AdminDelegationResource { @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); } }
AdminDelegationResource { @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); } }
AdminDelegationResource { @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); } @PostConstruct void init(); @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getDelegations(); @PUT @Path("myEdOrg") @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response setLocalDelegation(EntityBody body, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response create(EntityBody body, @Context final UriInfo uriInfo); @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getSingleDelegation(); }
AdminDelegationResource { @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); } @PostConstruct void init(); @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getDelegations(); @PUT @Path("myEdOrg") @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response setLocalDelegation(EntityBody body, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response create(EntityBody body, @Context final UriInfo uriInfo); @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getSingleDelegation(); static final String RESOURCE_NAME; static final String LEA_ID; }
@Test public void testGetTenantIdField() { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey("meta.data.tenantId", "test.id.key.field"); assertEquals(key.getTenantIdField().toString(), "meta.data.tenantId"); }
public Text getTenantIdField() { return fieldNames[TENANT_FIELD]; }
TenantAndIdEmittableKey extends EmittableKey { public Text getTenantIdField() { return fieldNames[TENANT_FIELD]; } }
TenantAndIdEmittableKey extends EmittableKey { public Text getTenantIdField() { return fieldNames[TENANT_FIELD]; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); }
TenantAndIdEmittableKey extends EmittableKey { public Text getTenantIdField() { return fieldNames[TENANT_FIELD]; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); Text getTenantId(); void setTenantId(final Text id); Text getTenantIdField(); Text getId(); void setId(final Text id); Text getIdField(); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }
TenantAndIdEmittableKey extends EmittableKey { public Text getTenantIdField() { return fieldNames[TENANT_FIELD]; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); Text getTenantId(); void setTenantId(final Text id); Text getTenantIdField(); Text getId(); void setId(final Text id); Text getIdField(); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }
@Test(expected = MissingConfigException.class) public void missingPassword() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-s", "server", "-d", "localDir", "-port", "22" }; propUtils.getUploadProperties(args); }
public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); }
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } }
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); }
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); UploadProperties getUploadProperties(String[] args); }
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); UploadProperties getUploadProperties(String[] args); static final String KEY_USER; static final String KEY_PASSWORD; static final String KEY_SFTP_SERVER; static final String KEY_LOCAL_DIRECTORY; static final String KEY_PORT; final static Options OPTIONS; }
@Test public void testGetDelegationsBadRole() throws Exception { securityContextInjector.setEducatorContext(); Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), resource.getDelegations().getStatus()); }
@GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); }
AdminDelegationResource { @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); } }
AdminDelegationResource { @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); } }
AdminDelegationResource { @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); } @PostConstruct void init(); @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getDelegations(); @PUT @Path("myEdOrg") @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response setLocalDelegation(EntityBody body, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response create(EntityBody body, @Context final UriInfo uriInfo); @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getSingleDelegation(); }
AdminDelegationResource { @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); } @PostConstruct void init(); @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getDelegations(); @PUT @Path("myEdOrg") @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response setLocalDelegation(EntityBody body, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response create(EntityBody body, @Context final UriInfo uriInfo); @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getSingleDelegation(); static final String RESOURCE_NAME; static final String LEA_ID; }
@Test public void testGetSingleDelegation() throws Exception { securityContextInjector.setLeaAdminContext(); ((SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).setEdOrg("1234"); ((SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).setEdOrgId("1234"); Assert.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resource.getSingleDelegation().getStatus()); }
@GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getSingleDelegation() { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entity).build(); }
AdminDelegationResource { @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getSingleDelegation() { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entity).build(); } }
AdminDelegationResource { @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getSingleDelegation() { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entity).build(); } }
AdminDelegationResource { @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getSingleDelegation() { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entity).build(); } @PostConstruct void init(); @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getDelegations(); @PUT @Path("myEdOrg") @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response setLocalDelegation(EntityBody body, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response create(EntityBody body, @Context final UriInfo uriInfo); @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getSingleDelegation(); }
AdminDelegationResource { @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getSingleDelegation() { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entity).build(); } @PostConstruct void init(); @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getDelegations(); @PUT @Path("myEdOrg") @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response setLocalDelegation(EntityBody body, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response create(EntityBody body, @Context final UriInfo uriInfo); @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getSingleDelegation(); static final String RESOURCE_NAME; static final String LEA_ID; }
@SuppressWarnings("rawtypes") @Test public void testGoodCreate() throws URISyntaxException { when(uriInfo.getRequestUri()).thenReturn(new URI("http: EntityBody app = getNewApp(); Response resp = resource.post(app, uriInfo); assertEquals(STATUS_CREATED, resp.getStatus()); assertTrue("Client id set", app.get(CLIENT_ID).toString().length() == 10); assertTrue("Client secret set", app.get(CLIENT_SECRET).toString().length() == 48); Map reg = (Map) app.get(REGISTRATION); assertEquals("Reg is pending", "PENDING", reg.get(STATUS)); assertTrue("request date set", reg.containsKey(REQUEST_DATE)); assertFalse("approval date not set", reg.containsKey(APPROVAL_DATE)); }
@POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) public Response post(EntityBody newApp, @Context final UriInfo uriInfo) { if (newApp.containsKey(CLIENT_SECRET) || newApp.containsKey(CLIENT_ID) || newApp.containsKey("id")) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Auto-generated attribute (id|client_secret|client_id) specified in POST. " + "Remove attribute and try again."); return Response.status(Status.BAD_REQUEST).entity(body).build(); } if (missingRequiredUrls(newApp)) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Applications that are not marked as installed must have a application url and redirect url"); return Response.status(Status.BAD_REQUEST).entity(body).build(); } newApp.put(AUTHORIZED_ED_ORGS, new ArrayList<String>()); String clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); while (isDuplicateToken(clientId)) { clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); } newApp.put(CLIENT_ID, clientId); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); newApp.put(CREATED_BY, principal.getExternalId()); if (principal.getSandboxTenant() != null) { newApp.put(AUTHOR_SANDBOX_TENANT, principal.getSandboxTenant()); } if (principal.getFirstName() != null) { newApp.put(AUTHOR_FIRST_NAME, principal.getFirstName()); } if (principal.getLastName() != null) { newApp.put(AUTHOR_LAST_NAME, principal.getLastName()); } Map<String, Object> registration = new HashMap<String, Object>(); registration.put(STATUS, STATUS_PENDING); if (autoRegister) { registration.put(APPROVAL_DATE, System.currentTimeMillis()); registration.put(STATUS, STATUS_APPROVED); } registration.put(REQUEST_DATE, System.currentTimeMillis()); newApp.put(REGISTRATION, registration); String clientSecret = TokenGenerator.generateToken(CLIENT_SECRET_LENGTH); newApp.put(CLIENT_SECRET, clientSecret); for (String fieldName : PERMANENT_FIELDS) { newApp.remove(fieldName); } return super.post(newApp, uriInfo); }
ApplicationResource extends UnversionedResource { @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) public Response post(EntityBody newApp, @Context final UriInfo uriInfo) { if (newApp.containsKey(CLIENT_SECRET) || newApp.containsKey(CLIENT_ID) || newApp.containsKey("id")) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Auto-generated attribute (id|client_secret|client_id) specified in POST. " + "Remove attribute and try again."); return Response.status(Status.BAD_REQUEST).entity(body).build(); } if (missingRequiredUrls(newApp)) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Applications that are not marked as installed must have a application url and redirect url"); return Response.status(Status.BAD_REQUEST).entity(body).build(); } newApp.put(AUTHORIZED_ED_ORGS, new ArrayList<String>()); String clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); while (isDuplicateToken(clientId)) { clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); } newApp.put(CLIENT_ID, clientId); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); newApp.put(CREATED_BY, principal.getExternalId()); if (principal.getSandboxTenant() != null) { newApp.put(AUTHOR_SANDBOX_TENANT, principal.getSandboxTenant()); } if (principal.getFirstName() != null) { newApp.put(AUTHOR_FIRST_NAME, principal.getFirstName()); } if (principal.getLastName() != null) { newApp.put(AUTHOR_LAST_NAME, principal.getLastName()); } Map<String, Object> registration = new HashMap<String, Object>(); registration.put(STATUS, STATUS_PENDING); if (autoRegister) { registration.put(APPROVAL_DATE, System.currentTimeMillis()); registration.put(STATUS, STATUS_APPROVED); } registration.put(REQUEST_DATE, System.currentTimeMillis()); newApp.put(REGISTRATION, registration); String clientSecret = TokenGenerator.generateToken(CLIENT_SECRET_LENGTH); newApp.put(CLIENT_SECRET, clientSecret); for (String fieldName : PERMANENT_FIELDS) { newApp.remove(fieldName); } return super.post(newApp, uriInfo); } }
ApplicationResource extends UnversionedResource { @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) public Response post(EntityBody newApp, @Context final UriInfo uriInfo) { if (newApp.containsKey(CLIENT_SECRET) || newApp.containsKey(CLIENT_ID) || newApp.containsKey("id")) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Auto-generated attribute (id|client_secret|client_id) specified in POST. " + "Remove attribute and try again."); return Response.status(Status.BAD_REQUEST).entity(body).build(); } if (missingRequiredUrls(newApp)) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Applications that are not marked as installed must have a application url and redirect url"); return Response.status(Status.BAD_REQUEST).entity(body).build(); } newApp.put(AUTHORIZED_ED_ORGS, new ArrayList<String>()); String clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); while (isDuplicateToken(clientId)) { clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); } newApp.put(CLIENT_ID, clientId); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); newApp.put(CREATED_BY, principal.getExternalId()); if (principal.getSandboxTenant() != null) { newApp.put(AUTHOR_SANDBOX_TENANT, principal.getSandboxTenant()); } if (principal.getFirstName() != null) { newApp.put(AUTHOR_FIRST_NAME, principal.getFirstName()); } if (principal.getLastName() != null) { newApp.put(AUTHOR_LAST_NAME, principal.getLastName()); } Map<String, Object> registration = new HashMap<String, Object>(); registration.put(STATUS, STATUS_PENDING); if (autoRegister) { registration.put(APPROVAL_DATE, System.currentTimeMillis()); registration.put(STATUS, STATUS_APPROVED); } registration.put(REQUEST_DATE, System.currentTimeMillis()); newApp.put(REGISTRATION, registration); String clientSecret = TokenGenerator.generateToken(CLIENT_SECRET_LENGTH); newApp.put(CLIENT_SECRET, clientSecret); for (String fieldName : PERMANENT_FIELDS) { newApp.remove(fieldName); } return super.post(newApp, uriInfo); } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); }
ApplicationResource extends UnversionedResource { @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) public Response post(EntityBody newApp, @Context final UriInfo uriInfo) { if (newApp.containsKey(CLIENT_SECRET) || newApp.containsKey(CLIENT_ID) || newApp.containsKey("id")) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Auto-generated attribute (id|client_secret|client_id) specified in POST. " + "Remove attribute and try again."); return Response.status(Status.BAD_REQUEST).entity(body).build(); } if (missingRequiredUrls(newApp)) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Applications that are not marked as installed must have a application url and redirect url"); return Response.status(Status.BAD_REQUEST).entity(body).build(); } newApp.put(AUTHORIZED_ED_ORGS, new ArrayList<String>()); String clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); while (isDuplicateToken(clientId)) { clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); } newApp.put(CLIENT_ID, clientId); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); newApp.put(CREATED_BY, principal.getExternalId()); if (principal.getSandboxTenant() != null) { newApp.put(AUTHOR_SANDBOX_TENANT, principal.getSandboxTenant()); } if (principal.getFirstName() != null) { newApp.put(AUTHOR_FIRST_NAME, principal.getFirstName()); } if (principal.getLastName() != null) { newApp.put(AUTHOR_LAST_NAME, principal.getLastName()); } Map<String, Object> registration = new HashMap<String, Object>(); registration.put(STATUS, STATUS_PENDING); if (autoRegister) { registration.put(APPROVAL_DATE, System.currentTimeMillis()); registration.put(STATUS, STATUS_APPROVED); } registration.put(REQUEST_DATE, System.currentTimeMillis()); newApp.put(REGISTRATION, registration); String clientSecret = TokenGenerator.generateToken(CLIENT_SECRET_LENGTH); newApp.put(CLIENT_SECRET, clientSecret); for (String fieldName : PERMANENT_FIELDS) { newApp.remove(fieldName); } return super.post(newApp, uriInfo); } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); void setAutoRegister(boolean register); @PostConstruct void init(); @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) Response post(EntityBody newApp, @Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) @Override Response getAll(@Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @SuppressWarnings("unchecked") @PUT @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD, Right.SLC_APP_APPROVE}) @Override Response put(@PathParam(UUID) String uuid, EntityBody app, @Context final UriInfo uriInfo); boolean isSandboxEnabled(); void setSandboxEnabled(boolean sandboxEnabled); }
ApplicationResource extends UnversionedResource { @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) public Response post(EntityBody newApp, @Context final UriInfo uriInfo) { if (newApp.containsKey(CLIENT_SECRET) || newApp.containsKey(CLIENT_ID) || newApp.containsKey("id")) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Auto-generated attribute (id|client_secret|client_id) specified in POST. " + "Remove attribute and try again."); return Response.status(Status.BAD_REQUEST).entity(body).build(); } if (missingRequiredUrls(newApp)) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Applications that are not marked as installed must have a application url and redirect url"); return Response.status(Status.BAD_REQUEST).entity(body).build(); } newApp.put(AUTHORIZED_ED_ORGS, new ArrayList<String>()); String clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); while (isDuplicateToken(clientId)) { clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); } newApp.put(CLIENT_ID, clientId); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); newApp.put(CREATED_BY, principal.getExternalId()); if (principal.getSandboxTenant() != null) { newApp.put(AUTHOR_SANDBOX_TENANT, principal.getSandboxTenant()); } if (principal.getFirstName() != null) { newApp.put(AUTHOR_FIRST_NAME, principal.getFirstName()); } if (principal.getLastName() != null) { newApp.put(AUTHOR_LAST_NAME, principal.getLastName()); } Map<String, Object> registration = new HashMap<String, Object>(); registration.put(STATUS, STATUS_PENDING); if (autoRegister) { registration.put(APPROVAL_DATE, System.currentTimeMillis()); registration.put(STATUS, STATUS_APPROVED); } registration.put(REQUEST_DATE, System.currentTimeMillis()); newApp.put(REGISTRATION, registration); String clientSecret = TokenGenerator.generateToken(CLIENT_SECRET_LENGTH); newApp.put(CLIENT_SECRET, clientSecret); for (String fieldName : PERMANENT_FIELDS) { newApp.remove(fieldName); } return super.post(newApp, uriInfo); } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); void setAutoRegister(boolean register); @PostConstruct void init(); @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) Response post(EntityBody newApp, @Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) @Override Response getAll(@Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @SuppressWarnings("unchecked") @PUT @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD, Right.SLC_APP_APPROVE}) @Override Response put(@PathParam(UUID) String uuid, EntityBody app, @Context final UriInfo uriInfo); boolean isSandboxEnabled(); void setSandboxEnabled(boolean sandboxEnabled); static final String AUTHORIZED_ED_ORGS; static final String APPLICATION; static final String MESSAGE; static final String STATUS_PENDING; static final String STATUS_APPROVED; static final String REGISTRATION; static final String CLIENT_ID; static final String CLIENT_SECRET; static final String APPROVAL_DATE; static final String REQUEST_DATE; static final String STATUS; static final String RESOURCE_NAME; static final String UUID; static final String LOCATION; }
@Test public void testBadDelete() throws URISyntaxException { String uuid = "9999999999"; when(uriInfo.getRequestUri()).thenReturn(new URI("http: try { @SuppressWarnings("unused") Response resp = resource.delete(uuid, uriInfo); } catch (EntityNotFoundException e) { assertTrue(true); return; } assertTrue(false); }
@DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) public Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { EntityBody ent = service.get(uuid); if (ent != null) { validateDeveloperHasAccessToApp(ent); } return super.delete(uuid, uriInfo); }
ApplicationResource extends UnversionedResource { @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) public Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { EntityBody ent = service.get(uuid); if (ent != null) { validateDeveloperHasAccessToApp(ent); } return super.delete(uuid, uriInfo); } }
ApplicationResource extends UnversionedResource { @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) public Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { EntityBody ent = service.get(uuid); if (ent != null) { validateDeveloperHasAccessToApp(ent); } return super.delete(uuid, uriInfo); } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); }
ApplicationResource extends UnversionedResource { @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) public Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { EntityBody ent = service.get(uuid); if (ent != null) { validateDeveloperHasAccessToApp(ent); } return super.delete(uuid, uriInfo); } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); void setAutoRegister(boolean register); @PostConstruct void init(); @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) Response post(EntityBody newApp, @Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) @Override Response getAll(@Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @SuppressWarnings("unchecked") @PUT @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD, Right.SLC_APP_APPROVE}) @Override Response put(@PathParam(UUID) String uuid, EntityBody app, @Context final UriInfo uriInfo); boolean isSandboxEnabled(); void setSandboxEnabled(boolean sandboxEnabled); }
ApplicationResource extends UnversionedResource { @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) public Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { EntityBody ent = service.get(uuid); if (ent != null) { validateDeveloperHasAccessToApp(ent); } return super.delete(uuid, uriInfo); } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); void setAutoRegister(boolean register); @PostConstruct void init(); @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) Response post(EntityBody newApp, @Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) @Override Response getAll(@Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @SuppressWarnings("unchecked") @PUT @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD, Right.SLC_APP_APPROVE}) @Override Response put(@PathParam(UUID) String uuid, EntityBody app, @Context final UriInfo uriInfo); boolean isSandboxEnabled(); void setSandboxEnabled(boolean sandboxEnabled); static final String AUTHORIZED_ED_ORGS; static final String APPLICATION; static final String MESSAGE; static final String STATUS_PENDING; static final String STATUS_APPROVED; static final String REGISTRATION; static final String CLIENT_ID; static final String CLIENT_SECRET; static final String APPROVAL_DATE; static final String REQUEST_DATE; static final String STATUS; static final String RESOURCE_NAME; static final String UUID; static final String LOCATION; }
@Test public void testGoodGet() throws URISyntaxException { String uuid = createApp(); when(uriInfo.getRequestUri()).thenReturn(new URI("http: Response resp = resource.getWithId(uuid, uriInfo); assertEquals(STATUS_FOUND, resp.getStatus()); }
@SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; }
ApplicationResource extends UnversionedResource { @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; } }
ApplicationResource extends UnversionedResource { @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); }
ApplicationResource extends UnversionedResource { @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); void setAutoRegister(boolean register); @PostConstruct void init(); @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) Response post(EntityBody newApp, @Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) @Override Response getAll(@Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @SuppressWarnings("unchecked") @PUT @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD, Right.SLC_APP_APPROVE}) @Override Response put(@PathParam(UUID) String uuid, EntityBody app, @Context final UriInfo uriInfo); boolean isSandboxEnabled(); void setSandboxEnabled(boolean sandboxEnabled); }
ApplicationResource extends UnversionedResource { @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); void setAutoRegister(boolean register); @PostConstruct void init(); @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) Response post(EntityBody newApp, @Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) @Override Response getAll(@Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @SuppressWarnings("unchecked") @PUT @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD, Right.SLC_APP_APPROVE}) @Override Response put(@PathParam(UUID) String uuid, EntityBody app, @Context final UriInfo uriInfo); boolean isSandboxEnabled(); void setSandboxEnabled(boolean sandboxEnabled); static final String AUTHORIZED_ED_ORGS; static final String APPLICATION; static final String MESSAGE; static final String STATUS_PENDING; static final String STATUS_APPROVED; static final String REGISTRATION; static final String CLIENT_ID; static final String CLIENT_SECRET; static final String APPROVAL_DATE; static final String REQUEST_DATE; static final String STATUS; static final String RESOURCE_NAME; static final String UUID; static final String LOCATION; }
@Test public void testBadGet() throws URISyntaxException { String uuid = "9999999999"; when(uriInfo.getRequestUri()).thenReturn(new URI("http: try { Response resp = resource.getWithId(uuid, uriInfo); assertEquals(STATUS_NOT_FOUND, resp.getStatus()); } catch (EntityNotFoundException e) { assertTrue(true); return; } assertTrue(false); }
@SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; }
ApplicationResource extends UnversionedResource { @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; } }
ApplicationResource extends UnversionedResource { @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); }
ApplicationResource extends UnversionedResource { @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); void setAutoRegister(boolean register); @PostConstruct void init(); @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) Response post(EntityBody newApp, @Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) @Override Response getAll(@Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @SuppressWarnings("unchecked") @PUT @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD, Right.SLC_APP_APPROVE}) @Override Response put(@PathParam(UUID) String uuid, EntityBody app, @Context final UriInfo uriInfo); boolean isSandboxEnabled(); void setSandboxEnabled(boolean sandboxEnabled); }
ApplicationResource extends UnversionedResource { @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); void setAutoRegister(boolean register); @PostConstruct void init(); @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) Response post(EntityBody newApp, @Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) @Override Response getAll(@Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @SuppressWarnings("unchecked") @PUT @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD, Right.SLC_APP_APPROVE}) @Override Response put(@PathParam(UUID) String uuid, EntityBody app, @Context final UriInfo uriInfo); boolean isSandboxEnabled(); void setSandboxEnabled(boolean sandboxEnabled); static final String AUTHORIZED_ED_ORGS; static final String APPLICATION; static final String MESSAGE; static final String STATUS_PENDING; static final String STATUS_APPROVED; static final String REGISTRATION; static final String CLIENT_ID; static final String CLIENT_SECRET; static final String APPROVAL_DATE; static final String REQUEST_DATE; static final String STATUS; static final String RESOURCE_NAME; static final String UUID; static final String LOCATION; }
@Test public void generateArtifactRequestTest() { ArtifactResolve ar = artifactBindingHelper.generateArtifactResolveRequest("test1234", pkEntry, idpUrl); Assert.assertEquals("test1234", ar.getArtifact().getArtifact()); Assert.assertTrue(ar.isSigned()); Assert.assertNotNull(ar.getSignature().getKeyInfo().getX509Datas()); Assert.assertEquals(ar.getDestination(), idpUrl); Assert.assertEquals(issuerName, ar.getIssuer().getValue()); }
protected ArtifactResolve generateArtifactResolveRequest(String artifactString, KeyStore.PrivateKeyEntry pkEntry, String idpUrl) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Artifact artifact = (Artifact) xmlObjectBuilderFactory.getBuilder(Artifact.DEFAULT_ELEMENT_NAME).buildObject(Artifact.DEFAULT_ELEMENT_NAME); artifact.setArtifact(artifactString); Issuer issuer = (Issuer) xmlObjectBuilderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME).buildObject(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(issuerName); ArtifactResolve artifactResolve = (ArtifactResolve) xmlObjectBuilderFactory.getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME).buildObject(ArtifactResolve.DEFAULT_ELEMENT_NAME); artifactResolve.setIssuer(issuer); artifactResolve.setIssueInstant(new DateTime()); artifactResolve.setID(UUID.randomUUID().toString()); artifactResolve.setDestination(idpUrl); artifactResolve.setArtifact(artifact); Signature signature = samlHelper.getDigitalSignature(pkEntry); artifactResolve.setSignature(signature); try { Configuration.getMarshallerFactory().getMarshaller(artifactResolve).marshall(artifactResolve); } catch (MarshallingException ex) { LOG.error("Error composing artifact resolution request: Marshalling artifact resolution request failed", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } try { Signer.signObject(signature); } catch (SignatureException ex) { LOG.error("Error composing artifact resolution request: Failed to sign artifact resolution request", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } return artifactResolve; }
ArtifactBindingHelper { protected ArtifactResolve generateArtifactResolveRequest(String artifactString, KeyStore.PrivateKeyEntry pkEntry, String idpUrl) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Artifact artifact = (Artifact) xmlObjectBuilderFactory.getBuilder(Artifact.DEFAULT_ELEMENT_NAME).buildObject(Artifact.DEFAULT_ELEMENT_NAME); artifact.setArtifact(artifactString); Issuer issuer = (Issuer) xmlObjectBuilderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME).buildObject(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(issuerName); ArtifactResolve artifactResolve = (ArtifactResolve) xmlObjectBuilderFactory.getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME).buildObject(ArtifactResolve.DEFAULT_ELEMENT_NAME); artifactResolve.setIssuer(issuer); artifactResolve.setIssueInstant(new DateTime()); artifactResolve.setID(UUID.randomUUID().toString()); artifactResolve.setDestination(idpUrl); artifactResolve.setArtifact(artifact); Signature signature = samlHelper.getDigitalSignature(pkEntry); artifactResolve.setSignature(signature); try { Configuration.getMarshallerFactory().getMarshaller(artifactResolve).marshall(artifactResolve); } catch (MarshallingException ex) { LOG.error("Error composing artifact resolution request: Marshalling artifact resolution request failed", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } try { Signer.signObject(signature); } catch (SignatureException ex) { LOG.error("Error composing artifact resolution request: Failed to sign artifact resolution request", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } return artifactResolve; } }
ArtifactBindingHelper { protected ArtifactResolve generateArtifactResolveRequest(String artifactString, KeyStore.PrivateKeyEntry pkEntry, String idpUrl) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Artifact artifact = (Artifact) xmlObjectBuilderFactory.getBuilder(Artifact.DEFAULT_ELEMENT_NAME).buildObject(Artifact.DEFAULT_ELEMENT_NAME); artifact.setArtifact(artifactString); Issuer issuer = (Issuer) xmlObjectBuilderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME).buildObject(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(issuerName); ArtifactResolve artifactResolve = (ArtifactResolve) xmlObjectBuilderFactory.getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME).buildObject(ArtifactResolve.DEFAULT_ELEMENT_NAME); artifactResolve.setIssuer(issuer); artifactResolve.setIssueInstant(new DateTime()); artifactResolve.setID(UUID.randomUUID().toString()); artifactResolve.setDestination(idpUrl); artifactResolve.setArtifact(artifact); Signature signature = samlHelper.getDigitalSignature(pkEntry); artifactResolve.setSignature(signature); try { Configuration.getMarshallerFactory().getMarshaller(artifactResolve).marshall(artifactResolve); } catch (MarshallingException ex) { LOG.error("Error composing artifact resolution request: Marshalling artifact resolution request failed", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } try { Signer.signObject(signature); } catch (SignatureException ex) { LOG.error("Error composing artifact resolution request: Failed to sign artifact resolution request", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } return artifactResolve; } }
ArtifactBindingHelper { protected ArtifactResolve generateArtifactResolveRequest(String artifactString, KeyStore.PrivateKeyEntry pkEntry, String idpUrl) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Artifact artifact = (Artifact) xmlObjectBuilderFactory.getBuilder(Artifact.DEFAULT_ELEMENT_NAME).buildObject(Artifact.DEFAULT_ELEMENT_NAME); artifact.setArtifact(artifactString); Issuer issuer = (Issuer) xmlObjectBuilderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME).buildObject(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(issuerName); ArtifactResolve artifactResolve = (ArtifactResolve) xmlObjectBuilderFactory.getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME).buildObject(ArtifactResolve.DEFAULT_ELEMENT_NAME); artifactResolve.setIssuer(issuer); artifactResolve.setIssueInstant(new DateTime()); artifactResolve.setID(UUID.randomUUID().toString()); artifactResolve.setDestination(idpUrl); artifactResolve.setArtifact(artifact); Signature signature = samlHelper.getDigitalSignature(pkEntry); artifactResolve.setSignature(signature); try { Configuration.getMarshallerFactory().getMarshaller(artifactResolve).marshall(artifactResolve); } catch (MarshallingException ex) { LOG.error("Error composing artifact resolution request: Marshalling artifact resolution request failed", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } try { Signer.signObject(signature); } catch (SignatureException ex) { LOG.error("Error composing artifact resolution request: Failed to sign artifact resolution request", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } return artifactResolve; } }
ArtifactBindingHelper { protected ArtifactResolve generateArtifactResolveRequest(String artifactString, KeyStore.PrivateKeyEntry pkEntry, String idpUrl) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Artifact artifact = (Artifact) xmlObjectBuilderFactory.getBuilder(Artifact.DEFAULT_ELEMENT_NAME).buildObject(Artifact.DEFAULT_ELEMENT_NAME); artifact.setArtifact(artifactString); Issuer issuer = (Issuer) xmlObjectBuilderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME).buildObject(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(issuerName); ArtifactResolve artifactResolve = (ArtifactResolve) xmlObjectBuilderFactory.getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME).buildObject(ArtifactResolve.DEFAULT_ELEMENT_NAME); artifactResolve.setIssuer(issuer); artifactResolve.setIssueInstant(new DateTime()); artifactResolve.setID(UUID.randomUUID().toString()); artifactResolve.setDestination(idpUrl); artifactResolve.setArtifact(artifact); Signature signature = samlHelper.getDigitalSignature(pkEntry); artifactResolve.setSignature(signature); try { Configuration.getMarshallerFactory().getMarshaller(artifactResolve).marshall(artifactResolve); } catch (MarshallingException ex) { LOG.error("Error composing artifact resolution request: Marshalling artifact resolution request failed", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } try { Signer.signObject(signature); } catch (SignatureException ex) { LOG.error("Error composing artifact resolution request: Failed to sign artifact resolution request", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } return artifactResolve; } }
@Test public void generateSOAPEnvelopeTest() { ArtifactResolve artifactRequest = Mockito.mock(ArtifactResolve.class); Envelope env = artifactBindingHelper.generateSOAPEnvelope(artifactRequest); Assert.assertEquals(artifactRequest, env.getBody().getUnknownXMLObjects().get(0)); Assert.assertEquals(Envelope.DEFAULT_ELEMENT_NAME, env.getElementQName()); }
protected Envelope generateSOAPEnvelope(ArtifactResolve artifactResolutionRequest) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Envelope envelope = (Envelope) xmlObjectBuilderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME).buildObject(Envelope.DEFAULT_ELEMENT_NAME); Body body = (Body) xmlObjectBuilderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME); body.getUnknownXMLObjects().add(artifactResolutionRequest); envelope.setBody(body); return envelope; }
ArtifactBindingHelper { protected Envelope generateSOAPEnvelope(ArtifactResolve artifactResolutionRequest) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Envelope envelope = (Envelope) xmlObjectBuilderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME).buildObject(Envelope.DEFAULT_ELEMENT_NAME); Body body = (Body) xmlObjectBuilderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME); body.getUnknownXMLObjects().add(artifactResolutionRequest); envelope.setBody(body); return envelope; } }
ArtifactBindingHelper { protected Envelope generateSOAPEnvelope(ArtifactResolve artifactResolutionRequest) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Envelope envelope = (Envelope) xmlObjectBuilderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME).buildObject(Envelope.DEFAULT_ELEMENT_NAME); Body body = (Body) xmlObjectBuilderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME); body.getUnknownXMLObjects().add(artifactResolutionRequest); envelope.setBody(body); return envelope; } }
ArtifactBindingHelper { protected Envelope generateSOAPEnvelope(ArtifactResolve artifactResolutionRequest) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Envelope envelope = (Envelope) xmlObjectBuilderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME).buildObject(Envelope.DEFAULT_ELEMENT_NAME); Body body = (Body) xmlObjectBuilderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME); body.getUnknownXMLObjects().add(artifactResolutionRequest); envelope.setBody(body); return envelope; } }
ArtifactBindingHelper { protected Envelope generateSOAPEnvelope(ArtifactResolve artifactResolutionRequest) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Envelope envelope = (Envelope) xmlObjectBuilderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME).buildObject(Envelope.DEFAULT_ELEMENT_NAME); Body body = (Body) xmlObjectBuilderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME); body.getUnknownXMLObjects().add(artifactResolutionRequest); envelope.setBody(body); return envelope; } }
@Test public void testGetAuthForNonExistingAppAndNonExistingAuth() { ResponseImpl resp = (ResponseImpl) res.getAuthorization("someAppId", null); Assert.assertEquals(404, resp.getStatus()); }
@GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); static final String RESOURCE_NAME; static final String APP_ID; static final String EDORG_IDS; }
@Test public void testGetAuthForNonExistingAppAndExistingAuth() { Map<String, Object> auth = new HashMap<String, Object>(); auth.put("applicationId", "someAppId"); auth.put("edorgs", getAuthList("someOtherEdorg")); repo.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorization("someAppId", null); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertFalse((Boolean) ent.get("authorized")); }
@GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); static final String RESOURCE_NAME; static final String APP_ID; static final String EDORG_IDS; }
@Test public void testGetIdField() { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey("meta.data.tenantId", "test.id.key.field"); assertEquals(key.getIdField().toString(), "test.id.key.field"); }
public Text getIdField() { return fieldNames[ID_FIELD]; }
TenantAndIdEmittableKey extends EmittableKey { public Text getIdField() { return fieldNames[ID_FIELD]; } }
TenantAndIdEmittableKey extends EmittableKey { public Text getIdField() { return fieldNames[ID_FIELD]; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); }
TenantAndIdEmittableKey extends EmittableKey { public Text getIdField() { return fieldNames[ID_FIELD]; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); Text getTenantId(); void setTenantId(final Text id); Text getTenantIdField(); Text getId(); void setId(final Text id); Text getIdField(); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }
TenantAndIdEmittableKey extends EmittableKey { public Text getIdField() { return fieldNames[ID_FIELD]; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); Text getTenantId(); void setTenantId(final Text id); Text getTenantIdField(); Text getId(); void setId(final Text id); Text getIdField(); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }
@Test public void testGetAuthForNonExistingAppAndExistingAuth2() { Map<String, Object> auth = new HashMap<String, Object>(); auth.put("applicationId", "someAppId"); auth.put("edorgs", getAuthList(SecurityUtil.getEdOrgId())); repo.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorization("someAppId", null); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertTrue((Boolean) ent.get("authorized")); }
@GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); static final String RESOURCE_NAME; static final String APP_ID; static final String EDORG_IDS; }
@Test public void testGetAuthForExistingAppAndNonExistingAuth() { Map<String, Object> appBody = new HashMap<String, Object>(); Entity app = repo.create("application", appBody); ResponseImpl resp = (ResponseImpl) res.getAuthorization(app.getEntityId(), null); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertFalse((Boolean) ent.get("authorized")); }
@GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); static final String RESOURCE_NAME; static final String APP_ID; static final String EDORG_IDS; }
@Test public void testGetAuthForExistingAppAndExistingAuth() { Map<String, Object> appBody = new HashMap<String, Object>(); Entity app = repo.create("application", appBody); Map<String, Object> auth = new HashMap<String, Object>(); auth.put("applicationId", app.getEntityId()); auth.put("edorgs", getAuthList(SecurityUtil.getEdOrgId())); repo.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorization(app.getEntityId(), null); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertTrue((Boolean) ent.get("authorized")); }
@GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); static final String RESOURCE_NAME; static final String APP_ID; static final String EDORG_IDS; }
@Test public void testGetAuthForExistingAppAndExistingAuth2() { Map<String, Object> appBody = new HashMap<String, Object>(); Entity app = repo.create("application", appBody); Map<String, Object> auth = new HashMap<String, Object>(); auth.put("applicationId", app.getEntityId()); auth.put("edorgs", getAuthList("someOtherEdorg")); repo.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorization(app.getEntityId(), null); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertFalse((Boolean) ent.get("authorized")); }
@GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); static final String RESOURCE_NAME; static final String APP_ID; static final String EDORG_IDS; }
@Test public void testGetAuthForExistingAppAndExistingAuthAndEdorg() { Map<String, Object> appBody = new HashMap<String, Object>(); Entity app = repo.create("application", appBody); Map<String, Object> auth = new HashMap<String, Object>(); auth.put("applicationId", app.getEntityId()); auth.put("edorgs", getAuthList("someOtherEdorg")); repo.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorization(app.getEntityId(), SecurityUtil.getEdOrgId()); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertFalse((Boolean) ent.get("authorized")); }
@GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); }
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); static final String RESOURCE_NAME; static final String APP_ID; static final String EDORG_IDS; }
@Test public void testGetAuths() { Map<String, Object> appBody = new HashMap<String, Object>(); Entity app = repo.create("application", appBody); Map<String, Object> auth = new HashMap<String, Object>(); auth.put("applicationId", app.getEntityId()); auth.put("edorgs", getAuthList(SecurityUtil.getEdOrgId())); repo.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorizations(null); Assert.assertEquals(200, resp.getStatus()); List ents = (List) resp.getEntity(); Assert.assertEquals(1, ents.size()); }
@GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorizations(@QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Iterable<EntityBody> ents = null; if (principal.isAdminRealmAuthenticated()) { ents = service.list(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs))); } else { ents = filterOutAutoAuthorized(service.listBasedOnContextualRoles(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs)))); } Iterable<Entity> appQuery = repo.findAll("application", new NeutralQuery()); Map<String, Entity> allApps = new HashMap<String, Entity>(); for (Entity ent : appQuery) { if(!isAutoAuthorizedApp(ent)) { allApps.put(ent.getEntityId(), ent); } } List<Map> results = new ArrayList<Map>(); for (EntityBody body : ents) { HashMap<String, Object> entity = new HashMap<String, Object>(); String appId = (String) body.get("applicationId"); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) body.get("edorgs"); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", true); if(!isSEAAdmin()) { entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } results.add(entity); allApps.remove(appId); } for (Map.Entry<String, Entity> entry : allApps.entrySet()) { Boolean autoApprove = (Boolean) entry.getValue().getBody().get("allowed_for_all_edorgs"); List<String> approvedEdorgs = (List<String>) entry.getValue().getBody().get("authorized_ed_orgs"); if ((autoApprove != null && autoApprove) || isSEAAdmin() || (approvedEdorgs != null && CollectionUtils.containsAny(approvedEdorgs, inScopeEdOrgs))) { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", entry.getKey()); entity.put("appId", entry.getKey()); entity.put("authorized", false); results.add(entity); } } return Response.status(Status.OK).entity(results).build(); }
ApplicationAuthorizationResource { @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorizations(@QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Iterable<EntityBody> ents = null; if (principal.isAdminRealmAuthenticated()) { ents = service.list(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs))); } else { ents = filterOutAutoAuthorized(service.listBasedOnContextualRoles(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs)))); } Iterable<Entity> appQuery = repo.findAll("application", new NeutralQuery()); Map<String, Entity> allApps = new HashMap<String, Entity>(); for (Entity ent : appQuery) { if(!isAutoAuthorizedApp(ent)) { allApps.put(ent.getEntityId(), ent); } } List<Map> results = new ArrayList<Map>(); for (EntityBody body : ents) { HashMap<String, Object> entity = new HashMap<String, Object>(); String appId = (String) body.get("applicationId"); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) body.get("edorgs"); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", true); if(!isSEAAdmin()) { entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } results.add(entity); allApps.remove(appId); } for (Map.Entry<String, Entity> entry : allApps.entrySet()) { Boolean autoApprove = (Boolean) entry.getValue().getBody().get("allowed_for_all_edorgs"); List<String> approvedEdorgs = (List<String>) entry.getValue().getBody().get("authorized_ed_orgs"); if ((autoApprove != null && autoApprove) || isSEAAdmin() || (approvedEdorgs != null && CollectionUtils.containsAny(approvedEdorgs, inScopeEdOrgs))) { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", entry.getKey()); entity.put("appId", entry.getKey()); entity.put("authorized", false); results.add(entity); } } return Response.status(Status.OK).entity(results).build(); } }
ApplicationAuthorizationResource { @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorizations(@QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Iterable<EntityBody> ents = null; if (principal.isAdminRealmAuthenticated()) { ents = service.list(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs))); } else { ents = filterOutAutoAuthorized(service.listBasedOnContextualRoles(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs)))); } Iterable<Entity> appQuery = repo.findAll("application", new NeutralQuery()); Map<String, Entity> allApps = new HashMap<String, Entity>(); for (Entity ent : appQuery) { if(!isAutoAuthorizedApp(ent)) { allApps.put(ent.getEntityId(), ent); } } List<Map> results = new ArrayList<Map>(); for (EntityBody body : ents) { HashMap<String, Object> entity = new HashMap<String, Object>(); String appId = (String) body.get("applicationId"); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) body.get("edorgs"); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", true); if(!isSEAAdmin()) { entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } results.add(entity); allApps.remove(appId); } for (Map.Entry<String, Entity> entry : allApps.entrySet()) { Boolean autoApprove = (Boolean) entry.getValue().getBody().get("allowed_for_all_edorgs"); List<String> approvedEdorgs = (List<String>) entry.getValue().getBody().get("authorized_ed_orgs"); if ((autoApprove != null && autoApprove) || isSEAAdmin() || (approvedEdorgs != null && CollectionUtils.containsAny(approvedEdorgs, inScopeEdOrgs))) { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", entry.getKey()); entity.put("appId", entry.getKey()); entity.put("authorized", false); results.add(entity); } } return Response.status(Status.OK).entity(results).build(); } }
ApplicationAuthorizationResource { @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorizations(@QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Iterable<EntityBody> ents = null; if (principal.isAdminRealmAuthenticated()) { ents = service.list(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs))); } else { ents = filterOutAutoAuthorized(service.listBasedOnContextualRoles(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs)))); } Iterable<Entity> appQuery = repo.findAll("application", new NeutralQuery()); Map<String, Entity> allApps = new HashMap<String, Entity>(); for (Entity ent : appQuery) { if(!isAutoAuthorizedApp(ent)) { allApps.put(ent.getEntityId(), ent); } } List<Map> results = new ArrayList<Map>(); for (EntityBody body : ents) { HashMap<String, Object> entity = new HashMap<String, Object>(); String appId = (String) body.get("applicationId"); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) body.get("edorgs"); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", true); if(!isSEAAdmin()) { entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } results.add(entity); allApps.remove(appId); } for (Map.Entry<String, Entity> entry : allApps.entrySet()) { Boolean autoApprove = (Boolean) entry.getValue().getBody().get("allowed_for_all_edorgs"); List<String> approvedEdorgs = (List<String>) entry.getValue().getBody().get("authorized_ed_orgs"); if ((autoApprove != null && autoApprove) || isSEAAdmin() || (approvedEdorgs != null && CollectionUtils.containsAny(approvedEdorgs, inScopeEdOrgs))) { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", entry.getKey()); entity.put("appId", entry.getKey()); entity.put("authorized", false); results.add(entity); } } return Response.status(Status.OK).entity(results).build(); } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); }
ApplicationAuthorizationResource { @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorizations(@QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Iterable<EntityBody> ents = null; if (principal.isAdminRealmAuthenticated()) { ents = service.list(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs))); } else { ents = filterOutAutoAuthorized(service.listBasedOnContextualRoles(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs)))); } Iterable<Entity> appQuery = repo.findAll("application", new NeutralQuery()); Map<String, Entity> allApps = new HashMap<String, Entity>(); for (Entity ent : appQuery) { if(!isAutoAuthorizedApp(ent)) { allApps.put(ent.getEntityId(), ent); } } List<Map> results = new ArrayList<Map>(); for (EntityBody body : ents) { HashMap<String, Object> entity = new HashMap<String, Object>(); String appId = (String) body.get("applicationId"); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) body.get("edorgs"); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", true); if(!isSEAAdmin()) { entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } results.add(entity); allApps.remove(appId); } for (Map.Entry<String, Entity> entry : allApps.entrySet()) { Boolean autoApprove = (Boolean) entry.getValue().getBody().get("allowed_for_all_edorgs"); List<String> approvedEdorgs = (List<String>) entry.getValue().getBody().get("authorized_ed_orgs"); if ((autoApprove != null && autoApprove) || isSEAAdmin() || (approvedEdorgs != null && CollectionUtils.containsAny(approvedEdorgs, inScopeEdOrgs))) { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", entry.getKey()); entity.put("appId", entry.getKey()); entity.put("authorized", false); results.add(entity); } } return Response.status(Status.OK).entity(results).build(); } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); static final String RESOURCE_NAME; static final String APP_ID; static final String EDORG_IDS; }
@Test public void testSLCOperatorOffsetGetSecurityEvents() throws URISyntaxException { injector.setOperatorContext(); URI mockUri = new URI("/rest/securityEvent?limit=100&offset=3"); when(uriInfo.getRequestUri()).thenReturn(mockUri); Response response = resource.getAll(uriInfo); Object responseEntityObj = null; if (response.getEntity() instanceof EntityResponse) { EntityResponse resp = (EntityResponse) response.getEntity(); responseEntityObj = resp.getEntity(); } else { fail("Should always return EntityResponse: " + response); } if (responseEntityObj instanceof EntityBody) { assertNotNull(responseEntityObj); } else if (responseEntityObj instanceof List<?>) { @SuppressWarnings("unchecked") List<EntityBody> results = (List<EntityBody>) responseEntityObj; assertEquals("unexpected number of entities", 2, results.size()); } else { fail("Response entity not recognized: " + response); } }
@Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) Response getAll(@Context final UriInfo uriInfo); @Override @GET @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response getWithId(@PathParam("id") final String idList, @Context final UriInfo uriInfo); @Override @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); @Override @POST @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override @DELETE @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @Override @PATCH @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @OPTIONS @RightsAllowed({Right.SECURITY_EVENT_VIEW}) Response options(); }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) Response getAll(@Context final UriInfo uriInfo); @Override @GET @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response getWithId(@PathParam("id") final String idList, @Context final UriInfo uriInfo); @Override @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); @Override @POST @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override @DELETE @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @Override @PATCH @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @OPTIONS @RightsAllowed({Right.SECURITY_EVENT_VIEW}) Response options(); static final String RESOURCE_NAME; }
@Test public void testSLCOperatorLimitGetSecurityEvents() throws URISyntaxException { injector.setOperatorContext(); URI mockUri = new URI("/rest/securityEvent?limit=2&offset=0"); when(uriInfo.getRequestUri()).thenReturn(mockUri); Response response = resource.getAll(uriInfo); Object responseEntityObj = null; if (response.getEntity() instanceof EntityResponse) { EntityResponse resp = (EntityResponse) response.getEntity(); responseEntityObj = resp.getEntity(); } else { fail("Should always return EntityResponse: " + response); } if (responseEntityObj instanceof EntityBody) { assertNotNull(responseEntityObj); } else if (responseEntityObj instanceof List<?>) { @SuppressWarnings("unchecked") List<EntityBody> results = (List<EntityBody>) responseEntityObj; assertEquals("unexpected number of entities", 2, results.size()); } else { fail("Response entity not recognized: " + response); } }
@Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) Response getAll(@Context final UriInfo uriInfo); @Override @GET @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response getWithId(@PathParam("id") final String idList, @Context final UriInfo uriInfo); @Override @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); @Override @POST @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override @DELETE @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @Override @PATCH @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @OPTIONS @RightsAllowed({Right.SECURITY_EVENT_VIEW}) Response options(); }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) Response getAll(@Context final UriInfo uriInfo); @Override @GET @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response getWithId(@PathParam("id") final String idList, @Context final UriInfo uriInfo); @Override @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); @Override @POST @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override @DELETE @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @Override @PATCH @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @OPTIONS @RightsAllowed({Right.SECURITY_EVENT_VIEW}) Response options(); static final String RESOURCE_NAME; }
@Test public void testSLCOperatorOffsetLimitGetSecurityEvents() throws URISyntaxException { injector.setOperatorContext(); URI mockUri = new URI("/rest/securityEvent?limit=3&offset=1"); when(uriInfo.getRequestUri()).thenReturn(mockUri); Response response = resource.getAll(uriInfo); Object responseEntityObj = null; if (response.getEntity() instanceof EntityResponse) { EntityResponse resp = (EntityResponse) response.getEntity(); responseEntityObj = resp.getEntity(); } else { fail("Should always return EntityResponse: " + response); } if (responseEntityObj instanceof EntityBody) { assertNotNull(responseEntityObj); } else if (responseEntityObj instanceof List<?>) { @SuppressWarnings("unchecked") List<EntityBody> results = (List<EntityBody>) responseEntityObj; assertEquals("unexpected number of entities", 3, results.size()); } else { fail("Response entity not recognized: " + response); } }
@Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) Response getAll(@Context final UriInfo uriInfo); @Override @GET @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response getWithId(@PathParam("id") final String idList, @Context final UriInfo uriInfo); @Override @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); @Override @POST @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override @DELETE @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @Override @PATCH @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @OPTIONS @RightsAllowed({Right.SECURITY_EVENT_VIEW}) Response options(); }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) Response getAll(@Context final UriInfo uriInfo); @Override @GET @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response getWithId(@PathParam("id") final String idList, @Context final UriInfo uriInfo); @Override @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); @Override @POST @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override @DELETE @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @Override @PATCH @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @OPTIONS @RightsAllowed({Right.SECURITY_EVENT_VIEW}) Response options(); static final String RESOURCE_NAME; }
@Test public void testSLCOperatorGetSecurityEvents() { injector.setOperatorContext(); Response response = resource.getAll(uriInfo); Object responseEntityObj = null; if (response.getEntity() instanceof EntityResponse) { EntityResponse resp = (EntityResponse) response.getEntity(); responseEntityObj = resp.getEntity(); } else { fail("Should always return EntityResponse: " + response); } if (responseEntityObj instanceof EntityBody) { assertNotNull(responseEntityObj); } else if (responseEntityObj instanceof List<?>) { @SuppressWarnings("unchecked") List<EntityBody> results = (List<EntityBody>) responseEntityObj; assertEquals("unexpected number of entities", 5, results.size()); } else { fail("Response entity not recognized: " + response); } }
@Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) Response getAll(@Context final UriInfo uriInfo); @Override @GET @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response getWithId(@PathParam("id") final String idList, @Context final UriInfo uriInfo); @Override @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); @Override @POST @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override @DELETE @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @Override @PATCH @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @OPTIONS @RightsAllowed({Right.SECURITY_EVENT_VIEW}) Response options(); }
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) Response getAll(@Context final UriInfo uriInfo); @Override @GET @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response getWithId(@PathParam("id") final String idList, @Context final UriInfo uriInfo); @Override @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); @Override @POST @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override @DELETE @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @Override @PATCH @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @OPTIONS @RightsAllowed({Right.SECURITY_EVENT_VIEW}) Response options(); static final String RESOURCE_NAME; }
@Test public void testToString() { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey("meta.data.tenantId", "test.id.key.field"); key.setTenantId(new Text("Midgar")); key.setId(new Text("1234")); assertEquals(key.toString(), "TenantAndIdEmittableKey [test.id.key.field=1234, meta.data.tenantId=Midgar]"); }
@Override public String toString() { return "TenantAndIdEmittableKey [" + getIdField() + "=" + getId().toString() + ", " + getTenantIdField() + "=" + getTenantId().toString() + "]"; }
TenantAndIdEmittableKey extends EmittableKey { @Override public String toString() { return "TenantAndIdEmittableKey [" + getIdField() + "=" + getId().toString() + ", " + getTenantIdField() + "=" + getTenantId().toString() + "]"; } }
TenantAndIdEmittableKey extends EmittableKey { @Override public String toString() { return "TenantAndIdEmittableKey [" + getIdField() + "=" + getId().toString() + ", " + getTenantIdField() + "=" + getTenantId().toString() + "]"; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); }
TenantAndIdEmittableKey extends EmittableKey { @Override public String toString() { return "TenantAndIdEmittableKey [" + getIdField() + "=" + getId().toString() + ", " + getTenantIdField() + "=" + getTenantId().toString() + "]"; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); Text getTenantId(); void setTenantId(final Text id); Text getTenantIdField(); Text getId(); void setId(final Text id); Text getIdField(); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }
TenantAndIdEmittableKey extends EmittableKey { @Override public String toString() { return "TenantAndIdEmittableKey [" + getIdField() + "=" + getId().toString() + ", " + getTenantIdField() + "=" + getTenantId().toString() + "]"; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); Text getTenantId(); void setTenantId(final Text id); Text getTenantIdField(); Text getId(); void setId(final Text id); Text getIdField(); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }
@Test public void testCreate() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); User newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.SLC_OPERATOR)); newUser.setFullName("Eddard Stark"); newUser.setEmail("[email protected]"); newUser.setUid("nedstark"); Response res = resource.create(newUser); Mockito.verify(ldap).createUser(REALM, newUser); Assert.assertNotNull(res); Assert.assertEquals(201, res.getStatus()); rights.remove(Right.CRUD_SLC_OPERATOR); res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(403, res.getStatus()); Mockito.when(secUtil.getEdOrg()).thenReturn(EDORG1); newUser.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); newUser.setEdorg(EDORG1); newUser.setTenant(TENANT); res = resource.create(newUser); Mockito.verify(ldap, Mockito.times(2)).createUser(REALM, newUser); Assert.assertNotNull(res); Assert.assertEquals(201, res.getStatus()); rights.remove(Right.CRUD_SEA_ADMIN); res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(403, res.getStatus()); Mockito.when(secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)).thenReturn(true); newUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); newUser.setEdorg(EDORG1); Mockito.when(adminService.getAllowedEdOrgs(Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(String.class), Mockito.anyBoolean())).thenReturn( new HashSet<String>(Arrays.asList(EDORG1))); res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(201, res.getStatus()); Mockito.verify(ldap, Mockito.times(3)).createUser(REALM, newUser); newUser.setEdorg(EDORG2); res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(400, res.getStatus()); rights.remove(Right.CRUD_LEA_ADMIN); res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(403, res.getStatus()); }
@POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testCreateWithOrWithoutLEA() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.hasRight(Right.CRUD_SLC_OPERATOR)).thenReturn(true); Mockito.when(adminService.getAllowedEdOrgs(Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(String.class), Mockito.anyBoolean())).thenReturn( new HashSet<String>(Arrays.asList(EDORG1))); Mockito.when(adminService.getAllowedEdOrgs(Mockito.anyString(), Mockito.anyString())).thenReturn( new HashSet<String>(Arrays.asList(EDORG1))); User newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.REALM_ADMINISTRATOR)); newUser.setFullName("Eddard Stark"); newUser.setEmail("[email protected]"); newUser.setUid("nedstark"); newUser.setEdorg(EDORG1); newUser.setTenant(TENANT); Response res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(400, res.getStatus()); User lea = new User(); lea.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); lea.setFullName("Eddard2 Stark"); lea.setEmail("[email protected]"); lea.setUid("nedstark2"); lea.setEdorg(EDORG1); lea.setTenant(TENANT); Mockito.when( ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class), Mockito.anyString(), Mockito.anyCollectionOf(String.class))).thenReturn(Arrays.asList(lea)); res = resource.create(newUser); Mockito.verify(ldap).createUser(REALM, newUser); Assert.assertNotNull(res); Assert.assertEquals(201, res.getStatus()); }
@POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testMailValidation() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); User userWithNoMail = new User(); userWithNoMail.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); userWithNoMail.setEdorg(EDORG1); userWithNoMail.setTenant(TENANT); userWithNoMail.setFullName("Mance Rayder"); userWithNoMail.setUid("mrayder"); userWithNoMail.setPassword("fr33folk"); Response response = resource.create(userWithNoMail); assertEquals(400, response.getStatus()); assertEquals("No email address", response.getEntity()); }
@POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testNameValidation() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); User userWithNoName = new User(); userWithNoName.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); userWithNoName.setEdorg(EDORG1); userWithNoName.setTenant(TENANT); userWithNoName.setUid("kindlyman"); userWithNoName.setPassword("k1ndlyman"); userWithNoName.setEmail("[email protected]"); assertEquals(400, resource.create(userWithNoName).getStatus()); }
@POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testNoLastName() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); User userWithNoSurname = new User(); userWithNoSurname.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); userWithNoSurname.setEdorg(EDORG1); userWithNoSurname.setTenant(TENANT); userWithNoSurname.setFullName("Jon"); userWithNoSurname.setUid("jsnow"); userWithNoSurname.setPassword("jsn0w"); userWithNoSurname.setEmail("[email protected]"); assertEquals(201, resource.create(userWithNoSurname).getStatus()); }
@POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testUidValidation() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); User userWithNoId = new User(); userWithNoId.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); userWithNoId.setEdorg(EDORG1); userWithNoId.setTenant(TENANT); userWithNoId.setFullName("Arya Stark"); userWithNoId.setPassword("@ry@"); userWithNoId.setEmail("[email protected]"); assertEquals(400, resource.create(userWithNoId).getStatus()); }
@POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testUpdate() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.getUid()).thenReturn(UUID1); User newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.INGESTION_USER)); newUser.setUid(UUID2); newUser.setTenant(TENANT); newUser.setEdorg(EDORG1); newUser.setFullName("Robb Stark"); newUser.setEmail("[email protected]"); User ldapUser = new User(); ldapUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); ldapUser.setUid(UUID2); ldapUser.setFullName("Robb Stark"); ldapUser.setEmail("[email protected]"); ldapUser.setTenant(TENANT); ldapUser.setEdorg(EDORG1); ldapUser.setHomeDir("test_dir"); User ldapUser2 = new User(); ldapUser2.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); ldapUser2.setUid(UUID2 + "2"); ldapUser2.setFullName("Robb Stark"); ldapUser2.setEmail("[email protected]"); ldapUser2.setTenant(TENANT); ldapUser2.setEdorg(EDORG1); Mockito.when(ldap.getUser(REALM, UUID2)).thenReturn(ldapUser); Mockito.when( ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class), Mockito.anyString(), Mockito.anyCollectionOf(String.class))).thenReturn(Arrays.asList(ldapUser)); Response res = resource.update(ldapUser); Assert.assertNotNull(res); Assert.assertEquals(204, res.getStatus()); Mockito.when( ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class), Mockito.anyString(), Mockito.anyCollectionOf(String.class))).thenReturn(Arrays.asList(ldapUser, ldapUser2)); res = resource.update(newUser); Mockito.verify(ldap).updateUser(REALM, newUser); Assert.assertNotNull(res); Assert.assertEquals(204, res.getStatus()); Assert.assertEquals(newUser.getHomeDir(), ldapUser.getHomeDir()); }
@PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testModifySelf() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(adminService.getAllowedEdOrgs(TENANT, null)).thenReturn( new HashSet<String>(Arrays.asList(EDORG1))); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.getUid()).thenReturn(UUID2); Mockito.when(secUtil.getEdOrg()).thenReturn(EDORG1); User newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); newUser.setUid(UUID2); newUser.setTenant(TENANT); newUser.setEdorg(EDORG1); newUser.setFullName("Robb Stark"); newUser.setEmail("[email protected]"); User ldapUser = new User(); ldapUser.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); ldapUser.setUid(UUID2); ldapUser.setFullName("Robb Stark"); ldapUser.setEmail("[email protected]"); ldapUser.setTenant(TENANT); ldapUser.setEdorg(EDORG1); Mockito.when(ldap.getUser(REALM, UUID2)).thenReturn(ldapUser); Response res = resource.update(newUser); Assert.assertNotNull(res); Assert.assertEquals(400, res.getStatus()); }
@PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testUpdateLastSEA() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(adminService.getAllowedEdOrgs(TENANT, null)).thenReturn( new HashSet<String>(Arrays.asList(EDORG1))); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.getUid()).thenReturn(UUID1); Mockito.when(secUtil.getEdOrg()).thenReturn(EDORG1); User newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); newUser.setUid(UUID2); newUser.setTenant(TENANT); newUser.setEdorg(EDORG1); newUser.setFullName("Robb Stark"); newUser.setEmail("[email protected]"); User ldapUser = new User(); ldapUser.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); ldapUser.setUid(UUID2); ldapUser.setFullName("Robb Stark"); ldapUser.setEmail("[email protected]"); ldapUser.setTenant(TENANT); ldapUser.setEdorg(EDORG1); Mockito.when(ldap.getUser(REALM, UUID2)).thenReturn(ldapUser); Mockito.when( ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class), Mockito.anyString(), Mockito.anyCollectionOf(String.class))).thenReturn(Arrays.asList(ldapUser)); Response res = resource.update(newUser); Assert.assertNotNull(res); Assert.assertEquals(400, res.getStatus()); }
@PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testDelete() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.getUid()).thenReturn(UUID1); User newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.SLC_OPERATOR)); newUser.setUid(UUID2); newUser.setTenant(""); Mockito.when(ldap.getUser(REALM, UUID2)).thenReturn(newUser); Mockito.when(secUtil.hasRole(RoleInitializer.SLC_OPERATOR)).thenReturn(true); Response res = resource.delete(newUser.getUid()); Mockito.verify(ldap, Mockito.atLeastOnce()).getUser(REALM, newUser.getUid()); Mockito.verify(ldap).removeUser(REALM, newUser.getUid()); Assert.assertNotNull(res); Assert.assertEquals(204, res.getStatus()); Collection<GrantedAuthority> rights2 = new HashSet<GrantedAuthority>(); rights2.addAll(Arrays.asList(Right.CRUD_SANDBOX_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights2); Mockito.when(secUtil.getUid()).thenReturn(UUID1); Mockito.when(secUtil.getTenantId()).thenReturn(TENANT); User userToDelete = new User(); userToDelete.setGroups(Arrays.asList(RoleInitializer.SLC_OPERATOR)); userToDelete.setUid(UUID2); userToDelete.setTenant(TENANT1); Mockito.when(ldap.getUser(REALM, UUID2)).thenReturn(userToDelete); Mockito.when(secUtil.hasRole(RoleInitializer.SLC_OPERATOR)).thenReturn(false); Mockito.when(secUtil.hasRole(RoleInitializer.SANDBOX_SLC_OPERATOR)).thenReturn(false); res = resource.delete(newUser.getUid()); Assert.assertNotNull(res); Assert.assertEquals(403, res.getStatus()); }
@DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response delete(@PathParam("uid") final String uid) { Response result = validateUserDelete(uid, secUtil.getTenantId()); if (result != null) { return result; } User userToDelete = ldapService.getUser(realm, uid); ldapService.removeUser(realm, uid); auditLogger.audit(createSecurityEvent("Deleted user " + uid + " with roles " + rolesToString(userToDelete), userToDelete.getTenant(), userToDelete.getEdorg())); return Response.status(Status.NO_CONTENT).build(); }
UserResource { @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response delete(@PathParam("uid") final String uid) { Response result = validateUserDelete(uid, secUtil.getTenantId()); if (result != null) { return result; } User userToDelete = ldapService.getUser(realm, uid); ldapService.removeUser(realm, uid); auditLogger.audit(createSecurityEvent("Deleted user " + uid + " with roles " + rolesToString(userToDelete), userToDelete.getTenant(), userToDelete.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } }
UserResource { @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response delete(@PathParam("uid") final String uid) { Response result = validateUserDelete(uid, secUtil.getTenantId()); if (result != null) { return result; } User userToDelete = ldapService.getUser(realm, uid); ldapService.removeUser(realm, uid); auditLogger.audit(createSecurityEvent("Deleted user " + uid + " with roles " + rolesToString(userToDelete), userToDelete.getTenant(), userToDelete.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } }
UserResource { @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response delete(@PathParam("uid") final String uid) { Response result = validateUserDelete(uid, secUtil.getTenantId()); if (result != null) { return result; } User userToDelete = ldapService.getUser(realm, uid); ldapService.removeUser(realm, uid); auditLogger.audit(createSecurityEvent("Deleted user " + uid + " with roles " + rolesToString(userToDelete), userToDelete.getTenant(), userToDelete.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response delete(@PathParam("uid") final String uid) { Response result = validateUserDelete(uid, secUtil.getTenantId()); if (result != null) { return result; } User userToDelete = ldapService.getUser(realm, uid); ldapService.removeUser(realm, uid); auditLogger.audit(createSecurityEvent("Deleted user " + uid + " with roles " + rolesToString(userToDelete), userToDelete.getTenant(), userToDelete.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testGetValue() { BSONObject field = new BasicBSONObject("field", "testing123"); BSONObject entry = new BasicBSONObject("string", field); BSONWritable entity = new BSONWritable(entry); StringValueMapper mapper = new StringValueMapper("string.field"); Writable value = mapper.getValue(entity); assertFalse(value instanceof NullWritable); assertTrue(value instanceof Text); assertEquals(value.toString(), "testing123"); }
@Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; }
StringValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; } }
StringValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; } StringValueMapper(String fieldName); }
StringValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; } StringValueMapper(String fieldName); @Override Writable getValue(BSONWritable entity); }
StringValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; } StringValueMapper(String fieldName); @Override Writable getValue(BSONWritable entity); }
@SuppressWarnings("unchecked") @Test public void testReadAll() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.getUid()).thenReturn("myUid"); Mockito.when(secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)).thenReturn(false); List<User> users = Arrays.asList(new User(), new User()); Mockito.when( ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class), Mockito.anyCollectionOf(String.class), Mockito.anyString(), (Collection<String>) Mockito.isNull())).thenReturn(users); Response res = resource.readAll(); Assert.assertEquals(200, res.getStatus()); Object entity = res.getEntity(); Assert.assertEquals(users, entity); }
@GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response readAll() { String tenant = secUtil.getTenantId(); String edorg = secUtil.getEdOrg(); Response result = validateAdminRights(secUtil.getAllRights(), tenant); if (result != null) { return result; } Collection<String> edorgs = null; if (secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)) { edorgs = new ArrayList<String>(); edorgs.addAll(adminService.getAllowedEdOrgs(tenant, edorg)); } Set<String> groupsToIgnore = new HashSet<String>(); if (isLeaAdmin()) { groupsToIgnore.add(RoleInitializer.SLC_OPERATOR); groupsToIgnore.add(RoleInitializer.SEA_ADMINISTRATOR); } Collection<User> users = ldapService.findUsersByGroups(realm, RightToGroupMapper.getInstance().getGroups(secUtil.getAllRights()), groupsToIgnore, secUtil.getTenantId(), edorgs); if (users != null && users.size() > 0) { for (User user : users) { user.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapGroupToRoles(user.getGroups()))); } } return Response.status(Status.OK).entity(users).build(); }
UserResource { @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response readAll() { String tenant = secUtil.getTenantId(); String edorg = secUtil.getEdOrg(); Response result = validateAdminRights(secUtil.getAllRights(), tenant); if (result != null) { return result; } Collection<String> edorgs = null; if (secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)) { edorgs = new ArrayList<String>(); edorgs.addAll(adminService.getAllowedEdOrgs(tenant, edorg)); } Set<String> groupsToIgnore = new HashSet<String>(); if (isLeaAdmin()) { groupsToIgnore.add(RoleInitializer.SLC_OPERATOR); groupsToIgnore.add(RoleInitializer.SEA_ADMINISTRATOR); } Collection<User> users = ldapService.findUsersByGroups(realm, RightToGroupMapper.getInstance().getGroups(secUtil.getAllRights()), groupsToIgnore, secUtil.getTenantId(), edorgs); if (users != null && users.size() > 0) { for (User user : users) { user.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapGroupToRoles(user.getGroups()))); } } return Response.status(Status.OK).entity(users).build(); } }
UserResource { @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response readAll() { String tenant = secUtil.getTenantId(); String edorg = secUtil.getEdOrg(); Response result = validateAdminRights(secUtil.getAllRights(), tenant); if (result != null) { return result; } Collection<String> edorgs = null; if (secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)) { edorgs = new ArrayList<String>(); edorgs.addAll(adminService.getAllowedEdOrgs(tenant, edorg)); } Set<String> groupsToIgnore = new HashSet<String>(); if (isLeaAdmin()) { groupsToIgnore.add(RoleInitializer.SLC_OPERATOR); groupsToIgnore.add(RoleInitializer.SEA_ADMINISTRATOR); } Collection<User> users = ldapService.findUsersByGroups(realm, RightToGroupMapper.getInstance().getGroups(secUtil.getAllRights()), groupsToIgnore, secUtil.getTenantId(), edorgs); if (users != null && users.size() > 0) { for (User user : users) { user.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapGroupToRoles(user.getGroups()))); } } return Response.status(Status.OK).entity(users).build(); } }
UserResource { @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response readAll() { String tenant = secUtil.getTenantId(); String edorg = secUtil.getEdOrg(); Response result = validateAdminRights(secUtil.getAllRights(), tenant); if (result != null) { return result; } Collection<String> edorgs = null; if (secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)) { edorgs = new ArrayList<String>(); edorgs.addAll(adminService.getAllowedEdOrgs(tenant, edorg)); } Set<String> groupsToIgnore = new HashSet<String>(); if (isLeaAdmin()) { groupsToIgnore.add(RoleInitializer.SLC_OPERATOR); groupsToIgnore.add(RoleInitializer.SEA_ADMINISTRATOR); } Collection<User> users = ldapService.findUsersByGroups(realm, RightToGroupMapper.getInstance().getGroups(secUtil.getAllRights()), groupsToIgnore, secUtil.getTenantId(), edorgs); if (users != null && users.size() > 0) { for (User user : users) { user.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapGroupToRoles(user.getGroups()))); } } return Response.status(Status.OK).entity(users).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response readAll() { String tenant = secUtil.getTenantId(); String edorg = secUtil.getEdOrg(); Response result = validateAdminRights(secUtil.getAllRights(), tenant); if (result != null) { return result; } Collection<String> edorgs = null; if (secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)) { edorgs = new ArrayList<String>(); edorgs.addAll(adminService.getAllowedEdOrgs(tenant, edorg)); } Set<String> groupsToIgnore = new HashSet<String>(); if (isLeaAdmin()) { groupsToIgnore.add(RoleInitializer.SLC_OPERATOR); groupsToIgnore.add(RoleInitializer.SEA_ADMINISTRATOR); } Collection<User> users = ldapService.findUsersByGroups(realm, RightToGroupMapper.getInstance().getGroups(secUtil.getAllRights()), groupsToIgnore, secUtil.getTenantId(), edorgs); if (users != null && users.size() > 0) { for (User user : users) { user.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapGroupToRoles(user.getGroups()))); } } return Response.status(Status.OK).entity(users).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testGetEdOrgs() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)).thenReturn(false); Response res = resource.getEdOrgs(); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals(new LinkedList<String>(), res.getEntity()); Mockito.when(secUtil.getTenantId()).thenReturn(TENANT); rights.remove(Right.CRUD_SLC_OPERATOR); Mockito.when(adminService.getAllowedEdOrgs(TENANT, null)).thenReturn( new HashSet<String>(Arrays.asList(EDORG1, EDORG2))); res = resource.getEdOrgs(); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals(Arrays.asList(EDORG1, EDORG2), res.getEntity()); rights.remove(Right.CRUD_SEA_ADMIN); Mockito.when(secUtil.getEdOrg()).thenReturn(EDORG1); Mockito.when(adminService.getAllowedEdOrgs(TENANT, EDORG1)).thenReturn( new HashSet<String>(Arrays.asList(EDORG1, EDORG2))); res = resource.getEdOrgs(); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals(Arrays.asList(EDORG1, EDORG2), res.getEntity()); }
@GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response getEdOrgs() { String tenant = secUtil.getTenantId(); Response result = validateAdminRights(secUtil.getAllRights(), tenant); if (result != null) { return result; } if (tenant == null) { List<String> edorgs = new LinkedList<String>(); return Response.status(Status.OK).entity(edorgs).build(); } String restrictByEdOrg = this.isLeaAdmin() ? secUtil.getEdOrg() : null; ArrayList<String> edOrgs = new ArrayList<String>(adminService.getAllowedEdOrgs(tenant, restrictByEdOrg)); Collections.sort(edOrgs); return Response.status(Status.OK).entity(edOrgs).build(); }
UserResource { @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response getEdOrgs() { String tenant = secUtil.getTenantId(); Response result = validateAdminRights(secUtil.getAllRights(), tenant); if (result != null) { return result; } if (tenant == null) { List<String> edorgs = new LinkedList<String>(); return Response.status(Status.OK).entity(edorgs).build(); } String restrictByEdOrg = this.isLeaAdmin() ? secUtil.getEdOrg() : null; ArrayList<String> edOrgs = new ArrayList<String>(adminService.getAllowedEdOrgs(tenant, restrictByEdOrg)); Collections.sort(edOrgs); return Response.status(Status.OK).entity(edOrgs).build(); } }
UserResource { @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response getEdOrgs() { String tenant = secUtil.getTenantId(); Response result = validateAdminRights(secUtil.getAllRights(), tenant); if (result != null) { return result; } if (tenant == null) { List<String> edorgs = new LinkedList<String>(); return Response.status(Status.OK).entity(edorgs).build(); } String restrictByEdOrg = this.isLeaAdmin() ? secUtil.getEdOrg() : null; ArrayList<String> edOrgs = new ArrayList<String>(adminService.getAllowedEdOrgs(tenant, restrictByEdOrg)); Collections.sort(edOrgs); return Response.status(Status.OK).entity(edOrgs).build(); } }
UserResource { @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response getEdOrgs() { String tenant = secUtil.getTenantId(); Response result = validateAdminRights(secUtil.getAllRights(), tenant); if (result != null) { return result; } if (tenant == null) { List<String> edorgs = new LinkedList<String>(); return Response.status(Status.OK).entity(edorgs).build(); } String restrictByEdOrg = this.isLeaAdmin() ? secUtil.getEdOrg() : null; ArrayList<String> edOrgs = new ArrayList<String>(adminService.getAllowedEdOrgs(tenant, restrictByEdOrg)); Collections.sort(edOrgs); return Response.status(Status.OK).entity(edOrgs).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response getEdOrgs() { String tenant = secUtil.getTenantId(); Response result = validateAdminRights(secUtil.getAllRights(), tenant); if (result != null) { return result; } if (tenant == null) { List<String> edorgs = new LinkedList<String>(); return Response.status(Status.OK).entity(edorgs).build(); } String restrictByEdOrg = this.isLeaAdmin() ? secUtil.getEdOrg() : null; ArrayList<String> edOrgs = new ArrayList<String>(adminService.getAllowedEdOrgs(tenant, restrictByEdOrg)); Collections.sort(edOrgs); return Response.status(Status.OK).entity(edOrgs).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testBadData() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); User newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); Response res = resource.create(newUser); Assert.assertEquals(400, res.getStatus()); newUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); res = resource.create(newUser); Assert.assertEquals(400, res.getStatus()); newUser.setTenant(TENANT); newUser.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); res = resource.create(newUser); Assert.assertEquals(400, res.getStatus()); newUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); res = resource.create(newUser); Assert.assertEquals(400, res.getStatus()); }
@POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testValidateAdminRights() { assertNotNull(resource.validateAdminRights(Arrays.asList(EMPTY_RIGHT), "tenant")); assertNotNull(resource.validateAdminRights(Arrays.asList(NO_ADMIN_RIGHT), "tenant")); assertNull(resource.validateAdminRights(Arrays.asList(ONE_ADMIN_RIGHT_ONLY), "tenant")); assertNull(resource.validateAdminRights(Arrays.asList(ONE_ADMIN_RIGHT_WITH_OTHERS), "tenant")); assertNull(resource.validateAdminRights(Arrays.asList(TWO_ADMIN_RIGHTS_ONLY), "tenant")); assertNull(resource.validateAdminRights(Arrays.asList(TWO_ADMIN_RIGHTS_WITH_OTHERS), "tenant")); }
Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; }
UserResource { Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; } }
UserResource { Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; } }
UserResource { Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test (expected = RuntimeException.class) public void testValidateAdminBadRights() { assertNull(resource.validateAdminRights(Arrays.asList(ONE_ADMIN_RIGHT_ONLY), null)); }
Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; }
UserResource { Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; } }
UserResource { Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; } }
UserResource { Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test public void testValidateAtMostOneAdminRole() { assertNull(UserResource.validateAtMostOneAdminRole(Arrays.asList(new String[] {}))); assertNull(UserResource.validateAtMostOneAdminRole(Arrays .asList(new String[] { RoleInitializer.INGESTION_USER }))); assertNull(UserResource .validateAtMostOneAdminRole(Arrays.asList(new String[] { RoleInitializer.SLC_OPERATOR }))); assertNotNull(UserResource.validateAtMostOneAdminRole(Arrays.asList(new String[] { RoleInitializer.SLC_OPERATOR, RoleInitializer.LEA_ADMINISTRATOR }))); assertNull(UserResource.validateAtMostOneAdminRole(Arrays.asList(new String[] { RoleInitializer.LEA_ADMINISTRATOR, RoleInitializer.LEA_ADMINISTRATOR }))); }
static Response validateAtMostOneAdminRole(final Collection<String> roles) { Collection<String> adminRoles = new ArrayList<String>(Arrays.asList(ADMIN_ROLES)); adminRoles.retainAll(roles); if (adminRoles.size() > 1) { return composeForbiddenResponse("You cannot assign more than one admin role to a user"); } return null; }
UserResource { static Response validateAtMostOneAdminRole(final Collection<String> roles) { Collection<String> adminRoles = new ArrayList<String>(Arrays.asList(ADMIN_ROLES)); adminRoles.retainAll(roles); if (adminRoles.size() > 1) { return composeForbiddenResponse("You cannot assign more than one admin role to a user"); } return null; } }
UserResource { static Response validateAtMostOneAdminRole(final Collection<String> roles) { Collection<String> adminRoles = new ArrayList<String>(Arrays.asList(ADMIN_ROLES)); adminRoles.retainAll(roles); if (adminRoles.size() > 1) { return composeForbiddenResponse("You cannot assign more than one admin role to a user"); } return null; } }
UserResource { static Response validateAtMostOneAdminRole(final Collection<String> roles) { Collection<String> adminRoles = new ArrayList<String>(Arrays.asList(ADMIN_ROLES)); adminRoles.retainAll(roles); if (adminRoles.size() > 1) { return composeForbiddenResponse("You cannot assign more than one admin role to a user"); } return null; } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
UserResource { static Response validateAtMostOneAdminRole(final Collection<String> roles) { Collection<String> adminRoles = new ArrayList<String>(Arrays.asList(ADMIN_ROLES)); adminRoles.retainAll(roles); if (adminRoles.size() > 1) { return composeForbiddenResponse("You cannot assign more than one admin role to a user"); } return null; } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }
@Test(expected = IOException.class) public void testEntityNullCollection() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); EntityBody body = new EntityBody(); body.put("id", "1234"); body.put("name", "test name"); Home response = new Home(null, body); writer.writeTo(response, null, null, null, null, null, out); }
@Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } @Override boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream); }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } @Override boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream); }
@Test public void testEntityHome() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); EntityBody body = new EntityBody(); body.put("id", "1234"); body.put("name", "test name"); Home response = new Home("TestEntity", body); writer.writeTo(response, null, null, null, null, null, out); assertNotNull("Should not be null", out); String value = new String(out.toByteArray()); assertTrue("Should match", value.startsWith("<Home")); assertTrue("Should match", value.indexOf("<id>") > 0); assertTrue("Should match", value.indexOf("<name>") > 0); }
@Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } @Override boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream); }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } @Override boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream); }
@Test(expected = IOException.class) public void testNullObject() throws IOException { EntityBody body = new EntityBody(); body.put("id", "1234"); body.put("name", "test name"); Home response = new Home("TestEntity", body); writer.writeTo(response, null, null, null, null, null, null); }
@Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } @Override boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream); }
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } @Override boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream); }
@Test public void testIsWritable() { assertTrue(writer.isWriteable(ErrorResponse.class, null, null, null)); assertTrue(writer.isWriteable(Home.class, null, null, null)); assertFalse(writer.isWriteable(EntityResponse.class, null, null, null)); }
@Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.Home") || type.getName().equals("org.slc.sli.api.representation.ErrorResponse")) { return true; } return false; }
ObjectXMLWriter implements MessageBodyWriter { @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.Home") || type.getName().equals("org.slc.sli.api.representation.ErrorResponse")) { return true; } return false; } }
ObjectXMLWriter implements MessageBodyWriter { @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.Home") || type.getName().equals("org.slc.sli.api.representation.ErrorResponse")) { return true; } return false; } }
ObjectXMLWriter implements MessageBodyWriter { @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.Home") || type.getName().equals("org.slc.sli.api.representation.ErrorResponse")) { return true; } return false; } @Override boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream); }
ObjectXMLWriter implements MessageBodyWriter { @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.Home") || type.getName().equals("org.slc.sli.api.representation.ErrorResponse")) { return true; } return false; } @Override boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream); }
@Test public void testValueNotFound() { BSONObject field = new BasicBSONObject("field", "testing123"); BSONObject entry = new BasicBSONObject("string", field); BSONWritable entity = new BSONWritable(entry); StringValueMapper mapper = new StringValueMapper("string.missing_field"); Writable value = mapper.getValue(entity); assertTrue(value instanceof NullWritable); }
@Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; }
StringValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; } }
StringValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; } StringValueMapper(String fieldName); }
StringValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; } StringValueMapper(String fieldName); @Override Writable getValue(BSONWritable entity); }
StringValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; } StringValueMapper(String fieldName); @Override Writable getValue(BSONWritable entity); }
@Test public void testValues() { final String xmlValues = "<test><k1>v1</k1><k2>v2</k2></test>"; EntityBody body = null; try { body = deserialize(xmlValues); } catch (XMLStreamException e) { fail(e.getMessage()); } assertNotNull(body); assertEquals("v1", body.get("k1")); assertEquals("v2", body.get("k2")); }
public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
@Test public void testLists() { final String xmlList = "<test xmlns:sli=\"urn:sli\"><l1 sli:member=\"true\">v1</l1><l1 sli:member=\"true\">v2</l1></test>"; EntityBody body = null; try { body = deserialize(xmlList); } catch (XMLStreamException e) { fail(e.getMessage()); } assertNotNull(body); assertTrue("Should be a list", body.get("l1") instanceof List); @SuppressWarnings("unchecked") final List<String> l1Values = (List<String>) body.get("l1"); assertTrue(l1Values.contains("v1")); assertTrue(l1Values.contains("v2")); }
public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
@Test public void testMaps() { final String xmlMaps = "<test>" + "<key1>" + "<ek1>ev1</ek1>" + "<ek2>ev2</ek2>" + "</key1>" + "</test>"; EntityBody body = null; try { body = deserialize(xmlMaps); } catch (XMLStreamException e) { fail(e.getMessage()); } assertNotNull(body); assertTrue("Should be a map", body.get("key1") instanceof Map); @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) body.get("key1"); assertEquals("ev1", map.get("ek1")); assertEquals("ev2", map.get("ek2")); }
public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
@Test public void testSomethingComplex() { final String complexXML = "<school xmlns:sli=\"urn:sli\">\n" + " <id>8cc0a1ac-ccb5-dffc-1d74-32964722179b</id>\n" + " <schoolCategories sli:member=\"true\">Middle School</schoolCategories>\n" + " <gradesOffered sli:member=\"true\">Sixth grade</gradesOffered>\n" + " <gradesOffered sli:member=\"true\">Eighth grade</gradesOffered>\n" + " <gradesOffered sli:member=\"true\">Seventh grade</gradesOffered>\n" + " <organizationCategories sli:member=\"true\">School</organizationCategories>\n" + " <address sli:member=\"true\">\n" + " <addressType>Physical</addressType>\n" + " <streetNumberName>456 Blah Street</streetNumberName>\n" + " <city>Las Vegas</city>\n" + " <stateAbbreviation>NV</stateAbbreviation>\n" + " <postalCode>66666</postalCode>\n" + " <nameOfCounty>Vegas County</nameOfCounty>\n" + " </address>\n" + " <address sli:member=\"true\">\n" + " <addressType>Physical</addressType>\n" + " <streetNumberName>123 Blah Street</streetNumberName>\n" + " <city>Durham</city>\n" + " <stateAbbreviation>NC</stateAbbreviation>\n" + " <postalCode>66666</postalCode>\n" + " <nameOfCounty>Durham</nameOfCounty>\n" + " </address>\n" + " <parentEducationAgencyReference>bd086bae-ee82-4cf2-baf9-221a9407ea07</parentEducationAgencyReference>\n" + " <stateOrganizationId>152901004</stateOrganizationId>\n" + " <entityType>school</entityType>\n" + " <telephone sli:member=\"true\">\n" + " <institutionTelephoneNumberType>Main</institutionTelephoneNumberType>\n" + " <telephoneNumber>(333) 344-7777</telephoneNumber>\n" + " </telephone>\n" + " <nameOfInstitution>Purple Middle School</nameOfInstitution>\n" + "</school>\n"; EntityBody body = null; try { body = deserialize(complexXML); } catch (XMLStreamException e) { fail(e.getMessage()); } assertNotNull(body); Object address = body.get("address"); assertTrue(address instanceof List); assertEquals(2, ((List) address).size()); Object telephone = body.get("telephone"); assertTrue(telephone instanceof List); assertEquals(1, ((List) telephone).size()); @SuppressWarnings("unchecked") Map<String, Object> telephoneHash = (Map<String, Object>) ((List) telephone).get(0); assertEquals("(333) 344-7777", telephoneHash.get("telephoneNumber").toString()); Object id = body.get("id"); assertTrue(id instanceof String); assertEquals("8cc0a1ac-ccb5-dffc-1d74-32964722179b", id.toString()); }
public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
@Test(expected = XMLStreamException.class) public void testMissingEndTag() throws XMLStreamException { final String xmlValues = "<test><k1>v1</k1><k2>v2</k2>"; final EntityBody body = deserialize(xmlValues); }
public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
@Test(expected = XMLStreamException.class) public void testMalformedXML() throws XMLStreamException { final String xmlValues = "<test><k1>v1</k1><k2>v2</k2></tset>"; final EntityBody body = deserialize(xmlValues); }
public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
@Test public void testProcessingInstruction() { final String xmlValues = "<?xml version=\"1.0\" ?><test><k1>v1</k1><k2>v2</k2></test>"; EntityBody body = null; try { body = deserialize(xmlValues); } catch (XMLStreamException e) { fail(); } assertNotNull(body); }
public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserialize(final InputStream body); }
@Test public void testNullStream() throws IOException { EntityBody body = reader.readFrom(EntityBody.class, null, null, null, null, null); assertNotNull("Should not be null", body); assertTrue("Should be empty", body.isEmpty()); }
@Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; }
XMLMsgBodyReader implements MessageBodyReader<EntityBody> { @Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; } }
XMLMsgBodyReader implements MessageBodyReader<EntityBody> { @Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; } }
XMLMsgBodyReader implements MessageBodyReader<EntityBody> { @Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; } @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); }
XMLMsgBodyReader implements MessageBodyReader<EntityBody> { @Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; } @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); }
@Test public void testBadXml() throws Exception { try { InputStream is = new ByteArrayInputStream("{\"test\":\"foo\"}".getBytes()); reader.readFrom(EntityBody.class, null, null, null, null, is); fail("Should throw Exception because of invalid XML format"); } catch(WebApplicationException wae) { assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), wae.getResponse().getStatus()); } }
@Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; }
XMLMsgBodyReader implements MessageBodyReader<EntityBody> { @Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; } }
XMLMsgBodyReader implements MessageBodyReader<EntityBody> { @Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; } }
XMLMsgBodyReader implements MessageBodyReader<EntityBody> { @Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; } @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); }
XMLMsgBodyReader implements MessageBodyReader<EntityBody> { @Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; } @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); }
@Test public void testEntityBody() throws IOException { EntityDefinition def = mock(EntityDefinition.class); when(entityDefinitionStore.lookupByEntityType(anyString())).thenReturn(def); ByteArrayOutputStream out = new ByteArrayOutputStream(); EntityBody body = new EntityBody(); body.put("id", "1234"); body.put("name", "test name"); EntityResponse response = new EntityResponse("TestEntity", body); writer.writeTo(response, null, null, null, null, null, out); assertNotNull("Should not be null", out); String value = new String(out.toByteArray()); assertTrue("Should match", value.indexOf("<TestEntity") > 0); assertTrue("Should match", value.indexOf("<id>") > 0); assertTrue("Should match", value.indexOf("<name>") > 0); }
@Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
@Test public void testExtractMultipleTenantsIntoSeparateZipFiles() throws Exception { extractor.execute(); File zipFile1 = new File(extractDir, TENANT1 + ".zip"); Assert.assertTrue(zipFile1.length() > 0); File zipFile2 = new File(extractDir, TENANT2 + ".zip"); Assert.assertTrue(zipFile2.length() > 0); }
@Override public void execute() { Future<String> call; List<Future<String>> futures = new LinkedList<Future<String>>(); for (String tenant : tenants) { try { call = executor.submit(new ExtractWorker(tenant)); futures.add(call); } catch (FileNotFoundException e) { LOG.error("Error while extracting data for tenant " + tenant, e); } } for (Future<String> future : futures) { processFuture(future); } destroy(); }
ExtractorImpl implements Extractor { @Override public void execute() { Future<String> call; List<Future<String>> futures = new LinkedList<Future<String>>(); for (String tenant : tenants) { try { call = executor.submit(new ExtractWorker(tenant)); futures.add(call); } catch (FileNotFoundException e) { LOG.error("Error while extracting data for tenant " + tenant, e); } } for (Future<String> future : futures) { processFuture(future); } destroy(); } }
ExtractorImpl implements Extractor { @Override public void execute() { Future<String> call; List<Future<String>> futures = new LinkedList<Future<String>>(); for (String tenant : tenants) { try { call = executor.submit(new ExtractWorker(tenant)); futures.add(call); } catch (FileNotFoundException e) { LOG.error("Error while extracting data for tenant " + tenant, e); } } for (Future<String> future : futures) { processFuture(future); } destroy(); } }
ExtractorImpl implements Extractor { @Override public void execute() { Future<String> call; List<Future<String>> futures = new LinkedList<Future<String>>(); for (String tenant : tenants) { try { call = executor.submit(new ExtractWorker(tenant)); futures.add(call); } catch (FileNotFoundException e) { LOG.error("Error while extracting data for tenant " + tenant, e); } } for (Future<String> future : futures) { processFuture(future); } destroy(); } void destroy(); void init(); void createExtractDir(); @Override void execute(); @Override void execute(String tenant); @Override String getHealth(); File extractEntity(String tenant, OutstreamZipFile zipFile, String entityName); void setExtractDir(String extractDir); void setExecutorThreads(int executorThreads); void setRunOnStartup(boolean runOnStartup); void setEntityRepository(Repository<Entity> entityRepository); void setTenants(List<String> tenants); void setEntities(List<String> entities); void setQueriedEntities(Map<String, String> queriedEntities); void setCombinedEntities(Map<String, List<String>> combinedEntities); }
ExtractorImpl implements Extractor { @Override public void execute() { Future<String> call; List<Future<String>> futures = new LinkedList<Future<String>>(); for (String tenant : tenants) { try { call = executor.submit(new ExtractWorker(tenant)); futures.add(call); } catch (FileNotFoundException e) { LOG.error("Error while extracting data for tenant " + tenant, e); } } for (Future<String> future : futures) { processFuture(future); } destroy(); } void destroy(); void init(); void createExtractDir(); @Override void execute(); @Override void execute(String tenant); @Override String getHealth(); File extractEntity(String tenant, OutstreamZipFile zipFile, String entityName); void setExtractDir(String extractDir); void setExecutorThreads(int executorThreads); void setRunOnStartup(boolean runOnStartup); void setEntityRepository(Repository<Entity> entityRepository); void setTenants(List<String> tenants); void setEntities(List<String> entities); void setQueriedEntities(Map<String, String> queriedEntities); void setCombinedEntities(Map<String, List<String>> combinedEntities); }
@Test public void testEntityNullCollection() throws IOException { EntityDefinition def = mock(EntityDefinition.class); when(entityDefinitionStore.lookupByEntityType(anyString())).thenReturn(def); ByteArrayOutputStream out = new ByteArrayOutputStream(); EntityBody body = new EntityBody(); body.put("id", "1234"); body.put("name", "test name"); EntityResponse response = new EntityResponse(null, body); writer.writeTo(response, null, null, null, null, null, out); assertNotNull("Should not be null", out); String value = new String(out.toByteArray()); assertTrue("Should match", value.indexOf("<Entity") > 0); }
@Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
@Test public void testIsWritable() { assertFalse(writer.isWriteable(ErrorResponse.class, null, null, null)); assertFalse(writer.isWriteable(Home.class, null, null, null)); assertTrue(writer.isWriteable(EntityResponse.class, null, null, null)); }
@Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.EntityResponse")) { return true; } return false; }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.EntityResponse")) { return true; } return false; } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.EntityResponse")) { return true; } return false; } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.EntityResponse")) { return true; } return false; } @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.EntityResponse")) { return true; } return false; } @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
@Test public void testHandleLists() throws IOException { final EntityDefinition def = mock(EntityDefinition.class); when(entityDefinitionStore.lookupByEntityType(anyString())).thenReturn(def); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final EntityBody body = new EntityBody(); final Map<String, Object> testMap = new HashMap<String, Object>(); testMap.put("k1", "v1"); testMap.put("k2", "v2"); body.put("mapKey", testMap); final List<String> list = new ArrayList<String>(); list.add("test1"); list.add("test2"); list.add("test3"); body.put("listItem", list); body.put("id", "1234"); body.put("name", "test name"); final EntityResponse response = new EntityResponse("TestEntity", Arrays.asList(body)); writer.writeTo(response, null, null, null, null, null, out); assertNotNull("Should not be null", out); String value = new String(out.toByteArray()); assertTrue("Should match", value.indexOf("<TestEntityList") > 0); assertTrue("Should match", value.indexOf("<id>") > 0); assertTrue("Should match", value.indexOf("<name>") > 0); assertEquals(3, StringUtils.countMatches(value, "<listItem")); assertEquals(1, StringUtils.countMatches(value, "<mapKey>")); }
@Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
@Test public void testGet() throws URISyntaxException { String studentId = resourceService.postEntity(studentResource, createTestEntity()); String sectionId = resourceService.postEntity(sectionResource, createSectionEntity()); String assocId = resourceService.postEntity(ssaResource, createAssociationEntity(studentId, sectionId)); setupMocks(BASE_URI + "/" + studentId + "/studentSectionAssociations/sections"); Response response = fourPartResource.get(uriInfo, studentId); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); }
@GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.FOUR_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.FOUR_PART); final Resource association = resourceHelper.getAssociationName(uriInfo, ResourceTemplate.FOUR_PART); return resourceService.getEntities(base, id, association, resource, uriInfo.getRequestUri()); } }); }
FourPartResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.FOUR_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.FOUR_PART); final Resource association = resourceHelper.getAssociationName(uriInfo, ResourceTemplate.FOUR_PART); return resourceService.getEntities(base, id, association, resource, uriInfo.getRequestUri()); } }); } }
FourPartResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.FOUR_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.FOUR_PART); final Resource association = resourceHelper.getAssociationName(uriInfo, ResourceTemplate.FOUR_PART); return resourceService.getEntities(base, id, association, resource, uriInfo.getRequestUri()); } }); } }
FourPartResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.FOUR_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.FOUR_PART); final Resource association = resourceHelper.getAssociationName(uriInfo, ResourceTemplate.FOUR_PART); return resourceService.getEntities(base, id, association, resource, uriInfo.getRequestUri()); } }); } @GET Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id); }
FourPartResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.FOUR_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.FOUR_PART); final Resource association = resourceHelper.getAssociationName(uriInfo, ResourceTemplate.FOUR_PART); return resourceService.getEntities(base, id, association, resource, uriInfo.getRequestUri()); } }); } @GET Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id); }
@Test public void testGetPath() { assertTrue(new ChangedUriInfo("/rest/foo/bar", null).getPath().equals("foo/bar")); }
@Override public String getPath() { String uriPath = this.uri.getPath(); if (uriPath != null) { String removeString = "/rest/"; if (uriPath.startsWith(removeString)) { return uriPath.substring(removeString.length()); } return uriPath; } return null; }
ChangedUriInfo implements UriInfo { @Override public String getPath() { String uriPath = this.uri.getPath(); if (uriPath != null) { String removeString = "/rest/"; if (uriPath.startsWith(removeString)) { return uriPath.substring(removeString.length()); } return uriPath; } return null; } }
ChangedUriInfo implements UriInfo { @Override public String getPath() { String uriPath = this.uri.getPath(); if (uriPath != null) { String removeString = "/rest/"; if (uriPath.startsWith(removeString)) { return uriPath.substring(removeString.length()); } return uriPath; } return null; } ChangedUriInfo(String uri, UriInfo uriInfo); }
ChangedUriInfo implements UriInfo { @Override public String getPath() { String uriPath = this.uri.getPath(); if (uriPath != null) { String removeString = "/rest/"; if (uriPath.startsWith(removeString)) { return uriPath.substring(removeString.length()); } return uriPath; } return null; } ChangedUriInfo(String uri, UriInfo uriInfo); String getOriginalUri(); @Override String getPath(); @Override String getPath(boolean decode); @Override List<PathSegment> getPathSegments(); @Override List<PathSegment> getPathSegments(boolean decode); @Override URI getRequestUri(); @Override UriBuilder getRequestUriBuilder(); @Override URI getAbsolutePath(); @Override UriBuilder getAbsolutePathBuilder(); @Override URI getBaseUri(); @Override UriBuilder getBaseUriBuilder(); @Override MultivaluedMap<String, String> getPathParameters(); @Override MultivaluedMap<String, String> getPathParameters(boolean decode); @Override MultivaluedMap<String, String> getQueryParameters(); @Override MultivaluedMap<String, String> getQueryParameters(boolean decode); @Override List<String> getMatchedURIs(); @Override List<String> getMatchedURIs(boolean decode); @Override List<Object> getMatchedResources(); }
ChangedUriInfo implements UriInfo { @Override public String getPath() { String uriPath = this.uri.getPath(); if (uriPath != null) { String removeString = "/rest/"; if (uriPath.startsWith(removeString)) { return uriPath.substring(removeString.length()); } return uriPath; } return null; } ChangedUriInfo(String uri, UriInfo uriInfo); String getOriginalUri(); @Override String getPath(); @Override String getPath(boolean decode); @Override List<PathSegment> getPathSegments(); @Override List<PathSegment> getPathSegments(boolean decode); @Override URI getRequestUri(); @Override UriBuilder getRequestUriBuilder(); @Override URI getAbsolutePath(); @Override UriBuilder getAbsolutePathBuilder(); @Override URI getBaseUri(); @Override UriBuilder getBaseUriBuilder(); @Override MultivaluedMap<String, String> getPathParameters(); @Override MultivaluedMap<String, String> getPathParameters(boolean decode); @Override MultivaluedMap<String, String> getQueryParameters(); @Override MultivaluedMap<String, String> getQueryParameters(boolean decode); @Override List<String> getMatchedURIs(); @Override List<String> getMatchedURIs(boolean decode); @Override List<Object> getMatchedResources(); static final String ORIGINAL_REQUEST_KEY; }
@Test public void testGetLearningStandards() throws URISyntaxException { String learningStandardId = resourceService.postEntity(learningStandards, createLearningStandardEntity()); String assessmentId = resourceService.postEntity(assessments, createAssessmentEntity(learningStandardId)); requestURI = new java.net.URI(URI + "/" + assessmentId + "/learningStandards"); List<EntityBody> entityBodyList = defaultAssessmentResourceService.getLearningStandards(assessments, assessmentId, learningStandards, requestURI).getEntityBodyList(); assertNotNull("Should return an entity", entityBodyList); assertEquals("Should match", 1, entityBodyList.size()); assertEquals("Should match", "learningStandard", entityBodyList.get(0).get("entityType")); }
@Override public ServiceResponse getLearningStandards(final Resource base, final String idList, final Resource returnResource, final URI requestURI) { final EntityDefinition baseEntityDefinition = resourceHelper.getEntityDefinition(base); final EntityDefinition finalEntityDefinition = resourceHelper.getEntityDefinition(returnResource); final List<String> ids = Arrays.asList(idList.split(",")); ApiQuery apiQuery = resourceServiceHelper.getApiQuery(baseEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", ids)); apiQuery.setLimit(0); apiQuery.setOffset(0); List<EntityBody> baseResults = (List<EntityBody>) baseEntityDefinition.getService().list(apiQuery); String key = null; if (returnResource.getResourceType().equals("learningStandards")) { key = "assessmentItem"; } else { key = "objectiveAssessment"; } List<String> finalIds = new ArrayList<String>(); for (EntityBody entityBody : baseResults) { List<Map<String, Object>> items = (List<Map<String, Object>>) entityBody.get(key); if (items != null) { for (Map<String, Object> item : items) { finalIds.addAll((List<String>) item.get(returnResource.getResourceType())); } } } apiQuery = resourceServiceHelper.getApiQuery(finalEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", finalIds)); List<EntityBody> finalResults = null; try { finalResults = logicalEntity.getEntities(apiQuery, returnResource.getResourceType()); } catch (UnsupportedSelectorException e) { finalResults = (List<EntityBody>) finalEntityDefinition.getService().list(apiQuery); } return new ServiceResponse(finalResults, finalResults.size()); }
DefaultAssessmentResourceService implements AssessmentResourceService { @Override public ServiceResponse getLearningStandards(final Resource base, final String idList, final Resource returnResource, final URI requestURI) { final EntityDefinition baseEntityDefinition = resourceHelper.getEntityDefinition(base); final EntityDefinition finalEntityDefinition = resourceHelper.getEntityDefinition(returnResource); final List<String> ids = Arrays.asList(idList.split(",")); ApiQuery apiQuery = resourceServiceHelper.getApiQuery(baseEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", ids)); apiQuery.setLimit(0); apiQuery.setOffset(0); List<EntityBody> baseResults = (List<EntityBody>) baseEntityDefinition.getService().list(apiQuery); String key = null; if (returnResource.getResourceType().equals("learningStandards")) { key = "assessmentItem"; } else { key = "objectiveAssessment"; } List<String> finalIds = new ArrayList<String>(); for (EntityBody entityBody : baseResults) { List<Map<String, Object>> items = (List<Map<String, Object>>) entityBody.get(key); if (items != null) { for (Map<String, Object> item : items) { finalIds.addAll((List<String>) item.get(returnResource.getResourceType())); } } } apiQuery = resourceServiceHelper.getApiQuery(finalEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", finalIds)); List<EntityBody> finalResults = null; try { finalResults = logicalEntity.getEntities(apiQuery, returnResource.getResourceType()); } catch (UnsupportedSelectorException e) { finalResults = (List<EntityBody>) finalEntityDefinition.getService().list(apiQuery); } return new ServiceResponse(finalResults, finalResults.size()); } }
DefaultAssessmentResourceService implements AssessmentResourceService { @Override public ServiceResponse getLearningStandards(final Resource base, final String idList, final Resource returnResource, final URI requestURI) { final EntityDefinition baseEntityDefinition = resourceHelper.getEntityDefinition(base); final EntityDefinition finalEntityDefinition = resourceHelper.getEntityDefinition(returnResource); final List<String> ids = Arrays.asList(idList.split(",")); ApiQuery apiQuery = resourceServiceHelper.getApiQuery(baseEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", ids)); apiQuery.setLimit(0); apiQuery.setOffset(0); List<EntityBody> baseResults = (List<EntityBody>) baseEntityDefinition.getService().list(apiQuery); String key = null; if (returnResource.getResourceType().equals("learningStandards")) { key = "assessmentItem"; } else { key = "objectiveAssessment"; } List<String> finalIds = new ArrayList<String>(); for (EntityBody entityBody : baseResults) { List<Map<String, Object>> items = (List<Map<String, Object>>) entityBody.get(key); if (items != null) { for (Map<String, Object> item : items) { finalIds.addAll((List<String>) item.get(returnResource.getResourceType())); } } } apiQuery = resourceServiceHelper.getApiQuery(finalEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", finalIds)); List<EntityBody> finalResults = null; try { finalResults = logicalEntity.getEntities(apiQuery, returnResource.getResourceType()); } catch (UnsupportedSelectorException e) { finalResults = (List<EntityBody>) finalEntityDefinition.getService().list(apiQuery); } return new ServiceResponse(finalResults, finalResults.size()); } }
DefaultAssessmentResourceService implements AssessmentResourceService { @Override public ServiceResponse getLearningStandards(final Resource base, final String idList, final Resource returnResource, final URI requestURI) { final EntityDefinition baseEntityDefinition = resourceHelper.getEntityDefinition(base); final EntityDefinition finalEntityDefinition = resourceHelper.getEntityDefinition(returnResource); final List<String> ids = Arrays.asList(idList.split(",")); ApiQuery apiQuery = resourceServiceHelper.getApiQuery(baseEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", ids)); apiQuery.setLimit(0); apiQuery.setOffset(0); List<EntityBody> baseResults = (List<EntityBody>) baseEntityDefinition.getService().list(apiQuery); String key = null; if (returnResource.getResourceType().equals("learningStandards")) { key = "assessmentItem"; } else { key = "objectiveAssessment"; } List<String> finalIds = new ArrayList<String>(); for (EntityBody entityBody : baseResults) { List<Map<String, Object>> items = (List<Map<String, Object>>) entityBody.get(key); if (items != null) { for (Map<String, Object> item : items) { finalIds.addAll((List<String>) item.get(returnResource.getResourceType())); } } } apiQuery = resourceServiceHelper.getApiQuery(finalEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", finalIds)); List<EntityBody> finalResults = null; try { finalResults = logicalEntity.getEntities(apiQuery, returnResource.getResourceType()); } catch (UnsupportedSelectorException e) { finalResults = (List<EntityBody>) finalEntityDefinition.getService().list(apiQuery); } return new ServiceResponse(finalResults, finalResults.size()); } @Override ServiceResponse getLearningStandards(final Resource base, final String idList, final Resource returnResource, final URI requestURI); }
DefaultAssessmentResourceService implements AssessmentResourceService { @Override public ServiceResponse getLearningStandards(final Resource base, final String idList, final Resource returnResource, final URI requestURI) { final EntityDefinition baseEntityDefinition = resourceHelper.getEntityDefinition(base); final EntityDefinition finalEntityDefinition = resourceHelper.getEntityDefinition(returnResource); final List<String> ids = Arrays.asList(idList.split(",")); ApiQuery apiQuery = resourceServiceHelper.getApiQuery(baseEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", ids)); apiQuery.setLimit(0); apiQuery.setOffset(0); List<EntityBody> baseResults = (List<EntityBody>) baseEntityDefinition.getService().list(apiQuery); String key = null; if (returnResource.getResourceType().equals("learningStandards")) { key = "assessmentItem"; } else { key = "objectiveAssessment"; } List<String> finalIds = new ArrayList<String>(); for (EntityBody entityBody : baseResults) { List<Map<String, Object>> items = (List<Map<String, Object>>) entityBody.get(key); if (items != null) { for (Map<String, Object> item : items) { finalIds.addAll((List<String>) item.get(returnResource.getResourceType())); } } } apiQuery = resourceServiceHelper.getApiQuery(finalEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", finalIds)); List<EntityBody> finalResults = null; try { finalResults = logicalEntity.getEntities(apiQuery, returnResource.getResourceType()); } catch (UnsupportedSelectorException e) { finalResults = (List<EntityBody>) finalEntityDefinition.getService().list(apiQuery); } return new ServiceResponse(finalResults, finalResults.size()); } @Override ServiceResponse getLearningStandards(final Resource base, final String idList, final Resource returnResource, final URI requestURI); }
@Test public void testDecoratorNonParam() { MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add(ParameterConstants.INCLUDE_CUSTOM, String.valueOf(false)); EntityBody body = createTestEntity(); customEntityDecorator.decorate(body, null, map); assertEquals("Should match", 3, body.keySet().size()); assertEquals("Should match", "Male", body.get("sex")); assertEquals("Should match", 1234, body.get("studentUniqueStateId")); }
@Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } }
CustomEntityDecorator implements EntityDecorator { @Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } } }
CustomEntityDecorator implements EntityDecorator { @Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } } }
CustomEntityDecorator implements EntityDecorator { @Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } } @Override void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams); }
CustomEntityDecorator implements EntityDecorator { @Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } } @Override void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams); }
@Test public void testDecoratorWithParam() { MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add(ParameterConstants.INCLUDE_CUSTOM, String.valueOf(true)); EntityBody custom = createCustomEntity(); EntityService service = mock(EntityService.class); when(service.getCustom("1234")).thenReturn(custom); EntityDefinition definition = mock(EntityDefinition.class); when(definition.getService()).thenReturn(service); EntityBody body = createTestEntity(); customEntityDecorator.decorate(body, definition, map); assertEquals("Should match", 4, body.keySet().size()); assertEquals("Should match", "Male", body.get("sex")); assertEquals("Should match", 1234, body.get("studentUniqueStateId")); EntityBody customBody = (EntityBody) body.get(ResourceConstants.CUSTOM); assertNotNull("Should not be null", customBody); assertEquals("Should match", "1", customBody.get("customValue")); }
@Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } }
CustomEntityDecorator implements EntityDecorator { @Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } } }
CustomEntityDecorator implements EntityDecorator { @Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } } }
CustomEntityDecorator implements EntityDecorator { @Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } } @Override void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams); }
CustomEntityDecorator implements EntityDecorator { @Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } } @Override void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams); }
@Test public void testAddTypeCriteria() { EntityDefinition def = entityDefs.lookupByResourceName(ResourceNames.TEACHERS); ApiQuery query = new ApiQuery(); query = resourceServiceHelper.addTypeCriteria(def, query); List<NeutralCriteria> criteriaList = query.getCriteria(); assertEquals("Should match", 1, criteriaList.size()); NeutralCriteria criteria = criteriaList.get(0); assertEquals("Should match", "type", criteria.getKey()); assertEquals("Should match", NeutralCriteria.CRITERIA_IN, criteria.getOperator()); assertEquals("Should match", Arrays.asList(def.getType()), criteria.getValue()); }
protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } ApiQuery getApiQuery(EntityDefinition definition, final URI requestURI); ApiQuery getApiQuery(EntityDefinition definition); }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } ApiQuery getApiQuery(EntityDefinition definition, final URI requestURI); ApiQuery getApiQuery(EntityDefinition definition); }
@Test public void testAddTypeCriteriaNoChange() { EntityDefinition def = entityDefs.lookupByResourceName(ResourceNames.STAFF); ApiQuery query = new ApiQuery(); query = resourceServiceHelper.addTypeCriteria(def, query); List<NeutralCriteria> criteriaList = query.getCriteria(); assertEquals("Should match", 0, criteriaList.size()); }
protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } ApiQuery getApiQuery(EntityDefinition definition, final URI requestURI); ApiQuery getApiQuery(EntityDefinition definition); }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } ApiQuery getApiQuery(EntityDefinition definition, final URI requestURI); ApiQuery getApiQuery(EntityDefinition definition); }
@Test public void testExecute() { WordCountCascading wc = new WordCountCascading(); wc.execute("src/main/resources/short.txt", "target/cascading-result"); System.out.println("completed Cascading word count"); }
public void execute(String inputPath, String outputPath) { Scheme sourceScheme = new TextLine( new Fields( "line" ) ); Tap source = new Hfs( sourceScheme, inputPath ); Scheme sinkScheme = new TextLine( new Fields( "word", "count" ) ); Tap sink = new Hfs( sinkScheme, outputPath, SinkMode.REPLACE ); Pipe assembly = new Pipe( "wordcount" ); String regex = "(?<!\\pL)(?=\\pL)[^ ]*(?<=\\pL)(?!\\pL)"; Function function = new RegexGenerator( new Fields( "word" ), regex ); assembly = new Each( assembly, new Fields( "line" ), function ); assembly = new GroupBy( assembly, new Fields( "word" ) ); Aggregator count = new Count( new Fields( "count" ) ); assembly = new Every( assembly, count ); Properties properties = new Properties(); FlowConnector.setApplicationJarClass( properties, WordCountCascading.class ); FlowConnector flowConnector = new FlowConnector( properties ); Flow flow = flowConnector.connect( "word-count", source, sink, assembly ); flow.complete(); }
WordCountCascading { public void execute(String inputPath, String outputPath) { Scheme sourceScheme = new TextLine( new Fields( "line" ) ); Tap source = new Hfs( sourceScheme, inputPath ); Scheme sinkScheme = new TextLine( new Fields( "word", "count" ) ); Tap sink = new Hfs( sinkScheme, outputPath, SinkMode.REPLACE ); Pipe assembly = new Pipe( "wordcount" ); String regex = "(?<!\\pL)(?=\\pL)[^ ]*(?<=\\pL)(?!\\pL)"; Function function = new RegexGenerator( new Fields( "word" ), regex ); assembly = new Each( assembly, new Fields( "line" ), function ); assembly = new GroupBy( assembly, new Fields( "word" ) ); Aggregator count = new Count( new Fields( "count" ) ); assembly = new Every( assembly, count ); Properties properties = new Properties(); FlowConnector.setApplicationJarClass( properties, WordCountCascading.class ); FlowConnector flowConnector = new FlowConnector( properties ); Flow flow = flowConnector.connect( "word-count", source, sink, assembly ); flow.complete(); } }
WordCountCascading { public void execute(String inputPath, String outputPath) { Scheme sourceScheme = new TextLine( new Fields( "line" ) ); Tap source = new Hfs( sourceScheme, inputPath ); Scheme sinkScheme = new TextLine( new Fields( "word", "count" ) ); Tap sink = new Hfs( sinkScheme, outputPath, SinkMode.REPLACE ); Pipe assembly = new Pipe( "wordcount" ); String regex = "(?<!\\pL)(?=\\pL)[^ ]*(?<=\\pL)(?!\\pL)"; Function function = new RegexGenerator( new Fields( "word" ), regex ); assembly = new Each( assembly, new Fields( "line" ), function ); assembly = new GroupBy( assembly, new Fields( "word" ) ); Aggregator count = new Count( new Fields( "count" ) ); assembly = new Every( assembly, count ); Properties properties = new Properties(); FlowConnector.setApplicationJarClass( properties, WordCountCascading.class ); FlowConnector flowConnector = new FlowConnector( properties ); Flow flow = flowConnector.connect( "word-count", source, sink, assembly ); flow.complete(); } }
WordCountCascading { public void execute(String inputPath, String outputPath) { Scheme sourceScheme = new TextLine( new Fields( "line" ) ); Tap source = new Hfs( sourceScheme, inputPath ); Scheme sinkScheme = new TextLine( new Fields( "word", "count" ) ); Tap sink = new Hfs( sinkScheme, outputPath, SinkMode.REPLACE ); Pipe assembly = new Pipe( "wordcount" ); String regex = "(?<!\\pL)(?=\\pL)[^ ]*(?<=\\pL)(?!\\pL)"; Function function = new RegexGenerator( new Fields( "word" ), regex ); assembly = new Each( assembly, new Fields( "line" ), function ); assembly = new GroupBy( assembly, new Fields( "word" ) ); Aggregator count = new Count( new Fields( "count" ) ); assembly = new Every( assembly, count ); Properties properties = new Properties(); FlowConnector.setApplicationJarClass( properties, WordCountCascading.class ); FlowConnector flowConnector = new FlowConnector( properties ); Flow flow = flowConnector.connect( "word-count", source, sink, assembly ); flow.complete(); } void execute(String inputPath, String outputPath); }
WordCountCascading { public void execute(String inputPath, String outputPath) { Scheme sourceScheme = new TextLine( new Fields( "line" ) ); Tap source = new Hfs( sourceScheme, inputPath ); Scheme sinkScheme = new TextLine( new Fields( "word", "count" ) ); Tap sink = new Hfs( sinkScheme, outputPath, SinkMode.REPLACE ); Pipe assembly = new Pipe( "wordcount" ); String regex = "(?<!\\pL)(?=\\pL)[^ ]*(?<=\\pL)(?!\\pL)"; Function function = new RegexGenerator( new Fields( "word" ), regex ); assembly = new Each( assembly, new Fields( "line" ), function ); assembly = new GroupBy( assembly, new Fields( "word" ) ); Aggregator count = new Count( new Fields( "count" ) ); assembly = new Every( assembly, count ); Properties properties = new Properties(); FlowConnector.setApplicationJarClass( properties, WordCountCascading.class ); FlowConnector flowConnector = new FlowConnector( properties ); Flow flow = flowConnector.connect( "word-count", source, sink, assembly ); flow.complete(); } void execute(String inputPath, String outputPath); }
@Test public void testAddTypeCriteriaNullValues() { ApiQuery query = null; assertNull("Should be null", resourceServiceHelper.addTypeCriteria(null, null)); query = new ApiQuery(); query = resourceServiceHelper.addTypeCriteria(null, query); List<NeutralCriteria> criteriaList = query.getCriteria(); assertEquals("Should match", 0, criteriaList.size()); }
protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } ApiQuery getApiQuery(EntityDefinition definition, final URI requestURI); ApiQuery getApiQuery(EntityDefinition definition); }
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } ApiQuery getApiQuery(EntityDefinition definition, final URI requestURI); ApiQuery getApiQuery(EntityDefinition definition); }
@Test public void testCreate() { String id = resourceService.postEntity(resource, new EntityBody(createTestEntity())); assertNotNull("ID should not be null", id); }
@Override @MigratePostedEntity public String postEntity(final Resource resource, EntityBody entity) { EntityDefinition definition = resourceHelper.getEntityDefinition(resource); List<String> entityIds = new ArrayList<String>(); if (SecurityUtil.isStaffUser()) { entityIds = definition.getService().createBasedOnContextualRoles(adapter.migrate(entity, definition.getResourceName(), POST)); } else { entityIds = definition.getService().create(adapter.migrate(entity, definition.getResourceName(), POST)); } return StringUtils.join(entityIds.toArray(), ","); }
DefaultResourceService implements ResourceService { @Override @MigratePostedEntity public String postEntity(final Resource resource, EntityBody entity) { EntityDefinition definition = resourceHelper.getEntityDefinition(resource); List<String> entityIds = new ArrayList<String>(); if (SecurityUtil.isStaffUser()) { entityIds = definition.getService().createBasedOnContextualRoles(adapter.migrate(entity, definition.getResourceName(), POST)); } else { entityIds = definition.getService().create(adapter.migrate(entity, definition.getResourceName(), POST)); } return StringUtils.join(entityIds.toArray(), ","); } }
DefaultResourceService implements ResourceService { @Override @MigratePostedEntity public String postEntity(final Resource resource, EntityBody entity) { EntityDefinition definition = resourceHelper.getEntityDefinition(resource); List<String> entityIds = new ArrayList<String>(); if (SecurityUtil.isStaffUser()) { entityIds = definition.getService().createBasedOnContextualRoles(adapter.migrate(entity, definition.getResourceName(), POST)); } else { entityIds = definition.getService().create(adapter.migrate(entity, definition.getResourceName(), POST)); } return StringUtils.join(entityIds.toArray(), ","); } }
DefaultResourceService implements ResourceService { @Override @MigratePostedEntity public String postEntity(final Resource resource, EntityBody entity) { EntityDefinition definition = resourceHelper.getEntityDefinition(resource); List<String> entityIds = new ArrayList<String>(); if (SecurityUtil.isStaffUser()) { entityIds = definition.getService().createBasedOnContextualRoles(adapter.migrate(entity, definition.getResourceName(), POST)); } else { entityIds = definition.getService().create(adapter.migrate(entity, definition.getResourceName(), POST)); } return StringUtils.join(entityIds.toArray(), ","); } @PostConstruct void init(); @Override @MigrateResponse ServiceResponse getEntitiesByIds(final Resource resource, final String idList, final URI requestURI); @Override @MigrateResponse ServiceResponse getEntities(final Resource resource, final URI requestURI, final boolean getAllEntities); @Override @MigratePostedEntity String postEntity(final Resource resource, EntityBody entity); @Override @MigratePostedEntity void putEntity(Resource resource, String id, EntityBody entity); @Override @MigratePostedEntity void patchEntity(Resource resource, String id, EntityBody entity); @Override void deleteEntity(Resource resource, String id); @Override String getEntityType(Resource resource); @Override CalculatedData<String> getCalculatedData(Resource resource, String id); @Override CalculatedData<Map<String, Integer>> getAggregateData(Resource resource, String id); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @MigrateResponse ServiceResponse getEntities(final Resource base, final String id, final Resource resource, final URI requestURI); @Override ServiceResponse getEntities(Resource base, String id, Resource association, Resource resource, URI requestUri); }
DefaultResourceService implements ResourceService { @Override @MigratePostedEntity public String postEntity(final Resource resource, EntityBody entity) { EntityDefinition definition = resourceHelper.getEntityDefinition(resource); List<String> entityIds = new ArrayList<String>(); if (SecurityUtil.isStaffUser()) { entityIds = definition.getService().createBasedOnContextualRoles(adapter.migrate(entity, definition.getResourceName(), POST)); } else { entityIds = definition.getService().create(adapter.migrate(entity, definition.getResourceName(), POST)); } return StringUtils.join(entityIds.toArray(), ","); } @PostConstruct void init(); @Override @MigrateResponse ServiceResponse getEntitiesByIds(final Resource resource, final String idList, final URI requestURI); @Override @MigrateResponse ServiceResponse getEntities(final Resource resource, final URI requestURI, final boolean getAllEntities); @Override @MigratePostedEntity String postEntity(final Resource resource, EntityBody entity); @Override @MigratePostedEntity void putEntity(Resource resource, String id, EntityBody entity); @Override @MigratePostedEntity void patchEntity(Resource resource, String id, EntityBody entity); @Override void deleteEntity(Resource resource, String id); @Override String getEntityType(Resource resource); @Override CalculatedData<String> getCalculatedData(Resource resource, String id); @Override CalculatedData<Map<String, Integer>> getAggregateData(Resource resource, String id); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @MigrateResponse ServiceResponse getEntities(final Resource base, final String id, final Resource resource, final URI requestURI); @Override ServiceResponse getEntities(Resource base, String id, Resource association, Resource resource, URI requestUri); }
@Test public void testGetEntityType() { assertEquals("Should match", "student", resourceService.getEntityType(new Resource("v1", "students"))); assertEquals("Should match", "staff", resourceService.getEntityType(new Resource("v1", "staff"))); assertEquals("Should match", "teacher", resourceService.getEntityType(new Resource("v1", "teachers"))); }
@Override public String getEntityType(Resource resource) { return resourceHelper.getEntityDefinition(resource).getType(); }
DefaultResourceService implements ResourceService { @Override public String getEntityType(Resource resource) { return resourceHelper.getEntityDefinition(resource).getType(); } }
DefaultResourceService implements ResourceService { @Override public String getEntityType(Resource resource) { return resourceHelper.getEntityDefinition(resource).getType(); } }
DefaultResourceService implements ResourceService { @Override public String getEntityType(Resource resource) { return resourceHelper.getEntityDefinition(resource).getType(); } @PostConstruct void init(); @Override @MigrateResponse ServiceResponse getEntitiesByIds(final Resource resource, final String idList, final URI requestURI); @Override @MigrateResponse ServiceResponse getEntities(final Resource resource, final URI requestURI, final boolean getAllEntities); @Override @MigratePostedEntity String postEntity(final Resource resource, EntityBody entity); @Override @MigratePostedEntity void putEntity(Resource resource, String id, EntityBody entity); @Override @MigratePostedEntity void patchEntity(Resource resource, String id, EntityBody entity); @Override void deleteEntity(Resource resource, String id); @Override String getEntityType(Resource resource); @Override CalculatedData<String> getCalculatedData(Resource resource, String id); @Override CalculatedData<Map<String, Integer>> getAggregateData(Resource resource, String id); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @MigrateResponse ServiceResponse getEntities(final Resource base, final String id, final Resource resource, final URI requestURI); @Override ServiceResponse getEntities(Resource base, String id, Resource association, Resource resource, URI requestUri); }
DefaultResourceService implements ResourceService { @Override public String getEntityType(Resource resource) { return resourceHelper.getEntityDefinition(resource).getType(); } @PostConstruct void init(); @Override @MigrateResponse ServiceResponse getEntitiesByIds(final Resource resource, final String idList, final URI requestURI); @Override @MigrateResponse ServiceResponse getEntities(final Resource resource, final URI requestURI, final boolean getAllEntities); @Override @MigratePostedEntity String postEntity(final Resource resource, EntityBody entity); @Override @MigratePostedEntity void putEntity(Resource resource, String id, EntityBody entity); @Override @MigratePostedEntity void patchEntity(Resource resource, String id, EntityBody entity); @Override void deleteEntity(Resource resource, String id); @Override String getEntityType(Resource resource); @Override CalculatedData<String> getCalculatedData(Resource resource, String id); @Override CalculatedData<Map<String, Integer>> getAggregateData(Resource resource, String id); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @MigrateResponse ServiceResponse getEntities(final Resource base, final String id, final Resource resource, final URI requestURI); @Override ServiceResponse getEntities(Resource base, String id, Resource association, Resource resource, URI requestUri); }
@Test public void testGetEntityCount() { String id = resourceService.postEntity(resource, new EntityBody(createTestEntity())); ApiQuery apiQuery = new ApiQuery(); apiQuery.addCriteria(new NeutralCriteria("_id", "in", Arrays.asList(id))); Long count = resourceService.getEntityCount(entityDefs.lookupByResourceName(resource.getResourceType()), apiQuery); assertEquals("Should match", 1, count.longValue()); }
protected long getEntityCount(EntityDefinition definition, ApiQuery apiQuery) { long count = 0; if (definition.getService() == null) { return count; } if (apiQuery == null) { return definition.getService().count(new NeutralQuery()); } int originalLimit = apiQuery.getLimit(); int originalOffset = apiQuery.getOffset(); apiQuery.setLimit(0); apiQuery.setOffset(0); if (SecurityUtil.isStaffUser()) { count = definition.getService().countBasedOnContextualRoles(apiQuery); } else { count = definition.getService().count(apiQuery); } apiQuery.setLimit(originalLimit); apiQuery.setOffset(originalOffset); return count; }
DefaultResourceService implements ResourceService { protected long getEntityCount(EntityDefinition definition, ApiQuery apiQuery) { long count = 0; if (definition.getService() == null) { return count; } if (apiQuery == null) { return definition.getService().count(new NeutralQuery()); } int originalLimit = apiQuery.getLimit(); int originalOffset = apiQuery.getOffset(); apiQuery.setLimit(0); apiQuery.setOffset(0); if (SecurityUtil.isStaffUser()) { count = definition.getService().countBasedOnContextualRoles(apiQuery); } else { count = definition.getService().count(apiQuery); } apiQuery.setLimit(originalLimit); apiQuery.setOffset(originalOffset); return count; } }
DefaultResourceService implements ResourceService { protected long getEntityCount(EntityDefinition definition, ApiQuery apiQuery) { long count = 0; if (definition.getService() == null) { return count; } if (apiQuery == null) { return definition.getService().count(new NeutralQuery()); } int originalLimit = apiQuery.getLimit(); int originalOffset = apiQuery.getOffset(); apiQuery.setLimit(0); apiQuery.setOffset(0); if (SecurityUtil.isStaffUser()) { count = definition.getService().countBasedOnContextualRoles(apiQuery); } else { count = definition.getService().count(apiQuery); } apiQuery.setLimit(originalLimit); apiQuery.setOffset(originalOffset); return count; } }
DefaultResourceService implements ResourceService { protected long getEntityCount(EntityDefinition definition, ApiQuery apiQuery) { long count = 0; if (definition.getService() == null) { return count; } if (apiQuery == null) { return definition.getService().count(new NeutralQuery()); } int originalLimit = apiQuery.getLimit(); int originalOffset = apiQuery.getOffset(); apiQuery.setLimit(0); apiQuery.setOffset(0); if (SecurityUtil.isStaffUser()) { count = definition.getService().countBasedOnContextualRoles(apiQuery); } else { count = definition.getService().count(apiQuery); } apiQuery.setLimit(originalLimit); apiQuery.setOffset(originalOffset); return count; } @PostConstruct void init(); @Override @MigrateResponse ServiceResponse getEntitiesByIds(final Resource resource, final String idList, final URI requestURI); @Override @MigrateResponse ServiceResponse getEntities(final Resource resource, final URI requestURI, final boolean getAllEntities); @Override @MigratePostedEntity String postEntity(final Resource resource, EntityBody entity); @Override @MigratePostedEntity void putEntity(Resource resource, String id, EntityBody entity); @Override @MigratePostedEntity void patchEntity(Resource resource, String id, EntityBody entity); @Override void deleteEntity(Resource resource, String id); @Override String getEntityType(Resource resource); @Override CalculatedData<String> getCalculatedData(Resource resource, String id); @Override CalculatedData<Map<String, Integer>> getAggregateData(Resource resource, String id); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @MigrateResponse ServiceResponse getEntities(final Resource base, final String id, final Resource resource, final URI requestURI); @Override ServiceResponse getEntities(Resource base, String id, Resource association, Resource resource, URI requestUri); }
DefaultResourceService implements ResourceService { protected long getEntityCount(EntityDefinition definition, ApiQuery apiQuery) { long count = 0; if (definition.getService() == null) { return count; } if (apiQuery == null) { return definition.getService().count(new NeutralQuery()); } int originalLimit = apiQuery.getLimit(); int originalOffset = apiQuery.getOffset(); apiQuery.setLimit(0); apiQuery.setOffset(0); if (SecurityUtil.isStaffUser()) { count = definition.getService().countBasedOnContextualRoles(apiQuery); } else { count = definition.getService().count(apiQuery); } apiQuery.setLimit(originalLimit); apiQuery.setOffset(originalOffset); return count; } @PostConstruct void init(); @Override @MigrateResponse ServiceResponse getEntitiesByIds(final Resource resource, final String idList, final URI requestURI); @Override @MigrateResponse ServiceResponse getEntities(final Resource resource, final URI requestURI, final boolean getAllEntities); @Override @MigratePostedEntity String postEntity(final Resource resource, EntityBody entity); @Override @MigratePostedEntity void putEntity(Resource resource, String id, EntityBody entity); @Override @MigratePostedEntity void patchEntity(Resource resource, String id, EntityBody entity); @Override void deleteEntity(Resource resource, String id); @Override String getEntityType(Resource resource); @Override CalculatedData<String> getCalculatedData(Resource resource, String id); @Override CalculatedData<Map<String, Integer>> getAggregateData(Resource resource, String id); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @MigrateResponse ServiceResponse getEntities(final Resource base, final String id, final Resource resource, final URI requestURI); @Override ServiceResponse getEntities(Resource base, String id, Resource association, Resource resource, URI requestUri); }
@Test public void testGetAll() throws URISyntaxException { setupMocks(BASE_URI); Response response = publicDefaultResource.getAll(uriInfo); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); }
@Override @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.ONE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), true); } }); }
PublicDefaultResource extends DefaultResource { @Override @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.ONE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), true); } }); } }
PublicDefaultResource extends DefaultResource { @Override @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.ONE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), true); } }); } }
PublicDefaultResource extends DefaultResource { @Override @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.ONE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), true); } }); } @Override @GET Response getAll(@Context final UriInfo uriInfo); }
PublicDefaultResource extends DefaultResource { @Override @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.ONE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), true); } }); } @Override @GET Response getAll(@Context final UriInfo uriInfo); }
@Test public void testGet() throws URISyntaxException { String learningStandardId = resourceService.postEntity(learningStandards, createLearningStandardEntity()); String assessmentId = resourceService.postEntity(assessments, createAssessmentEntity(learningStandardId)); setupMocks(BASE_URI + "/" + assessmentId + "/learningStandards"); Response response = assessmentResource.get(uriInfo, assessmentId); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); EntityResponse entityResponse = (EntityResponse) response.getEntity(); assertEquals("Should match", 1, ((List<EntityBody>) entityResponse.getEntity()).size()); }
@GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return assessmentResourceService.getLearningStandards(base, id, resource, uriInfo.getRequestUri()); } }); }
AssessmentResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return assessmentResourceService.getLearningStandards(base, id, resource, uriInfo.getRequestUri()); } }); } }
AssessmentResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return assessmentResourceService.getLearningStandards(base, id, resource, uriInfo.getRequestUri()); } }); } }
AssessmentResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return assessmentResourceService.getLearningStandards(base, id, resource, uriInfo.getRequestUri()); } }); } @GET Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id); }
AssessmentResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return assessmentResourceService.getLearningStandards(base, id, resource, uriInfo.getRequestUri()); } }); } @GET Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id); }
@Test public void testGetResourceClass() { ResourceEndPointTemplate template = new ResourceEndPointTemplate(); template.setResourceClass("templateClass"); assertEquals("Should match", "templateClass", resourceEndPoint.getResourceClass("/students", template)); template.setResourceClass(null); assertEquals("Should match", "org.slc.sli.api.resources.generic.FourPartResource", resourceEndPoint.getResourceClass("/students", template)); }
protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; }
ResourceEndPoint { protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; } }
ResourceEndPoint { protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; } }
ResourceEndPoint { protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }
ResourceEndPoint { protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }
@Test(expected = RuntimeException.class) public void testNoClass() { ResourceEndPointTemplate template = new ResourceEndPointTemplate(); template.setResourceClass(null); when(resourceHelper.resolveResourcePath("/students", ResourceTemplate.FOUR_PART)).thenReturn(false); when(resourceHelper.resolveResourcePath("/students", ResourceTemplate.THREE_PART)).thenReturn(false); when(resourceHelper.resolveResourcePath("/students", ResourceTemplate.TWO_PART)).thenReturn(false); when(resourceHelper.resolveResourcePath("/students", ResourceTemplate.ONE_PART)).thenReturn(false); resourceEndPoint.getResourceClass("/students", template); }
protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; }
ResourceEndPoint { protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; } }
ResourceEndPoint { protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; } }
ResourceEndPoint { protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }
ResourceEndPoint { protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }
@Test public void testBuildEndPoints() { when(resourceHelper.resolveResourcePath("/students", ResourceTemplate.THREE_PART)).thenReturn(true); ResourceEndPointTemplate template = new ResourceEndPointTemplate(); template.setPath("/students"); template.setResourceClass("someClass"); ResourceEndPointTemplate subResource = new ResourceEndPointTemplate(); subResource.setPath("/{id}/studentSectionAssociations"); template.setSubResources(Arrays.asList(subResource)); Map<String, String> resources = resourceEndPoint.buildEndPoints("v1", "", template); assertEquals("Should match", 2, resources.keySet().size()); assertEquals("Should match", "someClass", resources.get("v1/students")); assertEquals("Should match", "org.slc.sli.api.resources.generic.ThreePartResource", resources.get("v1/students/{id}/studentSectionAssociations")); }
protected Map<String, String> buildEndPoints(String nameSpace, String resourcePath, ResourceEndPointTemplate template) { Map<String, String> resources = new HashMap<String, String>(); String fullPath = nameSpace + resourcePath + template.getPath(); resources.put(fullPath, getResourceClass("/rest/" + fullPath, template)); List<ResourceEndPointTemplate> subResources = template.getSubResources(); if (subResources != null) { for (ResourceEndPointTemplate subTemplate : subResources) { resources.putAll(buildEndPoints(nameSpace, resourcePath + template.getPath(), subTemplate)); } } return resources; }
ResourceEndPoint { protected Map<String, String> buildEndPoints(String nameSpace, String resourcePath, ResourceEndPointTemplate template) { Map<String, String> resources = new HashMap<String, String>(); String fullPath = nameSpace + resourcePath + template.getPath(); resources.put(fullPath, getResourceClass("/rest/" + fullPath, template)); List<ResourceEndPointTemplate> subResources = template.getSubResources(); if (subResources != null) { for (ResourceEndPointTemplate subTemplate : subResources) { resources.putAll(buildEndPoints(nameSpace, resourcePath + template.getPath(), subTemplate)); } } return resources; } }
ResourceEndPoint { protected Map<String, String> buildEndPoints(String nameSpace, String resourcePath, ResourceEndPointTemplate template) { Map<String, String> resources = new HashMap<String, String>(); String fullPath = nameSpace + resourcePath + template.getPath(); resources.put(fullPath, getResourceClass("/rest/" + fullPath, template)); List<ResourceEndPointTemplate> subResources = template.getSubResources(); if (subResources != null) { for (ResourceEndPointTemplate subTemplate : subResources) { resources.putAll(buildEndPoints(nameSpace, resourcePath + template.getPath(), subTemplate)); } } return resources; } }
ResourceEndPoint { protected Map<String, String> buildEndPoints(String nameSpace, String resourcePath, ResourceEndPointTemplate template) { Map<String, String> resources = new HashMap<String, String>(); String fullPath = nameSpace + resourcePath + template.getPath(); resources.put(fullPath, getResourceClass("/rest/" + fullPath, template)); List<ResourceEndPointTemplate> subResources = template.getSubResources(); if (subResources != null) { for (ResourceEndPointTemplate subTemplate : subResources) { resources.putAll(buildEndPoints(nameSpace, resourcePath + template.getPath(), subTemplate)); } } return resources; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }
ResourceEndPoint { protected Map<String, String> buildEndPoints(String nameSpace, String resourcePath, ResourceEndPointTemplate template) { Map<String, String> resources = new HashMap<String, String>(); String fullPath = nameSpace + resourcePath + template.getPath(); resources.put(fullPath, getResourceClass("/rest/" + fullPath, template)); List<ResourceEndPointTemplate> subResources = template.getSubResources(); if (subResources != null) { for (ResourceEndPointTemplate subTemplate : subResources) { resources.putAll(buildEndPoints(nameSpace, resourcePath + template.getPath(), subTemplate)); } } return resources; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }
@Test public void testLoadNameSpace() throws IOException { String json = "[" + "{\n" + " \"nameSpace\": [\"v6.0\", \"v6.1\"],\n" + " \"resources\":[\n" + " {\n" + " \"path\":\"/reportCards\",\n" + " \"doc\":\"some doc.\"\n" + " }]}," + "{\n" + " \"nameSpace\": [\"v7.0\"],\n" + " \"resources\":[\n" + " {\n" + " \"path\":\"/schools\",\n" + " \"dateSearchDisallowed\":\"true\",\n" + " \"doc\":\"some school doc.\"\n" + " }]}]"; ByteArrayInputStream inputStream = new ByteArrayInputStream(json.getBytes()); ApiNameSpace[] nameSpaces = resourceEndPoint.loadNameSpace(inputStream); assertEquals("Should match", 2, nameSpaces.length); ApiNameSpace nameSpace = nameSpaces[0]; assertEquals("Should match", 2, nameSpace.getNameSpace().length); assertEquals("Should match", "v6.0", nameSpace.getNameSpace()[0]); assertEquals("Should match", "v6.1", nameSpace.getNameSpace()[1]); assertEquals("Should match", 1, nameSpace.getResources().size()); assertEquals("Should match", "/reportCards", nameSpace.getResources().get(0).getPath()); assertEquals("Should match", "some doc.", nameSpace.getResources().get(0).getDoc()); nameSpace = nameSpaces[1]; assertEquals("Should match", 1, nameSpace.getNameSpace().length); assertEquals("Should match", "v7.0", nameSpace.getNameSpace()[0]); assertEquals("Should match", 1, nameSpace.getResources().size()); assertEquals("Should match", "/schools", nameSpace.getResources().get(0).getPath()); assertEquals("Should match", "some school doc.", nameSpace.getResources().get(0).getDoc()); assertEquals("Should have one entry", 1, resourceEndPoint.getDateRangeDisallowedEndPoints().size()); assertTrue("Should match", resourceEndPoint.getDateRangeDisallowedEndPoints().contains("v7.0/schools")); }
protected ApiNameSpace[] loadNameSpace(InputStream fileStream) throws IOException { ObjectMapper mapper = new ObjectMapper(); ApiNameSpace[] apiNameSpaces = mapper.readValue(fileStream, ApiNameSpace[].class); for (ApiNameSpace apiNameSpace : apiNameSpaces) { String[] nameSpaces = apiNameSpace.getNameSpace(); for (String nameSpace : nameSpaces) { nameSpaceMappings.putAll(buildNameSpaceMappings(nameSpace, nameSpaceMappings)); List<ResourceEndPointTemplate> resources = apiNameSpace.getResources(); for (ResourceEndPointTemplate resource : resources) { if (!resource.isQueryable()) { queryingDisallowedEndPoints.add(resource.getPath().substring(1)); } if (resource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath()); } if (resource.isBlockGetRequest()) { blockGetRequestEndPoints.add(nameSpace + resource.getPath()); } if (resource.getSubResources() != null) { for (ResourceEndPointTemplate subResource : resource.getSubResources()) { if (subResource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath() + subResource.getPath()); } } } resourceEndPoints.putAll(buildEndPoints(nameSpace, "", resource)); } } } return apiNameSpaces; }
ResourceEndPoint { protected ApiNameSpace[] loadNameSpace(InputStream fileStream) throws IOException { ObjectMapper mapper = new ObjectMapper(); ApiNameSpace[] apiNameSpaces = mapper.readValue(fileStream, ApiNameSpace[].class); for (ApiNameSpace apiNameSpace : apiNameSpaces) { String[] nameSpaces = apiNameSpace.getNameSpace(); for (String nameSpace : nameSpaces) { nameSpaceMappings.putAll(buildNameSpaceMappings(nameSpace, nameSpaceMappings)); List<ResourceEndPointTemplate> resources = apiNameSpace.getResources(); for (ResourceEndPointTemplate resource : resources) { if (!resource.isQueryable()) { queryingDisallowedEndPoints.add(resource.getPath().substring(1)); } if (resource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath()); } if (resource.isBlockGetRequest()) { blockGetRequestEndPoints.add(nameSpace + resource.getPath()); } if (resource.getSubResources() != null) { for (ResourceEndPointTemplate subResource : resource.getSubResources()) { if (subResource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath() + subResource.getPath()); } } } resourceEndPoints.putAll(buildEndPoints(nameSpace, "", resource)); } } } return apiNameSpaces; } }
ResourceEndPoint { protected ApiNameSpace[] loadNameSpace(InputStream fileStream) throws IOException { ObjectMapper mapper = new ObjectMapper(); ApiNameSpace[] apiNameSpaces = mapper.readValue(fileStream, ApiNameSpace[].class); for (ApiNameSpace apiNameSpace : apiNameSpaces) { String[] nameSpaces = apiNameSpace.getNameSpace(); for (String nameSpace : nameSpaces) { nameSpaceMappings.putAll(buildNameSpaceMappings(nameSpace, nameSpaceMappings)); List<ResourceEndPointTemplate> resources = apiNameSpace.getResources(); for (ResourceEndPointTemplate resource : resources) { if (!resource.isQueryable()) { queryingDisallowedEndPoints.add(resource.getPath().substring(1)); } if (resource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath()); } if (resource.isBlockGetRequest()) { blockGetRequestEndPoints.add(nameSpace + resource.getPath()); } if (resource.getSubResources() != null) { for (ResourceEndPointTemplate subResource : resource.getSubResources()) { if (subResource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath() + subResource.getPath()); } } } resourceEndPoints.putAll(buildEndPoints(nameSpace, "", resource)); } } } return apiNameSpaces; } }
ResourceEndPoint { protected ApiNameSpace[] loadNameSpace(InputStream fileStream) throws IOException { ObjectMapper mapper = new ObjectMapper(); ApiNameSpace[] apiNameSpaces = mapper.readValue(fileStream, ApiNameSpace[].class); for (ApiNameSpace apiNameSpace : apiNameSpaces) { String[] nameSpaces = apiNameSpace.getNameSpace(); for (String nameSpace : nameSpaces) { nameSpaceMappings.putAll(buildNameSpaceMappings(nameSpace, nameSpaceMappings)); List<ResourceEndPointTemplate> resources = apiNameSpace.getResources(); for (ResourceEndPointTemplate resource : resources) { if (!resource.isQueryable()) { queryingDisallowedEndPoints.add(resource.getPath().substring(1)); } if (resource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath()); } if (resource.isBlockGetRequest()) { blockGetRequestEndPoints.add(nameSpace + resource.getPath()); } if (resource.getSubResources() != null) { for (ResourceEndPointTemplate subResource : resource.getSubResources()) { if (subResource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath() + subResource.getPath()); } } } resourceEndPoints.putAll(buildEndPoints(nameSpace, "", resource)); } } } return apiNameSpaces; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }
ResourceEndPoint { protected ApiNameSpace[] loadNameSpace(InputStream fileStream) throws IOException { ObjectMapper mapper = new ObjectMapper(); ApiNameSpace[] apiNameSpaces = mapper.readValue(fileStream, ApiNameSpace[].class); for (ApiNameSpace apiNameSpace : apiNameSpaces) { String[] nameSpaces = apiNameSpace.getNameSpace(); for (String nameSpace : nameSpaces) { nameSpaceMappings.putAll(buildNameSpaceMappings(nameSpace, nameSpaceMappings)); List<ResourceEndPointTemplate> resources = apiNameSpace.getResources(); for (ResourceEndPointTemplate resource : resources) { if (!resource.isQueryable()) { queryingDisallowedEndPoints.add(resource.getPath().substring(1)); } if (resource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath()); } if (resource.isBlockGetRequest()) { blockGetRequestEndPoints.add(nameSpace + resource.getPath()); } if (resource.getSubResources() != null) { for (ResourceEndPointTemplate subResource : resource.getSubResources()) { if (subResource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath() + subResource.getPath()); } } } resourceEndPoints.putAll(buildEndPoints(nameSpace, "", resource)); } } } return apiNameSpaces; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }
@Test public void testExecute() throws Exception { WordCountHadoop wc = new WordCountHadoop(); wc.execute("src/main/resources/short.txt", "target/hadoop-result"); System.out.println("completed Hadoop word count"); }
public void execute(String inputPath, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "wordcount"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); }
WordCountHadoop { public void execute(String inputPath, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "wordcount"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); } }
WordCountHadoop { public void execute(String inputPath, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "wordcount"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); } }
WordCountHadoop { public void execute(String inputPath, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "wordcount"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); } void execute(String inputPath, String outputPath); }
WordCountHadoop { public void execute(String inputPath, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "wordcount"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); } void execute(String inputPath, String outputPath); }
@Test public void testExceptionMethods() { assertEquals("Should match", 2, exception.getAllowedMethods().size()); assertTrue("Should be true", exception.getAllowedMethods().contains("GET")); assertTrue("Should be true", exception.getAllowedMethods().contains("POST")); }
public Set<String> getAllowedMethods() { return allowedMethods; }
MethodNotAllowedException extends RuntimeException { public Set<String> getAllowedMethods() { return allowedMethods; } }
MethodNotAllowedException extends RuntimeException { public Set<String> getAllowedMethods() { return allowedMethods; } MethodNotAllowedException(Set<String> allowedMethods); }
MethodNotAllowedException extends RuntimeException { public Set<String> getAllowedMethods() { return allowedMethods; } MethodNotAllowedException(Set<String> allowedMethods); Set<String> getAllowedMethods(); }
MethodNotAllowedException extends RuntimeException { public Set<String> getAllowedMethods() { return allowedMethods; } MethodNotAllowedException(Set<String> allowedMethods); Set<String> getAllowedMethods(); }
@Test public void testGet() throws URISyntaxException { String studentId = resourceService.postEntity(studentResource, createTestEntity()); String sectionId = resourceService.postEntity(sectionResource, createSectionEntity()); String assocId = resourceService.postEntity(ssaResource, createAssociationEntity(studentId, sectionId)); setupMocks(BASE_URI + "/" + studentId + "/studentSectionAssociations"); Response response = threePartResource.get(uriInfo, studentId); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); }
@GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return resourceService.getEntities(base, id, resource, uriInfo.getRequestUri()); } }); }
ThreePartResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return resourceService.getEntities(base, id, resource, uriInfo.getRequestUri()); } }); } }
ThreePartResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return resourceService.getEntities(base, id, resource, uriInfo.getRequestUri()); } }); } }
ThreePartResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return resourceService.getEntities(base, id, resource, uriInfo.getRequestUri()); } }); } @GET Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id); }
ThreePartResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return resourceService.getEntities(base, id, resource, uriInfo.getRequestUri()); } }); } @GET Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id); }
@Test public void testConstructAndCheckResource() { Resource resourceContainer = responseBuilder.constructAndCheckResource(uriInfo, ResourceTemplate.ONE_PART, ResourceMethod.GET); assertNotNull("Should not be null", resourceContainer); assertEquals("Should match", "v1", resourceContainer.getNamespace()); assertEquals("Should match", "students", resourceContainer.getResourceType()); }
protected Resource constructAndCheckResource(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method) { Resource resource = resourceHelper.getResourceName(uriInfo, template); resourceAccessLog.logAccessToRestrictedEntity(uriInfo, resource, GetResponseBuilder.class.toString()); return resource; }
ResponseBuilder { protected Resource constructAndCheckResource(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method) { Resource resource = resourceHelper.getResourceName(uriInfo, template); resourceAccessLog.logAccessToRestrictedEntity(uriInfo, resource, GetResponseBuilder.class.toString()); return resource; } }
ResponseBuilder { protected Resource constructAndCheckResource(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method) { Resource resource = resourceHelper.getResourceName(uriInfo, template); resourceAccessLog.logAccessToRestrictedEntity(uriInfo, resource, GetResponseBuilder.class.toString()); return resource; } }
ResponseBuilder { protected Resource constructAndCheckResource(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method) { Resource resource = resourceHelper.getResourceName(uriInfo, template); resourceAccessLog.logAccessToRestrictedEntity(uriInfo, resource, GetResponseBuilder.class.toString()); return resource; } }
ResponseBuilder { protected Resource constructAndCheckResource(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method) { Resource resource = resourceHelper.getResourceName(uriInfo, template); resourceAccessLog.logAccessToRestrictedEntity(uriInfo, resource, GetResponseBuilder.class.toString()); return resource; } }
@Ignore @Test(expected = QueryParseException.class) public void testValidatePublicResourceInvalidQuery() throws URISyntaxException { requestURI = new URI(URI + "?someField=someValue"); setupMocks("assessments"); getResponseBuilder.validatePublicResourceQuery(uriInfo); }
protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); static final String ORIGINAL_REQUEST_KEY; }
@Ignore @Test(expected = QueryParseException.class) public void testValidatePublicResourceMultiInvalidQuery() throws URISyntaxException { requestURI = new URI(URI + "?limit=0&someField=someValue&includeFields=somefield"); setupMocks("assessments"); getResponseBuilder.validatePublicResourceQuery(uriInfo); }
protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); static final String ORIGINAL_REQUEST_KEY; }
@Test public void testValidatePublicResourceQueryValidQuery() throws URISyntaxException { try { requestURI = new URI(URI + "?limit=0"); setupMocks("assessments"); getResponseBuilder.validatePublicResourceQuery(uriInfo); } catch (QueryParseException e) { fail("Should not throw an exception"); } }
protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); static final String ORIGINAL_REQUEST_KEY; }
@Test public void testValidatePublicResourceQueryMultiValidQuery() throws URISyntaxException { try { requestURI = new URI(URI + "?limit=0&includeFields=somefield"); setupMocks("assessments"); getResponseBuilder.validatePublicResourceQuery(uriInfo); } catch (QueryParseException e) { fail("Should not throw an exception"); } }
protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); static final String ORIGINAL_REQUEST_KEY; }
@Test public void testValidateNonPublicResourceFilter() throws URISyntaxException { try { requestURI = new URI(URI + "?someField=someValue"); setupMocks("students"); getResponseBuilder.validatePublicResourceQuery(uriInfo); } catch (QueryParseException e) { fail("Should not throw an exception"); } }
protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); static final String ORIGINAL_REQUEST_KEY; }
@Test public void testValidateNonPublicResource() throws URISyntaxException { try { requestURI = new URI(URI + "?limit=0"); setupMocks("students"); getResponseBuilder.validatePublicResourceQuery(uriInfo); } catch (QueryParseException e) { fail("Should not throw an exception"); } }
protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); }
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method, final GenericResource.GetResourceLogic logic); static final String ORIGINAL_REQUEST_KEY; }
@Ignore @Test public void testGetAll() throws URISyntaxException { setupMocks(BASE_URI); Response response = defaultResource.getAll(uriInfo); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); }
@GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } DefaultResource(); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
@Test public void testExecute() throws Exception { BigDiffHadoop bd = new BigDiffHadoop(); bd.execute("src/main/resources/bigdiff/left.txt", "src/main/resources/bigdiff/right-sorted.txt", outputDirectory); System.out.println("completed Hadoop big diff"); }
public void execute(String inputPath1, String inputPath2, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "bigdiff"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath1)); FileInputFormat.addInputPath(job, new Path(inputPath2)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); }
BigDiffHadoop { public void execute(String inputPath1, String inputPath2, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "bigdiff"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath1)); FileInputFormat.addInputPath(job, new Path(inputPath2)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); } }
BigDiffHadoop { public void execute(String inputPath1, String inputPath2, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "bigdiff"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath1)); FileInputFormat.addInputPath(job, new Path(inputPath2)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); } }
BigDiffHadoop { public void execute(String inputPath1, String inputPath2, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "bigdiff"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath1)); FileInputFormat.addInputPath(job, new Path(inputPath2)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); } void execute(String inputPath1, String inputPath2, String outputPath); }
BigDiffHadoop { public void execute(String inputPath1, String inputPath2, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "bigdiff"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath1)); FileInputFormat.addInputPath(job, new Path(inputPath2)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); } void execute(String inputPath1, String inputPath2, String outputPath); }
@Ignore @Test public void testPost() throws URISyntaxException { setupMocks(BASE_URI); Response response = defaultResource.post(createTestEntity(), uriInfo); assertEquals("Status code should be OK", Response.Status.CREATED.getStatusCode(), response.getStatus()); assertNotNull("Should not be null", parseIdFromLocation(response)); }
@POST public Response post(final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.POST, new ResourceLogic() { @Override public Response run(Resource resource) { if (entityBody == null) { return Response.status(Response.Status.BAD_REQUEST).build(); } final String id = resourceService.postEntity(resource, entityBody); final String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), resource.getResourceType(), id).toString(); return Response.status(Response.Status.CREATED).header("Location", uri).build(); } }); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @POST public Response post(final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.POST, new ResourceLogic() { @Override public Response run(Resource resource) { if (entityBody == null) { return Response.status(Response.Status.BAD_REQUEST).build(); } final String id = resourceService.postEntity(resource, entityBody); final String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), resource.getResourceType(), id).toString(); return Response.status(Response.Status.CREATED).header("Location", uri).build(); } }); } }
DefaultResource extends GenericResource implements CustomEntityReturnable { @POST public Response post(final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.POST, new ResourceLogic() { @Override public Response run(Resource resource) { if (entityBody == null) { return Response.status(Response.Status.BAD_REQUEST).build(); } final String id = resourceService.postEntity(resource, entityBody); final String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), resource.getResourceType(), id).toString(); return Response.status(Response.Status.CREATED).header("Location", uri).build(); } }); } DefaultResource(); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @POST public Response post(final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.POST, new ResourceLogic() { @Override public Response run(Resource resource) { if (entityBody == null) { return Response.status(Response.Status.BAD_REQUEST).build(); } final String id = resourceService.postEntity(resource, entityBody); final String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), resource.getResourceType(), id).toString(); return Response.status(Response.Status.CREATED).header("Location", uri).build(); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @POST public Response post(final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.POST, new ResourceLogic() { @Override public Response run(Resource resource) { if (entityBody == null) { return Response.status(Response.Status.BAD_REQUEST).build(); } final String id = resourceService.postEntity(resource, entityBody); final String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), resource.getResourceType(), id).toString(); return Response.status(Response.Status.CREATED).header("Location", uri).build(); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
@Ignore @Test public void testGetWithId() throws URISyntaxException { String id = resourceService.postEntity(resource, createTestEntity()); setupMocks(BASE_URI + "/" + id); Response response = defaultResource.getWithId(id, uriInfo); EntityResponse entityResponse = (EntityResponse) response.getEntity(); EntityBody body = (EntityBody) entityResponse.getEntity(); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("Should match", id, body.get("id")); assertEquals("Should match", 1234, body.get("studentUniqueStateId")); }
@GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); } }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); } DefaultResource(); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
@Test(expected = EntityNotFoundException.class) public void testGetInvalidId() throws URISyntaxException { setupMocks(BASE_URI + "/1234"); defaultResource.getWithId("1234", uriInfo); }
@GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); } }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); } DefaultResource(); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
@Test public void testPut() throws URISyntaxException { String id = resourceService.postEntity(resource, createTestEntity()); setupMocks(BASE_URI + "/" + id); Response response = defaultResource.put(id, createTestUpdateEntity(), uriInfo); assertEquals("Status code should be OK", Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); Response getResponse = defaultResource.getWithId(id, uriInfo); EntityResponse entityResponse = (EntityResponse) getResponse.getEntity(); EntityBody body = (EntityBody) entityResponse.getEntity(); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), getResponse.getStatus()); assertEquals("Should match", id, body.get("id")); assertEquals("Should match", 1234, body.get("studentUniqueStateId")); assertEquals("Should match", "Female", body.get("sex")); }
@PUT @Path("{id}") public Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PUT, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPut()) { resourceService.putEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @PUT @Path("{id}") public Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PUT, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPut()) { resourceService.putEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); } }
DefaultResource extends GenericResource implements CustomEntityReturnable { @PUT @Path("{id}") public Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PUT, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPut()) { resourceService.putEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); } DefaultResource(); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @PUT @Path("{id}") public Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PUT, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPut()) { resourceService.putEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @PUT @Path("{id}") public Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PUT, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPut()) { resourceService.putEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
@Test public void testPatch() throws URISyntaxException { String id = resourceService.postEntity(resource, createTestEntity()); setupMocks(BASE_URI + "/" + id); Response response = defaultResource.patch(id, createTestPatchEntity(), uriInfo); assertEquals("Status code should be OK", Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); Response getResponse = defaultResource.getWithId(id, uriInfo); EntityResponse entityResponse = (EntityResponse) getResponse.getEntity(); EntityBody body = (EntityBody) entityResponse.getEntity(); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), getResponse.getStatus()); assertEquals("Should match", id, body.get("id")); assertEquals("Should match", 1234, body.get("studentUniqueStateId")); assertEquals("Should match", "Female", body.get("sex")); }
@PATCH @Path("{id}") public Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PATCH, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPatch()) { resourceService.patchEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @PATCH @Path("{id}") public Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PATCH, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPatch()) { resourceService.patchEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); } }
DefaultResource extends GenericResource implements CustomEntityReturnable { @PATCH @Path("{id}") public Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PATCH, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPatch()) { resourceService.patchEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); } DefaultResource(); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @PATCH @Path("{id}") public Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PATCH, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPatch()) { resourceService.patchEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @PATCH @Path("{id}") public Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PATCH, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPatch()) { resourceService.patchEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
@Test(expected = EntityNotFoundException.class) public void testDelete() throws URISyntaxException { String id = resourceService.postEntity(resource, createTestEntity()); setupMocks(BASE_URI + "/" + id); Response response = defaultResource.delete(id, uriInfo); assertEquals("Status code should be OK", Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); defaultResource.getWithId(id, uriInfo); }
@DELETE @Path("{id}") public Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(null, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.DELETE, new ResourceLogic() { @Override public Response run(Resource resource) { resourceService.deleteEntity(resource, id); return Response.status(Response.Status.NO_CONTENT).build(); } }); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @DELETE @Path("{id}") public Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(null, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.DELETE, new ResourceLogic() { @Override public Response run(Resource resource) { resourceService.deleteEntity(resource, id); return Response.status(Response.Status.NO_CONTENT).build(); } }); } }
DefaultResource extends GenericResource implements CustomEntityReturnable { @DELETE @Path("{id}") public Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(null, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.DELETE, new ResourceLogic() { @Override public Response run(Resource resource) { resourceService.deleteEntity(resource, id); return Response.status(Response.Status.NO_CONTENT).build(); } }); } DefaultResource(); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @DELETE @Path("{id}") public Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(null, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.DELETE, new ResourceLogic() { @Override public Response run(Resource resource) { resourceService.deleteEntity(resource, id); return Response.status(Response.Status.NO_CONTENT).build(); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @DELETE @Path("{id}") public Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(null, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.DELETE, new ResourceLogic() { @Override public Response run(Resource resource) { resourceService.deleteEntity(resource, id); return Response.status(Response.Status.NO_CONTENT).build(); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
@Test public void testGetCustomResource() throws URISyntaxException { String id = resourceService.postEntity(resource, createTestEntity()); setupMocks(BASE_URI + "/" + id); CustomEntityResource resource = defaultResource.getCustomResource(id, uriInfo); assertNotNull("Should not be null", resource); }
@Override public CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo) { final Resource resource = resourceHelper.getResourceName(uriInfo, ResourceTemplate.CUSTOM); return new CustomEntityResource(id, resourceHelper.getEntityDefinition(resource.getResourceType()), resourceHelper); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @Override public CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo) { final Resource resource = resourceHelper.getResourceName(uriInfo, ResourceTemplate.CUSTOM); return new CustomEntityResource(id, resourceHelper.getEntityDefinition(resource.getResourceType()), resourceHelper); } }
DefaultResource extends GenericResource implements CustomEntityReturnable { @Override public CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo) { final Resource resource = resourceHelper.getResourceName(uriInfo, ResourceTemplate.CUSTOM); return new CustomEntityResource(id, resourceHelper.getEntityDefinition(resource.getResourceType()), resourceHelper); } DefaultResource(); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @Override public CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo) { final Resource resource = resourceHelper.getResourceName(uriInfo, ResourceTemplate.CUSTOM); return new CustomEntityResource(id, resourceHelper.getEntityDefinition(resource.getResourceType()), resourceHelper); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
DefaultResource extends GenericResource implements CustomEntityReturnable { @Override public CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo) { final Resource resource = resourceHelper.getResourceName(uriInfo, ResourceTemplate.CUSTOM); return new CustomEntityResource(id, resourceHelper.getEntityDefinition(resource.getResourceType()), resourceHelper); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }
@Test public void testGetEmailFailure() throws Exception { assertNotNull(resource); AnonymousAuthenticationToken anon = new AnonymousAuthenticationToken("anon", "anon", Arrays.<GrantedAuthority>asList(Right.ANONYMOUS_ACCESS)); anon.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(anon); try { resource.getEmail(); assertFalse(true); } catch (InsufficientAuthenticationException e) { assertTrue(true); } }
@GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; }
SupportResource { @GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; } }
SupportResource { @GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; } }
SupportResource { @GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; } @GET @Path("email") Object getEmail(); }
SupportResource { @GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; } @GET @Path("email") Object getEmail(); }
@Test public void testGetEmailPass() throws Exception { injector.setEducatorContext(); Map<String, String> returned = (Map<String, String>) resource.getEmail(); assertTrue(returned.get("email").equals(email)); }
@GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; }
SupportResource { @GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; } }
SupportResource { @GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; } }
SupportResource { @GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; } @GET @Path("email") Object getEmail(); }
SupportResource { @GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; } @GET @Path("email") Object getEmail(); }