index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/BaseResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.resources;
import java.io.Serializable;
import java.util.Set;
import java.util.TreeSet;
import jakarta.validation.constraints.Size;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import org.apache.directory.scim.spec.validator.Urn;
import lombok.Data;
/**
* All the different variations of SCIM responses require that the object
* contains a list of the schemas it conforms to.
*
* @author crh5255
*
*/
@Data
@XmlAccessorType(XmlAccessType.NONE)
public abstract class BaseResource<SELF extends BaseResource<SELF>> implements Serializable {
private static final long serialVersionUID = -7603956873008734403L;
@XmlElement(name="schemas")
@Size(min = 1)
@Urn
Set<String> schemas;
public BaseResource(@Urn String urn) {
addSchema(urn);
}
public SELF addSchema(@Urn String urn) {
if (schemas == null){
schemas = new TreeSet<>();
}
schemas.add(urn);
return self();
}
public SELF setSchemas(@Urn Set<String> schemas) {
if (schemas == null) {
this.schemas.clear();
} else {
this.schemas = new TreeSet<>(schemas);
}
return self();
}
@SuppressWarnings("unchecked")
protected SELF self() {
return (SELF) this;
}
}
| 4,200 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/TypedAttribute.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.resources;
@FunctionalInterface
public interface TypedAttribute {
String getType();
}
| 4,201 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/PhoneNumber.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
*
*/
package org.apache.directory.scim.spec.resources;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import lombok.ToString;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.directory.scim.spec.annotation.ScimAttribute;
import org.apache.directory.scim.spec.phonenumber.PhoneNumberLexer;
import org.apache.directory.scim.spec.phonenumber.PhoneNumberParseException;
import org.apache.directory.scim.spec.phonenumber.PhoneNumberParseTreeListener;
import org.apache.directory.scim.spec.phonenumber.PhoneNumberParser;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
/**
* Scim core schema, <a
* href="https://tools.ietf.org/html/rfc7643#section-4.1.2>section 4.1.2</a>
*
*/
@XmlType
@XmlAccessorType(XmlAccessType.NONE)
@ToString
public class PhoneNumber implements Serializable, TypedAttribute {
private static final long serialVersionUID = 607319505715224096L;
private static final String VISUAL_SEPARATORS = "[\\(\\)\\-\\.]";
private static final Logger log = LoggerFactory.getLogger(PhoneNumber.class);
@ScimAttribute(description = "Phone number of the User")
String value;
@XmlElement
@ScimAttribute(description = "A human readable name, primarily used for display purposes. READ-ONLY.")
@Getter
@Setter
String display;
@XmlElement
@ScimAttribute(canonicalValueList = { "work", "home", "mobile", "fax", "pager", "other" }, description = "A label indicating the attribute's function; e.g., 'work' or 'home' or 'mobile' etc.")
@Getter
@Setter
String type;
@XmlElement
@ScimAttribute(description = "A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g. the preferred phone number or primary phone number. The primary attribute value 'true' MUST appear no more than once.")
@Getter
@Setter
Boolean primary = false;
@Setter(AccessLevel.NONE)
@Getter
boolean isGlobalNumber = false;
@Getter
@Setter(AccessLevel.NONE)
String number;
@Setter(AccessLevel.NONE)
@Getter
String extension;
@Setter(AccessLevel.NONE)
@Getter
String subAddress;
@Setter(AccessLevel.NONE)
@Getter
String phoneContext;
@Setter(AccessLevel.NONE)
@Getter
boolean isDomainPhoneContext = false;
@Getter
@Setter(AccessLevel.NONE)
Map<String, String> params;
public void addParam(String name, String value) {
if (this.params == null) {
this.params = new LinkedHashMap<>();
}
this.params.put(name, value);
}
// This is annotated here to ensure that JAXB uses the setter rather than
// reflection
// to assigned the value. Do not move the XmlElement annotation to the field
// please.
@XmlElement
public String getValue() {
return value;
}
public PhoneNumber setValue(String value) throws PhoneNumberParseException {
return this.setValue(value, false);
}
public PhoneNumber setValue(String value, boolean strict) throws PhoneNumberParseException {
if (value == null) {
throw new PhoneNumberParseException("null values are illegal for phone numbers");
}
PhoneNumberLexer phoneNumberLexer = new PhoneNumberLexer(new ANTLRInputStream(value));
PhoneNumberParser p = new PhoneNumberParser(new CommonTokenStream(phoneNumberLexer));
p.setBuildParseTree(true);
p.addErrorListener(new PhoneNumberErrorListener());
PhoneNumberParseTreeListener tpl = new PhoneNumberParseTreeListener();
try {
ParseTree tree = p.phoneNumber();
ParseTreeWalker.DEFAULT.walk(tpl, tree);
PhoneNumber parsedPhoneNumber = tpl.getPhoneNumber();
this.value = parsedPhoneNumber.getValue();
this.number = parsedPhoneNumber.getNumber();
this.extension = parsedPhoneNumber.getExtension();
this.subAddress = parsedPhoneNumber.getSubAddress();
this.phoneContext = parsedPhoneNumber.getPhoneContext();
this.params = parsedPhoneNumber.getParams();
this.isGlobalNumber = parsedPhoneNumber.isGlobalNumber();
this.isDomainPhoneContext = parsedPhoneNumber.isDomainPhoneContext();
} catch (IllegalStateException e) {
// SCIM Core RFC section 4.1.2 states phone numbers SHOULD be formatted per RFC3966, e.g. 'tel:+1-201-555-0123'
// but this is not required, if exception is thrown while parsing, fall back to original value, unless `strict`
if (strict) {
throw new PhoneNumberParseException(e);
}
log.debug("Failed to parse phone number '{}'", value, e);
this.value = value;
}
return this;
}
/*
* Implements RFC 3996 URI Equality for the value property
* https://tools.ietf.org/html/rfc3966#section-3
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PhoneNumber other = (PhoneNumber) obj;
if (isGlobalNumber != other.isGlobalNumber)
return false;
String numberWithoutVisualSeparators = number != null ? number.replaceAll(VISUAL_SEPARATORS, "") : null;
String otherNumberWithoutVisualSeparators = other.number != null ? other.number.replaceAll(VISUAL_SEPARATORS, "") : null;
if (numberWithoutVisualSeparators == null) {
if (otherNumberWithoutVisualSeparators != null)
return false;
} else if (!numberWithoutVisualSeparators.equals(otherNumberWithoutVisualSeparators))
return false;
String extensionWithoutVisualSeparators = extension != null ? extension.replaceAll(VISUAL_SEPARATORS, "") : null;
String otherExtensionWithoutVisualSeparators = other.extension != null ? other.extension.replaceAll(VISUAL_SEPARATORS, "") : null;
if (extensionWithoutVisualSeparators == null) {
if (otherExtensionWithoutVisualSeparators != null)
return false;
} else if (!extensionWithoutVisualSeparators.equals(otherExtensionWithoutVisualSeparators))
return false;
if (subAddress == null) {
if (other.subAddress != null)
return false;
} else if (!equalsIgnoreCase(subAddress, other.subAddress))
return false;
String phoneContextTemp = phoneContext;
if (!StringUtils.isBlank(phoneContext) && !isDomainPhoneContext) {
phoneContextTemp = phoneContext.replaceAll(VISUAL_SEPARATORS, "");
}
String otherPhoneContextTemp = other.phoneContext;
if (!StringUtils.isBlank(other.phoneContext) && !other.isDomainPhoneContext) {
otherPhoneContextTemp = other.phoneContext.replaceAll(VISUAL_SEPARATORS, "");
}
if (phoneContextTemp == null) {
if (otherPhoneContextTemp != null)
return false;
} else if (!equalsIgnoreCase(phoneContextTemp, otherPhoneContextTemp))
return false;
if (!equalsIgnoreCaseAndOrderParams(other.params)) {
return false;
}
if (primary == null) {
if (other.primary != null)
return false;
} else if (!primary.equals(other.primary))
return false;
if (type == null) {
return other.type == null;
} else return equalsIgnoreCase(type, other.type);
}
/*
* Implements RFC 3996 URI Equality for the value property
* https://tools.ietf.org/html/rfc3966#section-3
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (isGlobalNumber ? 1231 : 1237);
result = prime * result + ((number == null) ? 0 : number.replaceAll(VISUAL_SEPARATORS, "").hashCode());
result = prime * result + ((extension == null) ? 0 : extension.replaceAll(VISUAL_SEPARATORS, "").hashCode());
result = prime * result + ((subAddress == null) ? 0 : subAddress.toLowerCase(Locale.ROOT).hashCode());
result = prime * result + ((phoneContext == null) ? 0 : (isDomainPhoneContext ? phoneContext.toLowerCase(Locale.ROOT).hashCode() : phoneContext.replaceAll(VISUAL_SEPARATORS, "").hashCode()));
result = prime * result + ((params == null) ? 0 : paramsToLowerCase().hashCode());
result = prime * result + ((primary == null) ? 0 : primary.hashCode());
result = prime * result + ((type == null) ? 0 : type.toLowerCase(Locale.ROOT).hashCode());
return result;
}
Map<String, String> paramsToLowerCase() {
Map<String, String> paramsLowercase = new LinkedHashMap<>();
for (Entry<String, String> entry : params.entrySet()) {
paramsLowercase.put(entry.getKey().toLowerCase(Locale.ROOT), entry.getValue().toLowerCase(Locale.ROOT));
}
return paramsLowercase;
}
private static boolean equalsIgnoreCase(String a, String b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
}
boolean equalsIgnoreCaseAndOrderParams(Map<String, String> otherParams) {
if (params == null && otherParams == null) {
return true;
}
if ((params == null && otherParams != null) || (params != null && otherParams == null) || (params.size() != otherParams.size())) {
return false;
}
Map<String, String> paramsLowercase = paramsToLowerCase();
for (Entry<String, String> entry : otherParams.entrySet()) {
String foundValue = paramsLowercase.get(entry.getKey().toLowerCase(Locale.ROOT));
if (!entry.getValue().toLowerCase(Locale.ROOT).equals(foundValue)) {
return false;
}
}
return true;
}
private static class PhoneNumberErrorListener extends BaseErrorListener {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
}
}
@Data
public abstract static class PhoneNumberBuilder {
static final Logger LOGGER = LoggerFactory.getLogger(PhoneNumberBuilder.class);
final String HYPHEN = "-";
final String INTERNATIONAL_PREFIX = "+";
final String PREFIX = "tel:%s";
final String EXTENSTION_PREFIX = ";ext=%s";
final String ISUB_PREFIX = ";isub=%s";
final String CONTEXT_PREFIX = ";phone-context=%s";
final String PARAMS_STRING = ";%s=%s";
final String LOCAL_SUBSCRIBER_NUMBER_REGEX = "^[\\d\\.\\-\\(\\)]+$";
final String DOMAIN_NAME_REGEX = "^[a-zA-Z0-9\\.\\-]+$";
final String GLOBAL_NUMBER_REGEX = "^(\\+)?[\\d\\.\\-\\(\\)]+$";
final String COUNTRY_CODE_REGEX = "^(\\+)?[1-9][0-9]{0,2}$";
String number;
String display;
String extension;
String subAddress;
String phoneContext;
LinkedHashMap<String, String> params;
boolean isGlobalNumber = false;
boolean isDomainPhoneContext = false;
public PhoneNumberBuilder display(String display) {
this.display = display;
return this;
}
public PhoneNumberBuilder extension(String extension) {
this.extension = extension;
return this;
}
public PhoneNumberBuilder subAddress(String subAddress) {
this.subAddress = subAddress;
return this;
}
public PhoneNumberBuilder phoneContext(String phoneContext) {
this.phoneContext = phoneContext;
return this;
}
public PhoneNumberBuilder setParams(Map<String, String> params) {
this.params = params != null ? new LinkedHashMap<>(params) : null;
return this;
}
public PhoneNumberBuilder param(String name, String value) {
if (this.params == null) {
this.params = new LinkedHashMap<>();
}
this.params.put(name, value);
return this;
}
String getFormattedExtension() {
if (this.extension != null && !this.extension.isEmpty()) {
return String.format(EXTENSTION_PREFIX, this.extension);
}
return null;
}
String getFormattedSubAddress() {
if (this.subAddress != null && !this.subAddress.isEmpty()) {
return String.format(ISUB_PREFIX, this.subAddress);
}
return null;
}
String getFormattedPhoneContext() {
if (this.phoneContext != null && !this.phoneContext.isEmpty()) {
return String.format(CONTEXT_PREFIX, this.phoneContext);
}
return null;
}
String getFormattedParams() {
String paramsFormatted = "";
if (params != null) {
paramsFormatted = params.entrySet().stream()
.map(entry -> String.format(PARAMS_STRING, entry.getKey(), entry.getValue() != null ? entry.getValue() : ""))
.collect(Collectors.joining());
}
return !paramsFormatted.isEmpty() ? paramsFormatted : null;
}
String getFormattedValue() {
String valueString = String.format(PREFIX, this.number);
String fExtension = getFormattedExtension();
if (fExtension != null) {
valueString += fExtension;
}
String fSubAddr = getFormattedSubAddress();
if (fSubAddr != null) {
valueString += fSubAddr;
}
String fContext = getFormattedPhoneContext();
if (fContext != null) {
valueString += fContext;
}
String fParams = getFormattedParams();
if (fParams != null) {
valueString += fParams;
}
return !valueString.isEmpty() ? valueString : null;
}
public PhoneNumber build() throws PhoneNumberParseException {
return build(true);
}
public PhoneNumber build(boolean validate) throws PhoneNumberParseException {
if (!StringUtils.isBlank(extension) && !StringUtils.isBlank(subAddress)) {
throw new IllegalArgumentException("PhoneNumberBuilder cannot have a value for both extension and subAddress.");
}
if (extension != null && !extension.matches(LOCAL_SUBSCRIBER_NUMBER_REGEX)) {
throw new IllegalArgumentException("PhoneNumberBuilder extension must contain only numeric characters and optional ., -, (, ) visual separator characters.");
}
if (params != null && !params.isEmpty()) {
if (params.get("") != null || params.get(null) != null || params.containsValue(null) || params.containsValue("")) { //NOPMD - suppressed CollapsibleIfStatements
throw new IllegalArgumentException("PhoneNumberBuilder params names and values cannot be null or empty.");
}
}
PhoneNumber phoneNumber = new PhoneNumber();
String formattedValue = getFormattedValue();
LOGGER.debug("Building phone number: '{}'", formattedValue);
if (validate) {
phoneNumber.setValue(formattedValue, true);
} else {
phoneNumber.value = formattedValue;
phoneNumber.extension = this.extension;
phoneNumber.isDomainPhoneContext = this.isDomainPhoneContext;
phoneNumber.isGlobalNumber = this.isGlobalNumber;
phoneNumber.number = this.number;
phoneNumber.params = this.params;
phoneNumber.phoneContext = this.phoneContext;
phoneNumber.subAddress = this.subAddress;
}
return phoneNumber;
}
}
public static class LocalPhoneNumberBuilder extends PhoneNumberBuilder {
String subscriberNumber;
String countryCode;
String areaCode;
String domainName;
public LocalPhoneNumberBuilder subscriberNumber(String subscriberNumber) {
this.subscriberNumber = subscriberNumber;
this.number = subscriberNumber;
return this;
}
public LocalPhoneNumberBuilder countryCode(String countryCode) {
String localCode = countryCode;
if (localCode != null && !localCode.isEmpty()) {
localCode = localCode.trim();
if (localCode.length() > 0 && localCode.charAt(0) != '+') {
localCode = '+' + localCode;
}
}
this.countryCode = localCode;
return this;
}
public LocalPhoneNumberBuilder areaCode(String areaCode) {
this.areaCode = areaCode;
return this;
}
public LocalPhoneNumberBuilder domainName(String domainName) {
this.domainName = domainName;
return this;
}
public LocalPhoneNumberBuilder isDomainPhoneContext(boolean hasDomainPhoneContext) {
this.isDomainPhoneContext = hasDomainPhoneContext;
return this;
}
@Override
public PhoneNumber build() throws PhoneNumberParseException {
if (StringUtils.isBlank(subscriberNumber) || !subscriberNumber.matches(LOCAL_SUBSCRIBER_NUMBER_REGEX)) {
throw new IllegalArgumentException("LocalPhoneNumberBuilder subscriberNumber must contain only numeric characters and optional ., -, (, ) visual separator characters.");
}
if (StringUtils.isBlank(countryCode) && StringUtils.isBlank(domainName)) {
throw new IllegalArgumentException("LocalPhoneNumberBuilder must have values for domainName or countryCode.");
}
if (StringUtils.isBlank(domainName)) {
if (StringUtils.isBlank(countryCode) || !countryCode.matches(COUNTRY_CODE_REGEX)) {
throw new IllegalArgumentException("LocalPhoneNumberBuilder countryCode must contain only numeric characters and an optional plus (+) prefix.");
}
if (areaCode != null && !StringUtils.isNumeric(areaCode)) {
throw new IllegalArgumentException("LocalPhoneNumberBuilder areaCode must contain only numberic characters.");
}
if (!countryCode.startsWith(INTERNATIONAL_PREFIX)) {
this.phoneContext = INTERNATIONAL_PREFIX + countryCode;
} else {
this.phoneContext = countryCode;
}
if (!StringUtils.isBlank(areaCode)) {
this.phoneContext += (HYPHEN + areaCode);
}
} else {
if (!domainName.matches(DOMAIN_NAME_REGEX)) {
throw new IllegalArgumentException("LocalPhoneNumberBuilder domainName must contain only alphanumeric, . and - characters.");
}
this.phoneContext = domainName;
}
return super.build();
}
}
public static class GlobalPhoneNumberBuilder extends PhoneNumberBuilder {
String globalNumber;
public GlobalPhoneNumberBuilder() {
this.isGlobalNumber = true;
}
public GlobalPhoneNumberBuilder globalNumber(String globalNumber) {
this.globalNumber = globalNumber;
if (globalNumber != null) {
if (globalNumber.startsWith(INTERNATIONAL_PREFIX)) {
this.number = globalNumber;
} else {
this.number = INTERNATIONAL_PREFIX + globalNumber;
}
}
return this;
}
@Override
public PhoneNumber build() throws PhoneNumberParseException {
if (StringUtils.isBlank(globalNumber) || !globalNumber.matches(GLOBAL_NUMBER_REGEX)) {
throw new IllegalArgumentException("GlobalPhoneNumberBuilder globalNumber must contain only numeric characters, optional ., -, (, ) visual separators, and an optional plus (+) prefix.");
}
return super.build();
}
}
}
| 4,202 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/resources/Entitlement.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.resources;
import java.io.Serializable;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import org.apache.directory.scim.spec.annotation.ScimAttribute;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* Scim core schema, <a href="https://tools.ietf.org/html/rfc7643#section-4.1.2>section 4.1.2</a>
*
*/
@XmlType
@XmlAccessorType(XmlAccessType.NONE)
@Data
@EqualsAndHashCode(callSuper=false)
public class Entitlement implements Serializable, TypedAttribute {
private static final long serialVersionUID = -5657063764529902479L;
@XmlElement(nillable=true)
@ScimAttribute(description="A label indicating the attribute's function.")
String type;
@XmlElement
@ScimAttribute(description="The value of an entitlement.")
String value;
@XmlElement
@ScimAttribute(description="A human readable name, primarily used for display purposes. READ-ONLY.")
String display;
@XmlElement
@ScimAttribute(description="A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g. the preferred mailing address or primary e-mail address. The primary attribute value 'true' MUST appear no more than once.")
Boolean primary = false;
}
| 4,203 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/annotation/ScimType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface ScimType {
} | 4,204 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/annotation/ScimExtensionType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface ScimExtensionType {
String id();
String name() default "";
boolean required() default false;
String description() default "";
} | 4,205 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/annotation/ScimResourceIdReference.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ScimResourceIdReference {
}
| 4,206 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/annotation/ScimAttribute.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.apache.directory.scim.spec.schema.Schema.Attribute.Mutability;
import org.apache.directory.scim.spec.schema.Schema.Attribute.Returned;
import org.apache.directory.scim.spec.schema.Schema.Attribute.Uniqueness;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface ScimAttribute {
//This is an ugly but necessary work around
//We need something to determine which canonical value
//parameter is desired and we can't use null so we had
//to create this little empty enum as a place holder
//for assignment checks.
enum NoOp {
}
String name() default "";
boolean required() default false;
//These two canonical attributes should be mutually exclusive, if both are
//present we will reject the registered repository
Class<? extends Enum<?>> canonicalValueEnum() default NoOp.class;
String [] canonicalValueList() default "";
boolean caseExact() default false;
Mutability mutability() default Mutability.READ_WRITE;
Returned returned() default Returned.DEFAULT;
Uniqueness uniqueness() default Uniqueness.NONE;
String [] referenceTypes() default "";
String description() default "";
}
| 4,207 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/annotation/ScimResourceType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface ScimResourceType {
String id();
String name() default "";
String description() default "";
String endpoint();
String schema();
} | 4,208 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/adapter/LocalDateTimeAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.adapter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_DATE_TIME;
@Override
public LocalDateTime unmarshal(String v) throws Exception {
if (v == null) {
return null;
}
return LocalDateTime.parse(v, FORMATTER);
}
@Override
public String marshal(LocalDateTime v) throws Exception {
if (v == null) {
return null;
}
return FORMATTER.format(v);
}
}
| 4,209 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/adapter/PatchOperationPathAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.adapter;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import org.apache.directory.scim.spec.patch.PatchOperationPath;
public class PatchOperationPathAdapter extends XmlAdapter<String, PatchOperationPath>{
@Override
public PatchOperationPath unmarshal(String v) throws Exception {
if (v == null) {
return null;
}
return new PatchOperationPath(v);
}
@Override
public String marshal(PatchOperationPath v) throws Exception {
if (v == null) {
return null;
}
return v.toString();
}
}
| 4,210 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/adapter/Iso8601DateTimeAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.adapter;
import java.text.SimpleDateFormat;
import java.util.Date;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public class Iso8601DateTimeAdapter extends XmlAdapter<String, Date> {
private static final String ISO_8601_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SS";
private SimpleDateFormat dateFormat = new SimpleDateFormat(ISO_8601_DATE_TIME_FORMAT);
@Override
public String marshal(Date date)
{
if (date == null)
{
return null;
}
return dateFormat.format(date);
}
@Override
public Date unmarshal(String date) throws Exception
{
if (date == null || date.isEmpty())
{
return null;
}
return dateFormat.parse(date);
}
}
| 4,211 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/phonenumber/PhoneNumberParseTreeListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.phonenumber;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.directory.scim.spec.phonenumber.PhoneNumberParser.GlobalNumberContext;
import org.apache.directory.scim.spec.phonenumber.PhoneNumberParser.LocalNumberContext;
import org.apache.directory.scim.spec.phonenumber.PhoneNumberParser.LocalNumberDigitsContext;
import org.apache.directory.scim.spec.phonenumber.PhoneNumberParser.ParameterContext;
import org.apache.directory.scim.spec.phonenumber.PhoneNumberParser.PhoneContextContext;
import org.apache.directory.scim.spec.phonenumber.PhoneNumberParser.PhoneNumberContext;
import org.apache.directory.scim.spec.resources.PhoneNumber;
import org.apache.directory.scim.spec.resources.PhoneNumber.GlobalPhoneNumberBuilder;
import org.apache.directory.scim.spec.resources.PhoneNumber.LocalPhoneNumberBuilder;
import org.apache.directory.scim.spec.resources.PhoneNumber.PhoneNumberBuilder;
public class PhoneNumberParseTreeListener extends PhoneNumberParserBaseListener {
private static final Logger LOGGER = LoggerFactory.getLogger(PhoneNumberParserBaseListener.class);
private PhoneNumberBuilder phoneNumberBuilder;
private int indent = -1;
@Override
public void enterPhoneNumber(PhoneNumberContext ctx) {
LOGGER.debug(indent("--- Enter PhoneNumber -->"));
}
@Override
public void exitPhoneNumber(PhoneNumberContext ctx) {
LOGGER.debug(indent("<-- Exit PhoneNumber ---"));
}
@Override
public void enterLocalNumber(LocalNumberContext ctx) {
LOGGER.debug(indent("--- Enter LocalNumber -->"));
phoneNumberBuilder = new LocalPhoneNumberBuilder();
}
@Override
public void exitLocalNumber(LocalNumberContext ctx) {
LOGGER.debug(indent("<-- Exit LocalNumber ---"));
((LocalPhoneNumberBuilder) phoneNumberBuilder).subscriberNumber(ctx.localDigits.getText());
if (ctx.Ext() != null && !StringUtils.isBlank(ctx.Ext().getText())) {
((LocalPhoneNumberBuilder) phoneNumberBuilder).extension(ctx.Ext().getText());
}
if (ctx.Isub() != null && !StringUtils.isBlank(ctx.Isub().getText())) {
((LocalPhoneNumberBuilder) phoneNumberBuilder).subAddress(ctx.Isub().getText());
}
}
@Override
public void enterLocalNumberDigits(LocalNumberDigitsContext ctx) {
LOGGER.debug(indent("--- Enter LocalNumberDigits -->"));
}
@Override
public void exitLocalNumberDigits(LocalNumberDigitsContext ctx) {
LOGGER.debug(indent("<-- Exit LocalNumberDigits ---"));
}
@Override
public void enterPhoneContext(PhoneContextContext ctx) {
LOGGER.debug(indent("--- Enter PhoneContext -->"));
}
@Override
public void exitPhoneContext(PhoneContextContext ctx) {
LOGGER.debug(indent("<-- Exit PhoneContext ---"));
if (!ctx.isEmpty()) {
if (ctx.dig != null) {
((LocalPhoneNumberBuilder) phoneNumberBuilder).isDomainPhoneContext(false);
phoneNumberBuilder.phoneContext("+"+ctx.dig.getText());
} else if (ctx.dn != null) {
((LocalPhoneNumberBuilder) phoneNumberBuilder).isDomainPhoneContext(true);
phoneNumberBuilder.phoneContext(ctx.dn.getText());
}
}
}
@Override
public void enterParameter(ParameterContext ctx) {
LOGGER.debug(indent("--- Enter Parameter -->"));
}
@Override
public void exitParameter(ParameterContext ctx) {
LOGGER.debug(indent("<-- Exit Parameter ---"));
if (!ctx.isEmpty()) {
phoneNumberBuilder.param(ctx.ParamName().getText(), ctx.ParamValue().getText());
}
}
@Override
public void enterGlobalNumber(GlobalNumberContext ctx) {
LOGGER.debug(indent("--- Enter GlobalNumber -->"));
phoneNumberBuilder = new GlobalPhoneNumberBuilder();
}
@Override
public void exitGlobalNumber(GlobalNumberContext ctx) {
LOGGER.debug(indent("<-- Exit GlobalNumber ---"));
((GlobalPhoneNumberBuilder) phoneNumberBuilder).globalNumber(ctx.globalDigits.getText() + ctx.GlobalNumberDigits().getText());
if (ctx.Ext() != null && !StringUtils.isBlank(ctx.Ext().getText())) {
phoneNumberBuilder.extension(ctx.Ext().getText());
}
if (ctx.Isub() != null && !StringUtils.isBlank(ctx.Isub().getText())) {
phoneNumberBuilder.subAddress(ctx.Isub().getText());
}
}
@Override
public void enterEveryRule(ParserRuleContext ctx) {
indent++;
}
@Override
public void exitEveryRule(ParserRuleContext ctx) {
indent--;
}
@Override
public void visitTerminal(TerminalNode node) {
String text = node.getText();
if (StringUtils.isNotEmpty(text.trim())) {
LOGGER.debug(indent(text));
}
}
@Override
public void visitErrorNode(ErrorNode node) {
LOGGER.error(indent(node.getText()));
}
private String indent(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indent; i++) {
sb.append(" ");
}
sb.append(s);
return sb.toString();
}
public PhoneNumber getPhoneNumber() throws PhoneNumberParseException {
return phoneNumberBuilder.build(false);
}
}
| 4,212 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/phonenumber/PhoneNumberParseException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
*
*/
package org.apache.directory.scim.spec.phonenumber;
/**
* @author heidielliott
*
*/
public class PhoneNumberParseException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public PhoneNumberParseException() {
}
/**
* @param message
*/
public PhoneNumberParseException(String message) {
super(message);
}
/**
* @param cause
*/
public PhoneNumberParseException(Throwable cause) {
super(cause);
}
/**
* @param message
* @param cause
*/
public PhoneNumberParseException(String message, Throwable cause) {
super(message, cause);
}
}
| 4,213 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/AttributeContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.schema;
import java.io.Serializable;
import java.util.List;
import org.apache.directory.scim.spec.schema.Schema.Attribute;
public interface AttributeContainer extends Serializable {
List<Attribute> getAttributes();
Attribute getAttribute(String attributeName);
}
| 4,214 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/Meta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.schema;
import java.io.Serializable;
import java.time.LocalDateTime;
import jakarta.validation.constraints.Size;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.directory.scim.spec.adapter.LocalDateTimeAdapter;
import lombok.Data;
import org.apache.directory.scim.spec.annotation.ScimAttribute;
/**
* Defines the structure of the meta attribute for all SCIM resources as defined
* by section 3.1 of the SCIM schema specification. See
* https://tools.ietf.org/html/draft-ietf-scim-core-schema-17#section-3.1 for more
* details.
*
* @author Steve Moyer <smoyer@psu.edu>
*/
@XmlType(name = "meta")
@XmlAccessorType(XmlAccessType.NONE)
@Data
public class Meta implements Serializable {
private static final long serialVersionUID = -9162917034280030708L;
@XmlElement
@Size(min = 1)
@ScimAttribute(description = "The name of the resource type of the resource.")
String resourceType;
@XmlElement
@XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
@ScimAttribute(description = "The DateTime that the resource was added to the service provider.")
LocalDateTime created;
@XmlElement
@XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
@ScimAttribute(description = "The most recent DateTime that the details of this resource were updated at the service provider.")
LocalDateTime lastModified;
@XmlElement
@ScimAttribute(description = "The URI of the resource being returned.")
String location;
@XmlElement
@ScimAttribute(description = "The version of the resource being returned. This value must be the same as the entity-tag (ETag) HTTP response header")
String version;
}
| 4,215 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/Mapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
*
*/
package org.apache.directory.scim.spec.schema;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
/**
* The Mapper provides methods to bi-directionally transform SCIM attribute
* values into Java types. The eight types supported by SCIM are defined in
* section 2.2 of the SCIM schema specification. The mapping to Java objects are
* as follows:
*
* <pre>
* String -> string -> String
* Boolean -> boolean -> Boolean
* Decimal -> decimal -> Double
* Integer - > integer -> Long
* DateTime -> dateTime -> Date
* Binary -> binary -> Byte[]
* Reference -> reference -> URN?
* Complex -> complex -> (Java Object as defined)
* </pre>
*
* @author Steve Moyer
*/
public class Mapper {
DateTimeFormatter iso8601DateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME;
public Mapper() {
}
public String convertDateTime(Instant instant) {
return iso8601DateTimeFormatter.format(instant);
}
/**
* Converts an ISO 8601 DateTime string into the equivalent Java Date object.
*
* @param isodate the ISO 8601 DateTime to be converted.
* @return the equivalent Java Instant object.
*/
public Instant convertDateTime(String isodate) {
TemporalAccessor temporal = iso8601DateTimeFormatter.parse(isodate);
return Instant.from(temporal);
}
}
| 4,216 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/ScimType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.schema;
public interface ScimType {
/**
* ScimTypes are generally implemented as Java enums but when we're generating
* hashcodes, we need access to the name of the enum element rather than the
* ordinal.
*
* @return a String containing the enum value's name
*/
String name();
}
| 4,217 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/Schemas.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.schema;
import jakarta.xml.bind.annotation.XmlEnumValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.directory.scim.spec.annotation.ScimAttribute;
import org.apache.directory.scim.spec.annotation.ScimExtensionType;
import org.apache.directory.scim.spec.annotation.ScimResourceIdReference;
import org.apache.directory.scim.spec.annotation.ScimResourceType;
import org.apache.directory.scim.spec.annotation.ScimType;
import org.apache.directory.scim.spec.exception.ScimResourceInvalidException;
import org.apache.directory.scim.spec.resources.BaseResource;
import org.apache.directory.scim.spec.resources.ScimExtension;
import org.apache.directory.scim.spec.resources.ScimResource;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.*;
@Slf4j
public final class Schemas {
private static final String STRING_TYPE_IDENTIFIER = "class java.lang.String";
private static final String CHARACTER_ARRAY_TYPE_IDENTIFIER = "class [C";
private static final String BIG_C_CHARACTER_ARRAY_TYPE_IDENTIFIER = "class [Ljava.lang.Character;";
private static final String INT_TYPE_IDENTIFIER = "int";
private static final String INTEGER_TYPE_IDENTIFIER = "class java.lang.Integer";
private static final String FLOAT_TYPE_IDENTIFIER = "float";
private static final String BIG_F_FLOAT_TYPE_IDENTIFIER = "class java.lang.Float";
private static final String DOUBLE_TYPE_IDENTIFIER = "double";
private static final String BIG_D_DOUBLE_TYPE_IDENTIFIER = "class java.lang.Double";
private static final String BOOLEAN_TYPE_IDENTIFIER = "boolean";
private static final String BIG_B_BOOLEAN_TYPE_IDENTIFIER = "class java.lang.Boolean";
private static final String LOCAL_TIME_TYPE_IDENTIFER = "class java.time.LocalTime";
private static final String LOCAL_DATE_TYPE_IDENTIFER = "class java.time.LocalDate";
private static final String LOCAL_DATE_TIME_TYPE_IDENTIFIER = "class java.time.LocalDateTime";
private static final String DATE_TYPE_IDENTIFIER = "class java.util.Date";
private static final String BYTE_ARRAY_TYPE_IDENTIFIER = "class [B";
private static final String RESOURCE_REFERENCE_TYPE_IDENTIFIER = "class org.apache.directory.scim.spec.schema.ResourceReference$ReferenceType";
private Schemas() {}
public static Schema schemaFor(Class<? extends ScimResource> clazz) throws ScimResourceInvalidException {
return generateSchema(clazz, getFieldsUpTo(clazz, BaseResource.class));
}
public static Schema schemaForExtension(Class<? extends ScimExtension> clazz) throws ScimResourceInvalidException {
return generateSchema(clazz, getFieldsUpTo(clazz, Object.class));
}
private static Schema generateSchema(Class<?> clazz, List<Field> fieldList) throws ScimResourceInvalidException {
Schema schema = new Schema();
ScimResourceType srt = clazz.getAnnotation(ScimResourceType.class);
ScimExtensionType set = clazz.getAnnotation(ScimExtensionType.class);
if (srt == null && set == null) {
// TODO - throw?
log.error("Neither a ScimResourceType or ScimExtensionType annotation found");
}
log.debug("calling set attributes with " + fieldList.size() + " fields");
String urn = set != null ? set.id() : srt.schema();
Set<String> invalidAttributes = new HashSet<>();
List<Schema.Attribute> createAttributes = createAttributes(urn, fieldList, invalidAttributes, clazz.getSimpleName());
schema.setAttributes(createAttributes);
if (!invalidAttributes.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append("Scim attributes cannot be primitive types unless they are required. The following values were found that are primitive and not required\n\n");
for (String s : invalidAttributes) {
sb.append(s);
sb.append("\n");
}
throw new ScimResourceInvalidException(sb.toString());
}
if (srt != null) {
schema.setId(srt.schema());
schema.setDescription(srt.description());
schema.setName(srt.name());
} else {
schema.setId(set.id());
schema.setDescription(set.description());
schema.setName(set.name());
}
return schema;
}
private static List<Schema.Attribute> createAttributes(String urn, List<Field> fieldList, Set<String> invalidAttributes, String nameBase) throws ScimResourceInvalidException {
List<Schema.Attribute> attributeList = new ArrayList<>();
for (Field f : fieldList) {
ScimAttribute sa = f.getAnnotation(ScimAttribute.class);
log.debug("++++++++++++++++++++ Processing field " + f.getName());
if (sa == null) {
log.debug("Attribute " + f.getName() + " did not have a ScimAttribute annotation");
continue;
}
String attributeName;
f.setAccessible(true);
if (sa.name() == null || sa.name().isEmpty()) {
attributeName = f.getName();
} else {
attributeName = sa.name();
}
if (f.getType().isPrimitive() && !sa.required()) {
invalidAttributes.add(nameBase + "." + attributeName);
continue;
}
//TODO - Fix this to look for the two types of canonical attributes
Schema.Attribute attribute = new Schema.Attribute();
attribute.setAccessor(Schema.AttributeAccessor.forField(f));
attribute.setName(attributeName);
attribute.setUrn(urn);
List<String> canonicalTypes = null;
Field [] enumFields = sa.canonicalValueEnum().getFields();
log.debug("Gathered fields of off the enum, there are " + enumFields.length + " " + sa.canonicalValueEnum().getName());
if (enumFields.length != 0) {
//This looks goofy, but there's always at least the default value, so it's not an empty list
if (sa.canonicalValueList().length != 1 && !sa.canonicalValueList()[0].isEmpty()) {
throw new ScimResourceInvalidException("You cannot set both the canonicalEnumValue and canonicalValueList attributes on the same ScimAttribute");
}
canonicalTypes = new ArrayList<>();
for (Field field : enumFields) {
XmlEnumValue[] annotation = field.getAnnotationsByType(XmlEnumValue.class);
if (annotation.length != 0) {
canonicalTypes.add(annotation[0].value());
} else {
canonicalTypes.add(field.getName());
}
}
} else {
canonicalTypes = Arrays.asList(sa.canonicalValueList());
}
// If we just have the default single empty string, set to null
if (canonicalTypes.isEmpty() || (canonicalTypes.size() == 1 && canonicalTypes.get(0).isEmpty())) {
attribute.setCanonicalValues(null);
} else {
attribute.setCanonicalValues(new HashSet<String>(canonicalTypes));
}
attribute.setCaseExact(sa.caseExact());
attribute.setDescription(sa.description());
String typeName = null;
if (Collection.class.isAssignableFrom(f.getType())) {
log.debug("We have a collection");
ParameterizedType stringListType = (ParameterizedType) f.getGenericType();
Class<?> attributeContainedClass = (Class<?>) stringListType.getActualTypeArguments()[0];
typeName = attributeContainedClass.getTypeName();
attribute.setMultiValued(true);
} else if (f.getType().isArray()) {
log.debug("We have an array");
Class<?> componentType = f.getType().getComponentType();
typeName = componentType.getTypeName();
attribute.setMultiValued(true);
} else {
typeName = f.getType().toString();
attribute.setMultiValued(false);
}
// attribute.setType(sa.type());
boolean attributeIsAString = false;
log.debug("Attempting to set the attribute type, raw value = " + typeName);
switch (typeName) {
case STRING_TYPE_IDENTIFIER:
case CHARACTER_ARRAY_TYPE_IDENTIFIER:
case BIG_C_CHARACTER_ARRAY_TYPE_IDENTIFIER:
log.debug("Setting type to String");
attribute.setType(Schema.Attribute.Type.STRING);
attributeIsAString = true;
break;
case INT_TYPE_IDENTIFIER:
case INTEGER_TYPE_IDENTIFIER:
log.debug("Setting type to integer");
attribute.setType(Schema.Attribute.Type.INTEGER);
break;
case FLOAT_TYPE_IDENTIFIER:
case BIG_F_FLOAT_TYPE_IDENTIFIER:
case DOUBLE_TYPE_IDENTIFIER:
case BIG_D_DOUBLE_TYPE_IDENTIFIER:
log.debug("Setting type to decimal");
attribute.setType(Schema.Attribute.Type.DECIMAL);
break;
case BOOLEAN_TYPE_IDENTIFIER:
case BIG_B_BOOLEAN_TYPE_IDENTIFIER:
log.debug("Setting type to boolean");
attribute.setType(Schema.Attribute.Type.BOOLEAN);
break;
case BYTE_ARRAY_TYPE_IDENTIFIER:
log.debug("Setting type to binary");
attribute.setType(Schema.Attribute.Type.BINARY);
break;
case DATE_TYPE_IDENTIFIER:
case LOCAL_DATE_TIME_TYPE_IDENTIFIER:
case LOCAL_TIME_TYPE_IDENTIFER:
case LOCAL_DATE_TYPE_IDENTIFER:
log.debug("Setting type to date time");
attribute.setType(Schema.Attribute.Type.DATE_TIME);
break;
case RESOURCE_REFERENCE_TYPE_IDENTIFIER:
log.debug("Setting type to reference");
attribute.setType(Schema.Attribute.Type.REFERENCE);
break;
default:
log.debug("Setting type to complex");
attribute.setType(Schema.Attribute.Type.COMPLEX);
}
if (f.getAnnotation(ScimResourceIdReference.class) != null) {
if (attributeIsAString) {
attribute.setScimResourceIdReference(true);
} else {
log.warn("Field annotated with @ScimResourceIdReference must be a string: {}", f);
}
}
attribute.setMutability(sa.mutability());
List<String> refType = Arrays.asList(sa.referenceTypes());
// If we just have the default single empty string, set to null
if (refType.isEmpty() || (refType.size() == 1 && refType.get(0).isEmpty())) {
attribute.setReferenceTypes(null);
} else {
attribute.setReferenceTypes(Arrays.asList(sa.referenceTypes()));
}
attribute.setRequired(sa.required());
attribute.setReturned(sa.returned());
attribute.setUniqueness(sa.uniqueness());
//if (sa.type().equals(Type.COMPLEX))
ScimType st = f.getType().getAnnotation(ScimType.class);
if (attribute.getType() == Schema.Attribute.Type.COMPLEX || st != null) {
Class<?> componentType;
if (!attribute.isMultiValued()) {
componentType = f.getType();
attribute.setSubAttributes(createAttributes(urn, Arrays.asList(f.getType().getDeclaredFields()), invalidAttributes, nameBase + "." + f.getName()), Schema.Attribute.AddAction.APPEND);
} else if (f.getType().isArray()) {
componentType = f.getType().getComponentType();
} else {
ParameterizedType stringListType = (ParameterizedType) f.getGenericType();
componentType = (Class<?>) stringListType.getActualTypeArguments()[0];
}
List<Field> fl = getFieldsUpTo(componentType, Object.class);
List<Schema.Attribute> la = createAttributes(urn, fl, invalidAttributes, nameBase + "." + f.getName());
attribute.setSubAttributes(la, Schema.Attribute.AddAction.APPEND);
}
attributeList.add(attribute);
}
attributeList.sort(Comparator.comparing(o -> o.name));
log.debug("Returning " + attributeList.size() + " attributes");
return attributeList;
}
static List<Field> getFieldsUpTo(Class<?> startClass, Class<?> exclusiveParent) {
List<Field> currentClassFields = new ArrayList<>();
Collections.addAll(currentClassFields, startClass.getDeclaredFields());
Class<?> parentClass = startClass.getSuperclass();
if (parentClass != null && (!(parentClass.equals(exclusiveParent)))) {
List<Field> parentClassFields = getFieldsUpTo(parentClass, exclusiveParent);
currentClassFields.addAll(parentClassFields);
}
return currentClassFields;
}
}
| 4,218 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/Schema.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import jakarta.xml.bind.annotation.*;
import lombok.*;
import org.apache.directory.scim.spec.exception.ScimResourceInvalidException;
import org.apache.directory.scim.spec.validator.Urn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.*;
/**
* Defines the structure of the SCIM schemas as defined by section 7 of the SCIM
* schema specification. See
* https://tools.ietf.org/html/draft-ietf-scim-core-schema-17#section-7 for more
* details.
*
* @author Steve Moyer <smoyer@psu.edu>
*/
@XmlRootElement(name = "schema")
@XmlAccessorType(XmlAccessType.NONE)
@Data
public class Schema implements AttributeContainer {
private static final Logger LOG = LoggerFactory.getLogger(Schema.class);
public static final String RESOURCE_NAME = "Schema";
public static final String SCHEMA_URI = "urn:ietf:params:scim:schemas:core:2.0:Schema";
private static final long serialVersionUID = 1869782412244161741L;
/**
* Defines the structure of attributes included in SCIM schemas as defined by
* section 7 of the SCIM schema specification. See
* https://tools.ietf.org/html/draft-ietf-scim-core-schema-17#section-7 for more
* details.
*
* @author Steve Moyer <smoyer@psu.edu>
*/
@XmlType(name = "attribute")
@XmlAccessorType(XmlAccessType.NONE)
@Data
public static class Attribute implements AttributeContainer {
private static final long serialVersionUID = 1683400114899587851L;
public enum Mutability {
@XmlEnumValue("immutable") IMMUTABLE,
@XmlEnumValue("readOnly") READ_ONLY,
@XmlEnumValue("readWrite") READ_WRITE,
@XmlEnumValue("writeOnly") WRITE_ONLY;
}
public enum Returned {
@XmlEnumValue("always") ALWAYS,
@XmlEnumValue("default") DEFAULT,
@XmlEnumValue("never") NEVER,
@XmlEnumValue("request") REQUEST;
}
@XmlEnum(String.class)
public enum Type {
@XmlEnumValue("binary") BINARY,
@XmlEnumValue("boolean") BOOLEAN,
@XmlEnumValue("complex") COMPLEX,
@XmlEnumValue("dateTime") DATE_TIME,
@XmlEnumValue("decimal") DECIMAL,
@XmlEnumValue("integer") INTEGER,
@XmlEnumValue("reference") REFERENCE,
@XmlEnumValue("string") STRING;
}
public enum Uniqueness {
@XmlEnumValue("global") GLOBAL,
@XmlEnumValue("none") NONE,
@XmlEnumValue("server") SERVER;
}
public enum AddAction {
REPLACE,
APPEND
}
String urn;
// The attribute name must match the ABNF pattern defined in section 2.1 of
// the SCIM Schema specification.
@XmlElement
@Pattern(regexp = "\\p{Alpha}(-|_|\\p{Alnum})*")
String name;
@XmlElement
Type type;
@XmlElement
List<Attribute> subAttributes;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
Map<String, Attribute> subAttributeNamesMap = new HashMap<>();
@XmlElement
boolean multiValued;
@XmlElement
String description;
@XmlElement
boolean required;
@XmlElement
Set<String> canonicalValues;
@XmlElement
boolean caseExact;
@XmlElement
Mutability mutability;
@XmlElement
Returned returned;
@XmlElement
Uniqueness uniqueness;
@XmlElement
List<String> referenceTypes;
transient AttributeAccessor accessor;
private boolean scimResourceIdReference;
@Override
public List<Attribute> getAttributes() {
return Collections.unmodifiableList(subAttributes);
}
public void setSubAttributes(List<Attribute> attributes, AddAction action) {
if (action.equals(AddAction.REPLACE)) {
subAttributeNamesMap.clear();
}
for (Attribute attribute : attributes) {
String name = attribute.getName();
if (name == null) {
LOG.warn("Attribute name was null, skipping name indexing");
continue;
}
subAttributeNamesMap.put(name.toLowerCase(Locale.ENGLISH), attribute);
}
if(action.equals(AddAction.REPLACE)) {
this.subAttributes = attributes;
} else {
if (subAttributes == null) {
subAttributes = new ArrayList<>();
}
this.subAttributes.addAll(attributes);
}
}
public Attribute getAttribute(String name) {
if (name == null) {
return null;
}
return subAttributeNamesMap.get(name.toLowerCase(Locale.ENGLISH));
}
}
@Urn
@NotNull
@Size(min = 1, max = 65535)
@XmlElement
String id;
@XmlElement
String name;
@XmlElement
String description;
@Size(min = 1, max = 65535)
@XmlElement
@XmlElementWrapper(name = "attributes")
List<Attribute> attributes;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
Map<String, Attribute> attributeNamesMap = new HashMap<>();
@XmlElement
Meta meta;
public List<Attribute> getAttributes() {
return Collections.unmodifiableList(attributes);
}
public void setAttributes(List<Attribute> attributes) {
attributeNamesMap.clear();
for (Attribute attribute : attributes) {
String name = attribute.getName();
if (name == null) {
LOG.warn("Attribute name was null, skipping name indexing");
continue;
}
attributeNamesMap.put(name.toLowerCase(Locale.ENGLISH), attribute);
}
this.attributes = attributes;
}
public Attribute getAttribute(String name) {
if (name == null) {
return null;
}
return attributeNamesMap.get(name.toLowerCase(Locale.ENGLISH));
}
public Attribute getAttributeFromPath(String path) {
if (path == null) {
return null;
}
String[] parts = path.split("\\.");
Attribute attribute = getAttribute(parts[0]);
for (int index = 1; index < parts.length; index++) {
attribute = attribute.getAttribute(parts[index]);
}
return attribute;
}
public interface AttributeAccessor {
<T> T get(Object resource);
void set(Object resource, Object value);
Class<?> getType();
static AttributeAccessor forField(Field field) {
return new FieldAttributeAccessor(field);
}
boolean isAccessible(Object resource);
}
@EqualsAndHashCode
private static class FieldAttributeAccessor implements AttributeAccessor {
private final Field field;
public FieldAttributeAccessor(Field field) {
this.field = field;
}
@Override
public <T> T get(Object resource) {
try {
field.setAccessible(true);
return (T) field.get(resource);
} catch (IllegalAccessException e) {
throw new ScimResourceInvalidException("Schema definition is invalid", e);
}
}
@Override
public void set(Object resource, Object value) {
try {
field.setAccessible(true);
field.set(resource, value);
} catch (IllegalAccessException e) {
throw new ScimResourceInvalidException("Schema definition is invalid", e);
}
}
@Override
public Class<?> getType() {
return field.getType();
}
@Override
public boolean isAccessible(Object resource)
{
try {
return field.canAccess(resource);
}
catch (IllegalArgumentException e) {
return false;
}
}
}
}
| 4,219 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/ResourceType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.schema;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import org.apache.directory.scim.spec.annotation.ScimResourceType;
import org.apache.directory.scim.spec.resources.ScimExtension;
import org.apache.directory.scim.spec.resources.ScimResourceWithOptionalId;
import org.apache.directory.scim.spec.validator.Urn;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* SCIM ResourceType
*
* @see <a href="https://tools.ietf.org/html/rfc7643#section-6">ResourceType Schema</a>
*
* @author Steve Moyer <smoyer@psu.edu>
*/
@Data
@EqualsAndHashCode(callSuper = true)
@XmlAccessorType(XmlAccessType.NONE)
public class ResourceType extends ScimResourceWithOptionalId {
public static final String RESOURCE_NAME = "ResourceType";
public static final String SCHEMA_URI = "urn:ietf:params:scim:schemas:core:2.0:ResourceType";
private static final long serialVersionUID = -696969911228870476L;
@Data
public static class SchemaExtensionConfiguration implements Serializable {
private static final long serialVersionUID = 7351651561572744255L;
@XmlElement(name = "schema")
@Urn
@Size(min = 1)
String schemaUrn;
@XmlElement
boolean required;
}
@XmlElement
@Size(min = 1)
String name;
@XmlElement
String description;
@XmlElement
@Size(min = 1)
String endpoint;
@XmlElement(name = "schema")
@Urn
@Size(min = 1)
String schemaUrn;
@XmlElement
List<SchemaExtensionConfiguration> schemaExtensions;
public ResourceType() {
super(SCHEMA_URI, RESOURCE_NAME);
}
public ResourceType(ScimResourceType annotation) {
super(SCHEMA_URI, RESOURCE_NAME);
this.name = annotation.name();
this.description = annotation.description();
this.schemaUrn = annotation.schema();
this.endpoint = annotation.endpoint();
}
@Override
public ResourceType setSchemas(Set<String> schemas) {
return (ResourceType) super.setSchemas(schemas);
}
@Override
public ResourceType setMeta(@NotNull Meta meta) {
return (ResourceType) super.setMeta(meta);
}
@Override
public ResourceType setExternalId(String externalId) {
return (ResourceType) super.setExternalId(externalId);
}
@Override
public ResourceType setExtensions(Map<String, ScimExtension> extensions) {
return (ResourceType) super.setExtensions(extensions);
}
@Override
public ResourceType setId(String id) {
return (ResourceType) super.setId(id);
}
@Override
public ResourceType addSchema(String urn) {
return (ResourceType) super.addSchema(urn);
}
@Override
public ResourceType addExtension(ScimExtension extension) {
return (ResourceType) super.addExtension(extension);
}
}
| 4,220 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/ScimSpecSchema.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.schema;
import java.util.Set;
import lombok.Data;
import lombok.Getter;
@Data
public class ScimSpecSchema {
@Getter
final static Set<String> schemaNames = Set.of(
"urn:ietf:params:scim:schemas:core:2.0:Group",
"urn:ietf:params:scim:schemas:core:2.0:ResourceType",
"urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig",
"urn:ietf:params:scim:schemas:core:2.0:User",
"urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
);
}
| 4,221 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/ServiceProviderConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.schema;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.validation.constraints.NotNull;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlEnumValue;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;
import org.apache.directory.scim.spec.resources.ScimExtension;
import org.apache.directory.scim.spec.resources.ScimResourceWithOptionalId;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class ServiceProviderConfiguration extends ScimResourceWithOptionalId {
public static final String RESOURCE_NAME = "ServiceProviderConfig";
public static final String SCHEMA_URI = "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig";
private static final long serialVersionUID = -6526116522184446474L;
@Data
@XmlType
@XmlAccessorType(XmlAccessType.NONE)
public static class AuthenticationSchema implements Serializable {
private static final long serialVersionUID = 1286852277186580002L;
public enum Type {
@XmlEnumValue("oauth") OAUTH(
"oauth",
"OAuth 1.0",
"Authentication scheme using the OAuth 1.0 Standard",
"https://www.rfc-editor.org/rfc/rfc5849.html"),
@XmlEnumValue("oauth2") OAUTH2(
"oauth2",
"OAuth 2.0",
"Authentication scheme using the OAuth 2.0 Standard",
"https://www.rfc-editor.org/rfc/rfc6749.html"),
@XmlEnumValue("oauthbearertoken") OAUTH_BEARER(
"oauthbearertoken",
"OAuth Bearer Token",
"Authentication scheme using the OAuth Bearer Token Standard",
"http://www.rfc-editor.org/info/rfc6750"),
@XmlEnumValue("httpbasic") HTTP_BASIC(
"httpbasic",
"HTTP Basic",
"Authentication scheme using the HTTP Basic Standard",
"http://www.rfc-editor.org/info/rfc2617"),
@XmlEnumValue("httpdigest") HTTP_DIGEST(
"httpdigest",
"HTTP Digest",
"Authentication scheme using the HTTP Digest Standard",
"https://www.rfc-editor.org/rfc/rfc7616.html");
private final String type;
private final String specUri;
private final String defaultName;
private final String defaultDescription;
Type(String type, String defaultName, String defaultDescription, String specUri) {
this.type = type;
this.defaultName = defaultName;
this.defaultDescription = defaultDescription;
this.specUri = specUri;
}
@Override
public String toString() {
return type;
}
}
@XmlElement
Type type;
@XmlElement
String name;
@XmlElement
String description;
@XmlElement
String specUri;
@XmlElement
String documentationUri;
public static AuthenticationSchema oauth() {
return fromType(Type.OAUTH);
}
public static AuthenticationSchema oauth2() {
return fromType(Type.OAUTH2);
}
public static AuthenticationSchema oauthBearer() {
return fromType(Type.OAUTH_BEARER);
}
public static AuthenticationSchema httpBasic() {
return fromType(Type.HTTP_BASIC);
}
public static AuthenticationSchema httpDigest() {
return fromType(Type.HTTP_DIGEST);
}
private static AuthenticationSchema fromType(Type type) {
return new ServiceProviderConfiguration.AuthenticationSchema()
.setType(type)
.setName(type.defaultName)
.setDescription(type.defaultDescription)
.setSpecUri(type.specUri);
}
}
@Data
public static class SupportedConfiguration implements Serializable {
private static final long serialVersionUID = 3646886915978382920L;
boolean supported;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class BulkConfiguration extends SupportedConfiguration {
private static final long serialVersionUID = 8312025367100671778L;
int maxOperations;
int maxPayloadSize;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class FilterConfiguration extends SupportedConfiguration {
private static final long serialVersionUID = 1887771731291732875L;
int maxResults;
}
@XmlElement
String documentationUrl;
@XmlElement
SupportedConfiguration patch;
@XmlElement
BulkConfiguration bulk;
@XmlElement
FilterConfiguration filter;
@XmlElement
SupportedConfiguration changePassword;
@XmlElement
SupportedConfiguration sort;
@XmlElement
SupportedConfiguration etag;
@XmlElement
List<AuthenticationSchema> authenticationSchemes;
public ServiceProviderConfiguration() {
super(SCHEMA_URI, RESOURCE_NAME);
}
@Override
public ServiceProviderConfiguration setSchemas(Set<String> schemas) {
return (ServiceProviderConfiguration) super.setSchemas(schemas);
}
@Override
public ServiceProviderConfiguration setExtensions(Map<String, ScimExtension> extensions) {
return (ServiceProviderConfiguration) super.setExtensions(extensions);
}
@Override
public ServiceProviderConfiguration setExternalId(String externalId) {
return (ServiceProviderConfiguration) super.setExternalId(externalId);
}
@Override
public ServiceProviderConfiguration setMeta(@NotNull Meta meta) {
return (ServiceProviderConfiguration) super.setMeta(meta);
}
@Override
public ServiceProviderConfiguration setId(String id) {
return (ServiceProviderConfiguration) super.setId(id);
}
@Override
public ServiceProviderConfiguration addSchema(String urn) {
return (ServiceProviderConfiguration) super.addSchema(urn);
}
@Override
public ServiceProviderConfiguration addExtension(ScimExtension extension) {
return (ServiceProviderConfiguration) super.addExtension(extension);
}
}
| 4,222 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/ResourceReference.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.schema;
import java.io.Serializable;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlEnum;
import jakarta.xml.bind.annotation.XmlEnumValue;
import jakarta.xml.bind.annotation.XmlType;
import org.apache.directory.scim.spec.annotation.ScimAttribute;
import org.apache.directory.scim.spec.annotation.ScimResourceIdReference;
import lombok.Data;
@Data
@XmlType(propOrder = {"value","ref","display","type"})
@XmlAccessorType(XmlAccessType.NONE)
public class ResourceReference implements Serializable {
private static final long serialVersionUID = 9126588075353486789L;
@XmlEnum
public enum ReferenceType {
@XmlEnumValue("direct") DIRECT,
@XmlEnumValue("indirect") INDIRECT,
@XmlEnumValue("User") USER,
@XmlEnumValue("Group") GROUP;
}
@ScimAttribute(description="Reference Element Identifier")
@ScimResourceIdReference
@XmlElement
String value;
@ScimAttribute(description="The URI of the corresponding resource ", referenceTypes={"User", "Group"})
@XmlElement(name = "$ref")
String ref;
@ScimAttribute(description="A human readable name, primarily used for display purposes. READ-ONLY.")
@XmlElement
String display;
@ScimAttribute(description="A label indicating the attribute's function; e.g., 'direct' or 'indirect'.", canonicalValueList={"direct", "indirect"})
@XmlElement
ReferenceType type;
}
| 4,223 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/patch/PatchOperationPath.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.patch;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.apache.directory.scim.spec.filter.FilterLexer;
import org.apache.directory.scim.spec.filter.FilterParser;
import org.apache.directory.scim.spec.filter.FilterParseException;
import org.apache.directory.scim.spec.filter.ValuePathExpression;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.Serializable;
@Data
@Slf4j
public class PatchOperationPath implements Serializable {
private static final long serialVersionUID = 449365558879593512L;
private ValuePathExpression valuePathExpression;
public PatchOperationPath() {
}
public PatchOperationPath(String patchPath) throws FilterParseException {
parsePatchPath(patchPath);
}
protected void parsePatchPath(String patchPath) throws FilterParseException {
FilterLexer l = new FilterLexer(new ANTLRInputStream(patchPath));
FilterParser p = new FilterParser(new CommonTokenStream(l));
p.setBuildParseTree(true);
p.addErrorListener(new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
}
});
try {
ParseTree tree = p.patchPath();
PatchPathListener patchPathListener = new PatchPathListener();
ParseTreeWalker.DEFAULT.walk(patchPathListener, tree);
this.valuePathExpression = patchPathListener.getValuePathExpression();
} catch (IllegalStateException e) {
throw new FilterParseException(e);
}
}
@Override
public String toString() {
return valuePathExpression.toFilter();
}
}
| 4,224 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/patch/PatchOperation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.patch;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlEnum;
import jakarta.xml.bind.annotation.XmlEnumValue;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.directory.scim.spec.adapter.PatchOperationPathAdapter;
import java.io.Serializable;
@Data
@EqualsAndHashCode
@XmlType(propOrder={"operation", "path", "value"})
@XmlAccessorType(XmlAccessType.NONE)
public class PatchOperation implements Serializable {
private static final long serialVersionUID = 7748584008639433236L;
@XmlEnum(String.class)
public enum Type {
@XmlEnumValue("add") ADD,
@XmlEnumValue("remove") REMOVE,
@XmlEnumValue("replace") REPLACE;
}
@XmlElement(name="op")
private Type operation;
@XmlElement
@XmlJavaTypeAdapter(PatchOperationPathAdapter.class)
private PatchOperationPath path;
@XmlElement
private Object value;
}
| 4,225 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/patch/PatchPathListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.patch;
import org.apache.directory.scim.spec.filter.FilterParser.PatchPathFullContext;
import org.apache.directory.scim.spec.filter.FilterParser.PatchPathPartialContext;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import org.apache.directory.scim.spec.filter.ExpressionBuildingListener;
import org.apache.directory.scim.spec.filter.FilterExpression;
import org.apache.directory.scim.spec.filter.ValuePathExpression;
import lombok.Getter;
@Getter
public class PatchPathListener extends ExpressionBuildingListener {
private ValuePathExpression valuePathExpression;
@Override
public void exitPatchPathFull(PatchPathFullContext ctx) {
super.exitPatchPathFull(ctx);
String attributePathText = ctx.attributePath.getText();
String subAttributeName = ctx.subAttributeName != null ? ctx.subAttributeName.getText() : null;
FilterExpression attributeExpression = expressionStack.pop();
AttributeReference attributePath = new AttributeReference(attributePathText);
String urn = attributePath.getUrn();
String parentAttributeName = attributePath.getAttributeName();
attributeExpression.setAttributePath(urn, parentAttributeName);
if (subAttributeName != null) {
attributePath.setAttributeName(parentAttributeName);
attributePath.setSubAttributeName(subAttributeName);
}
this.valuePathExpression = new ValuePathExpression(attributePath, attributeExpression);
}
@Override
public void exitPatchPathPartial(PatchPathPartialContext ctx) {
super.exitPatchPathPartial(ctx);
String attributePathText = ctx.attributePath.getText();
AttributeReference attributePath = new AttributeReference(attributePathText);
this.valuePathExpression = new ValuePathExpression(attributePath);
}
}
| 4,226 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/FilterExpressions.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import org.apache.directory.scim.spec.resources.ScimResource;
import org.apache.directory.scim.spec.schema.Schema;
import java.util.Map;
import java.util.function.Predicate;
public final class FilterExpressions {
private FilterExpressions() {}
/**
* Converts a filter into a Predicate used for in-memory evaluation. Production implementations should translate the Filter into
* the appropriate query language.
* <p>
*
* <b>This implementation should only be used for small collections or demo proposes.</b>
*/
public static Predicate<ScimResource> inMemory(Filter filter, Schema schema) {
if (filter == null) {
return x -> true;
}
FilterExpression expression = filter.getExpression();
if (expression == null) {
return x -> true;
}
return InMemoryScimFilterMatcher.toPredicate(expression, schema);
}
public static <R> Predicate<R> inMemory(FilterExpression expression, Schema schema) {
return InMemoryScimFilterMatcher.toPredicate(expression, schema);
}
public static <R> Predicate<R> inMemoryMap(FilterExpression expression, Schema schema) {
return new InMemoryMapScimFilterMatcher<R>().apply(expression, schema);
}
static class InMemoryMapScimFilterMatcher<R> extends InMemoryScimFilterMatcher<R> {
@Override
public <A> A get(Schema.Attribute attribute, A actual) {
Map<String, Object> map = (Map<String, Object>) actual;
return (A) map.get(attribute.getName());
}
}
}
| 4,227 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/GroupExpression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GroupExpression implements FilterExpression, ValueFilterExpression {
boolean not;
FilterExpression filterExpression;
@Override
public String toFilter() {
return (not ? "NOT" : "") + "(" + filterExpression.toFilter() + ")";
}
@Override
public void setAttributePath(String urn, String parentAttributeName) {
this.filterExpression.setAttributePath(urn, parentAttributeName);
}
@Override
public String toUnqualifiedFilter() {
return (not ? "NOT" : "") + "(" + filterExpression.toUnqualifiedFilter() + ")";
}
}
| 4,228 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/BaseFilterExpressionMapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import org.apache.directory.scim.spec.schema.AttributeContainer;
import org.apache.directory.scim.spec.schema.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.BiFunction;
/**
* The {@code BaseFilterExpressionMapper} is a utility class to aid in conversion of a {@link FilterExpression} into a
* class that can be used to look up or search for SCIM Resources. For example, convert a
* FilterExpression into a SQL query.
* @param <R>
*/
public abstract class BaseFilterExpressionMapper<R> implements BiFunction<FilterExpression, AttributeContainer, R> {
private static final Logger log = LoggerFactory.getLogger(BaseFilterExpressionMapper.class);
@Override
public R apply(FilterExpression expression, AttributeContainer attributeContainer) {
// attribute EQ "something"
if (expression instanceof AttributeComparisonExpression) {
return apply((AttributeComparisonExpression) expression, attributeContainer);
}
// (attribute EQ "something") AND (otherAttribute EQ "something else")
else if (expression instanceof LogicalExpression) {
return apply((LogicalExpression) expression, attributeContainer);
}
// NOT (attribute EQ "something")
else if (expression instanceof GroupExpression) {
return apply((GroupExpression) expression, attributeContainer);
}
// attribute PR
else if (expression instanceof AttributePresentExpression) {
return apply((AttributePresentExpression) expression, attributeContainer);
}
// addresses[type EQ "work"]
else if (expression instanceof ValuePathExpression) {
return apply((ValuePathExpression) expression, attributeContainer);
}
return unhandledExpression(expression, attributeContainer);
}
protected abstract R apply(AttributeComparisonExpression expression, AttributeContainer attributeContainer);
protected R apply(LogicalExpression expression, AttributeContainer attributeContainer) {
R left = apply(expression.getLeft(), attributeContainer);
R right = apply(expression.getRight(), attributeContainer);
LogicalOperator op = expression.getOperator();
return apply(op, left, right);
}
protected abstract R apply(LogicalOperator op, R left, R right);
protected R apply(GroupExpression expression, AttributeContainer attributeContainer) {
R result = apply(expression.getFilterExpression(), attributeContainer);
return expression.isNot()
? negate(result)
: result;
}
protected abstract R negate(R expression);
protected abstract R apply(AttributePresentExpression expression, AttributeContainer attributeContainer);
protected abstract R apply(ValuePathExpression expression, AttributeContainer attributeContainer);
protected R unhandledExpression(FilterExpression expression, AttributeContainer attributeContainer) {
throw new IllegalArgumentException("FilterExpression '" + expression + "' is not supported");
}
protected static Schema.Attribute attribute(AttributeContainer attributeContainer, AttributeReference attributeReference) {
String baseAttributeName = attributeReference.getAttributeName();
Schema.Attribute schemaAttribute = attributeContainer.getAttribute(baseAttributeName);
if (schemaAttribute == null) {
log.warn("Invalid filter: attribute '" + baseAttributeName + "' is NOT a valid SCIM attribute.");
return null;
}
String subAttribute = attributeReference.getSubAttributeName();
if (subAttribute != null) {
schemaAttribute = schemaAttribute.getAttribute(subAttribute);
if (schemaAttribute == null) {
log.warn("Invalid filter: attribute '" + attributeReference.getFullyQualifiedAttributeName() + "' is NOT a valid SCIM attribute.");
return null;
}
}
// filter out fields like passwords that should not be queried against
if (schemaAttribute.getReturned() == Schema.Attribute.Returned.NEVER) {
log.warn("Invalid filter: attribute '" + attributeReference.getAttributeName() + "' is not filterable.");
return null;
}
return schemaAttribute;
}
protected static boolean isStringExpression(Schema.Attribute attribute, Object compareValue) {
if (attribute.getType() != Schema.Attribute.Type.STRING) {
log.debug("Invalid query, non String value for expression : " + attribute.getType());
return false;
}
if (compareValue == null) {
log.debug("Invalid query, empty value for expression : " + attribute.getType());
return false;
}
return true;
}
}
| 4,229 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/ComplexLogicalFilterBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
abstract class ComplexLogicalFilterBuilder extends SimpleLogicalFilterBuilder {
@Override
public FilterBuilder or(FilterExpression fe1) {
if (filterExpression == null) {
throw new IllegalStateException("Cannot call or(Filter), call or(Filter, Filter) instead.");
}
LogicalExpression logicalExpression = new LogicalExpression();
logicalExpression.setLeft(groupIfNeeded(filterExpression));
logicalExpression.setRight(groupIfNeeded(fe1));
logicalExpression.setOperator(LogicalOperator.OR);
filterExpression = logicalExpression;
return this;
}
@Override
public FilterBuilder or(FilterExpression fe1, FilterExpression fe2) {
if (filterExpression == null) {
LogicalExpression logicalExpression = new LogicalExpression();
logicalExpression.setLeft(groupIfNeeded(fe1));
logicalExpression.setRight(groupIfNeeded(fe2));
logicalExpression.setOperator(LogicalOperator.OR);
filterExpression = logicalExpression;
} else {
this.or(fe1).or(fe2);
}
return this;
}
@Override
public FilterBuilder and(FilterExpression fe1, FilterExpression fe2) {
if (filterExpression == null) {
LogicalExpression logicalExpression = new LogicalExpression();
logicalExpression.setLeft(groupIfNeeded(fe1));
logicalExpression.setRight(groupIfNeeded(fe2));
logicalExpression.setOperator(LogicalOperator.AND);
filterExpression = logicalExpression;
} else {
this.and(fe1).and(fe2);
}
return this;
}
@Override
public FilterBuilder and(FilterExpression fe1) {
if (filterExpression == null) {
throw new IllegalStateException("Cannot call and(Filter), call and(Filter, Filter) instead.");
}
LogicalExpression logicalExpression = new LogicalExpression();
logicalExpression.setLeft(filterExpression);
logicalExpression.setRight(groupIfNeeded(fe1));
logicalExpression.setOperator(LogicalOperator.AND);
filterExpression = logicalExpression;
return this;
}
}
| 4,230 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/FilterResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import java.util.Collection;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@Data
@EqualsAndHashCode
@ToString
public class FilterResponse<T> {
private Collection<T> resources;
private PageRequest pageRequest;
private int totalResults;
public FilterResponse() {}
public FilterResponse(Collection<T> resources, PageRequest pageRequest, int totalResults) {
this.resources = resources;
this.pageRequest = pageRequest;
this.totalResults = totalResults;
}
}
| 4,231 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/FilterExpression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import java.io.Serializable;
import java.util.function.Function;
public interface FilterExpression extends Serializable {
String toFilter();
void setAttributePath(String urn, String parentAttributeName);
String toUnqualifiedFilter();
default <U> U map(Function<? super FilterExpression, U> mapper) {
return mapper.apply(this);
}
}
| 4,232 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/PageRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import lombok.Data;
@Data
public class PageRequest {
private Integer startIndex;
private Integer count;
}
| 4,233 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/FilterBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.function.UnaryOperator;
public interface FilterBuilder {
FilterBuilder and(FilterExpression fe1);
default FilterBuilder and(UnaryOperator<FilterBuilder> filter) {
return and(filter.apply(FilterBuilder.create()).build());
}
default FilterBuilder and(Filter filter) {
return and(filter.getExpression());
}
FilterBuilder and(FilterExpression left, FilterExpression right);
default FilterBuilder and(Filter left, Filter right) {
return and(left.getExpression(), right.getExpression());
}
default FilterBuilder and(UnaryOperator<FilterBuilder> left, UnaryOperator<FilterBuilder> right) {
return and(left.apply(FilterBuilder.create()).build(), right.apply(FilterBuilder.create()).build());
}
FilterBuilder or(FilterExpression fe1);
default FilterBuilder or(Filter filter) {
return or(filter.getExpression());
}
default FilterBuilder or(UnaryOperator<FilterBuilder> filter) {
return or(filter.apply(FilterBuilder.create()).build());
}
FilterBuilder or(FilterExpression left, FilterExpression right);
default FilterBuilder or(Filter left, Filter right) {
return or(left.getExpression(), right.getExpression());
}
default FilterBuilder or(UnaryOperator<FilterBuilder> left, UnaryOperator<FilterBuilder> right) {
return or(left.apply(FilterBuilder.create()).build(), right.apply(FilterBuilder.create()).build());
}
FilterBuilder equalTo(String key, String value);
FilterBuilder equalTo(String key, Boolean value);
FilterBuilder equalTo(String key, Date value);
FilterBuilder equalTo(String key, LocalDate value);
FilterBuilder equalTo(String key, LocalDateTime value);
<T extends Number> FilterBuilder equalTo(String key, T value);
FilterBuilder equalNull(String key);
FilterBuilder notEqual(String key, String value);
FilterBuilder notEqual(String key, Boolean value);
FilterBuilder notEqual(String key, Date value);
FilterBuilder notEqual(String key, LocalDate value);
FilterBuilder notEqual(String key, LocalDateTime value);
<T extends Number> FilterBuilder notEqual(String key, T value);
FilterBuilder notEqualNull(String key);
<T extends Number> FilterBuilder greaterThan(String key, T value);
FilterBuilder greaterThan(String key, Date value);
FilterBuilder greaterThan(String key, LocalDate value);
FilterBuilder greaterThan(String key, LocalDateTime value);
<T extends Number> FilterBuilder greaterThanOrEquals(String key, T value);
FilterBuilder greaterThanOrEquals(String key, Date value);
FilterBuilder greaterThanOrEquals(String key, LocalDate value);
FilterBuilder greaterThanOrEquals(String key, LocalDateTime value);
<T extends Number> FilterBuilder lessThan(String key, T value);
FilterBuilder lessThan(String key, Date value);
FilterBuilder lessThan(String key, LocalDate value);
FilterBuilder lessThan(String key, LocalDateTime value);
<T extends Number> FilterBuilder lessThanOrEquals(String key, T value);
FilterBuilder lessThanOrEquals(String key, Date value);
FilterBuilder lessThanOrEquals(String key, LocalDate value);
FilterBuilder lessThanOrEquals(String key, LocalDateTime value);
FilterBuilder endsWith(String key, String value);
FilterBuilder startsWith(String key, String value);
FilterBuilder contains(String key, String value);
FilterBuilder present(String key);
FilterBuilder not(FilterExpression fe);
default FilterBuilder not(Filter filter) {
return not(filter.getExpression());
}
default FilterBuilder not(UnaryOperator<FilterBuilder> filter) {
return not(filter.apply(FilterBuilder.create()).build());
}
FilterBuilder attributeHas(String attribute, FilterExpression filter);
default FilterBuilder attributeHas(String attribute, UnaryOperator<FilterBuilder> filter) {
return attributeHas(attribute, filter.apply(FilterBuilder.create()).build());
}
default FilterBuilder attributeHas(String attribute, Filter filter) {
return attributeHas(attribute, filter.getExpression());
}
FilterExpression filter();
Filter build();
static FilterBuilder create() {
return new FilterComparisonFilterBuilder();
}
}
| 4,234 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/LogicalExpression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LogicalExpression implements FilterExpression, ValueFilterExpression {
FilterExpression left;
LogicalOperator operator;
FilterExpression right;
@Override
public String toFilter() {
boolean leftParens = left instanceof LogicalExpression;
boolean rightParens = right instanceof LogicalExpression;
String leftString = (leftParens ? "(" : "") + left.toFilter() + (leftParens ? ")" : "");
String rightString = (rightParens ? "(" : "") + right.toFilter() + (rightParens ? ")" : "");
return leftString + " " + operator + " " + rightString;
}
@Override
public void setAttributePath(String urn, String parentAttributeName) {
this.left.setAttributePath(urn, parentAttributeName);
this.right.setAttributePath(urn, parentAttributeName);
}
@Override
public String toUnqualifiedFilter() {
boolean leftParens = this.left instanceof LogicalExpression;
boolean rightParens = this.right instanceof LogicalExpression;
String leftString = (leftParens ? "(" : "") + left.toUnqualifiedFilter() + (leftParens ? ")" : "");
String rightString = (rightParens ? "(" : "") + right.toUnqualifiedFilter() + (rightParens ? ")" : "");
return leftString + " " + operator + " " + rightString;
}
}
| 4,235 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/InMemoryScimFilterMatcher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import org.apache.directory.scim.spec.exception.ScimResourceInvalidException;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import org.apache.directory.scim.spec.schema.AttributeContainer;
import org.apache.directory.scim.spec.schema.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Comparator;
import java.util.function.Predicate;
class InMemoryScimFilterMatcher<R> extends BaseFilterExpressionMapper<Predicate<R>> {
private static final Logger log = LoggerFactory.getLogger(InMemoryScimFilterMatcher.class);
/**
* Converts a FilterExpression to a Predicate that can be used to later test a ScimResource (or child attribute).
* <p>
* The {@code attributeContainer} should be a top level Schema for the initial call, but recursive calls to this method
* will pass the AttributeContainer (a child-schema). For example, if given a
* {@link org.apache.directory.scim.spec.resources.ScimUser ScimUser} expression of {@code emails.value co "example.org"},
* The initial call to this method pass the ScimUser Schema object. When this method is called recursively, the
* {@link org.apache.directory.scim.spec.resources.Email Email}'s AttributeContainer will be used.
*
* @param expression the FilterExpression to build a predicate from.
* @param attributeContainer the Schema (or other sub attribute container) to build the predicate from.
* @return A Predicate that can be used to later test a ScimResource (or child attribute).
*/
static <R> Predicate<R> toPredicate(FilterExpression expression, AttributeContainer attributeContainer) {
return new InMemoryScimFilterMatcher<R>().apply(expression, attributeContainer);
}
@Override
protected Predicate<R> apply(AttributeComparisonExpression expression, AttributeContainer attributeContainer) {
return new AttributeComparisonPredicate<>(expression, attributeContainer);
}
@Override
protected Predicate<R> apply(LogicalOperator op, Predicate<R> left, Predicate<R> right) {
if (op == LogicalOperator.AND) {
return left.and(right);
} else {
return left.or(right);
}
}
@Override
protected Predicate<R> negate(Predicate<R> expression) {
return expression.negate();
}
@Override
protected Predicate<R> apply(AttributePresentExpression expression, AttributeContainer attributeContainer) {
return new AttributePresentPredicate<>(expression, attributeContainer);
}
@Override
protected Predicate<R> apply(ValuePathExpression expression, AttributeContainer attributeContainer) {
Predicate<Object> nestedPredicate = new InMemoryScimFilterMatcher<>().apply(expression.getAttributeExpression(), attribute(attributeContainer, expression.getAttributePath()));
return new ValuePathPredicate<>(expression, attributeContainer, nestedPredicate);
}
@Override
protected Predicate<R> unhandledExpression(FilterExpression expression, AttributeContainer attributeContainer) {
log.debug("Unsupported Filter expression of type: " + expression.getClass());
return scimResource -> false;
}
public <A> A get(Schema.Attribute attribute, A actual) {
return attribute.getAccessor().get(actual);
}
private abstract class AbstractAttributePredicate<T extends FilterExpression, R> implements Predicate<R> {
final T expression;
final AttributeContainer attributeContainer;
final AttributeReference attributeReference;
private AbstractAttributePredicate(T expression, AttributeContainer attributeContainer, AttributeReference attributeReference) {
this.expression = expression;
this.attributeContainer = attributeContainer;
this.attributeReference = attributeReference;
}
protected abstract boolean test(Schema.Attribute attribute, Object actualValue);
@Override
public boolean test(R actual) {
try {
// get and validate attribute
Schema.Attribute resolvedAttribute = attribute(attributeContainer, attributeReference);
if (resolvedAttribute != null) {
// now walk the attribute path again to get the accessor and value
Schema.Attribute schemaAttribute = attributeContainer.getAttribute(attributeReference.getAttributeName());
// check if the filter is nested such as: `emails[type eq "work"].value`
if (!(attributeReference.hasSubAttribute() && schemaAttribute.isMultiValued())) {
actual = get(schemaAttribute, actual);
}
// if the attribute has a sub-level, continue on
String subAttribute = attributeReference.getSubAttributeName();
if (subAttribute != null) {
schemaAttribute = schemaAttribute.getAttribute(subAttribute);
actual = get(schemaAttribute, actual);
}
return test(schemaAttribute, actual);
}
} catch (Exception e) {
// The SCIM spec states to ignore the query instead of rejecting it - rfc7644 - 3.4.2
log.debug("Invalid SCIM filter received", e);
}
return false;
}
}
private class ValuePathPredicate<R> extends AbstractAttributePredicate<ValuePathExpression, R> {
final private Predicate<Object> nestedPredicate;
ValuePathPredicate(ValuePathExpression expression, AttributeContainer attributeContainer, Predicate<Object> nestedPredicate) {
super(expression, attributeContainer, expression.getAttributePath());
this.nestedPredicate = nestedPredicate;
}
@Override
protected boolean test(Schema.Attribute attribute, Object actualValue) {
// actualValue must be a Collection
if (attribute.isMultiValued()) {
return ((Collection<?>) actualValue).stream().anyMatch(nestedPredicate);
}
return false;
}
}
private class AttributeComparisonPredicate<R> extends AbstractAttributePredicate<AttributeComparisonExpression, R> {
private AttributeComparisonPredicate(AttributeComparisonExpression expression, AttributeContainer attributeContainer) {
super(expression, attributeContainer, expression.getAttributePath());
}
@Override
protected boolean test(Schema.Attribute attribute, Object actualValue) {
if (actualValue == null) {
return false;
}
if (attribute.isMultiValued()) {
log.warn("Invalid expression, target is collection");
return false;
}
CompareOperator op = expression.getOperation();
Object compareValue = expression.getCompareValue();
if (op == CompareOperator.EQ) {
if (isStringExpression(attribute, compareValue) && !attribute.isCaseExact()) {
return actualValue.toString().equalsIgnoreCase(compareValue.toString());
}
return compareValue.equals(actualValue);
}
if (op == CompareOperator.NE) {
if (isStringExpression(attribute, compareValue) && !attribute.isCaseExact()) {
return !actualValue.toString().equalsIgnoreCase(compareValue.toString());
}
return !compareValue.equals(actualValue);
}
if (op == CompareOperator.SW) {
return isStringExpression(attribute, compareValue)
&& actualValue.toString().startsWith(compareValue.toString());
}
if (op == CompareOperator.EW) {
return isStringExpression(attribute, compareValue)
&& actualValue.toString().endsWith(compareValue.toString());
}
if (op == CompareOperator.CO) {
return isStringExpression(attribute, compareValue)
&& actualValue.toString().contains(compareValue.toString());
}
if (actualValue instanceof Comparable) {
Comparable actual = (Comparable) actualValue;
Comparable compare = (Comparable) compareValue;
return CompareOperatorPredicate.naturalOrder(op, compare).test(actual);
}
throw new ScimResourceInvalidException("Unsupported operation in filter: " + op.name());
}
}
private static class CompareOperatorPredicate<T> implements Predicate<T> {
private final CompareOperator op;
private final Comparator<T> comparator;
private final T comparedValue;
private CompareOperatorPredicate(CompareOperator op, T comparedValue, Comparator<T> comparator) {
this.op = op;
this.comparator = comparator;
this.comparedValue = comparedValue;
}
@Override
public boolean test(T actualValue) {
int compareResult = comparator.compare(actualValue, comparedValue);
if (op == CompareOperator.LT) {
return compareResult < 0;
} else if (op == CompareOperator.GT) {
return compareResult > 0;
} else if (op == CompareOperator.LE) {
return compareResult <= 0;
} else if (op == CompareOperator.GE) {
return compareResult >= 0;
}
return false;
}
static <T extends Comparable<T>> CompareOperatorPredicate<T> naturalOrder(CompareOperator op, T comparedValue) {
return new CompareOperatorPredicate<>(op, comparedValue, Comparator.naturalOrder());
}
}
private class AttributePresentPredicate<R> extends AbstractAttributePredicate<AttributePresentExpression, R> {
private AttributePresentPredicate(AttributePresentExpression expression, AttributeContainer attributeContainer) {
super(expression, attributeContainer, expression.getAttributePath());
}
@Override
protected boolean test(Schema.Attribute attribute, Object actualValue) {
if (attribute.isMultiValued()) {
log.debug("Invalid expression, target is collection");
return false;
}
return actualValue != null;
}
}
}
| 4,236 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/CompareOperator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
public enum CompareOperator {
EQ, // equal
NE, // not equal
CO, // contains
SW, // starts with
EW, // ends with
PR, // present (has value)
GT, // greater than
GE, // greater than or equal
LT, // greater than
LE; // greater than or equal
}
| 4,237 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/SimpleLogicalFilterBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
abstract class SimpleLogicalFilterBuilder implements FilterBuilder {
protected FilterExpression filterExpression;
static FilterExpression groupIfNeeded(FilterExpression filterExpression) {
return (filterExpression instanceof LogicalExpression)
? new GroupExpression(false, filterExpression)
: filterExpression;
}
protected void handleComparisonExpression(FilterExpression expression) {
if (expression == null) {
log.error("*** in handle comparison ---> expression == null");
}
if (filterExpression == null) {
filterExpression = expression;
} else {
if (!(filterExpression instanceof LogicalExpression)) {
throw new IllegalStateException("Invalid filter state");
}
LogicalExpression le = (LogicalExpression) filterExpression;
le.setRight(groupIfNeeded(expression));
}
}
@Override
public String toString() {
return filterExpression.toFilter();
}
@Override
public FilterExpression filter() {
return filterExpression;
}
@Override
public Filter build() {
return new Filter(filterExpression);
}
}
| 4,238 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/SortOrder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import jakarta.xml.bind.annotation.XmlEnumValue;
public enum SortOrder {
@XmlEnumValue("ascending")
ASCENDING,
@XmlEnumValue("descending")
DESCENDING
}
| 4,239 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/FilterParseException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
*
*/
package org.apache.directory.scim.spec.filter;
/**
* @author stevemoyer
*
*/
public class FilterParseException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public FilterParseException() {
}
/**
* @param message
*/
public FilterParseException(String message) {
super(message);
}
/**
* @param cause
*/
public FilterParseException(Throwable cause) {
super(cause);
}
/**
* @param message
* @param cause
*/
public FilterParseException(String message, Throwable cause) {
super(message, cause);
}
}
| 4,240 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/ValueFilterExpression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
public interface ValueFilterExpression {
String toFilter();
}
| 4,241 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/ExpressionBuildingListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Locale;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.directory.scim.spec.filter.FilterParser.AttributeCompareExpressionContext;
import org.apache.directory.scim.spec.filter.FilterParser.AttributeGroupExpressionContext;
import org.apache.directory.scim.spec.filter.FilterParser.AttributeLogicExpressionContext;
import org.apache.directory.scim.spec.filter.FilterParser.AttributePresentExpressionContext;
import org.apache.directory.scim.spec.filter.FilterParser.FilterAttributeCompareExpressionContext;
import org.apache.directory.scim.spec.filter.FilterParser.FilterAttributePresentExpressionContext;
import org.apache.directory.scim.spec.filter.FilterParser.FilterContext;
import org.apache.directory.scim.spec.filter.FilterParser.FilterGroupExpressionContext;
import org.apache.directory.scim.spec.filter.FilterParser.FilterLogicExpressionContext;
import org.apache.directory.scim.spec.filter.FilterParser.FilterValuePathExpressionContext;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
public class ExpressionBuildingListener extends FilterBaseListener {
private static final Logger LOG = LoggerFactory.getLogger(ExpressionBuildingListener.class);
protected Deque<FilterExpression> expressionStack = new ArrayDeque<>();
@Override
public void exitFilter(FilterContext ctx) {
if (expressionStack.size() != 1) {
throw new IllegalStateException("Wrong number (" + expressionStack.size() + ") of expressions on stack, should be 1");
}
}
@Override
public void exitFilterGroupExpression(FilterGroupExpressionContext ctx) {
boolean not = ctx.not != null;
FilterExpression pop = expressionStack.pop();
GroupExpression expression = new GroupExpression(not, pop);
expressionStack.push(expression);
}
@Override
public void exitFilterValuePathExpression(FilterValuePathExpressionContext ctx) {
String attributePath = ctx.attributePath.getText();
AttributeReference attributeReference = new AttributeReference(attributePath);
String urn = attributeReference.getUrn();
String parentAttributeName = attributeReference.getAttributeName();
if (expressionStack.size() == 0) {
throw new IllegalStateException("Invalid Expression " + ctx.attributePath);
}
FilterExpression attributeExpression = (FilterExpression) expressionStack.pop();
ValuePathExpression valuePathExpression = new ValuePathExpression(attributeReference, attributeExpression);
attributeExpression.setAttributePath(urn, parentAttributeName);
expressionStack.push(valuePathExpression);
}
@Override
public void exitFilterAttributePresentExpression(FilterAttributePresentExpressionContext ctx) {
AttributePresentExpression attributePresentExpression;
String attributePathText = ctx.attributePath.getText();
AttributeReference attributePath = new AttributeReference(attributePathText);
attributePresentExpression = new AttributePresentExpression(attributePath);
this.expressionStack.push(attributePresentExpression);
}
@Override
public void exitFilterAttributeCompareExpression(FilterAttributeCompareExpressionContext ctx) {
AttributeComparisonExpression attributeComparisonExpression;
String attributePathText = ctx.attributePath.getText();
AttributeReference attributePath = new AttributeReference(attributePathText);
CompareOperator compareOperator = CompareOperator.valueOf(ctx.op.getText().toUpperCase(Locale.ROOT));
String compareValueText = ctx.compareValue.getText();
Object compareValue = parseJsonType(compareValueText);
attributeComparisonExpression = new AttributeComparisonExpression(attributePath, compareOperator, compareValue);
this.expressionStack.push(attributeComparisonExpression);
}
@Override
public void exitFilterLogicExpression(FilterLogicExpressionContext ctx) {
String op = ctx.op.getText().toUpperCase(Locale.ROOT);
LogicalOperator logicalOperator = LogicalOperator.valueOf(op);
FilterExpression right = expressionStack.pop();
FilterExpression left = expressionStack.pop();
LogicalExpression expression = new LogicalExpression(left, logicalOperator, right);
expressionStack.push(expression);
}
@Override
public void exitAttributeLogicExpression(AttributeLogicExpressionContext ctx) {
String op = ctx.op.getText().toUpperCase(Locale.ROOT);
LogicalOperator logicalOperator = LogicalOperator.valueOf(op);
FilterExpression right = expressionStack.pop();
FilterExpression left = expressionStack.pop();
LogicalExpression attributeLogicExpression = new LogicalExpression(left, logicalOperator, right);
expressionStack.push(attributeLogicExpression);
}
@Override
public void exitAttributeGroupExpression(AttributeGroupExpressionContext ctx) {
boolean not = ctx.not != null;
FilterExpression attributeExpression = expressionStack.pop();
GroupExpression attributeGroupExpression = new GroupExpression(not, attributeExpression);
expressionStack.push(attributeGroupExpression);
}
@Override
public void exitAttributeCompareExpression(AttributeCompareExpressionContext ctx) {
String attributeName = ctx.attributeName.getText();
CompareOperator compareOperator = CompareOperator.valueOf(ctx.op.getText().toUpperCase(Locale.ROOT));
Object value = parseJsonType(ctx.compareValue.getText());
AttributeReference attributeReference = new AttributeReference(attributeName);
AttributeComparisonExpression expression = new AttributeComparisonExpression(attributeReference, compareOperator, value);
expressionStack.push(expression);
}
@Override
public void exitAttributePresentExpression(AttributePresentExpressionContext ctx) {
String attributeName = ctx.attributeName.getText();
AttributeReference attributeReference = new AttributeReference(attributeName);
AttributePresentExpression attributePresentExpression = new AttributePresentExpression(attributeReference);
expressionStack.push(attributePresentExpression);
}
public FilterExpression getFilterExpression() {
return expressionStack.peek();
}
private static Object parseJsonType(String jsonValue) {
if (jsonValue.startsWith("\"")) {
String doubleEscaped = jsonValue.substring(1, jsonValue.length() - 1)
// StringEscapeUtils follows the outdated JSON spec requiring "/" to be escaped, this could subtly break things
.replaceAll("\\\\/", "\\\\\\\\/")
// Just in case someone needs a single-quote with a backslash in front of it, this will be unnecessary with escapeJson()
.replaceAll("\\\\'", "\\\\\\\\'");
// TODO change this to escapeJson() when dependencies get upgraded
return StringEscapeUtils.unescapeEcmaScript(doubleEscaped);
} else if ("null".equals(jsonValue)) {
return null;
} else if ("true".equals(jsonValue)) {
return true;
} else if ("false".equals(jsonValue)) {
return false;
} else {
try {
if(jsonValue.contains(".")) {
return Double.parseDouble(jsonValue);
} else {
return Integer.parseInt(jsonValue);
}
} catch (NumberFormatException e) {
LOG.warn("Unable to parse a json number: " + jsonValue);
}
}
throw new IllegalStateException("Unable to parse JSON Value");
}
}
| 4,242 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/LogicalOperator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
public enum LogicalOperator {
AND,
OR;
}
| 4,243 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/SortRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import lombok.Data;
@Data
public class SortRequest {
private AttributeReference sortBy;
private SortOrder sortOrder;
}
| 4,244 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/ValuePathExpression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ValuePathExpression implements FilterExpression {
private static final long serialVersionUID = 2615135752981305135L;
// urn:parentAttribute[attributeExpression].subAttribute
AttributeReference attributePath;
FilterExpression attributeExpression;
public ValuePathExpression(AttributeReference attributePath) {
this.attributePath = attributePath;
}
public static ValuePathExpression fromFilterExpression(AttributeReference attrRef, FilterExpression attributeExpression) {
ValuePathExpression vpe = new ValuePathExpression(attrRef, attributeExpression);
return vpe;
}
public static ValuePathExpression fromFilterExpression(String attribute, FilterExpression expression) {
AttributeReference attributeReference = new AttributeReference(attribute);
return fromFilterExpression(attributeReference, expression);
}
@Override
public String toFilter() {
String filter;
if (this.attributeExpression != null) {
String subAttributeName = this.attributePath.getSubAttributeName();
String attributeExpressionFilter = this.attributeExpression.toUnqualifiedFilter();
if (subAttributeName != null) {
String base = this.attributePath.getAttributeBase();
filter = base + "[" + attributeExpressionFilter + "]." + subAttributeName;
} else {
String attribute = this.attributePath.getFullyQualifiedAttributeName();
filter = attribute + "[" + attributeExpressionFilter + "]";
}
} else {
filter = this.attributePath.getFullyQualifiedAttributeName();
}
return filter;
}
@Override
public void setAttributePath(String urn, String parentAttributeName) {
this.attributePath.setUrn(urn);
String subAttributeName = this.attributePath.getAttributeName();
this.attributePath.setAttributeName(parentAttributeName);
this.attributePath.setSubAttributeName(subAttributeName);
this.attributeExpression.setAttributePath(urn, parentAttributeName);
}
@Override
public String toUnqualifiedFilter() {
String filter;
if (this.attributeExpression != null) {
String attributeName = this.attributePath.getAttributeName();
String subAttributeName = this.attributePath.getSubAttributeName();
String attributeExpressionFilter = this.attributeExpression.toUnqualifiedFilter();
if (subAttributeName != null) {
filter = attributeName + "[" + attributeExpressionFilter + "]." + subAttributeName;
} else {
filter = attributeName + "[" + attributeExpressionFilter + "]";
}
} else {
String subAttributeName = this.attributePath.getSubAttributeName();
filter = this.attributePath.getAttributeName() + (subAttributeName != null ? "." + subAttributeName : "");
}
return filter;
}
}
| 4,245 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/FilterComparisonFilterBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
class FilterComparisonFilterBuilder extends ComplexLogicalFilterBuilder {
@Override
public FilterBuilder equalTo(String key, String value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.EQ, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder equalTo(String key, Boolean value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.EQ, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder equalTo(String key, Date value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.EQ, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder equalTo(String key, LocalDate value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.EQ, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder equalTo(String key, LocalDateTime value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.EQ, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public <T extends Number> FilterBuilder equalTo(String key, T value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.EQ, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder equalNull(String key) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.EQ, null);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder notEqual(String key, String value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.NE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder notEqual(String key, Boolean value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.NE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder notEqual(String key, Date value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.NE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder notEqual(String key, LocalDate value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.NE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder notEqual(String key, LocalDateTime value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.NE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public <T extends Number> FilterBuilder notEqual(String key, T value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.NE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder notEqualNull(String key) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.NE, null);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder endsWith(String key, String value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.EW, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder startsWith(String key, String value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.SW, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder contains(String key, String value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.CO, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder present(String key) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributePresentExpression(ar);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public <T extends Number> FilterBuilder greaterThan(String key, T value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.GT, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder greaterThan(String key, Date value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.GT, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder greaterThan(String key, LocalDate value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.GT, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder greaterThan(String key, LocalDateTime value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.GT, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public <T extends Number> FilterBuilder greaterThanOrEquals(String key, T value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.GE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder greaterThanOrEquals(String key, Date value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.GE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder greaterThanOrEquals(String key, LocalDate value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.GE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder greaterThanOrEquals(String key, LocalDateTime value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.GE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public <T extends Number> FilterBuilder lessThan(String key, T value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.LT, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder lessThan(String key, Date value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.LT, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder lessThan(String key, LocalDate value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.LT, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder lessThan(String key, LocalDateTime value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.LT, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public <T extends Number> FilterBuilder lessThanOrEquals(String key, T value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.LE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder lessThanOrEquals(String key, Date value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.LE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder lessThanOrEquals(String key, LocalDate value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.LE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder lessThanOrEquals(String key, LocalDateTime value) {
AttributeReference ar = new AttributeReference(key);
FilterExpression filterExpression = new AttributeComparisonExpression(ar, CompareOperator.LE, value);
handleComparisonExpression(filterExpression);
return this;
}
@Override
public FilterBuilder not(FilterExpression expression) {
GroupExpression groupExpression = new GroupExpression();
groupExpression.setNot(true);
groupExpression.setFilterExpression(expression);
handleComparisonExpression(groupExpression);
return this;
}
@Override
public FilterBuilder attributeHas(String attribute, FilterExpression expression) {
handleComparisonExpression(ValuePathExpression.fromFilterExpression(attribute, expression));
return this;
}
}
| 4,246 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/AttributePresentExpression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import lombok.Value;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
@Value
public class AttributePresentExpression implements FilterExpression, ValueFilterExpression {
private static final long serialVersionUID = -4491412651236977273L;
AttributeReference attributePath;
@Override
public String toFilter() {
return attributePath.getFullyQualifiedAttributeName() + " PR";
}
@Override
public String toUnqualifiedFilter() {
String subAttributeName = this.attributePath.getSubAttributeName();
String attributeName = subAttributeName != null ? subAttributeName : this.attributePath.getAttributeName();
return attributeName + " PR";
}
@Override
public void setAttributePath(String urn, String parentAttributeName) {
this.attributePath.setUrn(urn);
String subAttributeName = this.attributePath.getAttributeName();
this.attributePath.setAttributeName(parentAttributeName);
this.attributePath.setSubAttributeName(subAttributeName);
}
}
| 4,247 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/AttributeComparisonExpression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import lombok.Value;
@Value
public class AttributeComparisonExpression implements FilterExpression, ValueFilterExpression {
private static final long serialVersionUID = -2865840428089850575L;
AttributeReference attributePath;
CompareOperator operation;
Object compareValue;
private static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd";
private static final String ISO_8601_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SS";
private static final String QUOTE = "\"";
@Override
public String toFilter() {
String filter = this.attributePath.getFullyQualifiedAttributeName() + " " + this.operation + " " + this.createCompareValueString();
return filter;
}
@Override
public String toUnqualifiedFilter() {
String subAttributeName = this.attributePath.getSubAttributeName();
String unqualifiedAttributeName = subAttributeName != null ? subAttributeName : this.attributePath.getAttributeName();
return unqualifiedAttributeName + " " + operation + " " + this.createCompareValueString();
}
public static String toDateString(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat(ISO_8601_DATE_FORMAT);
return dateFormat.format(date);
}
public static String toDateTimeString(Date date) {
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(ISO_8601_DATE_TIME_FORMAT);
return dateTimeFormat.format(date);
}
public static String toDateString(LocalDate ld) {
return ld.format(DateTimeFormatter.ISO_DATE);
}
public static String toDateTimeString(LocalDateTime ldt) {
return ldt.format(DateTimeFormatter.ISO_DATE_TIME);
}
@Override
public void setAttributePath(String urn, String parentAttributeName) {
this.attributePath.setUrn(urn);
String subAttributeName = this.attributePath.getAttributeName();
this.attributePath.setAttributeName(parentAttributeName);
this.attributePath.setSubAttributeName(subAttributeName);
}
private String createCompareValueString() {
String compareValueString;
if (this.compareValue == null) {
compareValueString = "null";
} else if (this.compareValue instanceof String) {
// TODO change this to escapeJson() when dependencies get upgraded
String escaped = StringEscapeUtils.escapeEcmaScript((String) this.compareValue)
// StringEscapeUtils follows the outdated JSON spec requiring "/" to be escaped, this could subtly break things
.replaceAll("\\\\/", "/")
// We don't want single-quotes escaped, this will be unnecessary with escapeJson()
.replaceAll("\\\\'", "'");
compareValueString = QUOTE + escaped + QUOTE;
} else if (this.compareValue instanceof Date) {
compareValueString = QUOTE + toDateTimeString((Date) this.compareValue) + QUOTE;
} else if (this.compareValue instanceof LocalDate) {
compareValueString = QUOTE + toDateString((LocalDate) this.compareValue) + QUOTE;
} else if (this.compareValue instanceof LocalDateTime) {
compareValueString = QUOTE + toDateTimeString((LocalDateTime) this.compareValue) + QUOTE;
} else {
compareValueString = this.compareValue.toString();
}
return compareValueString;
}
}
| 4,248 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/Filter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.io.Serializable;
import java.net.URLDecoder;
import java.net.URLEncoder;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
*
* @author Steve Moyer <smoyer@psu.edu>
*/
@Data
@Slf4j
public class Filter implements Serializable {
private static final long serialVersionUID = -363511683199922297L;
@Setter(AccessLevel.NONE)
private FilterExpression expression;
private String filter;
protected Filter() {
}
public Filter(String filter) throws FilterParseException {
log.debug("Creating a filter - {}", filter);
setFilter(filter);
}
public Filter(FilterExpression filterExpression) {
log.debug("Creating a filter - {}", filterExpression);
expression = filterExpression;
this.filter = filterExpression.toFilter();
}
/**
* @param filter the filter to set
* @throws FilterParseException
*/
public void setFilter(String filter) throws FilterParseException {
this.filter = filter;
this.expression = parseFilter(filter);
}
protected FilterExpression parseFilter(String filter) throws FilterParseException {
FilterLexer l = new FilterLexer(CharStreams.fromString(filter));
FilterParser p = new FilterParser(new CommonTokenStream(l));
p.setBuildParseTree(true);
p.addErrorListener(new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
throw new IllegalStateException("failed to parse at line " + line + ":" + charPositionInLine + " due to " + msg, e);
}
});
try {
ParseTree tree = p.filter();
ExpressionBuildingListener expListener = new ExpressionBuildingListener();
ParseTreeWalker.DEFAULT.walk(expListener, tree);
return expListener.getFilterExpression();
} catch (IllegalStateException e) {
throw new FilterParseException("Failed to parse filter: " + filter, e);
}
}
@Override
public String toString() {
return expression.toFilter();
}
public String encode() {
String filterString = expression.toFilter();
return URLEncoder.encode(filterString, UTF_8).replace("+", "%20");
}
public static Filter decode(String encodedExpression) throws FilterParseException {
String decoded = URLDecoder.decode(encodedExpression, UTF_8).replace("%20", " ");
return new Filter(decoded);
}
public FilterExpression getExpression() {
return this.expression;
}
public String getFilter() {
return this.filter;
}
}
| 4,249 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/attribute/AttributeReference.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter.attribute;
import java.io.Serializable;
import org.apache.directory.scim.spec.validator.Urn;
import lombok.Data;
@Data
public class AttributeReference implements Serializable {
private static final long serialVersionUID = -3559538009692681470L;
@Urn
String urn;
String attributeName;
String subAttributeName;
public AttributeReference(String name) {
int endOfUrn = name.lastIndexOf(':');
String[] attributes = name.substring(endOfUrn + 1).split("\\.");
this.attributeName = attributes[0];
if (endOfUrn > -1) {
this.urn = name.substring(0, endOfUrn);
}
if (attributes.length > 1) {
this.subAttributeName = attributes[1];
}
}
public AttributeReference(String urn, String name) {
this.urn = urn;
if (name != null) {
String[] attributes = name.split("\\.");
this.attributeName = attributes[0];
if (attributes.length > 1) {
this.subAttributeName = attributes[1];
}
}
}
public AttributeReference(String urn, String attributeName, String subAttributeName) {
this.urn = urn;
this.attributeName = attributeName;
this.subAttributeName = subAttributeName;
}
public String getFullAttributeName() {
return this.attributeName + (this.subAttributeName != null ? "." + this.subAttributeName : "");
}
public String getFullyQualifiedAttributeName() {
String fullyQualifiedAttributeName;
StringBuilder sb = new StringBuilder();
if (this.urn != null) {
sb.append(this.urn);
if (this.attributeName != null) {
sb.append(":");
}
}
if (this.attributeName != null) {
sb.append(this.attributeName);
}
if (this.subAttributeName != null) {
sb.append(".");
sb.append(subAttributeName);
}
fullyQualifiedAttributeName = sb.toString();
return fullyQualifiedAttributeName;
}
public String getAttributeBase() {
String attributeBase;
StringBuilder sb = new StringBuilder();
if (this.urn != null) {
sb.append(this.urn);
if (this.subAttributeName != null) {
sb.append(":");
sb.append(this.attributeName);
}
} else if (this.subAttributeName != null) {
sb.append(this.attributeName);
}
attributeBase = sb.toString();
return attributeBase;
}
public boolean hasSubAttribute() {
return subAttributeName != null;
}
public boolean hasUrn() {
return urn != null;
}
public String toString() {
return (this.urn != null ? this.urn + ":" : "") + this.attributeName + (this.subAttributeName != null ? "." + this.subAttributeName : "");
}
}
| 4,250 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/attribute/ScimRequestContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter.attribute;
import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class ScimRequestContext {
private Set<AttributeReference> attributeReferences;
private Set<AttributeReference> excludedAttributeReferences;
}
| 4,251 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/filter/attribute/AttributeReferenceListWrapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.filter.attribute;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Data
@Slf4j
public class AttributeReferenceListWrapper {
@Setter(AccessLevel.NONE)
private Set<AttributeReference> attributeReferences = new HashSet<>();
public AttributeReferenceListWrapper(String attributeReferencesString) {
String[] split = StringUtils.split(attributeReferencesString, ",");
for (String af : split) {
log.debug("--> Attribute -> " + af);
AttributeReference attributeReference = new AttributeReference(af.trim());
attributeReferences.add(attributeReference);
}
}
public static AttributeReferenceListWrapper of(Set<AttributeReference> attributeReferences) {
AttributeReferenceListWrapper wrapper = new AttributeReferenceListWrapper("");
wrapper.attributeReferences = attributeReferences;
return wrapper;
}
public static Set<AttributeReference> getAttributeReferences(AttributeReferenceListWrapper attributeReferenceListWrapper) {
return Optional.ofNullable(attributeReferenceListWrapper)
.map(wrapper -> wrapper.getAttributeReferences())
.orElse(Collections.emptySet());
}
public String toString() {
if (attributeReferences == null || attributeReferences.isEmpty()) {
return "";
}
return attributeReferences.stream().map(AttributeReference::toString).collect(Collectors.joining(","));
}
}
| 4,252 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/exception/ConflictResourceException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.exception;
public class ConflictResourceException extends ResourceException {
public ConflictResourceException(String message) {
super(409, message);
}
public ConflictResourceException(String message, Throwable cause) {
super(409, message, cause);
}
}
| 4,253 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/exception/UnsupportedFilterException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.exception;
public class UnsupportedFilterException extends RuntimeException {
public UnsupportedFilterException(String message) {
super(message);
}
public UnsupportedFilterException(String message, Throwable cause) {
super(message, cause);
}
}
| 4,254 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/exception/ResourceException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.exception;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=true)
public class ResourceException extends Exception {
private final int status;
public ResourceException(int statusCode, String message) {
super(message);
this.status = statusCode;
}
public ResourceException(int statusCode, String message, Throwable cause) {
super(message, cause);
this.status = statusCode;
}
}
| 4,255 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/exception/InvalidExtensionException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.exception;
public class InvalidExtensionException extends RuntimeException {
private static final long serialVersionUID = -4113730866775103565L;
public InvalidExtensionException(String what) {
super(what);
}
}
| 4,256 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/exception/MutabilityException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.exception;
/**
* Thrown when a client attempts to update a ScimResource's attribute/sub-attribute that does not support being updated.
* e.g. The attribute is read-only, or is immutable but already has a value.
*/
public class MutabilityException extends RuntimeException {
public MutabilityException(String message) {
super(message);
}
public MutabilityException(String message, Throwable cause) {
super(message, cause);
}
}
| 4,257 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec | Create_ds/directory-scimple/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/exception/ScimResourceInvalidException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.spec.exception;
public class ScimResourceInvalidException extends RuntimeException {
private static final long serialVersionUID = -3378968149599082798L;
public ScimResourceInvalidException(String message) {
super(message);
}
public ScimResourceInvalidException(String message, Throwable cause) {
super(message, cause);
}
}
| 4,258 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/test/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/test/java/org/apache/directory/scim/protocol/adapter/StatusAdapterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.adapter;
import jakarta.ws.rs.core.Response.Status;
import org.apache.directory.scim.protocol.data.StatusAdapter;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StatusAdapterTest {
@Test
public void marshal() throws Exception {
String result = new StatusAdapter().marshal(Status.CONFLICT);
assertThat(result).isEqualTo("409");
}
@Test
public void marshalNull() throws Exception {
String result = new StatusAdapter().marshal(null);
assertThat(result).isNull();
}
@Test
public void unmarshal() throws Exception {
Status result = new StatusAdapter().unmarshal("400");
assertThat(result).isEqualTo(Status.BAD_REQUEST);
}
@Test
public void unmarshalNull() throws Exception {
Status result = new StatusAdapter().unmarshal(null);
assertThat(result).isNull();
}
}
| 4,259 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/test/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/test/java/org/apache/directory/scim/protocol/adapter/AttributeReferenceAdapterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.adapter;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.Map;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
public class AttributeReferenceAdapterTest {
private static Map<String, AttributeReference> TEST_DATA = Map.of(
"urn:test:testAttributeName.testSubAttributeName", new AttributeReference("urn:test", "testAttributeName", "testSubAttributeName"),
"urn:test:testAttributeName", new AttributeReference("urn:test", "testAttributeName"),
"testAttributeName", new AttributeReference("testAttributeName")
);
@ParameterizedTest
@MethodSource("marshalTestArgs")
public void marshal(AttributeReference input, String expected) throws Exception {
assertThat(new AttributeReferenceAdapter().marshal(input)).isEqualTo(expected);
}
@Test
public void marshalNull() throws Exception {
String result = new AttributeReferenceAdapter().marshal(null);
assertThat(result).isNull();
}
@ParameterizedTest
@MethodSource("unmarshalTestArgs")
public void unmarshal(String input, AttributeReference expected) throws Exception {
assertThat(new AttributeReferenceAdapter().unmarshal(input)).isEqualTo(expected);
}
@Test
public void unmarshalNull() throws Exception {
AttributeReference result = new AttributeReferenceAdapter().unmarshal(null);
assertThat(result).isNull();
}
private static Stream<Arguments> unmarshalTestArgs() {
return TEST_DATA.entrySet().stream()
.map(e -> Arguments.of(e.getKey(), e.getValue()));
}
private static Stream<Arguments> marshalTestArgs() {
return TEST_DATA.entrySet().stream()
.map(e -> Arguments.of(e.getValue(), e.getKey()));
}
}
| 4,260 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/ResourceTypesResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import org.apache.directory.scim.spec.schema.ResourceType;
/**
* From SCIM Protocol Specification, section 4, page 74
*
* @see <a href="https://tools.ietf.org/html/rfc7644#section-4">Scim spec
* section 4</a>
*
* /ResourceTypes An HTTP GET to this endpoint is used to discover the
* types of resources available on a SCIM service provider (e.g., Users and
* Groups). Each resource type defines the endpoints, the core schema URI
* that defines the resource, and any supported schema extensions. The
* attributes defining a resource type can be found in Section 6 of
* [RFC7643], and an example representation can be found in Section 8.6 of
* [RFC7643].
*
* In cases where a request is for a specific "ResourceType" or "Schema",
* the single JSON object is returned in the same way that a single User or
* Group is retrieved, as per Section 3.4.1. When returning multiple
* ResourceTypes or Schemas, the message form described by the
* "urn:ietf:params:scim:api:messages:2.0:ListResponse" (ListResponse) form
* SHALL be used as shown in Figure 3 and in Figure 9 below. Query
* parameters described in Section 3.4.2, such as filtering, sorting, and
* pagination, SHALL be ignored. If a "filter" is provided, the service
* provider SHOULD respond with HTTP status code 403 (Forbidden) to ensure
* that clients cannot incorrectly assume that any matching conditions
* specified in a filter are true.
*/
@Path("ResourceTypes")
@Tag(name="SCIM-Configuration")
public interface ResourceTypesResource {
@GET
@Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Operation(description = "Get All Resource Types")
@ApiResponse(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
array = @ArraySchema(schema = @Schema(implementation = ResourceType.class))))
default Response getAllResourceTypes(@QueryParam("filter") String filter) throws Exception {
if (filter != null) {
return Response.status(Status.FORBIDDEN).build();
}
return Response.status(Status.NOT_IMPLEMENTED).build();
}
@GET
@Path("{name}")
@Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Operation(description = "Get Resource Type by URN")
@ApiResponse(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE, schema = @Schema(implementation = ResourceType.class)))
default Response getResourceType(@PathParam("name") String name) throws Exception {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
}
| 4,261 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/SchemaResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.UriInfo;
/**
* From SCIM Protocol Specification, section 4, page 74
*
* @see <a href="https://tools.ietf.org/html/rfc7644#section-4">Scim spec section 4</a>
*
* /Schemas An HTTP GET to this endpoint is used to retrieve information
* about resource schemas supported by a SCIM service provider. An HTTP GET
* to the endpoint "/Schemas" SHALL return all supported schemas in
* ListResponse format (see Figure 3). Individual schema definitions can be
* returned by appending the schema URI to the /Schemas endpoint. For
* example:
*
* /Schemas/urn:ietf:params:scim:schemas:core:2.0:User
*
* The contents of each schema returned are described in Section 7 of
* [RFC7643]. An example representation of SCIM schemas may be found in
* Section 8.7 of [RFC7643].
*
* In cases where a request is for a specific "ResourceType" or "Schema",
* the single JSON object is returned in the same way that a single User or
* Group is retrieved, as per Section 3.4.1. When returning multiple
* ResourceTypes or Schemas, the message form described by the
* "urn:ietf:params:scim:api:messages:2.0:ListResponse" (ListResponse) form
* SHALL be used as shown in Figure 3 and in Figure 9 below. Query
* parameters described in Section 3.4.2, such as filtering, sorting, and
* pagination, SHALL be ignored. If a "filter" is provided, the service
* provider SHOULD respond with HTTP status code 403 (Forbidden) to ensure
* that clients cannot incorrectly assume that any matching conditions
* specified in a filter are true.
*/
@Path("Schemas")
@Tag(name="SCIM-Configuration")
public interface SchemaResource {
@GET
@Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Operation(description="Get All Schemas")
@ApiResponse(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
array = @ArraySchema(schema = @Schema(implementation = org.apache.directory.scim.spec.schema.Schema.class))))
default Response getAllSchemas(@QueryParam("filter") String filter, @Context UriInfo uriInfo) {
if (filter != null) {
return Response.status(Status.FORBIDDEN).build();
}
return Response.status(Status.NOT_IMPLEMENTED).build();
}
@GET
@Path("{uri}")
@Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Operation(description="Get Schemas by URN")
@ApiResponse(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
schema = @Schema(implementation = org.apache.directory.scim.spec.schema.Schema.class)))
default Response getSchema(@PathParam("uri") String uri, @Context UriInfo uriInfo) {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
}
| 4,262 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/BaseResourceTypeResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import org.apache.directory.scim.protocol.data.PatchRequest;
import org.apache.directory.scim.protocol.exception.ScimException;
import org.apache.directory.scim.protocol.adapter.FilterWrapper;
import org.apache.directory.scim.spec.exception.ResourceException;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import org.apache.directory.scim.spec.filter.attribute.AttributeReferenceListWrapper;
import org.apache.directory.scim.protocol.data.SearchRequest;
import org.apache.directory.scim.spec.filter.SortOrder;
import org.apache.directory.scim.spec.resources.ScimResource;
@Tag(name="SCIM")
@Hidden
public interface BaseResourceTypeResource<T> {
/**
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.4.1">Scim spec,
* retrieving known resources</a>
* @return
* @throws ScimException
* @throws UnableToRetrieveResourceException
*/
@GET
@Path("{id}")
@Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Operation(description="Find by id")
@ApiResponses(value={
@ApiResponse(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class))),
@ApiResponse(responseCode="400", description="Bad Request"),
@ApiResponse(responseCode="404", description="Not found"),
@ApiResponse(responseCode="500", description="Internal Server Error"),
@ApiResponse(responseCode="501", description="Not Implemented")
})
default Response getById(@Parameter(name="id", required=true) @PathParam("id") String id,
@Parameter(name="attributes") @QueryParam("attributes") AttributeReferenceListWrapper attributes,
@Parameter(name="excludedAttributes") @QueryParam("excludedAttributes") AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
/**
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.4.2">Scim spec,
* query resources</a>
* @return
*/
@GET
@Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Operation(description="Find by a combination of query parameters")
@ApiResponses(value={
@ApiResponse(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class))),
@ApiResponse(responseCode="400", description="Bad Request"),
@ApiResponse(responseCode="404", description="Not found"),
@ApiResponse(responseCode="500", description="Internal Server Error"),
@ApiResponse(responseCode="501", description="Not Implemented")
})
default Response query(@Parameter(name="attributes") @QueryParam("attributes") AttributeReferenceListWrapper attributes,
@Parameter(name="excludedAttributes") @QueryParam("excludedAttributes") AttributeReferenceListWrapper excludedAttributes,
@Parameter(name="filter") @QueryParam("filter") FilterWrapper filterWrapper,
@Parameter(name="sortBy") @QueryParam("sortBy") AttributeReference sortBy,
@Parameter(name="sortOrder") @QueryParam("sortOrder") SortOrder sortOrder,
@Parameter(name="startIndex") @QueryParam("startIndex") Integer startIndex,
@Parameter(name="count") @QueryParam("count") Integer count) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
/**
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.3">Scim spec,
* query resources</a>
* @return
*/
@POST
@Consumes({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Operation(description = "Create")
@ApiResponses(value = {
@ApiResponse(responseCode = "201",
content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class))),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "409", description = "Conflict"),
@ApiResponse(responseCode = "500", description = "Internal Server Error"),
@ApiResponse(responseCode = "501", description = "Not Implemented") })
default Response create(@RequestBody(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class)),
required = true) T resource,
@Parameter(name="attributes") @QueryParam("attributes") AttributeReferenceListWrapper attributes,
@Parameter(name="excludedAttributes") @QueryParam("excludedAttributes") AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
/**
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.4.3">Scim spec,
* query with post</a>
* @return
*/
@POST
@Path("/.search")
@Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Operation(description = "Search")
@ApiResponses(value = {
@ApiResponse(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class))),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "500", description = "Internal Server Error"),
@ApiResponse(responseCode = "501", description = "Not Implemented") })
default Response find(@RequestBody(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
schema = @Schema(implementation = SearchRequest.class)),
required = true) SearchRequest request) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
/**
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.5.1">Scim spec,
* update</a>
* @return
*/
@PUT
@Path("{id}")
@Consumes({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Operation(description = "Update")
@ApiResponses(value = {
@ApiResponse(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class))),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "500", description = "Internal Server Error"),
@ApiResponse(responseCode = "501", description = "Not Implemented") })
default Response update(@RequestBody(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class)),
required = true) T resource,
@PathParam("id") String id,
@Parameter(name="attributes") @QueryParam("attributes") AttributeReferenceListWrapper attributes,
@Parameter(name="excludedAttributes") @QueryParam("excludedAttributes") AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
@PATCH
@Path("{id}")
@Consumes({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON})
@Operation(description = "Patch a portion of the backing store")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "No Content"),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "404", description = "Not found"),
@ApiResponse(responseCode = "500", description = "Internal Server Error"),
@ApiResponse(responseCode = "501", description = "Not Implemented") })
default Response patch(@RequestBody(content = @Content(mediaType = Constants.SCIM_CONTENT_TYPE,
schema = @Schema(implementation = PatchRequest.class)),
required = true) PatchRequest patchRequest,
@PathParam("id") String id,
@Parameter(name="attributes") @QueryParam("attributes") AttributeReferenceListWrapper attributes,
@Parameter(name="excludedAttributes") @QueryParam("excludedAttributes") AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
@DELETE
@Path("{id}")
@Operation(description = "Delete from the backing store")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "No Content"),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "404", description = "Not found"),
@ApiResponse(responseCode = "500", description = "Internal Server Error"),
@ApiResponse(responseCode = "501", description = "Not Implemented") })
default Response delete(@Parameter(name = "id", required = true) @PathParam("id") String id) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
}
| 4,263 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/UserResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.Path;
import org.apache.directory.scim.spec.resources.ScimUser;
//@formatter:off
/**
* From SCIM Protocol Specification, section 3, page 9
*
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.2">Scim spec section 3.2</a>
*
* Resource Endpoint Operations Description
-------- ---------------- ---------------------- --------------------
User /Users GET (Section 3.4.1), Retrieve, add,
POST (Section 3.3), modify Users.
PUT (Section 3.5.1),
PATCH (Section 3.5.2),
DELETE (Section 3.6)
* @author chrisharm
*
*/
//@formatter:on
@Path("Users")
@Tag(name="SCIM")
public interface UserResource extends BaseResourceTypeResource<ScimUser> {
}
| 4,264 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/ErrorMessageType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
import jakarta.xml.bind.annotation.XmlEnum;
import jakarta.xml.bind.annotation.XmlEnumValue;
import lombok.AccessLevel;
import lombok.Getter;
@XmlEnum(String.class)
@Getter(AccessLevel.PUBLIC)
public enum ErrorMessageType {
//HTTP 400 Error messages (SCIM Protocol Specification, section 3.12, page 69)
//GET (Section specified attribute and filter 3.4.2), POST (Search - Section 3.4.3), PATCH (Path Filter - Section 3.5.2)
@XmlEnumValue("invalidFilter")
INVALID_FILTER("invalidFilter", "The specified filter syntax was invalid, or the specified attribute and filter comparison combination is not supported."),
//GET (Section 3.4.2), POST (Search - Section 3.4.3)
@XmlEnumValue("tooMany")
TOO_MANY("tooMany", "The specified filter yields many more results than the server is willing to calculate or process. For example, a filter such as \"(userName pr)\" by itself would return all entries with a \"userName\" and MAY not be acceptable to the service provider."),
//POST (Create - Section 3.3), PUT (Section 3.5.1), PATCH (Section 3.5.2)
@XmlEnumValue("uniqueness")
UNIQUENESS("uniqueness", "One or more of the attribute values are already in use or are reserved."),
//PUT (Section 3.5.1), PATCH (Section 3.5.2)
@XmlEnumValue("mutability")
MUTABILITY("mutability", "The attempted modification is not compatible with the target attribute's mutability or current state (e.g., modification of an \"immutable\" attribute with an existing value)."),
//POST (Search - Section 3.4.3, Create - Section 3.3, Bulk - Section 3.7), PUT (Section 3.5.1)
@XmlEnumValue("invalidSyntax")
INVALID_SYNTAX("invalidSyntax", "The request body message structure was invalid or did not conform to the request schema."),
//PATCH (Section 3.5.2)
@XmlEnumValue("invalidPath")
INVALID_PATH("invalidPath", "The \"path\" attribute was invalid or malformed (see invalid or malformed (see Figure 7)."),
//PATCH (Section 3.5.2)
@XmlEnumValue("noTarget")
NO_TARGET("noTarget", "The specified \"path\" did not yield an attribute or attribute value that could be operated on. This occurs when the specified \"path\" value contains a filter that yields no match."),
//GET (Section 3.4.2), POST (Create - Section 3.3, Query - Section 3.4.3), PUT (Section 3.5.1), PATCH (Section 3.5.2)
@XmlEnumValue("invalidValue")
INVALID_VALUE("invalidValue", "A required value was missing, or the value specified was not compatible with the operation or attribute type (see Section 2.2 of [RFC7643]), or resource schema (see Section 4 of [RFC7643])."),
//GET (Section 3.4.2), POST (ALL), PUT (Section 3.5.1), PATCH (Section 3.5.2), DELETE (Section 3.6)
@XmlEnumValue("invalidVers")
INVALID_VERS("invalidVers", "The specified SCIM protocol version is not supported (see Section 3.13)."),
//GET (Section 3.4.2)
@XmlEnumValue("sensitive")
SENSITIVE("sensitive", "The specified request cannot be completed, due to the passing of sensitive (e.g., personal) information in a request URI. For example, personal information SHALL NOT be transmitted over request URIs. See Section 7.5.2.");
private String scimType;
private String detail;
ErrorMessageType(String scimType, String detail) {
this.scimType = scimType;
this.detail = detail;
}
}
| 4,265 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/GroupResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.Path;
import org.apache.directory.scim.spec.resources.ScimGroup;
//@formatter:off
/**
* From SCIM Protocol Specification, section 3, page 9
*
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.2">Scim spec section 3.2</a>
*
* Resource Endpoint Operations Description
-------- ---------------- ---------------------- --------------------
Group /Groups GET (Section 3.4.1), Retrieve, add,
POST (Section 3.3), modify Groups.
PUT (Section 3.5.1),
PATCH (Section 3.5.2),
DELETE (Section 3.6)
* @author chrisharm
*
*/
//@formatter:on
@Path("Groups")
@Tag(name="SCIM")
public interface GroupResource extends BaseResourceTypeResource<ScimGroup> {
}
| 4,266 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/SelfResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import org.apache.directory.scim.protocol.data.PatchRequest;
import org.apache.directory.scim.protocol.exception.ScimException;
import org.apache.directory.scim.spec.exception.ResourceException;
import org.apache.directory.scim.spec.filter.attribute.AttributeReferenceListWrapper;
import org.apache.directory.scim.spec.resources.ScimResource;
import org.apache.directory.scim.spec.resources.ScimUser;
import static jakarta.ws.rs.core.MediaType.*;
import static org.apache.directory.scim.protocol.Constants.SCIM_CONTENT_TYPE;
//@formatter:off
/**
* From SCIM Protocol Specification, section 3, page 9
*
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.2">Scim spec section 3.2</a>
*
* Resource Endpoint Operations Description
-------- ---------------- ---------------------- --------------------
Self /Me GET, POST, PUT, PATCH, Alias for operations
DELETE (Section 3.11) against a resource
mapped to an
authenticated
subject (e.g.,
User).
* @author chrisharm
*
*/
//@formatter:on
@Path(SelfResource.PATH)
@Tag(name="SCIM")
public interface SelfResource {
String PATH = "Me";
/**
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.4.1">Scim spec,
* retrieving known resources</a>
* @return
* @throws UnableToRetrieveResourceException
*/
@GET
@Produces({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Operation(description="Get self record")
@ApiResponses(value={
@ApiResponse(content = @Content(mediaType = SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class))),
@ApiResponse(responseCode="400", description="Bad Request"),
@ApiResponse(responseCode="404", description="Not found"),
@ApiResponse(responseCode="500", description="Internal Server Error"),
@ApiResponse(responseCode="501", description="Not Implemented")
})
default Response getSelf(@Parameter(name="attributes") @QueryParam("attributes") AttributeReferenceListWrapper attributes,
@Parameter(name="excludedAttributes") @QueryParam("excludedAttributes") AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
/**
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.3">Scim spec,
* query resources</a>
* @return
*/
@POST
@Consumes({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Produces({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Operation(description = "Create self record")
@ApiResponses(value = {
@ApiResponse(responseCode = "201",
content = @Content(mediaType = SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class))),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "409", description = "Conflict"),
@ApiResponse(responseCode = "500", description = "Internal Server Error"),
@ApiResponse(responseCode = "501", description = "Not Implemented") })
default Response create(@RequestBody(content = @Content(mediaType = SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class)),
required = true) ScimUser resource,
@Parameter(name="attributes") @QueryParam("attributes") AttributeReferenceListWrapper attributes,
@Parameter(name="excludedAttributes") @QueryParam("excludedAttributes") AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
/**
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.5.1">Scim spec,
* update</a>
* @return
*/
@PUT
@Consumes({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Produces({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Operation(description = "Update self record")
@ApiResponses(value = {
@ApiResponse(content = @Content(mediaType = SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class))),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "500", description = "Internal Server Error"),
@ApiResponse(responseCode = "501", description = "Not Implemented") })
default Response update(@RequestBody(content = @Content(mediaType = SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimUser.class)),
required = true) ScimUser resource,
@Parameter(name="attributes") @QueryParam("attributes") AttributeReferenceListWrapper attributes,
@Parameter(name="excludedAttributes") @QueryParam("excludedAttributes") AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
@PATCH
@Consumes({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Produces({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Operation(description = "Patch a portion of the backing store")
@ApiResponses(value = {
@ApiResponse(responseCode = "204",
content = @Content(mediaType = SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ScimResource.class))),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "404", description = "Not found"),
@ApiResponse(responseCode = "500", description = "Internal Server Error"),
@ApiResponse(responseCode = "501", description = "Not Implemented") })
default Response patch(@RequestBody(content = @Content(mediaType = SCIM_CONTENT_TYPE,
schema = @Schema(implementation = PatchRequest.class)),
required = true) PatchRequest patchRequest,
@Parameter(name="attributes") @QueryParam("attributes") AttributeReferenceListWrapper attributes,
@Parameter(name="excludedAttributes") @QueryParam("excludedAttributes") AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
@DELETE
@Operation(description = "Delete self record")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "No Content"),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "404", description = "Not found"),
@ApiResponse(responseCode = "500", description = "Internal Server Error"),
@ApiResponse(responseCode = "501", description = "Not Implemented") })
default Response delete() throws ScimException, ResourceException {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
}
| 4,267 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/SearchResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import org.apache.directory.scim.protocol.data.SearchRequest;
import org.apache.directory.scim.spec.resources.ScimResource;
import static jakarta.ws.rs.core.MediaType.*;
import static org.apache.directory.scim.protocol.Constants.SCIM_CONTENT_TYPE;
//@formatter:off
/**
* From SCIM Protocol Specification, section 3, page 9
*
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.2">Scim spec section 3.2</a>
*
* Resource Endpoint Operations Description
-------- ---------------- ---------------------- --------------------
Search [prefix]/.search POST (Section 3.4.3) Search from system
root or within a
resource endpoint
for one or more
resource types using
POST.
* @author chrisharm
*
*/
//@formatter:on
@Path(".search")
@Tag(name="SCIM")
public interface SearchResource {
/**
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.4.3">Scim spec, query with post</a>
* @return
*/
@POST
@Produces({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Operation(description="Search")
@ApiResponses(value={
@ApiResponse(content = @Content(mediaType = SCIM_CONTENT_TYPE, array = @ArraySchema(schema = @Schema(implementation = ScimResource.class)))),
@ApiResponse(responseCode="400", description="Bad Request"),
@ApiResponse(responseCode="500", description="Internal Server Error"),
@ApiResponse(responseCode="501", description="Not Implemented")
})
default Response find(@RequestBody(content = @Content(mediaType = SCIM_CONTENT_TYPE,
schema = @Schema(implementation = SearchRequest.class)),
required = true) SearchRequest request){
return Response.status(Status.NOT_IMPLEMENTED).build();
}
}
| 4,268 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/BulkResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.UriInfo;
import org.apache.directory.scim.protocol.data.BulkRequest;
import org.apache.directory.scim.protocol.data.BulkResponse;
import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.apache.directory.scim.protocol.Constants.SCIM_CONTENT_TYPE;
//@formatter:off
/**
* From SCIM Protocol Specification, section 3, page 9
*
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.2">Scim spec section 3.2</a>
*
* Resource Endpoint Operations Description
-------- ---------------- ---------------------- --------------------
Bulk /Bulk POST (Section 3.7) Bulk updates to one
or more resources.
* @author chrisharm
*
*/
//@formatter:on
@Path("Bulk")
@Tag(name="SCIM")
public interface BulkResource {
/**
* @see <a href="https://tools.ietf.org/html/rfc7644#section-3.7">Bulk Operations</a>
* @return
*/
@POST
@Produces({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Consumes({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Operation(description="Bulk Operations")
@ApiResponses(value={
@ApiResponse(content = @Content(mediaType = SCIM_CONTENT_TYPE, schema = @Schema(implementation = BulkResponse.class))),
@ApiResponse(responseCode="400", description="Bad Request"),
@ApiResponse(responseCode="500", description="Internal Server Error"),
@ApiResponse(responseCode="501", description="Not Implemented")
})
default Response doBulk(@RequestBody(content = @Content(mediaType = SCIM_CONTENT_TYPE,
schema = @Schema(implementation = BulkRequest.class)),
required = true) BulkRequest bulkRequest,
@Context UriInfo uriInfo) {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
}
| 4,269 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/ServiceProviderConfigResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.UriInfo;
import org.apache.directory.scim.spec.schema.ServiceProviderConfiguration;
import static jakarta.ws.rs.core.MediaType.*;
import static org.apache.directory.scim.protocol.Constants.SCIM_CONTENT_TYPE;
//@formatter:off
/**
* From SCIM Protocol Specification, section 4, page 73
*
* @see <a href="https://tools.ietf.org/html/rfc7644#section-4">Scim spec section 4</a>
*
* /ServiceProviderConfig
* An HTTP GET to this endpoint will return a JSON structure that
* describes the SCIM specification features available on a service
* provider. This endpoint SHALL return responses with a JSON object
* using a "schemas" attribute of
* "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig".
* The attributes returned in the JSON object are defined in
* Section 5 of [RFC7643]. An example representation of SCIM service
* provider configuration may be found in Section 8.5 of [RFC7643].
*
* @author chrisharm
*
*/
//@formatter:on
@Path("ServiceProviderConfig")
@Tag(name="SCIM-Configuration")
public interface ServiceProviderConfigResource {
@GET
@Produces({SCIM_CONTENT_TYPE, APPLICATION_JSON})
@Operation(description="Get Service Provider Configuration")
@ApiResponse(content = @Content(mediaType = SCIM_CONTENT_TYPE,
schema = @Schema(implementation = ServiceProviderConfiguration.class)))
default Response getServiceProviderConfiguration(@Context UriInfo context) {
return Response.status(Status.NOT_IMPLEMENTED).build();
}
}
| 4,270 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/Constants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol;
public final class Constants {
private Constants() {
}
public static final String SCIM_CONTENT_TYPE = "application/scim+json";
public static final String PATCH = "PATCH";
}
| 4,271 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/adapter/FilterWrapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.adapter;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import org.apache.directory.scim.protocol.ErrorMessageType;
import org.apache.directory.scim.protocol.data.ErrorResponse;
import org.apache.directory.scim.spec.filter.FilterParseException;
import org.apache.directory.scim.spec.filter.Filter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
public class FilterWrapper {
public Filter filter;
public FilterWrapper(String string) {
try {
filter = new Filter(string);
} catch (FilterParseException e) {
log.error("Invalid Filter: {}", string);
ErrorResponse er = new ErrorResponse(Status.BAD_REQUEST, ErrorMessageType.INVALID_FILTER.getDetail());
er.setScimType(ErrorMessageType.INVALID_FILTER);
Response response = er.toResponse();
throw new WebApplicationException(e, response);
}
}
public FilterWrapper(Filter filter) {
this.filter = filter;
}
}
| 4,272 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/adapter/AttributeReferenceAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.adapter;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
public class AttributeReferenceAdapter extends XmlAdapter<String, AttributeReference> {
@Override
public AttributeReference unmarshal(String string) throws Exception {
if (string == null) {
return null;
}
return new AttributeReference(string);
}
@Override
public String marshal(AttributeReference attributeReference) throws Exception {
if (attributeReference == null) {
return null;
}
return attributeReference.getFullyQualifiedAttributeName();
}
}
| 4,273 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/adapter/FilterAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.adapter;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import org.apache.directory.scim.spec.filter.Filter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FilterAdapter extends XmlAdapter<String, Filter> {
@Override
public Filter unmarshal(String string) throws Exception {
if (string == null) {
return null;
}
return new Filter(string);
}
@Override
public String marshal(Filter filter) throws Exception {
if (filter == null) {
return null;
}
return filter.getExpression().toFilter();
}
}
| 4,274 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/data/PatchRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.data;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.directory.scim.spec.patch.PatchOperation;
import org.apache.directory.scim.spec.resources.BaseResource;
@Data
@EqualsAndHashCode(callSuper = true)
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class PatchRequest extends BaseResource<PatchRequest> {
public static final String SCHEMA_URI = "urn:ietf:params:scim:api:messages:2.0:PatchOp";
public PatchRequest() {
super(SCHEMA_URI);
}
@XmlElement(name = "Operations")
List<PatchOperation> patchOperationList;
public PatchRequest add(PatchOperation operation) {
if (patchOperationList == null){
patchOperationList = new ArrayList<>();
}
patchOperationList.add(operation);
return this;
}
}
| 4,275 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/data/BulkOperation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.data;
import jakarta.ws.rs.core.Response.Status;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlEnumValue;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.directory.scim.spec.resources.BaseResource;
import org.apache.directory.scim.spec.resources.ScimResource;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
@Data
@XmlType(propOrder = {"method","path","bulkId","data"})
@XmlAccessorType(XmlAccessType.NONE)
public class BulkOperation implements Serializable {
private static final long serialVersionUID = 6528874816710788132L;
public enum Method {
@XmlEnumValue("POST") POST,
@XmlEnumValue("PUT") PUT,
@XmlEnumValue("PATCH") PATCH,
@XmlEnumValue("DELETE") DELETE;
}
@Data
@AllArgsConstructor
@XmlAccessorType(XmlAccessType.NONE)
public static class StatusWrapper implements Serializable {
private static final long serialVersionUID = 1544738718748608248L;
public static StatusWrapper wrap(Status code) {
return new StatusWrapper(code);
}
@XmlElement
@XmlJavaTypeAdapter(StatusAdapter.class)
Status code;
}
@XmlElement
Method method;
@XmlElement
String bulkId;
@XmlElement
String version;
@XmlElement
String path;
@XmlElement
ScimResource data;
@XmlElement
String location;
@XmlElement
BaseResource response;
@XmlElement
StatusWrapper status;
}
| 4,276 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/data/ListResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.data;
import java.util.List;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.directory.scim.spec.resources.BaseResource;
@Data
@EqualsAndHashCode(callSuper = true)
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class ListResponse<T> extends BaseResource<ListResponse<T>> {
private static final long serialVersionUID = -2381780997440673136L;
public static final String SCHEMA_URI = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
@XmlElement
int totalResults;
@XmlElement
Integer startIndex;
@XmlElement
Integer itemsPerPage;
@XmlElement(name = "Resources")
List<T> resources;
public ListResponse() {
super(SCHEMA_URI);
}
}
| 4,277 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/data/BulkResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.data;
import java.util.List;
import jakarta.ws.rs.core.Response.Status;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.directory.scim.spec.resources.BaseResource;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@XmlType
@XmlAccessorType(XmlAccessType.NONE)
public class BulkResponse extends BaseResource<BulkResponse> {
public static final String SCHEMA_URI = "urn:ietf:params:scim:api:messages:2.0:BulkResponse";
@XmlElement(name = "Operations")
List<BulkOperation> operations;
@XmlElement(name="status")
@XmlJavaTypeAdapter(StatusAdapter.class)
Status status;
@XmlElement(name="response")
ErrorResponse errorResponse;
public BulkResponse() {
super(SCHEMA_URI);
}
}
| 4,278 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/data/ErrorResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.data;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.directory.scim.protocol.ErrorMessageType;
import org.apache.directory.scim.spec.resources.BaseResource;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class ErrorResponse extends BaseResource<ErrorResponse> {
private static final long serialVersionUID = 9045421198080348116L;
public static final String SCHEMA_URI = "urn:ietf:params:scim:api:messages:2.0:Error";
@XmlElement(nillable = true)
private String detail;
@XmlElement
@XmlJavaTypeAdapter(StatusAdapter.class)
private Status status;
@XmlElement
private ErrorMessageType scimType;
protected ErrorResponse() {
super(SCHEMA_URI);
}
public ErrorResponse(int statusCode, String detail) {
this(Status.fromStatusCode(statusCode), detail);
}
public ErrorResponse(Status status, String detail) {
this();
this.status = status;
this.detail = detail;
}
public Response toResponse() {
return toResponse(this);
}
public static Response toResponse(ErrorResponse error) {
return Response.status(error.status).entity(error).build();
}
}
| 4,279 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/data/StatusAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.data;
import jakarta.ws.rs.core.Response.Status;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public class StatusAdapter extends XmlAdapter<String, Status> {
@Override
public Status unmarshal(String v) throws Exception {
if (v == null) {
return null;
}
for (Status status : Status.values()) {
if (status.getStatusCode() == Integer.parseInt(v)) {
return status;
}
}
throw new EnumConstantNotPresentException(Status.class, v);
}
@Override
public String marshal(Status v) throws Exception {
if (v == null) {
return null;
}
return Integer.toString(v.getStatusCode());
}
}
| 4,280 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/data/BulkRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.data;
import java.util.List;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import org.apache.directory.scim.spec.resources.BaseResource;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@XmlType
@XmlAccessorType(XmlAccessType.NONE)
public class BulkRequest extends BaseResource<BulkRequest> {
public static final String SCHEMA_URI = "urn:ietf:params:scim:api:messages:2.0:BulkRequest";
private static final long serialVersionUID = -296570866318702047L;
@XmlElement
Integer failOnErrors;
@XmlElement(name = "Operations")
List<BulkOperation> operations;
public BulkRequest() {
super(SCHEMA_URI);
}
}
| 4,281 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/data/SearchRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.data;
import java.util.Set;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.directory.scim.protocol.adapter.AttributeReferenceAdapter;
import org.apache.directory.scim.protocol.adapter.FilterAdapter;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import org.apache.directory.scim.spec.filter.Filter;
import org.apache.directory.scim.spec.filter.PageRequest;
import org.apache.directory.scim.spec.filter.SortOrder;
import org.apache.directory.scim.spec.filter.SortRequest;
import org.apache.directory.scim.spec.resources.BaseResource;
/**
* See Section 3.4.3 Querying Resources Using HTTP POST
* (https://tools.ietf.org/html/rfc7644#section-3.4.3)
*
* @author crh5255
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
@XmlType
@XmlAccessorType(XmlAccessType.NONE)
public class SearchRequest extends BaseResource<SearchRequest> {
private static final long serialVersionUID = 8217513543318598565L;
public static final String SCHEMA_URI = "urn:ietf:params:scim:api:messages:2.0:SearchRequest";
@XmlElement
@XmlJavaTypeAdapter(AttributeReferenceAdapter.class)
Set<AttributeReference> attributes;
@XmlElement
@XmlJavaTypeAdapter(AttributeReferenceAdapter.class)
Set<AttributeReference> excludedAttributes;
@XmlElement
@XmlJavaTypeAdapter(FilterAdapter.class)
Filter filter;
@XmlElement
@XmlJavaTypeAdapter(AttributeReferenceAdapter.class)
AttributeReference sortBy;
@XmlElement
SortOrder sortOrder;
@XmlElement
Integer startIndex;
@XmlElement
Integer count;
public SearchRequest() {
super(SCHEMA_URI);
}
public PageRequest getPageRequest() {
PageRequest pageRequest = new PageRequest();
pageRequest.setStartIndex(startIndex);
pageRequest.setCount(count);
return pageRequest;
}
public SortRequest getSortRequest() {
SortRequest sortRequest = new SortRequest();
sortRequest.setSortBy(sortBy);
sortRequest.setSortOrder(sortOrder);
return sortRequest;
}
}
| 4,282 |
0 | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol | Create_ds/directory-scimple/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/protocol/exception/ScimException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.protocol.exception;
import jakarta.ws.rs.core.Response.Status;
import org.apache.directory.scim.protocol.data.ErrorResponse;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=true)
public class ScimException extends Exception {
private static final long serialVersionUID = 3643485564325176463L;
private final ErrorResponse error;
private final Status status;
public ScimException(Status status, String message, Throwable cause) {
super(message, cause);
this.error = new ErrorResponse(status, message);
this.status = status;
}
public ScimException(Status status, String message) {
this(new ErrorResponse(status, message), status);
}
public ScimException(ErrorResponse error, Status status) {
this.error = error;
this.status = status;
}
}
| 4,283 |
0 | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance/junit/EmbeddedServerExtension.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.compliance.junit;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.net.ServerSocket;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.ServiceLoader;
public class EmbeddedServerExtension implements BeforeAllCallback, BeforeEachCallback, AfterAllCallback {
private static final Logger logger = LoggerFactory.getLogger(EmbeddedServerExtension.class);
private ScimTestServer server;
private URI uri;
@Override
public void beforeAll(ExtensionContext context) throws Exception {
ServiceLoader<ScimTestServer> serviceLoader = ServiceLoader.load(ScimTestServer.class);
if (serviceLoader.findFirst().isPresent()) {
server = serviceLoader.findFirst().get();
uri = server.start(randomPort());
} else {
logger.info("Could not find implementation of ScimTestServer via ServiceLoader, assuming server is started using different technique");
}
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
if (uri != null) {
final List<Object> testInstances = context.getRequiredTestInstances().getAllInstances();
testInstances.forEach(test -> {
Field[] fields = FieldUtils.getFieldsWithAnnotation(test.getClass(), ScimServerUri.class);
Arrays.stream(fields).forEach(field -> {
try {
field.setAccessible(true);
FieldUtils.writeField(field, test, uri);
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to assign value to field annotated with '@ScimServerUri'", e);
}
});
}
);
}
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
if (server != null) {
server.shutdown();
}
}
private static int randomPort() {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
} catch (IOException e) {
throw new RuntimeException("Failed to find a free server port", e);
}
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ScimServerUri {
}
public interface ScimTestServer {
URI start(int port) throws Exception;
void shutdown() throws Exception;
}
}
| 4,284 |
0 | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance/tests/ResourceTypesIT.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.compliance.tests;
import org.apache.directory.scim.compliance.junit.EmbeddedServerExtension;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.Matchers.*;
@ExtendWith(EmbeddedServerExtension.class)
public class ResourceTypesIT extends ScimpleITSupport {
@Test
@DisplayName("ResourceTypes endpoint")
public void resourceTypes() {
get("/ResourceTypes")
.statusCode(200)
.body(
"Resources", not(empty()),
"schemas", hasItem(SCHEMA_LIST_RESPONSE),
"itemsPerPage", isNumber(),
"startIndex", isNumber(),
"totalResults", isNumber(),
"Resources[0].name", not(emptyString()),
"Resources[0].endpoint", not(emptyString()),
"Resources[0].schema", not(emptyString())
);
}
@Test
@DisplayName("Check if ResourceTypes is read-only")
public void endpointIsReadOnly() {
post("/ResourceTypes", "")
.statusCode(405);
}
}
| 4,285 |
0 | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance/tests/UsersIT.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.compliance.tests;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.directory.scim.compliance.junit.EmbeddedServerExtension;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.Map;
import static org.hamcrest.Matchers.*;
@ExtendWith(EmbeddedServerExtension.class)
public class UsersIT extends ScimpleITSupport {
private final String givenName = randomName("Given-");
private final String familyName = randomName("Family-");
private final String displayName = givenName + " " + familyName;
private final String email = givenName + "." + familyName + "@example.com";
@Test
@DisplayName("Test Users endpoint")
public void userEndpoint() {
get("/Users", Map.of("count", "1","startIndex", "1"))
.statusCode(200)
.body(
"Resources", not(empty()),
"schemas", hasItem(SCHEMA_LIST_RESPONSE),
"itemsPerPage", isNumber(),
"startIndex", isNumber(),
"totalResults", isNumber(),
"Resources[0].id", not(emptyString()),
"Resources[0].name.familyName", not(emptyString()),
"Resources[0].userName", not(emptyString()),
"Resources[0].active", isBoolean(),
"Resources[0].name.familyName", not(emptyString()),
"Resources[0].emails[0].value", not(emptyString())
);
}
@Test
@DisplayName("Test invalid User by username")
public void invalidUserNameFilter() {
String invalidUserName = RandomStringUtils.randomAlphanumeric(10);
get("/Users", Map.of("filter", "userName eq \"" + invalidUserName + "\""))
.statusCode(200)
.body(
"schemas", hasItem(SCHEMA_LIST_RESPONSE),
"totalResults", is(0)
);
}
@Test
@DisplayName("Test invalid User by ID")
public void invalidUserId() {
String invalidId = RandomStringUtils.randomAlphanumeric(10);
get("/Users/" + invalidId)
.statusCode(404)
.body(
"schemas", hasItem(SCHEMA_ERROR_RESPONSE),
"detail", not(emptyString())
);
}
@Test
@DisplayName("Create user with realistic values")
@Order(10)
public void createUser() {
String body = "{" +
"\"schemas\":[\"urn:ietf:params:scim:schemas:core:2.0:User\"]," +
"\"userName\":\"" + email + "\"," +
"\"name\":{" +
"\"givenName\":\"" + givenName + "\"," +
"\"familyName\":\"" + familyName + "\"}," +
"\"emails\":[{" +
"\"primary\":true," +
"\"value\":\"" + email + "\"," +
"\"type\":\"work\"}]," +
"\"displayName\":\"" + displayName + "\"," +
"\"active\":true" +
"}";
String id = post("/Users", body)
.statusCode(201)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:User"),
"active", is(true),
"id", not(emptyString()),
"name.givenName", is(givenName),
"name.familyName", is(familyName),
"userName", equalToIgnoringCase(email)
)
.extract().jsonPath().get("id");
// retrieve the user by id
get("/Users/" + id)
.statusCode(200)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:User"),
"active", is(true),
"id", not(emptyString()),
"name.givenName", is(givenName),
"name.familyName", is(familyName),
"userName", equalToIgnoringCase(email)
);
// posting same content again should return a conflict (409)
post("/Users", body)
.statusCode(409)
.body(
"schemas", hasItem(SCHEMA_ERROR_RESPONSE),
"detail", not(emptyString())
);
}
@Test
@DisplayName("Update User")
public void updateUser() {
String body = "{" +
"\"schemas\":[\"urn:ietf:params:scim:schemas:core:2.0:User\"]," +
"\"userName\":\"updateUser@example.com\"," +
"\"name\":{" +
"\"givenName\":\"Given-updateUser\"," +
"\"familyName\":\"Family-updateUser\"}," +
"\"emails\":[{" +
"\"primary\":true," +
"\"value\":\"updateUser@example.com\"," +
"\"type\":\"work\"}]," +
"\"displayName\":\"Given-updateUser Family-updateUser\"," +
"\"active\":true" +
"}";
String id = post("/Users", body)
.statusCode(201)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:User"),
"active", is(true),
"id", not(emptyString())
)
.extract().jsonPath().get("id");
String updatedBody = body.replaceFirst("}$",
",\"phoneNumbers\": [{\"value\": \"555-555-5555\",\"type\": \"work\"}]}");
put("/Users/" + id, updatedBody)
.statusCode(200)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:User"),
"active", is(true),
"id", not(emptyString()),
"name.givenName", is("Given-updateUser"),
"name.familyName", is("Family-updateUser"),
"userName", equalToIgnoringCase("updateUser@example.com"),
"phoneNumbers[0].value", is("555-555-5555"),
"phoneNumbers[0].type", is("work")
);
}
@Test
@DisplayName("Username Case Sensitivity Check")
public void userNameByFilter() {
String userName = get("/Users", Map.of("count", "1","startIndex", "1"))
.extract().jsonPath().get("Resources[0].userName");
get("/Users", Map.of("filter", "userName eq \"" + userName + "\""))
.statusCode(200)
.contentType("application/scim+json")
.body(
"schemas", contains(SCHEMA_LIST_RESPONSE),
"totalResults", is(1)
);
get("/Users", Map.of("filter", "userName eq \"" + userName.toUpperCase() + "\""))
.statusCode(200)
.body(
"schemas", contains(SCHEMA_LIST_RESPONSE),
"totalResults", is(1)
);
}
@Test
@DisplayName("Deactivate user with PATCH")
public void deactivateWithPatch() {
String body = "{" +
"\"schemas\":[\"urn:ietf:params:scim:schemas:core:2.0:User\"]," +
"\"userName\":\"deactivateWithPatch@example.com\"," +
"\"name\":{" +
"\"givenName\":\"Given-deactivateWithPatch\"," +
"\"familyName\":\"Family-deactivateWithPatch\"}," +
"\"emails\":[{" +
"\"primary\":true," +
"\"value\":\"deactivateWithPatch@example.com\"," +
"\"type\":\"work\"}]," +
"\"displayName\":\"Given-deactivateWithPatch Family-deactivateWithPatch\"," +
"\"active\":true" +
"}";
String id = post("/Users", body)
.statusCode(201)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:User"),
"active", is(true),
"id", not(emptyString())
)
.extract().jsonPath().get("id");
String patchBody = "{" +
"\"schemas\": [\"urn:ietf:params:scim:api:messages:2.0:PatchOp\"]," +
"\"Operations\": [{" +
"\"op\": \"replace\"," +
"\"value\": {" +
"\"active\": false" +
"}}]}";
patch("/Users/" + id, patchBody)
.statusCode(200)
.body(
"active", is(false)
);
}
}
| 4,286 |
0 | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance/tests/SchemasIT.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.compliance.tests;
import org.apache.directory.scim.compliance.junit.EmbeddedServerExtension;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.Matchers.*;
@ExtendWith(EmbeddedServerExtension.class)
public class SchemasIT extends ScimpleITSupport {
@Test
@DisplayName("ResourceTypes endpoint")
public void resourceTypes() {
get("/Schemas")
.statusCode(200)
.body(
"Resources", not(empty()),
"schemas", hasItem(SCHEMA_LIST_RESPONSE),
"itemsPerPage", isNumber(),
"startIndex", isNumber(),
"totalResults", isNumber(),
"Resources[0].id", not(emptyString()),
"Resources[0].attributes", not(emptyString())
);
}
@Test
@DisplayName("Check if Schemas is read-only")
public void endpointIsReadOnly() {
post("/Schemas", "")
.statusCode(405);
}
}
| 4,287 |
0 | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance/tests/ScimpleITSupport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.compliance.tests;
import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.filter.log.LogDetail;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.directory.scim.compliance.junit.EmbeddedServerExtension.ScimServerUri;
import org.hamcrest.Matcher;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.stream.Collectors;
import static io.restassured.RestAssured.given;
import static java.util.Collections.emptyMap;
import static org.hamcrest.Matchers.instanceOf;
public class ScimpleITSupport {
static final String SCIM_MEDIA_TYPE = "application/scim+json";
static final String SCHEMA_LIST_RESPONSE = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
static final String SCHEMA_ERROR_RESPONSE = "urn:ietf:params:scim:api:messages:2.0:Error";
@ScimServerUri
private URI uri = URI.create("http://localhost:8080/v2");
private final boolean loggingEnabled = Boolean.getBoolean("scim.tests.logging.enabled");
private final RestAssuredConfig config = RestAssured.config()
.logConfig(RestAssured.config().getLogConfig().enableLoggingOfRequestAndResponseIfValidationFails());
private final Map<String, String> requestHeaders = Map.of(
"User-Agent", "Apache SCIMple Compliance Tests",
"Accept-Charset", "utf-8",
"Authorization", "TODO"
);
protected URI uri() {
return uri;
}
protected URI uri(String path) {
return uri(path, emptyMap());
}
protected URI uri(String path, Map<String, String> query) {
URI uri = uri();
String queryString = query.isEmpty() ? null :
query.keySet()
.stream().map(key -> key + "=" + query.get(key))
.collect(Collectors.joining("&"));
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath() + path, queryString, null);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
protected ValidatableResponse get(String path) {
return get(path, emptyMap());
}
protected ValidatableResponse get(String path, Map<String, String> query) {
ValidatableResponse responseSpec =
given()
.config(config)
.urlEncodingEnabled(false) // URL encoding is handled but the URI
.redirects().follow(false)
.accept(SCIM_MEDIA_TYPE)
.headers(requestHeaders)
.when()
.filter(logging(loggingEnabled))
.get(uri(path, query))
.then()
.contentType(SCIM_MEDIA_TYPE);
if (loggingEnabled) {
responseSpec.log().everything();
}
return responseSpec;
}
protected ValidatableResponse post(String path, String body) {
ValidatableResponse responseSpec =
given()
.config(config)
.urlEncodingEnabled(false) // URL encoding is handled but the URI
.redirects().follow(false)
.accept(SCIM_MEDIA_TYPE)
.contentType(SCIM_MEDIA_TYPE)
.headers(requestHeaders)
.when()
.filter(logging(loggingEnabled))
.body(body)
.post(uri(path))
.then()
.contentType(SCIM_MEDIA_TYPE);
if (loggingEnabled) {
responseSpec.log().everything();
}
return responseSpec;
}
protected ValidatableResponse put(String path, String body) {
ValidatableResponse responseSpec =
given()
.config(config)
.urlEncodingEnabled(false) // URL encoding is handled but the URI
.redirects().follow(false)
.accept(SCIM_MEDIA_TYPE)
.contentType(SCIM_MEDIA_TYPE)
.headers(requestHeaders)
.when()
.filter(logging(loggingEnabled))
.body(body)
.put(uri(path))
.then()
.contentType(SCIM_MEDIA_TYPE);
if (loggingEnabled) {
responseSpec.log().everything();
}
return responseSpec;
}
protected ValidatableResponse patch(String path, String body) {
ValidatableResponse responseSpec =
given()
.config(config)
.urlEncodingEnabled(false) // URL encoding is handled but the URI
.redirects().follow(false)
.accept(SCIM_MEDIA_TYPE)
.contentType(SCIM_MEDIA_TYPE)
.headers(requestHeaders)
.when()
.filter(logging(loggingEnabled))
.body(body)
.patch(uri(path))
.then()
.contentType(SCIM_MEDIA_TYPE);
if (loggingEnabled) {
responseSpec.log().everything();
}
return responseSpec;
}
protected ValidatableResponse delete(String path) {
ValidatableResponse responseSpec =
given()
.config(config)
.urlEncodingEnabled(false) // URL encoding is handled but the URI
.redirects().follow(false)
.accept(SCIM_MEDIA_TYPE)
.contentType(SCIM_MEDIA_TYPE)
.headers(requestHeaders)
.when()
.filter(logging(loggingEnabled))
.delete(uri(path))
.then();
if (loggingEnabled) {
responseSpec.log().everything();
}
return responseSpec;
}
static Filter logging(boolean enabled) {
return enabled
? new RequestLoggingFilter(LogDetail.ALL)
: new NoOpFilter();
}
static String randomName(String base) {
return base + RandomStringUtils.randomAlphanumeric(10);
}
static String randomEmail(String base) {
return base + "-" + RandomStringUtils.randomAlphanumeric(10) + "@example.com";
}
static Matcher<?> isBoolean() {
return instanceOf(Boolean.class);
}
static Matcher<?> isNumber() {
return instanceOf(Number.class);
}
static class NoOpFilter implements Filter {
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
return ctx.next(requestSpec, responseSpec);
}
}
}
| 4,288 |
0 | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance/tests/ServiceProviderConfigIT.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.compliance.tests;
import org.apache.directory.scim.compliance.junit.EmbeddedServerExtension;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.Matchers.*;
@ExtendWith(EmbeddedServerExtension.class)
public class ServiceProviderConfigIT extends ScimpleITSupport {
@Test
@DisplayName("ServiceProviderConfig endpoint")
public void config() {
get("/ServiceProviderConfig")
.statusCode(200)
.body(
"schemas", hasItem("urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"),
"patch.supported", isBoolean(),
"bulk.supported", isBoolean(),
"bulk.maxOperations", isNumber(),
"bulk.maxPayloadSize", isNumber(),
"filter.supported", isBoolean(),
"filter.maxResults", isNumber(),
"changePassword.supported", isBoolean(),
"sort.supported", isBoolean(),
"etag.supported", isBoolean(),
"authenticationSchemes", not(empty()),
"authenticationSchemes[0].type", not(emptyString()),
"authenticationSchemes[0].description", not(emptyString())
);
}
@Test
@DisplayName("Check if ServiceProviderConfig is read-only")
public void endpoingIsReadOnly() {
post("/ServiceProviderConfig", "")
.statusCode(405);
}
}
| 4,289 |
0 | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance | Create_ds/directory-scimple/scim-compliance-tests/src/main/java/org/apache/directory/scim/compliance/tests/GroupsIT.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.compliance.tests;
import org.apache.directory.scim.compliance.junit.EmbeddedServerExtension;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.emptyString;
@ExtendWith(EmbeddedServerExtension.class)
public class GroupsIT extends ScimpleITSupport {
@Test
@DisplayName("Verify Groups endpoint")
public void groupsEndpoint() {
get("/Groups")
.statusCode(200)
.body(
"Resources", not(empty()),
"schemas", hasItem(SCHEMA_LIST_RESPONSE),
"itemsPerPage", isNumber(),
"startIndex", isNumber(),
"totalResults", isNumber(),
"Resources[0].id", not(emptyString())
);
}
@Test
@Order(10)
@DisplayName("Create group with member")
public void createGroup() {
String email = randomEmail("createGroup");
String userId = createUser(randomName("createGroupTest"), email);
String groupName = randomName("group-createGroup");
String body = "{" +
"\"schemas\": [\"urn:ietf:params:scim:schemas:core:2.0:Group\"]," +
"\"displayName\": \"" + groupName + "\"," +
"\"members\": [{" +
"\"value\": \"" + userId + "\"," +
"\"display\": \"" + email + "\"" +
"}]}";
String id = post("/Groups", body)
.statusCode(201)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:Group"),
"id", not(emptyString()),
"displayName", is(groupName),
"members[0].value", is(userId),
"members[0].display", is(email)
)
.extract().jsonPath().get("id");
// retrieve the group by id
get("/Groups/" + id)
.statusCode(200)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:Group"),
"id", not(emptyString()),
"displayName", is(groupName),
"members[0].value", is(userId),
"members[0].display", is(email)
);
// posting same content again should return a conflict (409)
post("/Groups", body)
.statusCode(409)
.body(
"schemas", hasItem(SCHEMA_ERROR_RESPONSE),
"detail", not(emptyString())
);
}
@Test
@DisplayName("Test invalid Group by ID")
public void invalidUserId() {
String invalidId = randomName("invalidUserId");
get("/Groups/" + invalidId)
.statusCode(404)
.body(
"schemas", hasItem(SCHEMA_ERROR_RESPONSE),
"detail", not(emptyString())
);
}
@Test
@DisplayName("Delete Group")
public void deleteGroup() {
String groupName = randomName("group-deleteGroup");
String body = "{" +
"\"schemas\": [\"urn:ietf:params:scim:schemas:core:2.0:Group\"]," +
"\"displayName\": \"" + groupName + "\"," +
"\"members\": []}";
String id = post("/Groups", body)
.statusCode(201)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:Group"),
"id", not(emptyString())
)
.extract().jsonPath().get("id");
delete("/Groups/" + id)
.statusCode(204);
}
@Test
@DisplayName("Update Group")
public void updateGroup() {
String email = randomEmail("updateGroup");
String userId = createUser(randomName("updateGroupTest"), email);
String groupName = randomName("group-updateGroup");
String body = "{" +
"\"schemas\": [\"urn:ietf:params:scim:schemas:core:2.0:Group\"]," +
"\"displayName\": \"" + groupName + "\"," +
"\"members\": [{" +
"\"value\": \"" + userId + "\"," +
"\"display\": \"" + email + "\"" +
"}]}";
String updatedBody = "{" +
"\"schemas\": [\"urn:ietf:params:scim:schemas:core:2.0:Group\"]," +
"\"displayName\": \"" + groupName + "\"," +
"\"members\": []}";
String id = post("/Groups", body)
.statusCode(201)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:Group"),
"id", not(emptyString()),
"displayName", is(groupName),
"members[0].value", is(userId),
"members[0].display", is(email)
)
.extract().jsonPath().get("id");
// update Group,
put("/Groups/" + id, updatedBody)
.statusCode(200)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:Group"),
"members", empty()
);
}
@Test
@DisplayName("Update Group with PATCH")
public void updateGroupWithPatch() {
String email = randomEmail("updateGroupWithPatch");
String userId = createUser(randomName("updateGroupWithPatchTest"), email);
String groupName = randomName("group-updateGroupWithPatch");
String body = "{" +
"\"schemas\": [\"urn:ietf:params:scim:schemas:core:2.0:Group\"]," +
"\"displayName\": \"" + groupName + "\"," +
"\"members\": [{" +
"\"value\": \"" + userId + "\"," +
"\"display\": \"" + email + "\"" +
"}]}";
String patchBody = "{" +
"\"schemas\": [\"urn:ietf:params:scim:api:messages:2.0:PatchOp\"]," +
"\"Operations\": [{" +
"\"op\": \"remove\"," +
"\"path\": \"members[value eq \\\"" + userId + "\\\"]\"" +
"}]}";
String id = post("/Groups", body)
.statusCode(201)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:Group"),
"id", not(emptyString()),
"displayName", is(groupName),
"members[0].value", is(userId),
"members[0].display", is(email)
)
.extract().jsonPath().get("id");
// update Group,
patch("/Groups/" + id, patchBody)
.statusCode(200)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:Group"),
"members", empty()
);
}
String createUser(String name, String email) {
String body = "{" +
"\"schemas\":[\"urn:ietf:params:scim:schemas:core:2.0:User\"]," +
"\"userName\":\"" + email + "\"," +
"\"name\":{" +
"\"givenName\":\"Given-" + name + "\"," +
"\"familyName\":\"Family-" + name + "\"}," +
"\"emails\":[{" +
"\"primary\":true," +
"\"value\":\"" + email + "\"," +
"\"type\":\"work\"}]," +
"\"displayName\":\"Given-" + name + " Family-" + name + "\"," +
"\"active\":true" +
"}";
return post("/Users", body)
.statusCode(201)
.body(
"schemas", contains("urn:ietf:params:scim:schemas:core:2.0:User"),
"active", is(true),
"id", not(emptyString())
)
.extract().jsonPath().get("id");
}
}
| 4,290 |
0 | Create_ds/directory-scimple/scim-client/src/test/java/org/apache/directory/scim/client | Create_ds/directory-scimple/scim-client/src/test/java/org/apache/directory/scim/client/rest/ClientTestSupport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.client.rest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import okhttp3.mockwebserver.MockResponse;
import org.apache.directory.scim.client.rest.junit.MockServerClientTestRunner;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.Map;
@ExtendWith(MockServerClientTestRunner.class)
abstract class ClientTestSupport {
private final ObjectWriter objectWriter = new ObjectMapper().writerWithDefaultPrettyPrinter();
MockResponse scimResponse() {
return new MockResponse()
.setHeader("Content-Type", "application/scim+json");
}
MockResponse scimResponse(Map json) {
try {
return scimResponse()
.setBody(objectWriter.writeValueAsString(json))
.setResponseCode(200);
} catch (JsonProcessingException e) {
Assertions.fail(e);
return null;
}
}
}
| 4,291 |
0 | Create_ds/directory-scimple/scim-client/src/test/java/org/apache/directory/scim/client | Create_ds/directory-scimple/scim-client/src/test/java/org/apache/directory/scim/client/rest/ScimUserClientTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.client.rest;
import jakarta.ws.rs.core.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.apache.directory.scim.protocol.data.ListResponse;
import org.apache.directory.scim.protocol.data.PatchRequest;
import org.apache.directory.scim.protocol.data.SearchRequest;
import org.apache.directory.scim.protocol.exception.ScimException;
import org.apache.directory.scim.spec.filter.FilterBuilder;
import org.apache.directory.scim.spec.patch.PatchOperation;
import org.apache.directory.scim.spec.patch.PatchOperationPath;
import org.apache.directory.scim.spec.resources.ScimUser;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ScimUserClientTest extends ClientTestSupport {
@Test
public void notFound(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(scimResponse()
.setResponseCode(404));
assertThat(client.getById("invalid-id")).isNotPresent();
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(request.getPath()).isEqualTo("/v2/Users/invalid-id");
}
@Test
public void basic200(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(scimResponse()
.setBody("{\"id\": \"valid-id\"}")
.setResponseCode(200));
assertThat(client.getById("valid-id")).isPresent().get().hasFieldOrPropertyWithValue("id", "valid-id");
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(request.getPath()).isEqualTo("/v2/Users/valid-id");
}
@Test
public void client500(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(new MockResponse()
.setResponseCode(500));
assertThrows(ScimException.class, () -> client.getById("id"));
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(request.getPath()).isEqualTo("/v2/Users/id");
}
@Test
public void queryAll(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(scimResponse(Map.of(
"schemas", List.of("urn:ietf:params:scim:api:messages:2.0:ListResponse"),
"totalResults", 2,
"Resources", List.of(
Map.of("id", "2819c223-7f76-453a-919d-413861904646",
"userName", "bjensen"),
Map.of("id", "c75ad752-64ae-4823-840d-ffa80929976c",
"userName", "jsmith")
)
)));
ScimUser bjensen = new ScimUser();
bjensen.setUserName("bjensen");
bjensen.setId("2819c223-7f76-453a-919d-413861904646");
ScimUser jsmith = new ScimUser();
jsmith.setUserName("jsmith");
jsmith.setId("c75ad752-64ae-4823-840d-ffa80929976c");
ListResponse<ScimUser> users = client.query(null, null, null, null, null, null, null);
assertThat(users.getItemsPerPage()).isNull();
assertThat(users.getStartIndex()).isNull();
assertThat(users.getTotalResults()).isEqualTo(2);
assertThat(users.getResources()).containsExactly(bjensen, jsmith);
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(request.getPath()).isEqualTo("/v2/Users");
}
@Test
public void create(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(scimResponse(Map.of(
"id", "created-id", "userName", "testUser")));
ScimUser testUser = new ScimUser();
testUser.setUserName("testUser");
ScimUser expectedUser = new ScimUser();
expectedUser.setUserName("testUser");
expectedUser.setId("created-id");
assertThat(client.create(testUser)).isEqualTo(expectedUser);
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getPath()).isEqualTo("/v2/Users");
}
@Test
public void findByFilter(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(scimResponse(Map.of(
"schemas", List.of("urn:ietf:params:scim:api:messages:2.0:ListResponse"),
"totalResults", 1,
"Resources", List.of(
Map.of("id", "2819c223-7f76-453a-919d-413861904646",
"userName", "bjensen")
)
)));
ScimUser bjensen = new ScimUser();
bjensen.setUserName("bjensen");
bjensen.setId("2819c223-7f76-453a-919d-413861904646");
SearchRequest searchRequest = new SearchRequest()
.setFilter(FilterBuilder.create().equalTo("userName", "bjensen").build());
ListResponse<ScimUser> users = client.find(searchRequest);
assertThat(users.getItemsPerPage()).isNull();
assertThat(users.getStartIndex()).isNull();
assertThat(users.getTotalResults()).isEqualTo(1);
assertThat(users.getResources()).containsExactly(bjensen);
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getPath()).isEqualTo("/v2/Users/.search");
}
@Test
public void update(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(scimResponse(Map.of(
"id", "updated-id", "userName", "testUser")));
ScimUser testUser = new ScimUser();
testUser.setUserName("testUser");
testUser.setId("updated-id");
ScimUser expectedUser = new ScimUser();
expectedUser.setUserName("testUser");
expectedUser.setId("updated-id");
ScimUser resultUser = client.update("updated-id", testUser);
assertThat(resultUser).isEqualTo(expectedUser);
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo("PUT");
assertThat(request.getPath()).isEqualTo("/v2/Users/updated-id");
}
@Test
public void update500(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(new MockResponse()
.setResponseCode(500));
ScimUser testUser = new ScimUser();
testUser.setUserName("testUser");
testUser.setId("500-id");
ScimException exception = assertThrows(ScimException.class, () -> client.update("500-id", testUser));
assertThat(exception.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR);
}
@Test
public void patch(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(scimResponse(Map.of(
"id", "patched-id", "userName", "testUser")));
PatchRequest patchRequest = new PatchRequest().add(
new PatchOperation()
.setOperation(PatchOperation.Type.REMOVE)
.setPath(new PatchOperationPath("name.honorificPrefix"))
);
ScimUser expectedUser = new ScimUser();
expectedUser.setUserName("testUser");
expectedUser.setId("patched-id");
ScimUser resultUser = client.patch("patched-id", patchRequest);
assertThat(resultUser).isEqualTo(expectedUser);
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo("PATCH");
assertThat(request.getPath()).isEqualTo("/v2/Users/patched-id");
}
@Test
public void delete(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(new MockResponse()
.setResponseCode(204));
client.delete("delete-id");
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo("DELETE");
assertThat(request.getPath()).isEqualTo("/v2/Users/delete-id");
}
@Test
public void delete500(MockWebServer server, ScimUserClient client) throws Exception {
server.enqueue(new MockResponse()
.setResponseCode(500));
ScimException exception = assertThrows(ScimException.class, () -> client.delete("500-id"));
assertThat(exception.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR);
}
}
| 4,292 |
0 | Create_ds/directory-scimple/scim-client/src/test/java/org/apache/directory/scim/client/rest | Create_ds/directory-scimple/scim-client/src/test/java/org/apache/directory/scim/client/rest/junit/MockServerClientTestRunner.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.client.rest.junit;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import okhttp3.mockwebserver.MockWebServer;
import org.apache.directory.scim.client.rest.ScimUserClient;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jdk.connector.JdkConnectorProvider;
import org.jboss.weld.environment.se.Weld;
import org.junit.jupiter.api.extension.*;
import java.util.List;
public class MockServerClientTestRunner implements ParameterResolver, BeforeEachCallback, AfterEachCallback, BeforeTestExecutionCallback {
private final List<Class<?>> supportedClasses = List.of(MockWebServer.class, ScimUserClient.class, Client.class);
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return supportedClasses.contains(parameterContext.getParameter().getType());
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) throws ParameterResolutionException {
Class<?> paramType = parameterContext.getParameter().getType();
if (ScimUserClient.class.equals(paramType)) {
MockWebServer server = fromStore(MockWebServer.class, context);
Client client = fromStore(Client.class, context);
ScimUserClient scimUserClient = new ScimUserClient(client, server.url("/v2").toString());
getStore(context).put(ScimUserClient.class, scimUserClient);
return scimUserClient;
}
return fromStore(paramType, context);
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
Weld weld = new Weld();
getStore(context).put(Weld.class, weld);
MockWebServer server = new MockWebServer();
getStore(context).put(MockWebServer.class, server);
Client client = ClientBuilder.newBuilder()
.withConfig( // the default Jersey client does not support PATCH requests
new ClientConfig().connectorProvider(new JdkConnectorProvider()))
.build();
getStore(context).put(Client.class, client);
}
@Override
public void beforeTestExecution(ExtensionContext context) throws Exception {
MockWebServer server = fromStore(MockWebServer.class, context);
if (server != null) {
server.start();
}
Weld weld = fromStore(Weld.class, context);
if (weld != null) {
weld.initialize();
}
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
MockWebServer server = fromStore(MockWebServer.class, context);
if (server != null) {
server.shutdown();
}
Weld weld = fromStore(Weld.class, context);
if (weld != null) {
weld.shutdown();
}
Client client = fromStore(Client.class, context);
if (client != null) {
client.close();
}
ScimUserClient userClient = fromStore(ScimUserClient.class, context);
if (userClient != null) {
userClient.close();
}
}
private ExtensionContext.Store getStore(ExtensionContext context) {
return context.getStore(ExtensionContext.Namespace.create(this));
}
private <T> T fromStore(Class<T> type, ExtensionContext context) {
return getStore(context).get(type, type);
}
}
| 4,293 |
0 | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/RestCall.java | /*
* The Pennsylvania State University © 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.client.rest;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.core.Response;
/**
* Corresponds to {@link java.util.function.Function} but specific to REST calls.
*/
@FunctionalInterface
public interface RestCall {
Response apply(Invocation request) throws RestException;
}
| 4,294 |
0 | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/RestException.java | /*
* The Pennsylvania State University © 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.client.rest;
/*
* The Pennsylvania State University © 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import jakarta.ws.rs.ProcessingException;
import jakarta.ws.rs.core.Response;
import org.apache.directory.scim.protocol.data.ErrorResponse;
public class RestException extends Exception {
private static final long serialVersionUID = 7360783673606191577L;
private final int statusCode;
private final Response.Status status;
private ErrorResponse errorResponse;
public RestException(Response response) {
statusCode = response.getStatus();
status = response.getStatusInfo().toEnum();
try {
errorResponse = response.readEntity(ErrorResponse.class);
} catch (ProcessingException e) {
errorResponse = null;
}
}
public RestException(int statusCode, ErrorResponse errorResponse) {
this.statusCode = statusCode;
this.status = Response.Status.fromStatusCode(statusCode);
this.errorResponse = errorResponse;
}
public int getStatusCode() {
return statusCode;
}
public Response.Status getStatus() {
return status;
}
public ErrorResponse getError() {
return errorResponse;
}
@Override
public String getMessage() {
String message = "Rest Client Exception: Status Code: " + statusCode + " ";
if (errorResponse != null) {
message += "Error Message: " + errorResponse.getDetail();
}
return message;
}
}
| 4,295 |
0 | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/ScimGroupClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.client.rest;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.core.GenericType;
import org.apache.directory.scim.protocol.data.ListResponse;
import org.apache.directory.scim.spec.resources.ScimGroup;
public class ScimGroupClient extends BaseScimClient<ScimGroup> {
private static final GenericType<ListResponse<ScimGroup>> SCIM_GROUP_LIST = new GenericType<ListResponse<ScimGroup>>(){};
public ScimGroupClient(Client client, String baseUrl) {
super(client, baseUrl, ScimGroup.class, SCIM_GROUP_LIST);
}
public ScimGroupClient(Client client, String baseUrl, RestCall invoke) {
super(client, baseUrl, ScimGroup.class, SCIM_GROUP_LIST, invoke);
}
}
| 4,296 |
0 | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/BaseScimClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.client.rest;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import jakarta.ws.rs.ProcessingException;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.GenericType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import org.apache.directory.scim.protocol.adapter.FilterWrapper;
import org.apache.directory.scim.spec.annotation.ScimResourceType;
import org.apache.directory.scim.protocol.BaseResourceTypeResource;
import org.apache.directory.scim.protocol.Constants;
import org.apache.directory.scim.spec.filter.attribute.AttributeReference;
import org.apache.directory.scim.spec.filter.attribute.AttributeReferenceListWrapper;
import org.apache.directory.scim.protocol.data.ErrorResponse;
import org.apache.directory.scim.protocol.data.ListResponse;
import org.apache.directory.scim.protocol.data.PatchRequest;
import org.apache.directory.scim.protocol.data.SearchRequest;
import org.apache.directory.scim.protocol.exception.ScimException;
import org.apache.directory.scim.spec.filter.Filter;
import org.apache.directory.scim.spec.filter.SortOrder;
import org.apache.directory.scim.spec.resources.ScimResource;
public abstract class BaseScimClient<T extends ScimResource> implements AutoCloseable {
static final String ATTRIBUTES_QUERY_PARAM = "attributes";
static final String EXCLUDED_ATTRIBUTES_QUERY_PARAM = "excludedAttributes";
private final Client client;
private final Class<T> scimResourceClass;
private final GenericType<ListResponse<T>> scimResourceListResponseGenericType;
private final WebTarget target;
private final InternalScimClient scimClient;
private RestCall invoke = Invocation::invoke;
public BaseScimClient(Client client, String baseUrl, Class<T> scimResourceClass, GenericType<ListResponse<T>> scimResourceListGenericType) {
ScimResourceType scimResourceType = scimResourceClass.getAnnotation(ScimResourceType.class);
String endpoint = scimResourceType != null ? scimResourceType.endpoint() : null;
if (endpoint == null) {
throw new IllegalArgumentException("scimResourceClass: " + scimResourceClass.getSimpleName() + " must have annotation " + ScimResourceType.class.getSimpleName() + " and annotation must have non-null endpoint");
}
this.client = client.register(ScimJacksonXmlBindJsonProvider.class);
this.scimResourceClass = scimResourceClass;
this.scimResourceListResponseGenericType = scimResourceListGenericType;
this.target = this.client.target(baseUrl).path(endpoint);
this.scimClient = new InternalScimClient();
}
public BaseScimClient(Client client, String baseUrl, Class<T> scimResourceClass, GenericType<ListResponse<T>> scimResourceListGenericType, RestCall invoke) {
this(client, baseUrl, scimResourceClass, scimResourceListGenericType);
this.invoke = invoke;
}
@Override
public void close() {
this.client.close();
}
public Optional<T> getById(String id) throws ScimException {
return this.getById(id, null, null);
}
public Optional<T> getById(String id, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Optional<T> resource;
Response response = this.scimClient.getById(id, attributes, excludedAttributes);
try {
if (RestClientUtil.isSuccessful(response)) {
resource = Optional.of(response.readEntity(this.scimResourceClass));
} else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
resource = Optional.empty();
} else {
ErrorResponse errorResponse = response.readEntity(ErrorResponse.class);
throw new ScimException(errorResponse, Status.fromStatusCode(response.getStatus()));
}
} finally {
RestClientUtil.close(response);
}
return resource;
}
public ListResponse<T> query(AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes, Filter filter, AttributeReference sortBy, SortOrder sortOrder, Integer startIndex, Integer count) throws ScimException {
ListResponse<T> listResponse;
FilterWrapper filterWrapper = new FilterWrapper(filter);
Response response = this.scimClient.query(attributes, excludedAttributes, filterWrapper, sortBy, sortOrder, startIndex, count);
listResponse = handleResponse(response, scimResourceListResponseGenericType, response::readEntity);
return listResponse;
}
public T create(T resource) throws ScimException {
return this.create(resource, null, null);
}
public T create(T resource, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response = this.scimClient.create(resource, attributes, excludedAttributes);
return handleResponse(response, scimResourceClass, response::readEntity);
}
public ListResponse<T> find(SearchRequest searchRequest) throws ScimException {
ListResponse<T> listResponse;
Response response = this.scimClient.find(searchRequest);
listResponse = handleResponse(response, scimResourceListResponseGenericType, response::readEntity);
return listResponse;
}
public T update(String id, T resource) throws ScimException {
return this.update(id, resource, null, null);
}
public T update(String id, T resource, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response = this.scimClient.update(resource, id, attributes, excludedAttributes);
return handleResponse(response, scimResourceClass, response::readEntity);
}
public T patch(String id, PatchRequest patchRequest) throws ScimException {
return this.patch(id, patchRequest, null, null);
}
public T patch(String id, PatchRequest patchRequest, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response = this.scimClient.patch(patchRequest, id, attributes, excludedAttributes);
return handleResponse(response, scimResourceClass, response::readEntity);
}
public void delete(String id) throws ScimException {
Response response = this.scimClient.delete(id);
handleResponse(response);
}
static <E, T> E handleResponse(Response response, T type, Function<T, E> readEntity) throws ScimException {
E entity;
try {
if (RestClientUtil.isSuccessful(response)) {
entity = readEntity.apply(type);
} else {
Status status = Status.fromStatusCode(response.getStatus());
ErrorResponse errorResponse = response.readEntity(ErrorResponse.class);
throw new ScimException(errorResponse, status);
}
} finally {
RestClientUtil.close(response);
}
return entity;
}
static void handleResponse(Response response) throws ScimException {
try {
if (!RestClientUtil.isSuccessful(response)) {
Status status = Status.fromStatusCode(response.getStatus());
ErrorResponse errorResponse = response.readEntity(ErrorResponse.class);
throw new ScimException(errorResponse, status);
}
} catch (ProcessingException e) {
ErrorResponse er = new ErrorResponse(Status.INTERNAL_SERVER_ERROR, e.getMessage());
throw new ScimException(er, Status.INTERNAL_SERVER_ERROR);
} finally {
RestClientUtil.close(response);
}
}
static ScimException toScimException(RestException restException) {
return new ScimException(restException.getError(), restException.getStatus());
}
public RestCall getInvoke() {
return this.invoke;
}
public void setInvoke(RestCall invoke) {
this.invoke = invoke;
}
private class InternalScimClient implements BaseResourceTypeResource<T> {
private static final String FILTER_QUERY_PARAM = "filter";
private static final String SORT_BY_QUERY_PARAM = "sortBy";
private static final String SORT_ORDER_QUERY_PARAM = "sortOrder";
private static final String START_INDEX_QUERY_PARAM = "startIndex";
private static final String COUNT_QUERY_PARAM = "count";
@Override
public Response getById(String id, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response;
Invocation request = BaseScimClient.this.target
.path(id)
.queryParam(ATTRIBUTES_QUERY_PARAM, nullOutQueryParamIfListIsNullOrEmpty(attributes))
.queryParam(EXCLUDED_ATTRIBUTES_QUERY_PARAM, nullOutQueryParamIfListIsNullOrEmpty(excludedAttributes))
.request(getContentType())
.buildGet();
try {
response = BaseScimClient.this.invoke.apply(request);
return response;
} catch (RestException restException) {
throw toScimException(restException);
}
}
@Override
public Response query(AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes, FilterWrapper filter, AttributeReference sortBy, SortOrder sortOrder, Integer startIndex, Integer count) throws ScimException {
Response response;
Invocation request = BaseScimClient.this.target
.queryParam(ATTRIBUTES_QUERY_PARAM, nullOutQueryParamIfListIsNullOrEmpty(attributes))
.queryParam(EXCLUDED_ATTRIBUTES_QUERY_PARAM, nullOutQueryParamIfListIsNullOrEmpty(excludedAttributes))
.queryParam(FILTER_QUERY_PARAM, filter.getFilter())
.queryParam(SORT_BY_QUERY_PARAM, sortBy)
.queryParam(SORT_ORDER_QUERY_PARAM, sortOrder != null ? sortOrder.name() : null)
.queryParam(START_INDEX_QUERY_PARAM, startIndex)
.queryParam(COUNT_QUERY_PARAM, count)
.request(getContentType())
.buildGet();
try {
response = BaseScimClient.this.invoke.apply(request);
return response;
} catch (RestException restException) {
throw toScimException(restException);
}
}
@Override
public Response create(T resource, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response;
Invocation request = BaseScimClient.this.target
.queryParam(ATTRIBUTES_QUERY_PARAM, nullOutQueryParamIfListIsNullOrEmpty(attributes))
.queryParam(EXCLUDED_ATTRIBUTES_QUERY_PARAM, nullOutQueryParamIfListIsNullOrEmpty(excludedAttributes))
.request(getContentType())
.buildPost(Entity.entity(resource, getContentType()));
try {
response = BaseScimClient.this.invoke.apply(request);
return response;
} catch (RestException restException) {
throw toScimException(restException);
}
}
@Override
public Response find(SearchRequest searchRequest) throws ScimException {
Response response;
Invocation request = BaseScimClient.this.target
.path(".search")
.request(getContentType())
.buildPost(Entity.entity(searchRequest, getContentType()));
try {
response = BaseScimClient.this.invoke.apply(request);
return response;
} catch (RestException restException) {
throw toScimException(restException);
}
}
@Override
public Response update(T resource, String id, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response;
Invocation request = BaseScimClient.this.target
.path(id)
.queryParam(ATTRIBUTES_QUERY_PARAM, nullOutQueryParamIfListIsNullOrEmpty(attributes))
.queryParam(EXCLUDED_ATTRIBUTES_QUERY_PARAM, nullOutQueryParamIfListIsNullOrEmpty(excludedAttributes))
.request(getContentType())
.buildPut(Entity.entity(resource, getContentType()));
try {
response = BaseScimClient.this.invoke.apply(request);
return response;
} catch (RestException restException) {
throw toScimException(restException);
}
}
@Override
public Response patch(PatchRequest patchRequest, String id, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response;
Invocation request = BaseScimClient.this.target
.path(id)
.queryParam(ATTRIBUTES_QUERY_PARAM, nullOutQueryParamIfListIsNullOrEmpty(attributes))
.queryParam(EXCLUDED_ATTRIBUTES_QUERY_PARAM, nullOutQueryParamIfListIsNullOrEmpty(excludedAttributes))
.request(getContentType())
.build("PATCH", Entity.entity(patchRequest, getContentType()));
try {
response = BaseScimClient.this.invoke.apply(request);
return response;
} catch (RestException restException) {
throw toScimException(restException);
}
}
@Override
public Response delete(String id) throws ScimException {
Response response;
Invocation request = BaseScimClient.this.target
.path(id)
.request(getContentType())
.buildDelete();
try {
response = BaseScimClient.this.invoke.apply(request);
return response;
} catch (RestException restException) {
throw toScimException(restException);
}
}
private AttributeReferenceListWrapper nullOutQueryParamIfListIsNullOrEmpty(AttributeReferenceListWrapper wrapper) {
if (wrapper == null) {
return null;
}
Set<AttributeReference> attributeReferences = wrapper.getAttributeReferences();
if (attributeReferences == null || attributeReferences.isEmpty()) {
return null;
}
return wrapper;
}
}
protected String getContentType() {
return Constants.SCIM_CONTENT_TYPE;
}
}
| 4,297 |
0 | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/ScimSelfClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.client.rest;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
import org.apache.directory.scim.protocol.Constants;
import org.apache.directory.scim.protocol.SelfResource;
import org.apache.directory.scim.spec.filter.attribute.AttributeReferenceListWrapper;
import org.apache.directory.scim.protocol.data.PatchRequest;
import org.apache.directory.scim.protocol.exception.ScimException;
import org.apache.directory.scim.spec.resources.ScimUser;
// purposefully does not extend BaseScimClient, has a different utility than other clients
public class ScimSelfClient implements AutoCloseable {
private Client client;
private WebTarget target;
private SelfResourceClient selfResourceClient;
private RestCall invoke = Invocation::invoke;
public ScimSelfClient(Client client, String baseUrl) {
this.client = client.register(ScimJacksonXmlBindJsonProvider.class);
this.target = this.client.target(baseUrl).path(SelfResource.PATH);
this.selfResourceClient = new SelfResourceClient();
}
public ScimSelfClient(Client client, String baseUrl, RestCall invoke) {
this(client, baseUrl);
this.invoke = invoke;
}
public ScimUser getSelf(AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
ScimUser self;
Response response = this.selfResourceClient.getSelf(attributes, excludedAttributes);
self = BaseScimClient.handleResponse(response, ScimUser.class, response::readEntity);
return self;
}
public ScimUser getSelf() throws ScimException {
ScimUser self = this.getSelf(null, null);
return self;
}
public void updateSelf(ScimUser scimUser, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response = this.selfResourceClient.update(scimUser, attributes, excludedAttributes);
BaseScimClient.handleResponse(response);
}
public void updateSelf(ScimUser scimUser) throws ScimException {
this.updateSelf(scimUser, null, null);
}
public void patchSelf(PatchRequest patchRequest, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response = this.selfResourceClient.patch(patchRequest, attributes, excludedAttributes);
BaseScimClient.handleResponse(response);
}
public void patchSelf(PatchRequest patchRequest) throws ScimException {
this.patchSelf(patchRequest, null, null);
}
public void deleteSelf() throws ScimException {
Response response = this.selfResourceClient.delete();
BaseScimClient.handleResponse(response);
}
public RestCall getInvoke() {
return this.invoke;
}
public void setInvoke(RestCall invoke) {
this.invoke = invoke;
}
@Override
public void close() throws Exception {
this.client.close();
}
private class SelfResourceClient implements SelfResource {
@Override
public Response getSelf(AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response;
Invocation request = ScimSelfClient.this.target
.queryParam(BaseScimClient.ATTRIBUTES_QUERY_PARAM, attributes)
.queryParam(BaseScimClient.EXCLUDED_ATTRIBUTES_QUERY_PARAM, excludedAttributes)
.request(Constants.SCIM_CONTENT_TYPE)
.buildGet();
try {
response = ScimSelfClient.this.invoke.apply(request);
} catch (RestException restException) {
throw BaseScimClient.toScimException(restException);
}
return response;
}
@Override
public Response update(ScimUser scimUser, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response;
Invocation request = ScimSelfClient.this.target
.queryParam(BaseScimClient.ATTRIBUTES_QUERY_PARAM, attributes)
.queryParam(BaseScimClient.EXCLUDED_ATTRIBUTES_QUERY_PARAM, excludedAttributes)
.request(Constants.SCIM_CONTENT_TYPE)
.buildPut(Entity.entity(scimUser, Constants.SCIM_CONTENT_TYPE));
try {
response = ScimSelfClient.this.invoke.apply(request);
} catch (RestException restException) {
throw BaseScimClient.toScimException(restException);
}
return response;
}
@Override
public Response patch(PatchRequest patchRequest, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException {
Response response;
Invocation request = ScimSelfClient.this.target
.queryParam(BaseScimClient.ATTRIBUTES_QUERY_PARAM, attributes)
.queryParam(BaseScimClient.EXCLUDED_ATTRIBUTES_QUERY_PARAM, excludedAttributes)
.request(Constants.SCIM_CONTENT_TYPE)
.build(Constants.PATCH, Entity.entity(patchRequest, Constants.SCIM_CONTENT_TYPE));
try {
response = ScimSelfClient.this.invoke.apply(request);
} catch (RestException restException) {
throw BaseScimClient.toScimException(restException);
}
return response;
}
@Override
public Response delete() throws ScimException {
Response response;
Invocation request = ScimSelfClient.this.target
.request(Constants.SCIM_CONTENT_TYPE)
.buildDelete();
try {
response = ScimSelfClient.this.invoke.apply(request);
} catch (RestException restException) {
throw BaseScimClient.toScimException(restException);
}
return response;
}
}
}
| 4,298 |
0 | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client | Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/ScimUserClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.directory.scim.client.rest;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.core.GenericType;
import org.apache.directory.scim.protocol.data.ListResponse;
import org.apache.directory.scim.spec.resources.ScimUser;
public class ScimUserClient extends BaseScimClient<ScimUser> {
private static final GenericType<ListResponse<ScimUser>> LIST_SCIM_USER = new GenericType<ListResponse<ScimUser>>(){};
public ScimUserClient(Client client, String baseUrl) {
super(client, baseUrl, ScimUser.class, LIST_SCIM_USER);
}
public ScimUserClient(Client client, String baseUrl, RestCall invoke) {
super(client, baseUrl, ScimUser.class, LIST_SCIM_USER, invoke);
}
}
| 4,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.