下面列出了怎么用io.jsonwebtoken.lang.Collections的API类实例代码及写法,或者点击链接到github查看源代码。
public List<GrantedAuthority> getRolesForUser(String user) {
List<GrantedAuthority> authorities = new ArrayList<>();
if (authPropsConfig.isFileAuthorization()) {
List<String > roles = simpleRolesMap.get(user);
if (!Collections.isEmpty(roles)) {
for (String role : roles) {
String roleName = "ROLE_" + role;
logger.debug("Found role '{}' for user '{}'", roleName, user);
authorities.add(createRoleWithReadPrivilage(roleName));
}
} else {
logger.warn("Not found roles for user '{}'", user);
}
return authorities;
} else {
return createDefaultAuthorities();
}
}
@Override
public String[] deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
final List<String> list = new ArrayList<>();
final JsonNode node = jsonParser.readValueAsTree();
if (node.isArray()) {
final Iterator elements = node.elements();
while (elements.hasNext()) {
final JsonNode childNode = (JsonNode) elements.next();
final String value = StringUtils.trimToNull(childNode.asText());
if (value != null) {
list.add(value);
}
}
}
if (Collections.isEmpty(list)) {
return null;
} else {
return list.toArray(new String[list.size()]);
}
}
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String payload = (String) principals.getPrimaryPrincipal();
String appId = CommonUtils.hmacPayload(payload);
if (Objects.isNull(appId))
return null;
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Set<String> roles = this.accountProvider.loadRoles(appId);
Set<String> permissions = this.accountProvider.loadPermissions(appId);
if (!Collections.isEmpty(roles))
info.setRoles(roles);
if (!Collections.isEmpty(permissions))
info.setStringPermissions(permissions);
return info;
}
public ForwardedUserFilter(String headerName,
Function<HttpServletRequest, User> userFactory,
Collection<String> requestAttributeNames) {
Assert.hasText(headerName, "headerName cannot be null or empty.");
Assert.notNull(userFactory, "userFactory function cannot be null.");
this.headerName = headerName;
this.userFactory = userFactory;
//always ensure that the fully qualified interface name is accessible:
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add(User.class.getName());
if (!Collections.isEmpty(requestAttributeNames)) {
set.addAll(requestAttributeNames);
}
this.requestAttributeNames = set;
}
Map<String, Set<?>> getPermittedData(String action) {
Map<String, Set<?>> permittedData = Maps.newHashMap();
if (roleCiTypeRule.isActionPermissionEnabled(action)) {
if (isNotEmpty(conditionMatchers)) {
for (RoleCiTypeRuleConditionMatcher conditionMatcher : conditionMatchers) {
Set matchedData = conditionMatcher.getMatchedData();
if(!Collections.isEmpty(matchedData)) {
permittedData.put(conditionMatcher.getPropertyName(), matchedData);
}
}
}
}
return permittedData;
}
public boolean validate(EndpointPolicy policy) {
boolean hasId = Optional.ofNullable(policy.getId()).isPresent();
boolean hasEndpoints = Optional.ofNullable(policy.getEndpoints()).isPresent();
boolean hasEmailNotificationTemplate = Optional.ofNullable(policy.getEmailNotificationTemplate()).isPresent();
boolean valid = !hasId && hasEndpoints && hasEmailNotificationTemplate;
if (hasEndpoints) {
if (Collections.isEmpty(policy.getEndpoints())) {
valid = false;
} else {
for (String e: policy.getEndpoints()) {
if (StringUtils.isBlank(e) || !e.startsWith("/")) {
valid = false;
log.warn(ENDPOINT_REJECTED_MESSAGE, policy.toString());
break;
}
}
}
}
if (hasEmailNotificationTemplate) {
if (!policy.getEmailNotificationTemplate().isValid()) {
valid = false;
log.warn(EMAIL_NOTIFICATION_TEMPLATE_REJECTED_MESSAGE, policy.toString());
}
}
if (valid == false) {
log.warn(REQUIRED_PROPERTIES_REJECTED_MESSAGE, policy.toString());
}
return valid;
}
public boolean validate(QueryPolicy policy) {
boolean hasId = Optional.ofNullable(policy.getId()).isPresent();
boolean hasQueries = Optional.ofNullable(policy.getQueries()).isPresent();
boolean hasEmailNotificationTemplate = Optional.ofNullable(policy.getEmailNotificationTemplate()).isPresent();
boolean valid = !hasId && hasQueries && hasEmailNotificationTemplate;
if (hasQueries) {
if (Collections.isEmpty(policy.getQueries())) {
valid = false;
} else {
for (Query q: policy.getQueries()) {
if (!q.isValid()) {
valid = false;
log.warn(QUERY_REJECTED_MESSAGE, policy.toString());
break;
}
}
}
}
if (hasEmailNotificationTemplate) {
if (!policy.getEmailNotificationTemplate().isValid()) {
valid = false;
log.warn(EMAIL_NOTIFICATION_TEMPLATE_REJECTED_MESSAGE, policy.toString());
}
}
if (valid == false) {
log.warn(REQUIRED_PROPERTIES_REJECTED_MESSAGE, policy.toString());
}
return valid;
}
private static boolean areRecipientsValid(List<String> recipients) {
boolean result = true;
if (!Collections.isEmpty(recipients)) {
for (String recipient: recipients) {
if (!EmailValidator.isValid(recipient)) {
result = false;
break;
}
}
}
return result;
}
/**
* Returns an API key.
* @param key the key to return
* @return an ApiKey
* @since 1.0.0
*/
@SuppressWarnings("unchecked")
public ApiKey getApiKey(final String key) {
final Query query = pm.newQuery(ApiKey.class, "key == :key");
final List<ApiKey> result = (List<ApiKey>) query.execute(key);
return Collections.isEmpty(result) ? null : result.get(0);
}
/**
* Retrieves a Permission by its name.
* @param name The name of the permission
* @return a Permission
* @since 1.1.0
*/
@SuppressWarnings("unchecked")
public Permission getPermission(final String name) {
final Query query = pm.newQuery(Permission.class, "name == :name");
final List<Permission> result = (List<Permission>) query.execute(name);
return Collections.isEmpty(result) ? null : result.get(0);
}
/**
* Returns the most recent log entry for the specified Subscriber.
* If no log entries are found, this method will return null.
* @param clazz The LoggableSubscriber class to query on
* @return a EventServiceLog
* @since 1.0.0
*/
@SuppressWarnings("unchecked")
public EventServiceLog getLatestEventServiceLog(final Class<LoggableSubscriber> clazz) {
final Query query = pm.newQuery(EventServiceLog.class, "eventClass == :clazz");
query.setOrdering("completed desc");
final List<EventServiceLog> result = (List<EventServiceLog>) query.execute(clazz);
return Collections.isEmpty(result) ? null : result.get(0);
}
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String account = (String) principals.getPrimaryPrincipal();
if(Objects.isNull(account)||!Strings.isNullOrEmpty(CommonUtils.jwtPayload(account))
||!Strings.isNullOrEmpty(CommonUtils.hmacPayload(account)))
return null;
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Set<String> roles = this.accountProvider.loadRoles(account);
Set<String> permissions = this.accountProvider.loadPermissions(account);
if(!Collections.isEmpty(roles)) info.setRoles(roles);
if(!Collections.isEmpty(permissions)) info.setStringPermissions(permissions);
return info;
}
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String payload = (String) principals.getPrimaryPrincipal();
String jwtPayload = CommonUtils.jwtPayload(payload);
if(Objects.isNull(jwtPayload)) return null;
Map<String, Object> payloadMap = CommonUtils.readJSON(jwtPayload,Map.class);
Set<String> roles = CommonUtils.split((String)payloadMap.get("roles"));
Set<String> permissions = CommonUtils.split((String)payloadMap.get("perms"));
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
if(!Collections.isEmpty(roles)) info.setRoles(roles);
if(!Collections.isEmpty(permissions)) info.setStringPermissions(permissions);
return info;
}
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String account = (String) principals.getPrimaryPrincipal();
if(Objects.isNull(account)||!Strings.isNullOrEmpty(CommonUtils.jwtPayload(account))
||!Strings.isNullOrEmpty(CommonUtils.hmacPayload(account)))
return null;
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Set<String> roles = this.accountProvider.loadRoles(account);
Set<String> permissions = this.accountProvider.loadPermissions(account);
if(!Collections.isEmpty(roles)) info.setRoles(roles);
if(!Collections.isEmpty(permissions)) info.setStringPermissions(permissions);
return info;
}
@Override
public JwtBuilder setHeaderParams(Map<String, Object> params) {
if (!Collections.isEmpty(params)) {
Header header = ensureHeader();
for (Map.Entry<String, Object> entry : params.entrySet()) {
header.put(entry.getKey(), entry.getValue());
}
}
return this;
}
private static JsonValue toJson(final Object input) {
if (input == null) {
return JsonFactory.nullLiteral();
} else if (input instanceof Boolean) {
return JsonFactory.newValue((boolean) input);
} else if (input instanceof Byte || input instanceof Short || input instanceof Integer) {
return JsonFactory.newValue((int) input);
} else if (input instanceof Long) {
return JsonFactory.newValue((long) input);
} else if (input instanceof Float) {
return JsonFactory.newValue((float) input);
} else if (input instanceof Double) {
return JsonFactory.newValue((double) input);
} else if (input instanceof Character || input instanceof String || input instanceof Enum) {
return JsonFactory.newValue(input.toString());
} else if (input instanceof Calendar) {
return JsonFactory.newValue(DateFormats.formatIso8601(((Calendar) input).getTime()));
} else if (input instanceof Date) {
return JsonFactory.newValue(DateFormats.formatIso8601((Date) input));
} else if (input instanceof byte[]) {
return JsonFactory.newValue(Encoders.BASE64.encode((byte[]) input));
} else if (input instanceof char[]) {
return JsonFactory.newValue(new String((char[]) input));
} else if (input instanceof Map) {
return toJsonObject((Map<?, ?>) input);
} else if (input instanceof Collection) {
return toJsonArray((Collection<?>) input);
} else if (Objects.isArray(input)) {
return toJsonArray(Collections.arrayToList(input));
}
throw new SerializationException("Unable to serialize object of type " + input.getClass().getName() +
" to JSON using known heuristics.");
}
@Override
public JwtBuilder setHeaderParams(Map<String, Object> params) {
if (!Collections.isEmpty(params)) {
Header header = ensureHeader();
for (Map.Entry<String, Object> entry : params.entrySet()) {
header.put(entry.getKey(), entry.getValue());
}
}
return this;
}
private Object toJSONInstance(Object object) {
if (object == null) {
return JSONObject.NULL;
}
if (object instanceof JSONObject || object instanceof JSONArray
|| JSONObject.NULL.equals(object) || isJSONString(object)
|| object instanceof Byte || object instanceof Character
|| object instanceof Short || object instanceof Integer
|| object instanceof Long || object instanceof Boolean
|| object instanceof Float || object instanceof Double
|| object instanceof String || object instanceof BigInteger
|| object instanceof BigDecimal || object instanceof Enum) {
return object;
}
if (object instanceof Calendar) {
object = ((Calendar) object).getTime(); //sets object to date, will be converted in next if-statement:
}
if (object instanceof Date) {
Date date = (Date) object;
return DateFormats.formatIso8601(date);
}
if (object instanceof byte[]) {
return Encoders.BASE64.encode((byte[]) object);
}
if (object instanceof char[]) {
return new String((char[]) object);
}
if (object instanceof Map) {
Map<?, ?> map = (Map<?, ?>) object;
return toJSONObject(map);
}
if (object instanceof Collection) {
Collection<?> coll = (Collection<?>) object;
return toJSONArray(coll);
}
if (Objects.isArray(object)) {
Collection c = Collections.arrayToList(object);
return toJSONArray(c);
}
//not an immediately JSON-compatible object and probably a JavaBean (or similar). We can't convert that
//directly without using a marshaller of some sort:
String msg = "Unable to serialize object of type " + object.getClass().getName() + " to JSON using known heuristics.";
throw new SerializationException(msg);
}
/**
* Wrapper around {@link #contOnValidationError(Set[])} but instead of returning
* a list of errors, this method will halt processing of the request by throwing
* a BadRequestException, setting the HTTP status to 400 (BAD REQUEST) and providing
* a full list of validation errors in the body of the response.
*
* Usage:
* <pre>
* Validator validator = getValidator();
* failOnValidationError(
* validator.validateProperty(myObject, "uuid"),
* validator.validateProperty(myObject, "name")
* );
* // If validation fails, this line will not be reached.
* </pre>
*
* @param violationsArray a Set of one or more ConstraintViolations
* @since 1.0.0
*/
@SafeVarargs
protected final void failOnValidationError(final Set<ConstraintViolation<Object>>... violationsArray) {
final List<ValidationError> errors = contOnValidationError(violationsArray);
if (! Collections.isEmpty(errors)) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST).entity(errors).build());
}
}
/**
* Wrapper around {@link #contOnValidationError(ValidationTask[])} but instead of returning
* a list of errors, this method will halt processing of the request by throwing
* a BadRequestException, setting the HTTP status to 400 (BAD REQUEST) and providing
* a full list of validation errors in the body of the response.
*
* Usage:
* <pre>
* List<ValidationException> errors = failOnValidationError(
* new ValidationTask(pattern, input, errorMessage),
* new ValidationTask(pattern, input, errorMessage)
* );
* // If validation fails, this line will not be reached.
* </pre>
*
* @param validationTasks an array of one or more ValidationTasks
* @since 1.0.0
*/
protected final void failOnValidationError(final ValidationTask... validationTasks) {
final List<ValidationException> errors = contOnValidationError(validationTasks);
if (! Collections.isEmpty(errors)) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST).entity(errors).build());
}
}
/**
* Retrieves an object by its UUID.
* @param <T> A type parameter. This type will be returned
* @param clazz the persistence class to retrive the ID for
* @param uuid the uuid of the object to retrieve
* @return an object of the specified type
* @since 1.0.0
*/
@SuppressWarnings("unchecked")
public <T> T getObjectByUuid(Class<T> clazz, UUID uuid) {
final Query query = pm.newQuery(clazz, "uuid == :uuid");
final List<T> result = (List<T>) query.execute(uuid);
return Collections.isEmpty(result) ? null : result.get(0);
}
/**
* Retrieves an OidcUser containing the specified username. If the username
* does not exist, returns null.
* @param username The username to retrieve
* @return an OidcUser
* @since 1.8.0
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public OidcUser getOidcUser(final String username) {
final Query query = pm.newQuery(OidcUser.class, "username == :username");
final List<OidcUser> result = (List<OidcUser>) query.execute(username);
return Collections.isEmpty(result) ? null : result.get(0);
}
/**
* Returns an OidcGroup containing the specified name. If the name
* does not exist, returns null.
* @param name Name of the group to retrieve
* @return an OidcGroup
* @since 1.8.0
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public OidcGroup getOidcGroup(final String name) {
final Query query = pm.newQuery(OidcGroup.class, "name == :name");
final List<OidcGroup> result = (List<OidcGroup>) query.execute(name);
return Collections.isEmpty(result) ? null : result.get(0);
}
/**
* Retrieves an LdapUser containing the specified username. If the username
* does not exist, returns null.
* @param username The username to retrieve
* @return an LdapUser
* @since 1.0.0
*/
@SuppressWarnings("unchecked")
public LdapUser getLdapUser(final String username) {
final Query query = pm.newQuery(LdapUser.class, "username == :username");
final List<LdapUser> result = (List<LdapUser>) query.execute(username);
return Collections.isEmpty(result) ? null : result.get(0);
}
/**
* Returns a ManagedUser with the specified username. If the username
* does not exist, returns null.
* @param username The username to retrieve
* @return a ManagedUser
* @since 1.0.0
*/
@SuppressWarnings("unchecked")
public ManagedUser getManagedUser(final String username) {
final Query query = pm.newQuery(ManagedUser.class, "username == :username");
final List<ManagedUser> result = (List<ManagedUser>) query.execute(username);
return Collections.isEmpty(result) ? null : result.get(0);
}
/**
* Retrieves a MappedLdapGroup object for the specified Team and LDAP group.
* @param team a Team object
* @param dn a String representation of Distinguished Name
* @return a MappedLdapGroup if found, or null if no mapping exists
* @since 1.4.0
*/
@SuppressWarnings("unchecked")
public MappedLdapGroup getMappedLdapGroup(final Team team, final String dn) {
final Query query = pm.newQuery(MappedLdapGroup.class, "team == :team && dn == :dn");
final List<MappedLdapGroup> result = (List<MappedLdapGroup>) query.execute(team, dn);
return Collections.isEmpty(result) ? null : result.get(0);
}
/**
* Retrieves a MappedOidcGroup object for the specified Team and OIDC group.
* @param team a Team object
* @param group a OidcGroup object
* @return a MappedOidcGroup if found, or null if no mapping exists
* @since 1.8.0
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public MappedOidcGroup getMappedOidcGroup(final Team team, final OidcGroup group) {
final Query query = pm.newQuery(MappedOidcGroup.class, "team == :team && group == :group");
final List<MappedOidcGroup> result = (List<MappedOidcGroup>) query.execute(team, group);
return Collections.isEmpty(result) ? null : result.get(0);
}
/**
* Returns a ConfigProperty with the specified groupName and propertyName.
* @param groupName the group name of the config property
* @param propertyName the name of the property
* @return a ConfigProperty object
* @since 1.3.0
*/
@SuppressWarnings("unchecked")
public ConfigProperty getConfigProperty(final String groupName, final String propertyName) {
final Query query = pm.newQuery(ConfigProperty.class, "groupName == :groupName && propertyName == :propertyName");
final List<ConfigProperty> result = (List<ConfigProperty>) query.execute(groupName, propertyName);
return Collections.isEmpty(result) ? null : result.get(0);
}