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-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/UnableToResolveIdResourceException.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.server.exception; import jakarta.ws.rs.core.Response.Status; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.directory.scim.spec.exception.ResourceException; @Data @EqualsAndHashCode(callSuper=true) public class UnableToResolveIdResourceException extends ResourceException { private static final long serialVersionUID = -7401709416973728017L; public UnableToResolveIdResourceException(Status status, String message) { super(status.getStatusCode(), message); } public UnableToResolveIdResourceException(Status status, String message, Throwable cause) { super(status.getStatusCode(), message, cause); } }
4,400
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/UnableToCreateResourceException.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.server.exception; import jakarta.ws.rs.core.Response.Status; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.directory.scim.spec.exception.ResourceException; @Data @EqualsAndHashCode(callSuper=true) public class UnableToCreateResourceException extends ResourceException { private static final long serialVersionUID = -3872700870424005641L; public UnableToCreateResourceException(Status status, String message) { super(status.getStatusCode(), message); } public UnableToCreateResourceException(Status status, String message, Throwable cause) { super(status.getStatusCode(), message, cause); } }
4,401
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/GenericExceptionMapper.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.server.exception; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.Provider; import org.apache.directory.scim.protocol.Constants; import org.apache.directory.scim.protocol.data.ErrorResponse; @Provider @Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON}) public class GenericExceptionMapper extends BaseScimExceptionMapper<Throwable> { @Override protected ErrorResponse errorResponse(Throwable throwable) { return new ErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, throwable.getMessage()); } }
4,402
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/AttributeDoesNotExistException.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.server.exception; public class AttributeDoesNotExistException extends AttributeException { private static final long serialVersionUID = 547510233114396694L; public AttributeDoesNotExistException() { } public AttributeDoesNotExistException(String message) { super(message); } public AttributeDoesNotExistException(Throwable cause) { super(cause); } public AttributeDoesNotExistException(String message, Throwable cause) { super(message, cause); } public AttributeDoesNotExistException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
4,403
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/MutabilityExceptionMapper.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.server.exception; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.ext.Provider; import org.apache.directory.scim.protocol.Constants; import org.apache.directory.scim.protocol.ErrorMessageType; import org.apache.directory.scim.protocol.data.ErrorResponse; import org.apache.directory.scim.spec.filter.FilterParseException; @Provider @Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON}) public class MutabilityExceptionMapper extends BaseScimExceptionMapper<FilterParseException> { @Override protected ErrorResponse errorResponse(FilterParseException exception) { return new ErrorResponse(Status.BAD_REQUEST, exception.getMessage()) .setScimType(ErrorMessageType.MUTABILITY); } }
4,404
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/SchemaResourceImpl.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.server.rest; import java.util.ArrayList; import java.util.Collection; import java.util.List; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; 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.SchemaResource; import org.apache.directory.scim.protocol.data.ListResponse; import org.apache.directory.scim.spec.schema.Meta; import org.apache.directory.scim.spec.schema.Schema; import org.apache.directory.scim.core.schema.SchemaRegistry; @ApplicationScoped public class SchemaResourceImpl implements SchemaResource { private final SchemaRegistry schemaRegistry; @Inject public SchemaResourceImpl(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } public SchemaResourceImpl() { // CDI this(null); } @Override public Response getAllSchemas(String filter, UriInfo uriInfo) { if (filter != null) { return Response.status(Status.FORBIDDEN).build(); } ListResponse<Schema> listResponse = new ListResponse<>(); Collection<Schema> schemas = schemaRegistry.getAllSchemas(); for (Schema schema : schemas) { Meta meta = new Meta(); meta.setLocation(uriInfo.getAbsolutePathBuilder().path(schema.getId()).build().toString()); meta.setResourceType(Schema.RESOURCE_NAME); schema.setMeta(meta); } listResponse.setItemsPerPage(schemas.size()); listResponse.setStartIndex(1); listResponse.setTotalResults(schemas.size()); List<Schema> objectList = new ArrayList<>(schemas); listResponse.setResources(objectList); return Response.ok(listResponse).build(); } @Override public Response getSchema(String urn, UriInfo uriInfo) { Schema schema = schemaRegistry.getSchema(urn); if (schema == null){ return Response.status(Status.NOT_FOUND).build(); } Meta meta = new Meta(); meta.setLocation(uriInfo.getAbsolutePath().toString()); meta.setResourceType(Schema.RESOURCE_NAME); schema.setMeta(meta); return Response.ok(schema).build(); } }
4,405
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/SelfResourceImpl.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.server.rest; import java.security.Principal; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import jakarta.ws.rs.core.*; import jakarta.ws.rs.core.Response.Status; import org.apache.directory.scim.spec.exception.ResourceException; import org.apache.directory.scim.server.exception.UnableToResolveIdResourceException; import org.apache.directory.scim.core.repository.SelfIdResolver; import org.apache.directory.scim.protocol.SelfResource; import org.apache.directory.scim.protocol.UserResource; 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; import lombok.extern.slf4j.Slf4j; @Slf4j @ApplicationScoped public class SelfResourceImpl implements SelfResource { private final UserResource userResource; private final Instance<SelfIdResolver> selfIdResolver; // TODO: Field injection of SecurityContext should work with all implementations // CDI can be used directly in Jakarta WS 4 @Context SecurityContext securityContext; @Inject public SelfResourceImpl(UserResource userResource, Instance<SelfIdResolver> selfIdResolver) { this.userResource = userResource; this.selfIdResolver = selfIdResolver; } public SelfResourceImpl() { // CDI this(null, null); } @Override public Response getSelf(AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException { String internalId = getInternalId(); return userResource.getById(internalId, attributes, excludedAttributes); } // @Override // public Response create(ScimUser resource, AttributeReferenceListWrapper // attributes, AttributeReferenceListWrapper excludedAttributes) { // String internalId = getInternalId(); // //TODO check if ids match in request // return userResourceImpl.create(resource, attributes, excludedAttributes); // } @Override public Response update(ScimUser resource, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException { String internalId = getInternalId(); return userResource.update(resource, internalId, attributes, excludedAttributes); } @Override public Response patch(PatchRequest patchRequest, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException { String internalId = getInternalId(); return userResource.patch(patchRequest, internalId, attributes, excludedAttributes); } @Override public Response delete() throws ScimException, ResourceException { String internalId = getInternalId(); return userResource.delete(internalId); } private String getInternalId() throws ResourceException { Principal callerPrincipal = securityContext.getUserPrincipal(); if (callerPrincipal != null) { log.debug("Resolved SelfResource principal to : {}", callerPrincipal.getName()); } else { throw new UnableToResolveIdResourceException(Status.UNAUTHORIZED, "Unauthorized"); } if (selfIdResolver.isUnsatisfied()) { throw new UnableToResolveIdResourceException(Status.NOT_IMPLEMENTED, "Caller SelfIdResolver not available"); } return selfIdResolver.get().resolveToInternalId(callerPrincipal); } }
4,406
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/ScimResourceHelper.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.server.rest; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.directory.scim.server.exception.*; /** * Provides the SCIM defined set of end-points and resources without declaring a * JAX-RS application. Additional end-points and extensions can be added by the * implementing class. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ public final class ScimResourceHelper { static final Set<Class<?>> RESOURCE_CLASSES = Set.of( BulkResourceImpl.class, GroupResourceImpl.class, ResourceTypesResourceImpl.class, SchemaResourceImpl.class, SearchResourceImpl.class, SelfResourceImpl.class, ServiceProviderConfigResourceImpl.class, UserResourceImpl.class); static final Set<Class<?>> EXCEPTION_MAPPER_CLASSES = Set.of( UnsupportedFilterExceptionMapper.class, ResourceExceptionMapper.class, ScimExceptionMapper.class, FilterParseExceptionMapper.class, WebApplicationExceptionMapper.class, UnsupportedOperationExceptionMapper.class, MutabilityExceptionMapper.class, GenericExceptionMapper.class); static final Set<Class<?>> MEDIA_TYPE_SUPPORT_CLASSES = Set.of( ScimJacksonXmlBindJsonProvider.class ); static final Set<Class<?>> SCIMPLE_CLASSES = Stream.of( RESOURCE_CLASSES, EXCEPTION_MAPPER_CLASSES, MEDIA_TYPE_SUPPORT_CLASSES) .flatMap(Collection::stream) .collect(Collectors.toUnmodifiableSet()); private ScimResourceHelper() { // Make this a utility class } public static Set<Class<?>> scimpleFeatureAndResourceClasses() { Set<Class<?>> classes = new HashSet<>(RESOURCE_CLASSES); classes.add(ScimpleFeature.class); return Collections.unmodifiableSet(classes); } }
4,407
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/BulkResourceImpl.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.server.rest; import java.util.*; import java.util.regex.Pattern; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.UriInfo; import org.apache.commons.lang3.StringUtils; import org.apache.directory.scim.spec.exception.ResourceException; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToDeleteResourceException; import org.apache.directory.scim.server.exception.UnableToRetrieveResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.RepositoryRegistry; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.protocol.BulkResource; import org.apache.directory.scim.protocol.data.BulkOperation; import org.apache.directory.scim.protocol.data.BulkOperation.Method; import org.apache.directory.scim.protocol.data.BulkOperation.StatusWrapper; import org.apache.directory.scim.protocol.data.BulkRequest; import org.apache.directory.scim.protocol.data.BulkResponse; import org.apache.directory.scim.protocol.data.ErrorResponse; import org.apache.directory.scim.spec.resources.BaseResource; import org.apache.directory.scim.spec.resources.ScimResource; import org.apache.directory.scim.spec.schema.Schema; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.directory.scim.core.schema.SchemaRegistry; @Slf4j @ApplicationScoped public class BulkResourceImpl implements BulkResource { // private static final StatusWrapper OKAY_STATUS = new StatusWrapper(); // private static final StatusWrapper CREATED_STATUS = new StatusWrapper(); // private static final StatusWrapper NO_CONTENT_STATUS = new StatusWrapper(); // private static final StatusWrapper METHOD_NOT_ALLOWED_STATUS = new StatusWrapper(); // private static final StatusWrapper CONFLICT_STATUS = new StatusWrapper(); // private static final StatusWrapper CLIENT_ERROR_STATUS = new StatusWrapper(); // private static final StatusWrapper NOT_FOUND_STATUS = new StatusWrapper(); // private static final StatusWrapper INTERNAL_SERVER_ERROR_STATUS = new StatusWrapper(); // private static final StatusWrapper METHOD_NOT_IMPLEMENTED_STATUS = new StatusWrapper(); // private static final String OKAY = "200"; // private static final String CREATED = "201"; // private static final String NO_CONTENT = "204"; // private static final String CLIENT_ERROR = "400"; // private static final String NOT_FOUND = "404"; // private static final String METHOD_NOT_ALLOWED = "405"; // private static final String CONFLICT = "409"; // private static final String INTERNAL_SERVER_ERROR = "500"; // private static final String METHOD_NOT_IMPLEMENTED = "501"; private static final String BULK_ID_DOES_NOT_EXIST = "Bulk ID cannot be resolved because it refers to no bulkId in any Bulk Operation: %s"; private static final String BULK_ID_REFERS_TO_FAILED_RESOURCE = "Bulk ID cannot be resolved because the resource it refers to had failed to be created: %s"; private static final String OPERATION_DEPENDS_ON_FAILED_OPERATION = "Operation depends on failed bulk operation: %s"; private static final Pattern PATH_PATTERN = Pattern.compile("^/[^/]+/[^/]+$"); // static { // METHOD_NOT_ALLOWED_STATUS.setCode(METHOD_NOT_ALLOWED); // OKAY_STATUS.setCode(OKAY); // CREATED_STATUS.setCode(CREATED); // NO_CONTENT_STATUS.setCode(NO_CONTENT); // CONFLICT_STATUS.setCode(CONFLICT); // CLIENT_ERROR_STATUS.setCode(CLIENT_ERROR); // NOT_FOUND_STATUS.setCode(NOT_FOUND); // INTERNAL_SERVER_ERROR_STATUS.setCode(INTERNAL_SERVER_ERROR); // METHOD_NOT_IMPLEMENTED_STATUS.setCode(METHOD_NOT_IMPLEMENTED); // } private final SchemaRegistry schemaRegistry; private final RepositoryRegistry repositoryRegistry; @Inject public BulkResourceImpl(SchemaRegistry schemaRegistry, RepositoryRegistry repositoryRegistry) { this.schemaRegistry = schemaRegistry; this.repositoryRegistry = repositoryRegistry; } public BulkResourceImpl() { // CDI this(null, null); } @Override public Response doBulk(BulkRequest request, UriInfo uriInfo) { BulkResponse response; int errorCount = 0; Integer requestFailOnErrors = request.getFailOnErrors(); int maxErrorCount = requestFailOnErrors != null && requestFailOnErrors > 0 ? requestFailOnErrors : Integer.MAX_VALUE; int errorCountIncrement = requestFailOnErrors == null || requestFailOnErrors > 0 ? 1 : 0; List<BulkOperation> bulkOperations = request.getOperations(); Map<String, BulkOperation> bulkIdKeyToOperationResult = new HashMap<>(); List<IWishJavaHadTuples> allUnresolveds = new ArrayList<>(); Map<String, Set<String>> reverseDependenciesGraph = this.generateReverseDependenciesGraph(bulkOperations); Map<String, Set<String>> transitiveReverseDependencies = generateTransitiveDependenciesGraph(reverseDependenciesGraph); log.debug("Reverse dependencies: {}", reverseDependenciesGraph); log.debug("Transitive reverse dependencies: {}", transitiveReverseDependencies); // clean out unwanted data for (BulkOperation operationRequest : bulkOperations) { operationRequest.setResponse(null); operationRequest.setStatus(null); } // get all known bulkIds, handle bad input for (BulkOperation operationRequest : bulkOperations) { String bulkId = operationRequest.getBulkId(); Method method = operationRequest.getMethod(); String bulkIdKey = bulkId != null ? "bulkId:" + bulkId : null; boolean errorOccurred = false; // duplicate bulkId if (bulkIdKey != null) { if (!bulkIdKeyToOperationResult.containsKey(bulkIdKey)) { bulkIdKeyToOperationResult.put(bulkIdKey, operationRequest); } else { errorOccurred = true; BulkOperation duplicateOperation = bulkIdKeyToOperationResult.get(bulkIdKey); createAndSetErrorResponse(operationRequest, Status.CONFLICT, "Duplicate bulkId"); if (!(duplicateOperation.getResponse() instanceof ErrorResponse)) { duplicateOperation.setData(null); createAndSetErrorResponse(duplicateOperation, Status.CONFLICT, "Duplicate bulkId"); } } } // bad/missing input for method if (method != null && !(operationRequest.getResponse() instanceof ErrorResponse)) { switch (method) { case POST: case PUT: { if (operationRequest.getData() == null) { errorOccurred = true; createAndSetErrorResponse(operationRequest, Status.BAD_REQUEST, "data not provided"); } } break; case DELETE: { String path = operationRequest.getPath(); if (path == null) { errorOccurred = true; createAndSetErrorResponse(operationRequest, Status.BAD_REQUEST, "path not provided"); } else if (!PATH_PATTERN.matcher(path) .matches()) { errorOccurred = true; createAndSetErrorResponse(operationRequest, Status.BAD_REQUEST, "path is not a valid path (e.g. \"/Groups/123abc\", \"/Users/123xyz\", ...)"); } else { String endPoint = path.substring(0, path.lastIndexOf('/')); Class<ScimResource> clazz = (Class<ScimResource>) schemaRegistry.getScimResourceClassFromEndpoint(endPoint); if (clazz == null) { errorOccurred = true; createAndSetErrorResponse(operationRequest, Status.BAD_REQUEST, "path does not contain a recognized endpoint (e.g. \"/Groups/...\", \"/Users/...\", ...)"); } } } break; case PATCH: { errorOccurred = true; createAndSetErrorResponse(operationRequest, Status.NOT_IMPLEMENTED, "Method not implemented: PATCH"); } break; default: { } break; } } else if (method == null) { errorOccurred = true; operationRequest.setData(null); createAndSetErrorResponse(operationRequest, Status.BAD_REQUEST, "no method provided (e.g. PUT, POST, ..."); } if (errorOccurred) { operationRequest.setData(null); if (bulkIdKey != null) { Set<String> reverseDependencies = transitiveReverseDependencies.getOrDefault(bulkIdKey, Collections.emptySet()); String detail = String.format(OPERATION_DEPENDS_ON_FAILED_OPERATION, bulkIdKey); for (String dependentBulkIdKey : reverseDependencies) { BulkOperation dependentOperation = bulkIdKeyToOperationResult.get(dependentBulkIdKey); if (!(dependentOperation.getResponse() instanceof ErrorResponse)) { dependentOperation.setData(null); createAndSetErrorResponse(dependentOperation, Status.CONFLICT, detail); } } } } } boolean errorCountExceeded = false; // do the operations for (BulkOperation operationResult : bulkOperations) { if (!errorCountExceeded && !(operationResult.getResponse() instanceof ErrorResponse)) { try { this.handleBulkOperationMethod(allUnresolveds, operationResult, bulkIdKeyToOperationResult, uriInfo); } catch (ResourceException resourceException) { log.error("Failed to do bulk operation", resourceException); errorCount += errorCountIncrement; errorCountExceeded = errorCount >= maxErrorCount; String detail = resourceException.getLocalizedMessage(); createAndSetErrorResponse(operationResult, resourceException.getStatus(), detail); if (operationResult.getBulkId() != null) { String bulkIdKey = "bulkId:" + operationResult.getBulkId(); this.cleanup(bulkIdKey, transitiveReverseDependencies, bulkIdKeyToOperationResult); operationResult.setData(null); } } catch (UnresolvableOperationException unresolvableOperationException) { log.error("Could not resolve bulkId during Bulk Operation method handling", unresolvableOperationException); errorCount += errorCountIncrement; String detail = unresolvableOperationException.getLocalizedMessage(); createAndSetErrorResponse(operationResult, Status.CONFLICT, detail); if (operationResult.getBulkId() != null) { String bulkIdKey = "bulkId:" + operationResult.getBulkId(); this.cleanup(bulkIdKey, transitiveReverseDependencies, bulkIdKeyToOperationResult); operationResult.setData(null); } } } else if (errorCountExceeded) { // continue processing bulk operations to cleanup any dependencies createAndSetErrorResponse(operationResult, Status.CONFLICT, "failOnErrors count reached"); if (operationResult.getBulkId() != null) { String bulkIdKey = "bulkId:" + operationResult.getBulkId(); this.cleanup(bulkIdKey, transitiveReverseDependencies, bulkIdKeyToOperationResult); } } } // Resolve unresolved bulkIds for (IWishJavaHadTuples iwjht : allUnresolveds) { BulkOperation bulkOperationResult = iwjht.bulkOperationResult; String bulkIdKey = iwjht.bulkIdKey; ScimResource scimResource = bulkOperationResult.getData(); try { for (UnresolvedTopLevel unresolved : iwjht.unresolveds) { log.debug("Final resolution pass for {}", unresolved); unresolved.resolve(scimResource, bulkIdKeyToOperationResult); } String scimResourceId = scimResource.getId(); @SuppressWarnings("unchecked") Class<ScimResource> scimResourceClass = (Class<ScimResource>) scimResource.getClass(); Repository<ScimResource> repository = repositoryRegistry.getRepository(scimResourceClass); ScimResource original = repository.get(scimResourceId); UpdateRequest<ScimResource> updateRequest = new UpdateRequest<>(scimResourceId, original, scimResource, schemaRegistry); repository.update(updateRequest); } catch (UnresolvableOperationException unresolvableOperationException) { log.error("Could not complete final resolution pass, unresolvable bulkId", unresolvableOperationException); String detail = unresolvableOperationException.getLocalizedMessage(); bulkOperationResult.setData(null); bulkOperationResult.setLocation(null); createAndSetErrorResponse(bulkOperationResult, Status.CONFLICT, detail); this.cleanup(bulkIdKey, transitiveReverseDependencies, bulkIdKeyToOperationResult); } catch (UnableToUpdateResourceException unableToUpdateResourceException) { log.error("Failed to update Scim Resource with resolved bulkIds", unableToUpdateResourceException); String detail = unableToUpdateResourceException.getLocalizedMessage(); bulkOperationResult.setData(null); bulkOperationResult.setLocation(null); createAndSetErrorResponse(bulkOperationResult, unableToUpdateResourceException.getStatus(), detail); this.cleanup(bulkIdKey, transitiveReverseDependencies, bulkIdKeyToOperationResult); } catch (ResourceException e) { log.error("Could not complete final resolution pass, unresolvable bulkId", e); String detail = e.getLocalizedMessage(); bulkOperationResult.setData(null); bulkOperationResult.setLocation(null); createAndSetErrorResponse(bulkOperationResult, Status.NOT_FOUND, detail); this.cleanup(bulkIdKey, transitiveReverseDependencies, bulkIdKeyToOperationResult); } } Status status = errorCountExceeded ? Status.BAD_REQUEST : Status.OK; response = new BulkResponse() .setOperations(bulkOperations) .setStatus(status); return Response.status(status) .entity(response) .build(); } /** * Delete resources that depend on {@code bulkIdKeyToCleanup}, remove * {@link BulkOperation}s data, and set their code and response * * @param bulkIdKeyToCleanup * @param transitiveReverseDependencies * @param bulkIdKeyToOperationResult */ private void cleanup(String bulkIdKeyToCleanup, Map<String, Set<String>> transitiveReverseDependencies, Map<String, BulkOperation> bulkIdKeyToOperationResult) { Set<String> reverseDependencies = transitiveReverseDependencies.getOrDefault(bulkIdKeyToCleanup, Collections.emptySet()); BulkOperation operationResult = bulkIdKeyToOperationResult.get(bulkIdKeyToCleanup); String bulkId = operationResult.getBulkId(); ScimResource scimResource = operationResult.getData(); @SuppressWarnings("unchecked") Class<ScimResource> scimResourceClass = (Class<ScimResource>) scimResource.getClass(); Repository<ScimResource> repository = this.repositoryRegistry.getRepository(scimResourceClass); try { if (StringUtils.isNotBlank(scimResource.getId())) { repository.delete(scimResource.getId()); } } catch (ResourceException unableToDeleteResourceException) { log.error("Could not delete ScimResource after failure: {}", scimResource); } for (String dependentBulkIdKey : reverseDependencies) { BulkOperation dependentOperationResult = bulkIdKeyToOperationResult.get(dependentBulkIdKey); if (!(dependentOperationResult.getResponse() instanceof ErrorResponse)) try { ScimResource dependentResource = dependentOperationResult.getData(); String dependentResourceId = dependentResource.getId(); @SuppressWarnings("unchecked") Class<ScimResource> dependentResourceClass = (Class<ScimResource>) dependentResource.getClass(); Repository<ScimResource> dependentResourceRepository = this.repositoryRegistry.getRepository(dependentResourceClass); dependentOperationResult.setData(null); dependentOperationResult.setLocation(null); createAndSetErrorResponse(dependentOperationResult, Status.CONFLICT, String.format(OPERATION_DEPENDS_ON_FAILED_OPERATION, bulkId, dependentBulkIdKey)); dependentResourceRepository.delete(dependentResourceId); } catch (ResourceException unableToDeleteResourceException) { log.error("Could not delete depenedent ScimResource after failing to update dependee", unableToDeleteResourceException); } } } /** * Based on the method requested by {@code operationResult}, invoke that * method. Fill {@code unresolveds} with unresolved bulkIds and complexes that * contain unresolved bulkIds. * * @param unresolveds * @param operationResult * @param bulkIdKeyToOperationResult * @param uriInfo * @throws UnableToCreateResourceException * @throws UnableToDeleteResourceException * @throws UnableToUpdateResourceException * @throws UnresolvableOperationException */ private void handleBulkOperationMethod(List<IWishJavaHadTuples> unresolveds, BulkOperation operationResult, Map<String, BulkOperation> bulkIdKeyToOperationResult, UriInfo uriInfo) throws ResourceException, UnresolvableOperationException { ScimResource scimResource = operationResult.getData(); Method bulkOperationMethod = operationResult.getMethod(); String bulkId = operationResult.getBulkId(); Class<ScimResource> scimResourceClass; if (scimResource == null) { String path = operationResult.getPath(); String endPoint = path.substring(0, path.lastIndexOf('/')); Class<ScimResource> clazz = (Class<ScimResource>) schemaRegistry.getScimResourceClassFromEndpoint(endPoint); scimResourceClass = clazz; } else { @SuppressWarnings("unchecked") Class<ScimResource> clazz = (Class<ScimResource>) scimResource.getClass(); scimResourceClass = clazz; } Repository<ScimResource> repository = repositoryRegistry.getRepository(scimResourceClass); switch (bulkOperationMethod) { case POST: { log.debug("POST: {}", scimResource); this.resolveTopLevel(unresolveds, operationResult, bulkIdKeyToOperationResult); log.debug("Creating {}", scimResource); ScimResource newScimResource = repository.create(scimResource); String bulkOperationPath = operationResult.getPath(); String newResourceId = newScimResource.getId(); String newResourceUri = uriInfo.getBaseUriBuilder() .path(bulkOperationPath) .path(newResourceId) .build() .toString(); if (bulkId != null) { String bulkIdKey = "bulkId:" + bulkId; log.debug("adding {} = {}", bulkIdKey, newResourceId); bulkIdKeyToOperationResult.get(bulkIdKey) .setData(newScimResource); } operationResult.setData(newScimResource); operationResult.setLocation(newResourceUri); operationResult.setPath(null); operationResult.setStatus(StatusWrapper.wrap(Status.CREATED)); } break; case DELETE: { log.debug("DELETE: {}", operationResult.getPath()); String scimResourceId = operationResult.getPath() .substring(operationResult.getPath() .lastIndexOf("/") + 1); repository.delete(scimResourceId); operationResult.setStatus(StatusWrapper.wrap(Status.NO_CONTENT)); } break; case PUT: { log.debug("PUT: {}", scimResource); this.resolveTopLevel(unresolveds, operationResult, bulkIdKeyToOperationResult); String id = operationResult.getPath() .substring(operationResult.getPath() .lastIndexOf("/") + 1); try { ScimResource original = repository.get(id); UpdateRequest<ScimResource> updateRequest = new UpdateRequest<>(id, original, scimResource, schemaRegistry); repository.update(updateRequest); operationResult.setStatus(StatusWrapper.wrap(Status.OK)); } catch (UnableToRetrieveResourceException e) { operationResult.setStatus(StatusWrapper.wrap(Status.NOT_FOUND)); } } break; default: { BulkOperation.Method method = operationResult.getMethod(); String detail = "Method not allowed: " + method; log.error("Received unallowed method: {}", method); createAndSetErrorResponse(operationResult, Status.METHOD_NOT_ALLOWED, detail); } break; } } private static void createAndSetErrorResponse(BulkOperation operationResult, int statusCode, String detail) { createAndSetErrorResponse(operationResult, Status.fromStatusCode(statusCode), detail); } private static void createAndSetErrorResponse(BulkOperation operationResult, Status status, String detail) { ErrorResponse error = new ErrorResponse(status, detail); operationResult.setResponse(error); operationResult.setStatus(new StatusWrapper(status)); operationResult.setPath(null); } @AllArgsConstructor private static class IWishJavaHadTuples { public final String bulkIdKey; public final List<UnresolvedTopLevel> unresolveds; public final BulkOperation bulkOperationResult; } private static class UnresolvableOperationException extends Exception { private static final long serialVersionUID = -6081994707016671935L; public UnresolvableOperationException(String message) { super(message); } } @AllArgsConstructor private static class UnresolvedComplex { private final Object object; private final Schema.AttributeAccessor accessor; private final String bulkIdKey; public void resolve(Map<String, BulkOperation> bulkIdKeyToOperationResult) throws UnresolvableOperationException { BulkOperation resolvedOperation = bulkIdKeyToOperationResult.get(this.bulkIdKey); BaseResource response = resolvedOperation.getResponse(); ScimResource resolvedResource = resolvedOperation.getData(); if ((response == null || !(response instanceof ErrorResponse)) && resolvedResource != null) { String resolvedId = resolvedResource.getId(); this.accessor.set(this.object, resolvedId); } else { throw new UnresolvableOperationException(String.format(BULK_ID_REFERS_TO_FAILED_RESOURCE, this.bulkIdKey)); } } } @AllArgsConstructor private static abstract class UnresolvedTopLevel { protected final Schema.AttributeAccessor accessor; public abstract void resolve(ScimResource scimResource, Map<String, BulkOperation> bulkIdKeyToOperationResult) throws UnresolvableOperationException; } private static class UnresolvedTopLevelBulkId extends UnresolvedTopLevel { private final String unresolvedBulkIdKey; public UnresolvedTopLevelBulkId(Schema.AttributeAccessor accessor, String bulkIdKey) { super(accessor); this.unresolvedBulkIdKey = bulkIdKey; } @Override public void resolve(ScimResource scimResource, Map<String, BulkOperation> bulkIdKeyToOperationResult) throws UnresolvableOperationException { BulkOperation resolvedOperationResult = bulkIdKeyToOperationResult.get(this.unresolvedBulkIdKey); BaseResource response = resolvedOperationResult.getResponse(); ScimResource resolvedResource = resolvedOperationResult.getData(); if ((response == null || !(response instanceof ErrorResponse)) && resolvedResource != null) { String resolvedId = resolvedResource.getId(); super.accessor.set(scimResource, resolvedId); } else { throw new UnresolvableOperationException("Bulk ID cannot be resolved because the resource it refers to had failed to be created: " + this.unresolvedBulkIdKey); } } } private static class UnresolvedTopLevelComplex extends UnresolvedTopLevel { public final Object complex; public final List<UnresolvedComplex> unresolveds; public UnresolvedTopLevelComplex(Schema.AttributeAccessor accessor, Object complex, List<UnresolvedComplex> unresolveds) { super(accessor); this.complex = complex; this.unresolveds = unresolveds; } @Override public void resolve(ScimResource scimResource, Map<String, BulkOperation> bulkIdKeyToOperationResult) throws UnresolvableOperationException { for (UnresolvedComplex unresolved : this.unresolveds) { unresolved.resolve(bulkIdKeyToOperationResult); } this.accessor.set(scimResource, this.complex); } } /** * Search through the subattribute {@code subAttributeValue} and fill * {@code unresolveds} with unresolved bulkIds. * * @param unresolveds * @param attributeValue * @param attribute * @param bulkIdKeyToOperationResult * @return * @throws UnresolvableOperationException */ private static List<UnresolvedComplex> resolveAttribute(List<UnresolvedComplex> unresolveds, Object attributeValue, Schema.Attribute attribute, Map<String, BulkOperation> bulkIdKeyToOperationResult) throws UnresolvableOperationException { if (attributeValue == null) { return unresolveds; } List<Schema.Attribute> attributes = attribute.getAttributes(); for (Schema.Attribute subAttribute : attributes) { Schema.AttributeAccessor accessor = subAttribute.getAccessor(); if (subAttribute.isScimResourceIdReference()) { // TODO - This will fail if field is a char or Character array String bulkIdKey = accessor.get(attributeValue); if (bulkIdKey != null && bulkIdKey.startsWith("bulkId:")) { log.debug("Found bulkId: {}", bulkIdKey); if (bulkIdKeyToOperationResult.containsKey(bulkIdKey)) { BulkOperation resolvedOperationResult = bulkIdKeyToOperationResult.get(bulkIdKey); BaseResource response = resolvedOperationResult.getResponse(); ScimResource resolvedResource = resolvedOperationResult.getData(); if ((response == null || !(response instanceof ErrorResponse)) && resolvedResource != null && resolvedResource.getId() != null) { String resolvedId = resolvedResource.getId(); accessor.set(attributeValue, resolvedId); } else { UnresolvedComplex unresolved = new UnresolvedComplex(attributeValue, accessor, bulkIdKey); unresolveds.add(unresolved); } } else { throw new UnresolvableOperationException(String.format(BULK_ID_DOES_NOT_EXIST, bulkIdKey)); } } } else if (subAttribute.getType() == Schema.Attribute.Type.COMPLEX) { Object subFieldValue = accessor.get(attributeValue); if (subFieldValue != null) { Class<?> subFieldClass = subFieldValue.getClass(); boolean isCollection = Collection.class.isAssignableFrom(subFieldClass); if (isCollection || subFieldClass.isArray()) { @SuppressWarnings("unchecked") Collection<Object> subFieldValues = isCollection ? (Collection<Object>) subFieldValue : Arrays.asList((Object[]) subFieldValue); for (Object subArrayFieldValue : subFieldValues) { resolveAttribute(unresolveds, subArrayFieldValue, subAttribute, bulkIdKeyToOperationResult); } } else { resolveAttribute(unresolveds, subFieldValue, subAttribute, bulkIdKeyToOperationResult); } } } } log.debug("Resolved attribute had {} unresolved fields", unresolveds.size()); return unresolveds; } /** * Attempt to resolve the bulkIds referenced inside of the * {@link ScimResource} contained inside of {@code bulkOperationResult}. Fill * {@code unresolveds} with bulkIds that could not be yet resolved. * * @param unresolveds * @param bulkOperationResult * @param bulkIdKeyToOperationResult * @throws UnresolvableOperationException */ private void resolveTopLevel(List<IWishJavaHadTuples> unresolveds, BulkOperation bulkOperationResult, Map<String, BulkOperation> bulkIdKeyToOperationResult) throws UnresolvableOperationException { ScimResource scimResource = bulkOperationResult.getData(); String schemaUrn = scimResource.getBaseUrn(); Schema schema = this.schemaRegistry.getSchema(schemaUrn); List<UnresolvedTopLevel> unresolvedTopLevels = new ArrayList<>(); for (Schema.Attribute attribute : schema.getAttributes()) { Schema.AttributeAccessor accessor = attribute.getAccessor(); if (attribute.isScimResourceIdReference()) { String bulkIdKey = accessor.get(scimResource); if (bulkIdKey != null && bulkIdKey.startsWith("bulkId:")) { if (bulkIdKeyToOperationResult.containsKey(bulkIdKey)) { BulkOperation resolvedOperationResult = bulkIdKeyToOperationResult.get(bulkIdKey); BaseResource response = resolvedOperationResult.getResponse(); ScimResource resolvedResource = resolvedOperationResult.getData(); if ((response == null || !(response instanceof ErrorResponse)) && resolvedResource != null) { String resolvedId = resolvedResource.getId(); accessor.set(scimResource, resolvedId); } else { UnresolvedTopLevel unresolved = new UnresolvedTopLevelBulkId(accessor, bulkIdKey); accessor.set(scimResource, null); unresolvedTopLevels.add(unresolved); } } else { throw new UnresolvableOperationException(String.format(BULK_ID_DOES_NOT_EXIST, bulkIdKey)); } } } else if (attribute.getType() == Schema.Attribute.Type.COMPLEX) { Object attributeFieldValue = accessor.get(scimResource); if (attributeFieldValue != null) { List<UnresolvedComplex> subUnresolveds = new ArrayList<>(); Class<?> subFieldClass = attributeFieldValue.getClass(); boolean isCollection = Collection.class.isAssignableFrom(subFieldClass); if (isCollection || subFieldClass.isArray()) { @SuppressWarnings("unchecked") Collection<Object> subFieldValues = isCollection ? (Collection<Object>) attributeFieldValue : Arrays.asList((Object[]) attributeFieldValue); for (Object subArrayFieldValue : subFieldValues) { resolveAttribute(subUnresolveds, subArrayFieldValue, attribute, bulkIdKeyToOperationResult); } } else { resolveAttribute(subUnresolveds, attributeFieldValue, attribute, bulkIdKeyToOperationResult); } if (subUnresolveds.size() > 0) { UnresolvedTopLevel unresolved = new UnresolvedTopLevelComplex(accessor, attributeFieldValue, subUnresolveds); accessor.set(scimResource, null); unresolvedTopLevels.add(unresolved); } } } } if (unresolvedTopLevels.size() > 0) { String bulkIdKey = "bulkId:" + bulkOperationResult.getBulkId(); unresolveds.add(new IWishJavaHadTuples(bulkIdKey, unresolvedTopLevels, bulkOperationResult)); } } /** * Traverse the provided dependency graph and fill {@code visited} with * visited bulkIds. * * @param visited * @param dependencyGraph * @param root * @param current */ private static void generateVisited(Set<String> visited, Map<String, Set<String>> dependencyGraph, String root, String current) { if (!root.equals(current) && !visited.contains(current)) { visited.add(current); Set<String> dependencies = dependencyGraph.getOrDefault(current, Collections.emptySet()); for (String dependency : dependencies) { generateVisited(visited, dependencyGraph, root, dependency); } } } /** * If A -> {B} and B -> {C} then A -> {B, C}. * * @param dependenciesGraph * @return */ private static Map<String, Set<String>> generateTransitiveDependenciesGraph(Map<String, Set<String>> dependenciesGraph) { Map<String, Set<String>> transitiveDependenciesGraph = new HashMap<>(); for (Map.Entry<String, Set<String>> entry : dependenciesGraph.entrySet()) { String root = entry.getKey(); Set<String> dependencies = entry.getValue(); Set<String> visited = new HashSet<>(); transitiveDependenciesGraph.put(root, visited); for (String dependency : dependencies) { generateVisited(visited, dependenciesGraph, root, dependency); } } return transitiveDependenciesGraph; } private static void generateReverseDependenciesGraph(Map<String, Set<String>> reverseDependenciesGraph, String dependentBulkId, Object scimObject, List<Schema.Attribute> scimObjectAttributes) { for (Schema.Attribute scimObjectAttribute : scimObjectAttributes) if (scimObjectAttribute.isScimResourceIdReference()) { String reference = scimObjectAttribute.getAccessor().get(scimObject); if (reference != null && reference.startsWith("bulkId:")) { Set<String> dependents = reverseDependenciesGraph.computeIfAbsent(reference, (unused) -> new HashSet<>()); dependents.add("bulkId:" + dependentBulkId); } } else if (scimObjectAttribute.isMultiValued()) { // all multiValueds // are COMPLEX, not // all COMPLEXES are // multiValued Object attributeObject = scimObjectAttribute.getAccessor().get(scimObject); if (attributeObject != null) { Class<?> attributeObjectClass = attributeObject.getClass(); boolean isCollection = Collection.class.isAssignableFrom(attributeObjectClass); Collection<?> attributeValues = isCollection ? (Collection<?>) attributeObject : List.of(attributeObject); List<Schema.Attribute> subAttributes = scimObjectAttribute.getAttributes(); for (Object attributeValue : attributeValues) { generateReverseDependenciesGraph(reverseDependenciesGraph, dependentBulkId, attributeValue, subAttributes); } } } else if (scimObjectAttribute.getType() == Schema.Attribute.Type.COMPLEX) { Object attributeValue = scimObjectAttribute.getAccessor().get(scimObject); List<Schema.Attribute> subAttributes = scimObjectAttribute.getAttributes(); generateReverseDependenciesGraph(reverseDependenciesGraph, dependentBulkId, attributeValue, subAttributes); } } /** * Finds the reverse dependencies of each {@link BulkOperation}. * * @param bulkOperations * @return */ private Map<String, Set<String>> generateReverseDependenciesGraph(List<BulkOperation> bulkOperations) { Map<String, Set<String>> reverseDependenciesGraph = new HashMap<>(); for (BulkOperation bulkOperation : bulkOperations) { String bulkId = bulkOperation.getBulkId(); if (bulkId != null) { ScimResource scimResource = bulkOperation.getData(); String scimResourceBaseUrn = scimResource.getBaseUrn(); Schema schema = this.schemaRegistry.getSchema(scimResourceBaseUrn); List<Schema.Attribute> attributes = schema.getAttributes(); generateReverseDependenciesGraph(reverseDependenciesGraph, bulkId, scimResource, attributes); } } return reverseDependenciesGraph; } }
4,408
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/UserResourceImpl.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.server.rest; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import lombok.extern.slf4j.Slf4j; import org.apache.directory.scim.core.repository.RepositoryRegistry; import org.apache.directory.scim.protocol.UserResource; import org.apache.directory.scim.spec.resources.ScimUser; import org.apache.directory.scim.core.schema.SchemaRegistry; /** * @author shawn * */ @Slf4j @ApplicationScoped public class UserResourceImpl extends BaseResourceTypeResourceImpl<ScimUser> implements UserResource { @Inject public UserResourceImpl(SchemaRegistry schemaRegistry, RepositoryRegistry repositoryRegistry, EtagGenerator etagGenerator) { super(schemaRegistry, repositoryRegistry, etagGenerator, ScimUser.class); } public UserResourceImpl() { // CDI this(null, null, null); } }
4,409
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/AttributeUtil.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.server.rest; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.directory.scim.core.json.ObjectMapperFactory; import org.apache.directory.scim.server.exception.AttributeDoesNotExistException; import org.apache.directory.scim.server.exception.AttributeException; import org.apache.directory.scim.spec.filter.attribute.AttributeReference; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimGroup; import org.apache.directory.scim.spec.resources.ScimResource; import org.apache.directory.scim.spec.resources.ScimUser; import org.apache.directory.scim.spec.schema.AttributeContainer; import org.apache.directory.scim.spec.schema.Schema; import org.apache.directory.scim.spec.schema.Schema.Attribute; import org.apache.directory.scim.spec.schema.Schema.Attribute.Returned; import org.apache.directory.scim.spec.schema.Schema.Attribute.Type; import org.apache.directory.scim.core.schema.SchemaRegistry; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.function.Function; @Slf4j class AttributeUtil { SchemaRegistry schemaRegistry; private final ObjectMapper objectMapper; AttributeUtil(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; this.objectMapper = ObjectMapperFactory.createObjectMapper(schemaRegistry); } public <T extends ScimResource> T keepAlwaysAttributesForDisplay(T resource) throws AttributeException { return setAttributesForDisplayInternal(resource, Returned.DEFAULT, Returned.REQUEST, Returned.NEVER); } public <T extends ScimResource> T setAttributesForDisplay(T resource) throws AttributeException { return setAttributesForDisplayInternal(resource, Returned.REQUEST, Returned.NEVER); } private <T extends ScimResource> T setAttributesForDisplayInternal(T resource, Returned ... removeAttributesOfTypes) throws AttributeException { T copy = cloneScimResource(resource); String resourceType = copy.getResourceType(); Schema schema = schemaRegistry.getBaseSchemaOfResourceType(resourceType); // return always and default, exclude never and requested for (Returned removeAttributesOfType : removeAttributesOfTypes) { removeAttributesOfType(copy, schema, removeAttributesOfType); } for (Entry<String, ScimExtension> extensionEntry : copy.getExtensions().entrySet()) { String extensionUrn = extensionEntry.getKey(); ScimExtension scimExtension = extensionEntry.getValue(); Schema extensionSchema = schemaRegistry.getSchema(extensionUrn); for (Returned removeAttributesOfType : removeAttributesOfTypes) { removeAttributesOfType(scimExtension, extensionSchema, removeAttributesOfType); } } return copy; } public <T extends ScimResource> T setAttributesForDisplay(T resource, Set<AttributeReference> attributes) throws AttributeException { if (attributes.isEmpty()) { return setAttributesForDisplay(resource); } else { T copy = cloneScimResource(resource); String resourceType = copy.getResourceType(); Schema schema = schemaRegistry.getBaseSchemaOfResourceType(resourceType); // return always and specified attributes, exclude never Set<Attribute> attributesToKeep = resolveAttributeReferences(attributes, true); Set<String> extensionsToRemove = new HashSet<>(); removeAttributesOfType(copy, schema, Returned.DEFAULT, attributesToKeep); removeAttributesOfType(copy, schema, Returned.REQUEST, attributesToKeep); removeAttributesOfType(copy, schema, Returned.NEVER); for (Entry<String, ScimExtension> extensionEntry : copy.getExtensions().entrySet()) { String extensionUrn = extensionEntry.getKey(); ScimExtension scimExtension = extensionEntry.getValue(); boolean removeExtension = true; for (Attribute attributeToKeep : attributesToKeep) { if (extensionUrn.equalsIgnoreCase(attributeToKeep.getUrn())) { removeExtension = false; break; } } if (removeExtension) { extensionsToRemove.add(extensionUrn); continue; } Schema extensionSchema = schemaRegistry.getSchema(extensionUrn); removeAttributesOfType(scimExtension, extensionSchema, Returned.DEFAULT, attributesToKeep); removeAttributesOfType(scimExtension, extensionSchema, Returned.REQUEST, attributesToKeep); removeAttributesOfType(scimExtension, extensionSchema, Returned.NEVER); } for (String extensionUrn : extensionsToRemove) { copy.removeExtension(extensionUrn); } return copy; } } public <T extends ScimResource> T setExcludedAttributesForDisplay(T resource, Set<AttributeReference> excludedAttributes) throws AttributeException { if (excludedAttributes.isEmpty()) { return setAttributesForDisplay(resource); } else { T copy = cloneScimResource(resource); String resourceType = copy.getResourceType(); Schema schema = schemaRegistry.getBaseSchemaOfResourceType(resourceType); // return always and default, exclude never and specified attributes Set<Attribute> attributesToRemove = resolveAttributeReferences(excludedAttributes, false); removeAttributesOfType(copy, schema, Returned.REQUEST); removeAttributesOfType(copy, schema, Returned.NEVER); removeAttributes(copy, schema, attributesToRemove); for (Entry<String, ScimExtension> extensionEntry : copy.getExtensions().entrySet()) { String extensionUrn = extensionEntry.getKey(); ScimExtension scimExtension = extensionEntry.getValue(); Schema extensionSchema = schemaRegistry.getSchema(extensionUrn); removeAttributesOfType(scimExtension, extensionSchema, Returned.REQUEST); removeAttributesOfType(scimExtension, extensionSchema, Returned.NEVER); removeAttributes(scimExtension, extensionSchema, attributesToRemove); } return copy; } } @SuppressWarnings("unchecked") private <T extends ScimResource> T cloneScimResource(T original) { return (T) this.objectMapper.convertValue(original, original.getClass()); } private void removeAttributesOfType(Object object, AttributeContainer attributeContainer, Returned returned) throws AttributeException { Function<Attribute, Boolean> function = (attribute) -> returned == attribute.getReturned(); processAttributes(object, attributeContainer, function); } private void removeAttributesOfType(Object object, AttributeContainer attributeContainer, Returned returned, Set<Attribute> attributesToKeep) throws AttributeException { Function<Attribute, Boolean> function = (attribute) -> !attributesToKeep.contains(attribute) && returned == attribute.getReturned(); processAttributes(object, attributeContainer, function); } private void removeAttributes(Object object, AttributeContainer attributeContainer, Set<Attribute> attributesToRemove) throws AttributeException { Function<Attribute, Boolean> function = (attribute) -> attributesToRemove.contains(attribute); processAttributes(object, attributeContainer, function); } private void processAttributes(Object object, AttributeContainer attributeContainer, Function<Attribute, Boolean> function) throws AttributeException { try { if (attributeContainer != null && object != null) { for (Attribute attribute : attributeContainer.getAttributes()) { Schema.AttributeAccessor accessor = attribute.getAccessor(); if (function.apply(attribute)) { if (!accessor.getType().isPrimitive()) { Object obj = accessor.get(object); if (obj == null) { continue; } log.info("field to be set to null = " + accessor.getType().getName()); accessor.set(object, null); } } else if (!attribute.isMultiValued() && attribute.getType() == Type.COMPLEX) { log.debug("### Processing single value complex field " + attribute.getName()); Object subObject = accessor.get(object); if (subObject == null) { continue; } Attribute subAttribute = attributeContainer.getAttribute(attribute.getName()); log.debug("### container type = " + attributeContainer.getClass().getName()); if (subAttribute == null) { log.debug("#### subattribute == null"); } processAttributes(subObject, subAttribute, function); } else if (attribute.isMultiValued() && attribute.getType() == Type.COMPLEX) { log.debug("### Processing multi-valued complex field " + attribute.getName()); Object subObject = accessor.get(object); if (subObject == null) { continue; } if (Collection.class.isAssignableFrom(subObject.getClass())) { Collection<?> collection = (Collection<?>) subObject; for (Object o : collection) { Attribute subAttribute = attributeContainer.getAttribute(attribute.getName()); processAttributes(o, subAttribute, function); } } else if (accessor.getType().isArray()) { Object[] array = (Object[]) subObject; for (Object o : array) { Attribute subAttribute = attributeContainer.getAttribute(attribute.getName()); processAttributes(o, subAttribute, function); } } } } } } catch (IllegalArgumentException e) { throw new AttributeException(e); } } public Set<AttributeReference> getAttributeReferences(String s) { Set<AttributeReference> attributeReferences = new HashSet<>(); String[] split = StringUtils.split(s, ","); for (String af : split) { AttributeReference attributeReference = new AttributeReference(af); attributeReferences.add(attributeReference); } return attributeReferences; } private Set<Attribute> resolveAttributeReferences(Set<AttributeReference> attributeReferences, boolean includeAttributeChain) throws AttributeDoesNotExistException { Set<Attribute> attributes = new HashSet<>(); for (AttributeReference attributeReference : attributeReferences) { Set<Attribute> findAttributes = findAttribute(attributeReference, includeAttributeChain); if (!findAttributes.isEmpty()) { attributes.addAll(findAttributes); } } return attributes; } private Set<Attribute> findAttribute(AttributeReference attributeReference, boolean includeAttributeChain) throws AttributeDoesNotExistException { String schemaUrn = attributeReference.getUrn(); Schema schema = null; Set<Attribute> attributes; if (!StringUtils.isEmpty(schemaUrn)) { schema = schemaRegistry.getSchema(schemaUrn); attributes = findAttributeInSchema(schema, attributeReference, includeAttributeChain); if (attributes.isEmpty()) { log.error("Attribute " + attributeReference.getFullyQualifiedAttributeName() + "not found in schema " + schemaUrn); throw new AttributeDoesNotExistException(attributeReference.getFullyQualifiedAttributeName()); } return attributes; } // Handle unqualified attributes, look in the core schemas schema = schemaRegistry.getSchema(ScimUser.SCHEMA_URI); attributes = findAttributeInSchema(schema, attributeReference, includeAttributeChain); if (!attributes.isEmpty()) { return attributes; } schema = schemaRegistry.getSchema(ScimGroup.SCHEMA_URI); attributes = findAttributeInSchema(schema, attributeReference, includeAttributeChain); if (!attributes.isEmpty()) { return attributes; } log.error("Attribute " + attributeReference.getFullyQualifiedAttributeName() + "not found in any schema."); throw new AttributeDoesNotExistException(attributeReference.getFullyQualifiedAttributeName()); } private Set<Attribute> findAttributeInSchema(Schema schema, AttributeReference attributeReference, boolean includeAttributeChain) { if (schema == null) { return Collections.emptySet(); } Set<Attribute> attributes = new HashSet<>(); String attributeName = attributeReference.getAttributeName(); String subAttributeName = attributeReference.getSubAttributeName(); Attribute attribute = schema.getAttribute(attributeName); if (attribute == null) { return Collections.emptySet(); } if (includeAttributeChain || subAttributeName == null) { attributes.add(attribute); } if (subAttributeName != null) { attribute = attribute.getAttribute(subAttributeName); if (attribute == null) { return Collections.emptySet(); } attributes.add(attribute); } if (attribute.getType() == Type.COMPLEX && includeAttributeChain) { List<Attribute> remaininAttributes = attribute.getAttributes(); attributes.addAll(remaininAttributes); } return attributes; } }
4,410
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/SearchResourceImpl.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.server.rest; import org.apache.directory.scim.protocol.SearchResource; public class SearchResourceImpl implements SearchResource { }
4,411
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/EtagGenerator.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.server.rest; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.enterprise.context.ApplicationScoped; import org.apache.directory.scim.core.json.ObjectMapperFactory; import org.apache.directory.scim.server.exception.EtagGenerationException; import org.apache.directory.scim.spec.resources.ScimResource; import org.apache.directory.scim.spec.schema.Meta; import jakarta.ws.rs.core.EntityTag; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; @ApplicationScoped public class EtagGenerator { private final ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(); public EntityTag generateEtag(ScimResource resource) throws EtagGenerationException { try { Meta meta = resource.getMeta(); if (meta == null) { meta = new Meta(); } resource.setMeta(null); String writeValueAsString = objectMapper.writeValueAsString(resource); EntityTag etag = hash(writeValueAsString); meta.setVersion(etag.getValue()); resource.setMeta(meta); return etag; } catch (JsonProcessingException | NoSuchAlgorithmException e) { throw new EtagGenerationException("Failed to generate etag for SCIM resource: " + resource.getId(), e); } } private static EntityTag hash(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(input.getBytes(StandardCharsets.UTF_8)); byte[] hash = digest.digest(); return new EntityTag(Base64.getEncoder().encodeToString(hash)); } }
4,412
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/GroupResourceImpl.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.server.rest; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import lombok.extern.slf4j.Slf4j; import org.apache.directory.scim.core.repository.RepositoryRegistry; import org.apache.directory.scim.protocol.GroupResource; import org.apache.directory.scim.spec.resources.ScimGroup; import org.apache.directory.scim.core.schema.SchemaRegistry; @Slf4j @ApplicationScoped public class GroupResourceImpl extends BaseResourceTypeResourceImpl<ScimGroup> implements GroupResource { @Inject public GroupResourceImpl(SchemaRegistry schemaRegistry, RepositoryRegistry repositoryRegistry, EtagGenerator etagGenerator) { super(schemaRegistry, repositoryRegistry, etagGenerator, ScimGroup.class); } public GroupResourceImpl() { // CDI this(null, null, null); } }
4,413
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/BaseResourceTypeResourceImpl.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.server.rest; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Function; import jakarta.enterprise.inject.spi.CDI; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.*; import jakarta.ws.rs.core.Response.ResponseBuilder; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.Response.Status.Family; import org.apache.directory.scim.protocol.exception.ScimException; import org.apache.directory.scim.server.exception.*; import org.apache.directory.scim.core.repository.RepositoryRegistry; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.spec.exception.ResourceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.core.repository.annotations.ScimProcessingExtension; import org.apache.directory.scim.core.repository.extensions.AttributeFilterExtension; import org.apache.directory.scim.core.repository.extensions.ProcessingExtension; import org.apache.directory.scim.spec.filter.attribute.ScimRequestContext; import org.apache.directory.scim.core.repository.extensions.ClientFilterException; import org.apache.directory.scim.protocol.adapter.FilterWrapper; import org.apache.directory.scim.protocol.BaseResourceTypeResource; 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.spec.filter.FilterResponse; 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.ScimResource; import lombok.extern.slf4j.Slf4j; @Slf4j public abstract class BaseResourceTypeResourceImpl<T extends ScimResource> implements BaseResourceTypeResource<T> { private static final Logger LOG = LoggerFactory.getLogger(BaseResourceTypeResourceImpl.class); private final SchemaRegistry schemaRegistry; private final RepositoryRegistry repositoryRegistry; private final AttributeUtil attributeUtil; private final EtagGenerator etagGenerator; private final Class<T> resourceClass; // TODO: Field injection of UriInfo, Request should work with all implementations // CDI can be used directly in Jakarta WS 4 @Context UriInfo uriInfo; @Context Request request; public BaseResourceTypeResourceImpl(SchemaRegistry schemaRegistry, RepositoryRegistry repositoryRegistry, EtagGenerator etagGenerator, Class<T> resourceClass) { this.schemaRegistry = schemaRegistry; this.repositoryRegistry = repositoryRegistry; this.etagGenerator = etagGenerator; this.resourceClass = resourceClass; this.attributeUtil = new AttributeUtil(schemaRegistry); } public Repository<T> getRepository() { return repositoryRegistry.getRepository(resourceClass); } Repository<T> getRepositoryInternal() throws ScimException { Repository<T> repository = getRepository(); if (repository == null) { throw new ScimException(Status.NOT_IMPLEMENTED, "Provider not defined"); } return repository; } @Override public Response getById(String id, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException { if (uriInfo.getQueryParameters().getFirst("filter") != null) { return Response.status(Status.FORBIDDEN).build(); } Repository<T> repository = getRepositoryInternal(); T resource = null; try { resource = repository.get(id); } catch (UnableToRetrieveResourceException e2) { Status status = Status.fromStatusCode(e2.getStatus()); if (status.getFamily().equals(Family.SERVER_ERROR)) { throw e2; } } if (resource != null) { EntityTag backingETag = requireEtag(resource); ResponseBuilder evaluatePreconditionsResponse = request.evaluatePreconditions(backingETag); if (evaluatePreconditionsResponse != null) { return Response.status(Status.NOT_MODIFIED).build(); } } Set<AttributeReference> attributeReferences = AttributeReferenceListWrapper.getAttributeReferences(attributes); Set<AttributeReference> excludedAttributeReferences = AttributeReferenceListWrapper.getAttributeReferences(excludedAttributes); validateAttributes(attributeReferences, excludedAttributeReferences); if (resource == null) { throw notFoundException(id); } EntityTag etag = requireEtag(resource); // Process Attributes resource = processFilterAttributeExtensions(repository, resource, attributeReferences, excludedAttributeReferences); resource = attributesForDisplayThrowOnError(resource, attributeReferences, excludedAttributeReferences); return Response.ok() .entity(resource) .location(buildLocationTag(resource)) .tag(etag) .build(); } @Override public Response query(AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes, FilterWrapper filter, AttributeReference sortBy, SortOrder sortOrder, Integer startIndex, Integer count) throws ScimException, ResourceException { SearchRequest searchRequest = new SearchRequest(); searchRequest.setAttributes(AttributeReferenceListWrapper.getAttributeReferences(attributes)); searchRequest.setExcludedAttributes(AttributeReferenceListWrapper.getAttributeReferences(excludedAttributes)); if (filter != null) { searchRequest.setFilter(filter.getFilter()); } else { searchRequest.setFilter(null); } searchRequest.setSortBy(sortBy); searchRequest.setSortOrder(sortOrder); searchRequest.setStartIndex(startIndex); searchRequest.setCount(count); return find(searchRequest); } @Override public Response create(T resource, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException { Repository<T> repository = getRepositoryInternal(); Set<AttributeReference> attributeReferences = AttributeReferenceListWrapper.getAttributeReferences(attributes); Set<AttributeReference> excludedAttributeReferences = AttributeReferenceListWrapper.getAttributeReferences(excludedAttributes); validateAttributes(attributeReferences, excludedAttributeReferences); T created = repository.create(resource); EntityTag etag = etag(created); // Process Attributes created = processFilterAttributeExtensions(repository, created, attributeReferences, excludedAttributeReferences); try { created = attributesForDisplay(created, attributeReferences, excludedAttributeReferences); } catch (AttributeException e) { log.debug("Exception thrown while processing attributes", e); return Response.status(Status.CREATED) .location(buildLocationTag(created)) .tag(etag) .build(); } return Response.status(Status.CREATED) .location(buildLocationTag(created)) .tag(etag) .entity(created) .build(); } @Override public Response find(SearchRequest request) throws ScimException, ResourceException { Repository<T> repository = getRepositoryInternal(); Set<AttributeReference> attributeReferences = Optional.ofNullable(request.getAttributes()) .orElse(Collections.emptySet()); Set<AttributeReference> excludedAttributeReferences = Optional.ofNullable(request.getExcludedAttributes()) .orElse(Collections.emptySet()); validateAttributes(attributeReferences, excludedAttributeReferences); Filter filter = request.getFilter(); PageRequest pageRequest = request.getPageRequest(); SortRequest sortRequest = request.getSortRequest(); ListResponse<T> listResponse = new ListResponse<>(); FilterResponse<T> filterResp = repository.find(filter, pageRequest, sortRequest); // If no resources are found, we should still return a ListResponse with // the totalResults set to 0; // (https://tools.ietf.org/html/rfc7644#section-3.4.2) if (filterResp == null || filterResp.getResources() == null || filterResp.getResources() .isEmpty()) { listResponse.setTotalResults(0); } else { log.debug("Find returned " + filterResp.getResources() .size()); listResponse.setItemsPerPage(filterResp.getResources() .size()); int startIndex = Optional.ofNullable(filterResp.getPageRequest().getStartIndex()).orElse(1); listResponse.setStartIndex(startIndex); listResponse.setTotalResults(filterResp.getTotalResults()); List<T> results = new ArrayList<>(); for (T resource : filterResp.getResources()) { requireEtag(resource); // Process Attributes resource = processFilterAttributeExtensions(repository, resource, attributeReferences, excludedAttributeReferences); resource = attributesForDisplayThrowOnError(resource, attributeReferences, excludedAttributeReferences); results.add(resource); } listResponse.setResources(results); } return Response.ok() .entity(listResponse) .build(); } @Override public Response update(T resource, String id, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException { return update(id, attributes, excludedAttributes, (stored) -> new UpdateRequest<>(id, stored, resource, schemaRegistry)); } @Override public Response patch(PatchRequest patchRequest, String id, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes) throws ScimException, ResourceException { return update(id, attributes, excludedAttributes, (stored) -> new UpdateRequest<>(id, stored, patchRequest.getPatchOperationList(), schemaRegistry)); } @Override public Response delete(String id) throws ScimException, ResourceException { Repository<T> repository = getRepositoryInternal(); repository.delete(id); return Response.noContent() .build(); } private Response update(String id, AttributeReferenceListWrapper attributes, AttributeReferenceListWrapper excludedAttributes, Function<T, UpdateRequest<T>> updateRequestFunction) throws ScimException, ResourceException { Repository<T> repository = getRepositoryInternal(); Set<AttributeReference> attributeReferences = AttributeReferenceListWrapper.getAttributeReferences(attributes); Set<AttributeReference> excludedAttributeReferences = AttributeReferenceListWrapper.getAttributeReferences(excludedAttributes); validateAttributes(attributeReferences, excludedAttributeReferences); T stored = repository.get(id); if (stored == null) { throw notFoundException(id); } EntityTag backingETag = requireEtag(stored); validatePreconditions(id, backingETag); UpdateRequest<T> updateRequest = updateRequestFunction.apply(stored); T updated = repository.update(updateRequest); // Process Attributes updated = processFilterAttributeExtensions(repository, updated, attributeReferences, excludedAttributeReferences); updated = attributesForDisplayIgnoreErrors(updated, attributeReferences, excludedAttributeReferences); EntityTag etag = etag(updated); return Response.ok(updated) .location(buildLocationTag(updated)) .tag(etag) .build(); } @SuppressWarnings("unchecked") private T processFilterAttributeExtensions(Repository<T> repository, T resource, Set<AttributeReference> attributeReferences, Set<AttributeReference> excludedAttributeReferences) throws ScimException { ScimProcessingExtension annotation = repository.getClass() .getAnnotation(ScimProcessingExtension.class); if (annotation != null) { Class<? extends ProcessingExtension>[] value = annotation.value(); for (Class<? extends ProcessingExtension> class1 : value) { ProcessingExtension processingExtension = CDI.current().select(class1).get(); if (processingExtension instanceof AttributeFilterExtension) { AttributeFilterExtension attributeFilterExtension = (AttributeFilterExtension) processingExtension; ScimRequestContext scimRequestContext = new ScimRequestContext(attributeReferences, excludedAttributeReferences); try { resource = (T) attributeFilterExtension.filterAttributes(resource, scimRequestContext); log.debug("Resource now - " + resource.toString()); } catch (ClientFilterException e) { throw new ScimException(Status.fromStatusCode(e.getStatus()), e.getMessage(), e); } } } } return resource; } private URI buildLocationTag(T resource) { String id = resource.getId(); if (id == null) { LOG.warn("Repository must supply an id for a resource"); id = "unknown"; } return uriInfo.getAbsolutePathBuilder() .path(id) .build(); } private <T extends ScimResource> T attributesForDisplay(T resource, Set<AttributeReference> includedAttributes, Set<AttributeReference> excludedAttributes) throws AttributeException { if (!excludedAttributes.isEmpty()) { resource = attributeUtil.setExcludedAttributesForDisplay(resource, excludedAttributes); } else { resource = attributeUtil.setAttributesForDisplay(resource, includedAttributes); } return resource; } private T attributesForDisplayIgnoreErrors(T resource, Set<AttributeReference> includedAttributes, Set<AttributeReference> excludedAttributes) { try { return attributesForDisplay(resource, includedAttributes, excludedAttributes); } catch (AttributeException e) { if (log.isDebugEnabled()) { log.debug("Failed to handle attribute processing in update " + e.getMessage(), e); } else { log.warn("Failed to handle attribute processing in update " + e.getMessage()); } } return resource; } private T attributesForDisplayThrowOnError(T resource, Set<AttributeReference> includedAttributes, Set<AttributeReference> excludedAttributes) throws ScimException { try { return attributesForDisplay(resource, includedAttributes, excludedAttributes); } catch (AttributeException e) { throw new ScimException(Status.INTERNAL_SERVER_ERROR, "Failed to parse the attribute query value " + e.getMessage(), e); } } private ScimException notFoundException(String id) { return new ScimException(Status.NOT_FOUND, "Resource " + id + " not found"); } private void validatePreconditions(String id, EntityTag etag) { ResponseBuilder response = request.evaluatePreconditions(etag); if (response != null) { throw new WebApplicationException(response .entity(new ErrorResponse(Status.PRECONDITION_FAILED, "Failed to update record, backing record has changed - " + id)) .build()); } } private EntityTag requireEtag(ScimResource resource) throws ScimException { try { return etagGenerator.generateEtag(resource); } catch (EtagGenerationException e) { throw new ScimException(Status.INTERNAL_SERVER_ERROR, "Failed to generate the etag", e); } } private EntityTag etag(ScimResource resource) { try { return etagGenerator.generateEtag(resource); } catch (EtagGenerationException e) { log.warn("Failed to generate etag for resource", e); return null; } } private void validateAttributes(Set<AttributeReference> attributeReferences, Set<AttributeReference> excludedAttributeReferences) throws ScimException { if (!attributeReferences.isEmpty() && !excludedAttributeReferences.isEmpty()) { throw new ScimException(Status.BAD_REQUEST, "Cannot include both attributes and excluded attributes in a single request"); } } }
4,414
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/ScimJacksonXmlBindJsonProvider.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.server.rest; import com.fasterxml.jackson.jakarta.rs.json.JacksonXmlBindJsonProvider; import jakarta.enterprise.context.ApplicationScoped; import org.apache.directory.scim.core.json.ObjectMapperFactory; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.protocol.Constants; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.Produces; import jakarta.ws.rs.ext.Provider; /** * Adds JacksonJaxbJsonProvider for custom MediaType {@code application/scim+json}. */ @Provider @Consumes(Constants.SCIM_CONTENT_TYPE) @Produces(Constants.SCIM_CONTENT_TYPE) @ApplicationScoped public class ScimJacksonXmlBindJsonProvider extends JacksonXmlBindJsonProvider { public ScimJacksonXmlBindJsonProvider() { // CDI } @Inject public ScimJacksonXmlBindJsonProvider(SchemaRegistry schemaRegistry) { super(ObjectMapperFactory.createObjectMapper(schemaRegistry), DEFAULT_ANNOTATIONS); } }
4,415
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/ScimpleFeature.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.server.rest; import jakarta.ws.rs.core.Feature; import jakarta.ws.rs.core.FeatureContext; import jakarta.ws.rs.ext.Provider; import java.util.Collection; import java.util.stream.Stream; import static org.apache.directory.scim.server.rest.ScimResourceHelper.*; @Provider public class ScimpleFeature implements Feature { @Override public boolean configure(FeatureContext context) { Stream.of(EXCEPTION_MAPPER_CLASSES, MEDIA_TYPE_SUPPORT_CLASSES) .flatMap(Collection::stream) .forEach(context::register); return true; } }
4,416
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/ServiceProviderConfigResourceImpl.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.server.rest; import java.time.LocalDateTime; import java.util.List; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.EntityTag; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; import jakarta.ws.rs.core.Response.Status; import org.apache.directory.scim.server.configuration.ServerConfiguration; import org.apache.directory.scim.protocol.ServiceProviderConfigResource; import org.apache.directory.scim.protocol.data.ErrorResponse; import org.apache.directory.scim.server.exception.EtagGenerationException; import org.apache.directory.scim.spec.schema.Meta; import org.apache.directory.scim.spec.schema.ServiceProviderConfiguration; import org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.AuthenticationSchema; import org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.BulkConfiguration; import org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.FilterConfiguration; import org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.SupportedConfiguration; @ApplicationScoped public class ServiceProviderConfigResourceImpl implements ServiceProviderConfigResource { private final ServerConfiguration serverConfiguration; private final EtagGenerator etagGenerator; @Inject public ServiceProviderConfigResourceImpl(ServerConfiguration serverConfiguration, EtagGenerator etagGenerator) { this.serverConfiguration = serverConfiguration; this.etagGenerator = etagGenerator; } public ServiceProviderConfigResourceImpl() { // CDI this(null, null); } @Override public Response getServiceProviderConfiguration(UriInfo uriInfo) { ServiceProviderConfiguration serviceProviderConfiguration = new ServiceProviderConfiguration(); List<AuthenticationSchema> authenticationSchemas = serverConfiguration.getAuthenticationSchemas(); BulkConfiguration bulk = serverConfiguration.getBulkConfiguration(); SupportedConfiguration changePassword = serverConfiguration.getChangePasswordConfiguration(); SupportedConfiguration etagConfig = serverConfiguration.getEtagConfiguration(); FilterConfiguration filter = serverConfiguration.getFilterConfiguration(); SupportedConfiguration patch = serverConfiguration.getPatchConfiguration(); SupportedConfiguration sort = serverConfiguration.getSortConfiguration(); String documentationUrl = serverConfiguration.getDocumentationUri(); String externalId = serverConfiguration.getId(); String id = serverConfiguration.getId(); Meta meta = new Meta(); String location = uriInfo.getAbsolutePath().toString(); String resourceType = "ServiceProviderConfig"; LocalDateTime now = LocalDateTime.now(); meta.setCreated(now); meta.setLastModified(now); meta.setLocation(location); meta.setResourceType(resourceType); serviceProviderConfiguration.setAuthenticationSchemes(authenticationSchemas); serviceProviderConfiguration.setBulk(bulk); serviceProviderConfiguration.setChangePassword(changePassword); serviceProviderConfiguration.setDocumentationUrl(documentationUrl); serviceProviderConfiguration.setEtag(etagConfig); serviceProviderConfiguration.setExternalId(externalId); serviceProviderConfiguration.setFilter(filter); serviceProviderConfiguration.setId(id); serviceProviderConfiguration.setMeta(meta); serviceProviderConfiguration.setPatch(patch); serviceProviderConfiguration.setSort(sort); try { EntityTag etag = etagGenerator.generateEtag(serviceProviderConfiguration); return Response.ok(serviceProviderConfiguration).tag(etag).build(); } catch (EtagGenerationException e) { return createETagErrorResponse(); } } private Response createETagErrorResponse() { ErrorResponse er = new ErrorResponse(Status.INTERNAL_SERVER_ERROR, "Failed to generate the etag"); return er.toResponse(); } }
4,417
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/rest/ResourceTypesResourceImpl.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.server.rest; import java.util.ArrayList; import java.util.Collection; import java.util.List; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.*; import jakarta.ws.rs.core.Response.Status; import org.apache.directory.scim.protocol.ResourceTypesResource; import org.apache.directory.scim.protocol.data.ListResponse; import org.apache.directory.scim.spec.schema.Meta; import org.apache.directory.scim.spec.schema.ResourceType; import org.apache.directory.scim.core.schema.SchemaRegistry; @ApplicationScoped public class ResourceTypesResourceImpl implements ResourceTypesResource { private final SchemaRegistry schemaRegistry; // TODO: Field injection of UriInfo should work with all implementations // CDI can be used directly in Jakarta WS 4 @Context UriInfo uriInfo; @Inject public ResourceTypesResourceImpl(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } public ResourceTypesResourceImpl() { // CDI this(null); } @Override public Response getAllResourceTypes(String filter) { if (filter != null) { return Response.status(Status.FORBIDDEN).build(); } Collection<ResourceType> resourceTypes = schemaRegistry.getAllResourceTypes(); for (ResourceType resourceType : resourceTypes) { Meta meta = new Meta(); meta.setLocation(uriInfo.getAbsolutePathBuilder().path(resourceType.getName()).build().toString()); meta.setResourceType(resourceType.getResourceType()); resourceType.setMeta(meta); } ListResponse<ResourceType> listResponse = new ListResponse<>(); listResponse.setItemsPerPage(resourceTypes.size()); listResponse.setStartIndex(1); listResponse.setTotalResults(resourceTypes.size()); List<ResourceType> objectList = new ArrayList<>(resourceTypes); listResponse.setResources(objectList); return Response.ok(listResponse).build(); } @Override public Response getResourceType(String name) { ResourceType resourceType = schemaRegistry.getResourceType(name); if (resourceType == null){ return Response.status(Status.NOT_FOUND).build(); } Meta meta = new Meta(); meta.setLocation(uriInfo.getAbsolutePath().toString()); meta.setResourceType(resourceType.getResourceType()); resourceType.setMeta(meta); return Response.ok(resourceType).build(); } }
4,418
0
Create_ds/commons-ognl/src/test/java/org/apache/commons
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/TestOgnlException.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.commons.ognl; import org.junit.Test; import static junit.framework.Assert.assertTrue; /** * Tests {@link OgnlException}. */ public class TestOgnlException { @Test public void test_Throwable_Reason() { try { throwException(); } catch ( OgnlException e ) { assertTrue( NumberFormatException.class.isInstance( e.getReason() ) ); } } void throwException() throws OgnlException { try { Integer.parseInt( "45ac" ); } catch ( NumberFormatException et ) { throw new OgnlException( "Unable to parse input string.", et ); } } }
4,419
0
Create_ds/commons-ognl/src/test/java/org/apache/commons
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/InExpressionTest.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.commons.ognl; import static junit.framework.Assert.assertEquals; import org.junit.Test; /** * Test for OGNL-118. */ public class InExpressionTest { @Test public void test_String_In() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); Object node = Ognl.parseExpression( "#name in {\"Greenland\", \"Austin\", \"Africa\", \"Rome\"}" ); Object root = null; context.put( "name", "Austin" ); assertEquals( Boolean.TRUE, Ognl.getValue( node, context, root ) ); } }
4,420
0
Create_ds/commons-ognl/src/test/java/org/apache/commons
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/TestOgnlRuntime.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.commons.ognl; import org.apache.commons.ognl.enhance.OgnlExpressionCompiler; import org.apache.commons.ognl.internal.CacheException; import org.apache.commons.ognl.test.objects.BaseGeneric; import org.apache.commons.ognl.test.objects.Bean1; import org.apache.commons.ognl.test.objects.Bean2; import org.apache.commons.ognl.test.objects.FormImpl; import org.apache.commons.ognl.test.objects.GameGeneric; import org.apache.commons.ognl.test.objects.GameGenericObject; import org.apache.commons.ognl.test.objects.GenericCracker; import org.apache.commons.ognl.test.objects.GenericService; import org.apache.commons.ognl.test.objects.GenericServiceImpl; import org.apache.commons.ognl.test.objects.GetterMethods; import org.apache.commons.ognl.test.objects.IComponent; import org.apache.commons.ognl.test.objects.IForm; import org.apache.commons.ognl.test.objects.ListSource; import org.apache.commons.ognl.test.objects.ListSourceImpl; import org.apache.commons.ognl.test.objects.OtherObjectIndexed; import org.apache.commons.ognl.test.objects.Root; import org.apache.commons.ognl.test.objects.SetterReturns; import org.apache.commons.ognl.test.objects.SubclassSyntheticObject; import org.junit.Test; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import static junit.framework.Assert.*; /** * Tests various methods / functionality of {@link org.apache.commons.ognl.OgnlRuntime}. */ public class TestOgnlRuntime { @Test public void test_Get_Super_Or_Interface_Class() throws Exception { ListSource list = new ListSourceImpl(); Method method = OgnlRuntime.getReadMethod( list.getClass(), "total" ); assertNotNull( method ); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); assertEquals( ListSource.class, OgnlRuntime.getCompiler( context ).getSuperOrInterfaceClass( method, list.getClass() ) ); } @Test public void test_Get_Private_Class() throws Exception { List<String> list = Arrays.asList( "hello", "world" ); Method m = OgnlRuntime.getReadMethod( list.getClass(), "iterator" ); assertNotNull( m ); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); assertEquals( Iterable.class, OgnlRuntime.getCompiler( context ).getSuperOrInterfaceClass( m, list.getClass() ) ); } @Test public void test_Complicated_Inheritance() throws Exception { IForm form = new FormImpl(); Method method = OgnlRuntime.getWriteMethod( form.getClass(), "clientId" ); assertNotNull( method ); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); assertEquals( IComponent.class, OgnlRuntime.getCompiler( context ).getSuperOrInterfaceClass( method, form.getClass() ) ); } @Test public void test_Get_Read_Method() throws Exception { Method method = OgnlRuntime.getReadMethod( Bean2.class, "pageBreakAfter" ); assertNotNull( method ); assertEquals( "isPageBreakAfter", method.getName() ); } class TestGetters { public boolean isEditorDisabled() { return false; } public boolean isDisabled() { return true; } public boolean isNotAvailable() { return false; } public boolean isAvailable() { return true; } } @Test public void test_Get_Read_Method_Multiple() throws Exception { Method method = OgnlRuntime.getReadMethod( TestGetters.class, "disabled" ); assertNotNull( method ); assertEquals( "isDisabled", method.getName() ); } @Test public void test_Get_Read_Method_Multiple_Boolean_Getters() throws Exception { Method method = OgnlRuntime.getReadMethod( TestGetters.class, "available" ); assertNotNull( method ); assertEquals( "isAvailable", method.getName() ); method = OgnlRuntime.getReadMethod( TestGetters.class, "notAvailable" ); assertNotNull( method ); assertEquals( "isNotAvailable", method.getName() ); } @Test public void test_Find_Method_Mixed_Boolean_Getters() throws Exception { Method method = OgnlRuntime.getReadMethod( GetterMethods.class, "allowDisplay" ); assertNotNull( method ); assertEquals( "getAllowDisplay", method.getName() ); } @Test public void test_Get_Appropriate_Method() throws Exception { ListSource list = new ListSourceImpl(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); Object ret = OgnlRuntime.callMethod( context, list, "addValue", new String[]{ null } ); assert ret != null; } @Test public void test_Call_Static_Method_Invalid_Class() { try { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); OgnlRuntime.callStaticMethod( context, "made.up.Name", "foo", null ); fail( "ClassNotFoundException should have been thrown by previous reference to <made.up.Name> class." ); } catch ( Exception et ) { assertTrue( MethodFailedException.class.isInstance( et ) ); assertTrue( et.getMessage().contains( "made.up.Name" ) ); } } @Test public void test_Setter_Returns() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); SetterReturns root = new SetterReturns(); Method m = OgnlRuntime.getWriteMethod( root.getClass(), "value" ); assertNotNull(m); Ognl.setValue( "value", context, root, "12__" ); assertEquals( Ognl.getValue( "value", context, root ), "12__" ); } @Test public void test_Call_Method_VarArgs() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); GenericService service = new GenericServiceImpl(); GameGenericObject argument = new GameGenericObject(); Object[] args = new Object[2]; args[0] = argument; assertEquals( "Halo 3", OgnlRuntime.callMethod( context, service, "getFullMessageFor", args ) ); } @Test public void test_Class_Cache_Inspector() throws Exception { OgnlRuntime.cache.clear(); assertEquals( 0, OgnlRuntime.cache.propertyDescriptorCache.getSize() ); Root root = new Root(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); Node expr = Ognl.compileExpression( context, root, "property.bean3.value != null" ); assertTrue( (Boolean) expr.getAccessor().get( context, root ) ); int size = OgnlRuntime.cache.propertyDescriptorCache.getSize(); assertTrue( size > 0 ); OgnlRuntime.clearCache(); assertEquals( 0, OgnlRuntime.cache.propertyDescriptorCache.getSize() ); // now register class cache prevention OgnlRuntime.setClassCacheInspector( new TestCacheInspector() ); expr = Ognl.compileExpression( context, root, "property.bean3.value != null" ); assertTrue( (Boolean) expr.getAccessor().get( context, root ) ); assertEquals( ( size - 1 ), OgnlRuntime.cache.propertyDescriptorCache.getSize() ); } class TestCacheInspector implements ClassCacheInspector { public boolean shouldCache( Class<?> type ) { return !( type == null || type == Root.class ); } } @Test public void test_Set_Generic_Parameter_Types() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); Method method = OgnlRuntime.getSetMethod( context, GenericCracker.class, "param" ); assertNotNull( method ); Class<?>[] types = method.getParameterTypes(); assertEquals( 1, types.length ); assertEquals( Integer.class, types[0] ); } @Test public void test_Get_Generic_Parameter_Types() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); Method method = OgnlRuntime.getGetMethod( context, GenericCracker.class, "param" ); assertNotNull( method ); assertEquals( Integer.class, method.getReturnType() ); } @Test public void test_Find_Parameter_Types() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); Method method = OgnlRuntime.getSetMethod( context, GameGeneric.class, "ids" ); assertNotNull( method ); Class<?>[] types = OgnlRuntime.findParameterTypes( GameGeneric.class, method ); assertEquals( 1, types.length ); assertEquals( Long[].class, types[0] ); } @Test public void test_Find_Parameter_Types_Superclass() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); Method method = OgnlRuntime.getSetMethod( context, BaseGeneric.class, "ids" ); assertNotNull( method ); Class<?>[] types = OgnlRuntime.findParameterTypes( BaseGeneric.class, method ); assertEquals( 1, types.length ); assertEquals( Serializable[].class, types[0] ); } @Test public void test_Get_Declared_Methods_With_Synthetic_Methods() throws Exception { List<Method> result = OgnlRuntime.getDeclaredMethods( SubclassSyntheticObject.class, "list", false ); // synthetic method would be // "public volatile java.util.List org.ognl.test.objects.SubclassSyntheticObject.getList()", // causing method return size to be 3 assertEquals( 2, result.size() ); } @Test public void test_Get_Property_Descriptors_With_Synthetic_Methods() throws Exception { PropertyDescriptor propertyDescriptor = OgnlRuntime.getPropertyDescriptor( SubclassSyntheticObject.class, "list" ); assert propertyDescriptor != null; assert OgnlRuntime.isMethodCallable( propertyDescriptor.getReadMethod() ); } private static class GenericParent<T> { @SuppressWarnings( "unused" ) public void save( T entity ) { } } private static class StringChild extends GenericParent<String> { } private static class LongChild extends GenericParent<Long> { } /** * Tests OGNL parameter discovery. */ @Test public void testOGNLParameterDiscovery() throws NoSuchMethodException, CacheException { Method saveMethod = GenericParent.class.getMethod( "save", Object.class ); System.out.println( saveMethod ); Class<?>[] longClass = OgnlRuntime.findParameterTypes( LongChild.class, saveMethod ); assertNotSame( longClass[0], String.class ); assertSame( longClass[0], Long.class ); Class<?>[] stringClass = OgnlRuntime.findParameterTypes( StringChild.class, saveMethod ); assertNotSame( "The cached parameter types from previous calls are used", stringClass[0], Long.class ); assertSame( stringClass[0], String.class ); } @Test public void testGetField() throws OgnlException { Field field = OgnlRuntime.getField( OtherObjectIndexed.class, "attributes" ); assertNotNull( "Field is null", field ); } @Test public void testGetSetMethod() throws IntrospectionException, OgnlException { Method setter = OgnlRuntime.getSetMethod( null, Bean1.class, "bean2" ); Method getter = OgnlRuntime.getGetMethod( null, Bean1.class, "bean2" ); assertNotNull( getter ); assertNull( setter ); } @Test public void testGetCompiler() { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); OgnlExpressionCompiler compiler1 = OgnlRuntime.getCompiler( context ); context.put( "root2", new Root() ); OgnlExpressionCompiler compiler2 = OgnlRuntime.getCompiler( context ); assertSame( "compilers are not the same", compiler1, compiler2 ); } @Test public void testGetPropertyDescriptorFromArray() throws Exception { PropertyDescriptor propertyDescriptor = OgnlRuntime.getPropertyDescriptorFromArray( Root.class, "disabled" ); assertEquals( "disabled", propertyDescriptor.getName() ); } }
4,421
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/CollectionDirectPropertyTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.apache.commons.ognl.test.objects.Root; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class CollectionDirectPropertyTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final Object[][] TESTS = { // Collection direct properties { Arrays.asList( "hello", "world" ), "size", 2 }, { Arrays.asList( "hello", "world" ), "isEmpty", Boolean.FALSE }, { Arrays.asList(), "isEmpty", Boolean.TRUE }, { Arrays.asList( "hello", "world" ), "iterator.next", "hello" }, { Arrays.asList( "hello", "world" ), "iterator.hasNext", Boolean.TRUE }, { Arrays.asList( "hello", "world" ), "#it = iterator, #it.next, #it.next, #it.hasNext", Boolean.FALSE }, { Arrays.asList( "hello", "world" ), "#it = iterator, #it.next, #it.next", "world" }, { Arrays.asList( "hello", "world" ), "size", 2 }, { ROOT, "map[\"test\"]", ROOT }, { ROOT, "map.size", ROOT.getMap().size() }, { ROOT, "map.keySet", ROOT.getMap().keySet() }, { ROOT, "map.values", ROOT.getMap().values() }, { ROOT, "map.keys.size", ROOT.getMap().size() }, { ROOT, "map[\"size\"]", ROOT.getMap().get( "size" ) }, { ROOT, "map.isEmpty", ROOT.getMap().isEmpty() ? Boolean.TRUE : Boolean.FALSE }, { ROOT, "map[\"isEmpty\"]", null }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for ( Object[] TEST : TESTS ) { Object[] tmp = new Object[6]; tmp[0] = TEST[1]; tmp[1] = TEST[0]; tmp[2] = TEST[1]; switch ( TEST.length ) { case 3: tmp[3] = TEST[2]; break; case 4: tmp[3] = TEST[2]; tmp[4] = TEST[3]; break; case 5: tmp[3] = TEST[2]; tmp[4] = TEST[3]; tmp[5] = TEST[4]; break; default: fail( "don't understand TEST format with length" ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public CollectionDirectPropertyTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,422
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/StaticsAndConstructorsTest.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.commons.ognl.test; import org.apache.commons.ognl.test.objects.Root; import org.apache.commons.ognl.test.objects.Simple; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Collection; @RunWith(value = Parameterized.class) public class StaticsAndConstructorsTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final Object[][] TESTS = { { "@java.lang.Class@forName(\"java.lang.Object\")", Object.class }, { "@java.lang.Integer@MAX_VALUE", Integer.MAX_VALUE }, { "@@max(3,4)", 4 }, { "new java.lang.StringBuilder().append(55).toString()", "55" }, { "class", ROOT.getClass() }, { "@org.apache.commons.ognl.test.objects.Root@class", ROOT.getClass() }, { "class.getName()", ROOT.getClass().getName() }, { "@org.apache.commons.ognl.test.objects.Root@class.getName()", ROOT.getClass().getName() }, { "@org.apache.commons.ognl.test.objects.Root@class.name", ROOT.getClass().getName() }, { "class.getSuperclass()", ROOT.getClass().getSuperclass() }, { "class.superclass", ROOT.getClass().getSuperclass() }, { "class.name", ROOT.getClass().getName() }, { "getStaticInt()", Root.getStaticInt() }, { "@org.apache.commons.ognl.test.objects.Root@getStaticInt()", Root.getStaticInt() }, { "new org.apache.commons.ognl.test.objects.Simple(property).getStringValue()", new Simple().getStringValue() }, { "new org.apache.commons.ognl.test.objects.Simple(map['test'].property).getStringValue()", new Simple().getStringValue() }, { "map.test.getCurrentClass(@org.apache.commons.ognl.test.StaticsAndConstructorsTest@KEY.toString())", "size stop" }, { "new org.apache.commons.ognl.test.StaticsAndConstructorsTest$IntWrapper(index)", new IntWrapper( ROOT.getIndex() ) }, { "new org.apache.commons.ognl.test.StaticsAndConstructorsTest$IntObjectWrapper(index)", new IntObjectWrapper( ROOT.getIndex() ) }, { "new org.apache.commons.ognl.test.StaticsAndConstructorsTest$A(#root)", new A( ROOT ) }, { "@org.apache.commons.ognl.test.StaticsAndConstructorsTest$Animals@values().length != 2", Boolean.TRUE }, { "isOk(@org.apache.commons.ognl.test.objects.SimpleEnum@ONE, null)", Boolean.TRUE }, }; public static final String KEY = "size"; public static class IntWrapper { public IntWrapper( int value ) { this.value = value; } private final int value; public String toString() { return Integer.toString( value ); } public boolean equals( Object o ) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; IntWrapper that = (IntWrapper) o; return value == that.value; } } public static class IntObjectWrapper { public IntObjectWrapper( Integer value ) { this.value = value; } private final Integer value; public String toString() { return value.toString(); } public boolean equals( Object o ) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; IntObjectWrapper that = (IntObjectWrapper) o; return value.equals( that.value ); } } public static class A { String key = "A"; public A( Root root ) { } public boolean equals( Object o ) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; A a = (A) o; return !( key != null ? !key.equals( a.key ) : a.key != null ); } } public enum Animals { Dog, Cat, Wallabee, Bear } /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for ( Object[] TEST : TESTS ) { Object[] tmp = new Object[6]; tmp[0] = TEST[0] + " (" + TEST[1] + ")"; tmp[1] = ROOT; tmp[2] = TEST[0]; tmp[3] = TEST[1]; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public StaticsAndConstructorsTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } @Test @Override public void runTest() throws Exception { super.runTest(); } }
4,423
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/InheritedMethodsTest.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.commons.ognl.test; import junit.framework.TestCase; import org.apache.commons.ognl.Node; import org.apache.commons.ognl.Ognl; import org.apache.commons.ognl.OgnlContext; import org.apache.commons.ognl.test.objects.BaseBean; import org.apache.commons.ognl.test.objects.FirstBean; import org.apache.commons.ognl.test.objects.Root; import org.apache.commons.ognl.test.objects.SecondBean; /** * Tests functionality of casting inherited method expressions. */ public class InheritedMethodsTest extends TestCase { private static final Root ROOT = new Root(); public void test_Base_Inheritance() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); String expression = "map.bean.name"; BaseBean first = new FirstBean(); BaseBean second = new SecondBean(); ROOT.getMap().put( "bean", first ); Node node = Ognl.compileExpression( context, ROOT, expression ); assertEquals( first.getName(), node.getAccessor().get( context, ROOT ) ); ROOT.getMap().put( "bean", second ); assertEquals( second.getName(), node.getAccessor().get( context, ROOT ) ); } }
4,424
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/InterfaceInheritanceTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.ognl.OgnlRuntime; import org.apache.commons.ognl.test.objects.Bean1; import org.apache.commons.ognl.test.objects.BeanProvider; import org.apache.commons.ognl.test.objects.BeanProviderAccessor; import org.apache.commons.ognl.test.objects.EvenOdd; import org.apache.commons.ognl.test.objects.ListSourceImpl; import org.apache.commons.ognl.test.objects.Root; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class InterfaceInheritanceTest extends OgnlTestCase { private static final Root ROOT = new Root(); static { ROOT.getBeans().setBean( "testBean", new Bean1() ); ROOT.getBeans().setBean( "evenOdd", new EvenOdd() ); List list = new ListSourceImpl(); list.add( "test1" ); ROOT.getMap().put( "customList", list ); } private static final Object[][] TESTS = { { ROOT, "myMap", ROOT.getMyMap() }, { ROOT, "myMap.test", ROOT }, { ROOT.getMyMap(), "list", ROOT.getList() }, { ROOT, "myMap.array[0]", new Integer( ROOT.getArray()[0] ) }, { ROOT, "myMap.list[1]", ROOT.getList().get( 1 ) }, { ROOT, "myMap[^]", new Integer( 99 ) }, { ROOT, "myMap[$]", null }, { ROOT.getMyMap(), "array[$]", new Integer( ROOT.getArray()[ROOT.getArray().length - 1] ) }, { ROOT, "[\"myMap\"]", ROOT.getMyMap() }, { ROOT, "myMap[null]", null }, { ROOT, "myMap[#x = null]", null }, { ROOT, "myMap.(null,test)", ROOT }, { ROOT, "myMap[null] = 25", new Integer( 25 ) }, { ROOT, "myMap[null]", new Integer( 25 ), new Integer( 50 ), new Integer( 50 ) }, { ROOT, "beans.testBean", ROOT.getBeans().getBean( "testBean" ) }, { ROOT, "beans.evenOdd.next", "even" }, { ROOT, "map.comp.form.clientId", "form1" }, { ROOT, "map.comp.getCount(genericIndex)", Integer.valueOf( 0 ) }, { ROOT, "map.customList.total", Integer.valueOf( 1 ) }, { ROOT, "myTest.theMap['key']", "value" }, { ROOT, "contentProvider.hasChildren(property)", Boolean.TRUE }, { ROOT, "objectIndex instanceof java.lang.Object", Boolean.TRUE } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public InterfaceInheritanceTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } @Override @Before public void setUp() { super.setUp(); OgnlRuntime.setPropertyAccessor( BeanProvider.class, new BeanProviderAccessor() ); } @Override @Test public void runTest() throws Exception { super.runTest(); } }
4,425
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/PrimitiveNullHandlingTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.test.objects.Simple; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class PrimitiveNullHandlingTest extends OgnlTestCase { private static final Simple SIMPLE = new Simple(); static { SIMPLE.setFloatValue( 10.56f ); SIMPLE.setIntValue( 34 ); } private static final Object[][] TESTS = { // Primitive null handling { SIMPLE, "floatValue", new Float( 10.56f ), null, new Float( 0f ) }, // set float to // null, should // yield 0.0f { SIMPLE, "intValue", new Integer( 34 ), null, new Integer( 0 ) },// set int to null, // should yield 0 { SIMPLE, "booleanValue", Boolean.FALSE, Boolean.TRUE, Boolean.TRUE },// set boolean // to TRUE, // should yield // true { SIMPLE, "booleanValue", Boolean.TRUE, null, Boolean.FALSE }, // set boolean to null, // should yield false }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public PrimitiveNullHandlingTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,426
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ConstantTreeTest.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.commons.ognl.test; import static junit.framework.Assert.assertTrue; import java.util.ArrayList; import java.util.Collection; import junit.framework.Assert; import org.apache.commons.ognl.Ognl; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class ConstantTreeTest extends OgnlTestCase { public static int nonFinalStaticVariable = 15; private static final Object[][] TESTS = { { "true", Boolean.TRUE }, { "55", Boolean.TRUE }, { "@java.awt.Color@black", Boolean.TRUE }, { "@org.apache.commons.ognl.test.ConstantTreeTest@nonFinalStaticVariable", Boolean.FALSE }, { "@org.apache.commons.ognl.test.ConstantTreeTest@nonFinalStaticVariable + 10", Boolean.FALSE }, { "55 + 24 + @java.awt.Event@ALT_MASK", Boolean.TRUE }, { "name", Boolean.FALSE }, { "name[i]", Boolean.FALSE }, { "name[i].property", Boolean.FALSE }, { "name.{? foo }", Boolean.FALSE }, { "name.{ foo }", Boolean.FALSE }, { "name.{ 25 }", Boolean.FALSE } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[0] + " (" + element[1] + ")"; tmp[1] = null; tmp[2] = element[0]; tmp[3] = element[1]; tmp[4] = null; tmp[5] = null; data.add( tmp ); } return data; } /* * =================================================================== Overridden methods * =================================================================== */ @Override public void runTest() throws Exception { Assert.assertEquals(Ognl.isConstant(getExpression(), _context), ((Boolean) getExpectedResult()).booleanValue()); } /* * =================================================================== Constructors * =================================================================== */ public ConstantTreeTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,427
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/NullStringCatenationTest.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.commons.ognl.test; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.test.objects.Root; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class NullStringCatenationTest extends OgnlTestCase { public static final String MESSAGE = "blarney"; private static final Root ROOT = new Root(); private static final Object[][] TESTS = { // Null string catenation { ROOT, "\"bar\" + null", "barnull" }, // Catenate null to a string { ROOT, "\"bar\" + nullObject", "barnull" }, // Catenate null to a string { ROOT, "20.56 + nullObject", NullPointerException.class }, // Catenate null to a number { ROOT, "(true ? 'tabHeader' : '') + (false ? 'tabHeader' : '')", "tabHeader" }, { ROOT, "theInt == 0 ? '5%' : theInt + '%'", "6%" }, { ROOT, "'width:' + width + ';'", "width:238px;" }, { ROOT, "theLong + '_' + index", "4_1" }, { ROOT, "'javascript:' + @org.apache.commons.ognl.test.NullStringCatenationTest@MESSAGE", "javascript:blarney" }, { ROOT, "printDelivery ? '' : 'javascript:deliverySelected(' + property.carrier + ',' + currentDeliveryId + ')'", "" }, { ROOT, "bean2.id + '_' + theInt", "1_6" } }; /** * Setup parameters for this test which are used to call this class constructor * @return the collection of paramaters */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[4]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; tmp[3] = element[2]; data.add( tmp ); } return data; } /** * Constructor: size of the Object[] returned by the @Parameter annotated method must match * the number of arguments in this constructor */ public NullStringCatenationTest( String name, Object root, String expressionString, Object expectedResult) { super( name, root, expressionString, expectedResult ); } @Test @Override public void runTest() throws Exception { super.runTest(); } }
4,428
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/NumberFormatExceptionTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.OgnlException; import org.apache.commons.ognl.test.objects.Simple; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class NumberFormatExceptionTest extends OgnlTestCase { private static final Simple SIMPLE = new Simple(); private static final Object[][] TESTS = { // NumberFormatException handling (default is to throw NumberFormatException on bad string conversions) { SIMPLE, "floatValue", 0f, 10f, 10f }, { SIMPLE, "floatValue", 10f, "x10x", OgnlException.class }, { SIMPLE, "intValue", 0, 34, 34 }, { SIMPLE, "intValue", 34, "foobar", OgnlException.class }, { SIMPLE, "intValue", 34, "", OgnlException.class }, { SIMPLE, "intValue", 34, " \t", OgnlException.class }, { SIMPLE, "intValue", 34, " \t1234\t\t", 1234 }, { SIMPLE, "bigIntValue", BigInteger.valueOf( 0 ), BigInteger.valueOf( 34 ), BigInteger.valueOf( 34 ) }, { SIMPLE, "bigIntValue", BigInteger.valueOf( 34 ), null, null }, { SIMPLE, "bigIntValue", null, "", OgnlException.class }, { SIMPLE, "bigIntValue", null, "foobar", OgnlException.class }, { SIMPLE, "bigDecValue", new BigDecimal( 0.0 ), new BigDecimal( 34.55 ), new BigDecimal( 34.55 ) }, { SIMPLE, "bigDecValue", new BigDecimal( 34.55 ), null, null }, { SIMPLE, "bigDecValue", null, "", OgnlException.class }, { SIMPLE, "bigDecValue", null, "foobar", OgnlException.class } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for ( Object[] TEST : TESTS ) { Object[] tmp = new Object[6]; tmp[0] = TEST[1]; tmp[1] = TEST[0]; tmp[2] = TEST[1]; switch ( TEST.length ) { case 3: tmp[3] = TEST[2]; break; case 4: tmp[3] = TEST[2]; tmp[4] = TEST[3]; break; case 5: tmp[3] = TEST[2]; tmp[4] = TEST[3]; tmp[5] = TEST[4]; break; default: fail( "don't understand TEST format with length " + TEST.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public NumberFormatExceptionTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, true, expectedAfterSetResult, true ); } }
4,429
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ASTChainTest.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.commons.ognl.test; import junit.framework.TestCase; import org.apache.commons.ognl.Ognl; import org.apache.commons.ognl.OgnlContext; import org.apache.commons.ognl.test.objects.IndexedSetObject; /** * Tests for {@link org.apache.commons.ognl.ASTChain}. */ public class ASTChainTest extends TestCase { public void test_Get_Indexed_Value() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext(null); IndexedSetObject root = new IndexedSetObject(); String expr = "thing[\"x\"].val"; assertEquals(1, (int) Ognl.getValue(expr, context, root)); Ognl.setValue(expr, context, root, 2); assertEquals(2, (int) Ognl.getValue(expr, context, root)); } }
4,430
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ProtectedInnerClassTest.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.commons.ognl.test; import org.apache.commons.ognl.test.objects.Root; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Collection; @RunWith(value = Parameterized.class) public class ProtectedInnerClassTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final Object[][] TESTS = { // member access of inner class (Arrays.asList() returned protected inner class) { ROOT, "list.size()", ROOT.getList().size() }, { ROOT, "list[0]", ROOT.getList().get( 0 ) } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for ( Object[] TEST : TESTS ) { Object[] tmp = new Object[6]; tmp[0] = TEST[1]; tmp[1] = TEST[0]; tmp[2] = TEST[1]; tmp[3] = TEST[2]; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public ProtectedInnerClassTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,431
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/IndexAccessTest.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.commons.ognl.test; import org.apache.commons.ognl.MethodFailedException; import org.apache.commons.ognl.NoSuchPropertyException; import org.apache.commons.ognl.test.objects.IndexedSetObject; import org.apache.commons.ognl.test.objects.Root; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Collection; @RunWith(value = Parameterized.class) public class IndexAccessTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final IndexedSetObject INDEXED_SET = new IndexedSetObject(); private static final Object[][] TESTS = { { ROOT, "list[index]", ROOT.getList().get( ROOT.getIndex() ) }, { ROOT, "list[objectIndex]", ROOT.getList().get( ROOT.getObjectIndex().intValue() ) }, { ROOT, "array[objectIndex]", ROOT.getArray()[ROOT.getObjectIndex().intValue()] }, { ROOT, "array[getObjectIndex()]", ROOT.getArray()[ROOT.getObjectIndex().intValue()] }, { ROOT, "array[genericIndex]", ROOT.getArray()[( (Integer) ROOT.getGenericIndex() ).intValue()] }, { ROOT, "booleanArray[self.objectIndex]", Boolean.FALSE }, { ROOT, "booleanArray[getObjectIndex()]", Boolean.FALSE }, { ROOT, "booleanArray[nullIndex]", NoSuchPropertyException.class }, { ROOT, "list[size() - 1]", MethodFailedException.class }, { ROOT, "(index == (array.length - 3)) ? 'toggle toggleSelected' : 'toggle'", "toggle toggleSelected" }, { ROOT, "\"return toggleDisplay('excdisplay\"+index+\"', this)\"", "return toggleDisplay('excdisplay1', this)" }, { ROOT, "map[mapKey].split('=')[0]", "StringStuff" }, { ROOT, "booleanValues[index1][index2]", Boolean.FALSE }, { ROOT, "tab.searchCriteria[index1].displayName", "Woodland creatures" }, { ROOT, "tab.searchCriteriaSelections[index1][index2]", Boolean.TRUE }, { ROOT, "tab.searchCriteriaSelections[index1][index2]", Boolean.TRUE, Boolean.FALSE, Boolean.FALSE }, { ROOT, "map['bar'].value", 100, 50, 50 }, { INDEXED_SET, "thing[\"x\"].val", 1, 2, 2 } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; tmp[3] = element[2]; if ( element.length == 5 ) { tmp[4] = element[3]; tmp[5] = element[4]; } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public IndexAccessTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,432
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ShortCircuitingExpressionTest.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.commons.ognl.test; import org.apache.commons.ognl.NoSuchPropertyException; import org.apache.commons.ognl.OgnlException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Collection; @RunWith(value = Parameterized.class) public class ShortCircuitingExpressionTest extends OgnlTestCase { private static final Object[][] TESTS = { { "#root ? someProperty : 99", new Integer( 99 ) }, { "#root ? 99 : someProperty", OgnlException.class }, { "(#x=99)? #x.someProperty : #x", NoSuchPropertyException.class }, { "#xyzzy.doubleValue()", NullPointerException.class }, { "#xyzzy && #xyzzy.doubleValue()", null }, { "(#x=99) && #x.doubleValue()", new Double( 99 ) }, { "#xyzzy || 101", new Integer( 101 ) }, { "99 || 101", new Integer( 99 ) }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[0] + " (" + element[1] + ")"; tmp[1] = null; tmp[2] = element[0]; tmp[3] = element[1]; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public ShortCircuitingExpressionTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,433
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ArithmeticAndLogicalOperatorsTest.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.commons.ognl.test; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; @RunWith(value = Parameterized.class) public class ArithmeticAndLogicalOperatorsTest extends OgnlTestCase { private static final Object[][] TESTS = { // Double-valued arithmetic expressions { "-1d", new Double( -1 ) }, { "+1d", new Double( 1 ) }, { "--1f", new Double( 1 ) }, { "2*2.0", new Double( 4.0 ) }, { "5/2.", new Double( 2.5 ) }, { "5+2D", new Double( 7 ) }, { "5f-2F", new Double( 3.0 ) }, { "5.+2*3", new Double( 11 ) }, { "(5.+2)*3", new Double( 21 ) }, // BigDecimal-valued arithmetic expressions { "-1b", new Integer( -1 ) }, { "+1b", new Integer( 1 ) }, { "--1b", new Integer( 1 ) }, { "2*2.0b", new Double( 4.0 ) }, { "5/2.B", new Integer( 2 ) }, { "5.0B/2", new Double( 2.5 ) }, { "5+2b", new Integer( 7 ) }, { "5-2B", new Integer( 3 ) }, { "5.+2b*3", new Double( 11 ) }, { "(5.+2b)*3", new Double( 21 ) }, // Integer-valued arithmetic expressions { "-1", new Integer( -1 ) }, { "+1", new Integer( 1 ) }, { "--1", new Integer( 1 ) }, { "2*2", new Integer( 4 ) }, { "5/2", new Integer( 2 ) }, { "5+2", new Integer( 7 ) }, { "5-2", new Integer( 3 ) }, { "5+2*3", new Integer( 11 ) }, { "(5+2)*3", new Integer( 21 ) }, { "~1", new Integer( ~1 ) }, { "5%2", new Integer( 1 ) }, { "5<<2", new Integer( 20 ) }, { "5>>2", new Integer( 1 ) }, { "5>>1+1", new Integer( 1 ) }, { "-5>>>2", new Integer( -5 >>> 2 ) }, { "-5L>>>2", new Long( -5L >>> 2 ) }, { "5. & 3", new Long( 1 ) }, { "5 ^3", new Integer( 6 ) }, { "5l&3|5^3", new Long( 7 ) }, { "5&(3|5^3)", new Long( 5 ) }, { "true ? 1 : 1/0", new Integer( 1 ) }, // BigInteger-valued arithmetic expressions { "-1h", Integer.valueOf( -1 ) }, { "+1H", Integer.valueOf( 1 ) }, { "--1h", Integer.valueOf( 1 ) }, { "2h*2", Integer.valueOf( 4 ) }, { "5/2h", Integer.valueOf( 2 ) }, { "5h+2", Integer.valueOf( 7 ) }, { "5-2h", Integer.valueOf( 3 ) }, { "5+2H*3", Integer.valueOf( 11 ) }, { "(5+2H)*3", Integer.valueOf( 21 ) }, { "~1h", Integer.valueOf( ~1 ) }, { "5h%2", Integer.valueOf( 1 ) }, { "5h<<2", Integer.valueOf( 20 ) }, { "5h>>2", Integer.valueOf( 1 ) }, { "5h>>1+1", Integer.valueOf( 1 ) }, { "-5h>>>2", Integer.valueOf( -2 ) }, { "5.b & 3", new Long( 1 ) }, { "5h ^3", Integer.valueOf( 6 ) }, { "5h&3|5^3", new Long( 7 ) }, { "5H&(3|5^3)", new Long( 5 ) }, // Logical expressions { "!1", Boolean.FALSE }, { "!null", Boolean.TRUE }, { "5<2", Boolean.FALSE }, { "5>2", Boolean.TRUE }, { "5<=5", Boolean.TRUE }, { "5>=3", Boolean.TRUE }, { "5<-5>>>2", Boolean.TRUE }, { "5==5.0", Boolean.TRUE }, { "5!=5.0", Boolean.FALSE }, { "null in {true,false,null}", Boolean.TRUE }, { "null not in {true,false,null}", Boolean.FALSE }, { "null in {true,false,null}.toArray()", Boolean.TRUE }, { "5 in {true,false,null}", Boolean.FALSE }, { "5 not in {true,false,null}", Boolean.TRUE }, { "5 instanceof java.lang.Integer", Boolean.TRUE }, { "5. instanceof java.lang.Integer", Boolean.FALSE }, { "!false || true", Boolean.TRUE }, { "!(true && true)", Boolean.FALSE }, { "(1 > 0 && true) || 2 > 0", Boolean.TRUE }, // Logical expressions (string versions) { "2 or 0", Integer.valueOf( 2 ) }, { "1 and 0", Integer.valueOf( 0 ) }, { "1 bor 0", new Integer( 1 ) }, { "true && 12", Integer.valueOf( 12 ) }, { "1 xor 0", new Integer( 1 ) }, { "1 band 0", new Long( 0 ) }, { "1 eq 1", Boolean.TRUE }, { "1 neq 1", Boolean.FALSE }, { "1 lt 5", Boolean.TRUE }, { "1 lte 5", Boolean.TRUE }, { "1 gt 5", Boolean.FALSE }, { "1 gte 5", Boolean.FALSE }, { "1 lt 5", Boolean.TRUE }, { "1 shl 2", new Integer( 4 ) }, { "4 shr 2", new Integer( 1 ) }, { "4 ushr 2", new Integer( 1 ) }, { "not null", Boolean.TRUE }, { "not 1", Boolean.FALSE }, { "#x > 0", Boolean.TRUE }, { "#x < 0", Boolean.FALSE }, { "#x == 0", Boolean.FALSE }, { "#x == 1", Boolean.TRUE }, { "0 > #x", Boolean.FALSE }, { "0 < #x", Boolean.TRUE }, { "0 == #x", Boolean.FALSE }, { "1 == #x", Boolean.TRUE }, { "\"1\" > 0", Boolean.TRUE }, { "\"1\" < 0", Boolean.FALSE }, { "\"1\" == 0", Boolean.FALSE }, { "\"1\" == 1", Boolean.TRUE }, { "0 > \"1\"", Boolean.FALSE }, { "0 < \"1\"", Boolean.TRUE }, { "0 == \"1\"", Boolean.FALSE }, { "1 == \"1\"", Boolean.TRUE }, { "#x + 1", "11" }, { "1 + #x", "11" }, { "#y == 1", Boolean.TRUE }, { "#y == \"1\"", Boolean.TRUE }, { "#y + \"1\"", "11" }, { "\"1\" + #y", "11" } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for ( Object[] TEST : TESTS ) { Object[] tmp = new Object[4]; tmp[0] = TEST[0] + " (" + TEST[1] + ")"; tmp[1] = null; tmp[2] = TEST[0]; tmp[3] = TEST[1]; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public ArithmeticAndLogicalOperatorsTest( String name, Object root, String expressionString, Object expectedResult ) { super( name, root, expressionString, expectedResult ); } /* * =================================================================== Overridden methods * =================================================================== */ @Before @Override public void setUp() { super.setUp(); _context.put( "x", "1" ); _context.put("y", new BigDecimal(1)); } }
4,434
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/PropertyNotFoundTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import org.apache.commons.ognl.OgnlContext; import org.apache.commons.ognl.OgnlException; import org.apache.commons.ognl.OgnlRuntime; import org.apache.commons.ognl.PropertyAccessor; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class PropertyNotFoundTest extends OgnlTestCase { private static final Blah BLAH = new Blah(); private static final Object[][] TESTS = { { BLAH, "webwork.token.name", OgnlException.class, "W value", OgnlException.class }, }; /* * =================================================================== Public static classes * =================================================================== */ public static class Blah { String x; String y; public String getX() { return x; } public void setX( String x ) { this.x = x; } public String getY() { return y; } public void setY( String y ) { this.y = y; } } public static class BlahPropertyAccessor implements PropertyAccessor { public void setProperty( Map<String, Object> context, Object target, Object name, Object value ) throws OgnlException { } public Object getProperty( Map<String, Object> context, Object target, Object name ) throws OgnlException { if ( "x".equals( name ) || "y".equals( name ) ) { return OgnlRuntime.getProperty( (OgnlContext) context, target, name ); } return null; } public String getSourceAccessor( OgnlContext context, Object target, Object index ) { return index.toString(); } public String getSourceSetter( OgnlContext context, Object target, Object index ) { return index.toString(); } } /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public PropertyNotFoundTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } @Before @Override public void setUp() { super.setUp(); OgnlRuntime.setPropertyAccessor( Blah.class, new BlahPropertyAccessor() ); } }
4,435
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/PrimitiveArrayTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.test.objects.Root; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class PrimitiveArrayTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final Object[][] TESTS = { // Primitive array creation { ROOT, "new boolean[5]", new boolean[5] }, { ROOT, "new boolean[] { true, false }", new boolean[] { true, false } }, { ROOT, "new boolean[] { 0, 1, 5.5 }", new boolean[] { false, true, true } }, { ROOT, "new char[] { 'a', 'b' }", new char[] { 'a', 'b' } }, { ROOT, "new char[] { 10, 11 }", new char[] { (char) 10, (char) 11 } }, { ROOT, "new byte[] { 1, 2 }", new byte[] { 1, 2 } }, { ROOT, "new short[] { 1, 2 }", new short[] { 1, 2 } }, { ROOT, "new int[six]", new int[ROOT.six] }, { ROOT, "new int[#root.six]", new int[ROOT.six] }, { ROOT, "new int[6]", new int[6] }, { ROOT, "new int[] { 1, 2 }", new int[] { 1, 2 } }, { ROOT, "new long[] { 1, 2 }", new long[] { 1, 2 } }, { ROOT, "new float[] { 1, 2 }", new float[] { 1, 2 } }, { ROOT, "new double[] { 1, 2 }", new double[] { 1, 2 } }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for ( Object[] TEST : TESTS ) { Object[] tmp = new Object[6]; tmp[0] = TEST[1]; tmp[1] = TEST[0]; tmp[2] = TEST[1]; switch ( TEST.length ) { case 3: tmp[3] = TEST[2]; break; case 4: tmp[3] = TEST[2]; tmp[4] = TEST[3]; break; case 5: tmp[3] = TEST[2]; tmp[4] = TEST[3]; tmp[5] = TEST[4]; break; default: fail( "don't understand TEST format with length " + TEST.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public PrimitiveArrayTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,436
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/PrivateMemberTest.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.commons.ognl.test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.ognl.DefaultMemberAccess; import org.apache.commons.ognl.Ognl; import org.apache.commons.ognl.OgnlContext; import org.apache.commons.ognl.OgnlException; import org.junit.Before; /** * This is a test program for private access in OGNL. shows the failures and a summary. */ public class PrivateMemberTest extends TestCase { private final String _privateProperty = "private value"; protected OgnlContext context; /* * =================================================================== Public static methods * =================================================================== */ public static TestSuite suite() { return new TestSuite( PrivateMemberTest.class ); } /* * =================================================================== Constructors * =================================================================== */ public PrivateMemberTest( String name ) { super( name ); } /* * =================================================================== Public methods * =================================================================== */ private String getPrivateProperty() { return _privateProperty; } public void testPrivateAccessor() throws OgnlException { assertEquals( Ognl.getValue( "privateProperty", context, this ), getPrivateProperty() ); } public void testPrivateField() throws OgnlException { assertEquals( Ognl.getValue( "_privateProperty", context, this ), _privateProperty ); } /* * =================================================================== Overridden methods * =================================================================== */ @Before @Override public void setUp() { context = (OgnlContext) Ognl.createDefaultContext( null ); context.setMemberAccess( new DefaultMemberAccess( true ) ); } }
4,437
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ObjectIndexedPropertyTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.OgnlException; import org.apache.commons.ognl.test.objects.Bean1; import org.apache.commons.ognl.test.objects.ObjectIndexed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class ObjectIndexedPropertyTest extends OgnlTestCase { private static final ObjectIndexed OBJECT_INDEXED = new ObjectIndexed(); private static final Bean1 ROOT = new Bean1(); private static final Object[][] TESTS = { // Arbitrary indexed properties { OBJECT_INDEXED, "attributes[\"bar\"]", "baz" }, // get non-indexed property through // attributes Map { OBJECT_INDEXED, "attribute[\"foo\"]", "bar" }, // get indexed property { OBJECT_INDEXED, "attribute[\"bar\"]", "baz", "newValue", "newValue" }, // set // indexed // property { OBJECT_INDEXED, "attribute[\"bar\"]", "newValue" },// get indexed property back to // confirm { OBJECT_INDEXED, "attributes[\"bar\"]", "newValue" }, // get property back through Map // to confirm { OBJECT_INDEXED, "attribute[\"other\"].attribute[\"bar\"]", "baz" }, // get indexed // property from // indexed, then // through other { OBJECT_INDEXED, "attribute[\"other\"].attributes[\"bar\"]", "baz" }, // get property // back through // Map to // confirm { OBJECT_INDEXED, "attribute[$]", OgnlException.class }, // illegal DynamicSubscript // access to object indexed // property { ROOT, "bean2.bean3.indexedValue[25]", null } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public ObjectIndexedPropertyTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,438
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/PropertySetterTest.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.commons.ognl.test; import junit.framework.TestCase; import org.apache.commons.ognl.Node; import org.apache.commons.ognl.Ognl; import org.apache.commons.ognl.OgnlContext; import java.util.Map; /** * Tests being able to set property on object with interface that doesn't define setter. See OGNL-115. */ public class PropertySetterTest extends TestCase { private Map<String, String> map; private final TestObject testObject = new TestObject( "propertyValue" ); private final String propertyKey = "property"; public interface TestInterface { String getProperty(); } public class TestObject implements TestInterface { private String property; private final Integer integerProperty = 1; public TestObject( String property ) { this.property = property; } public String getProperty() { return property; } public void setProperty( String property ) { this.property = property; } public Integer getIntegerProperty() { return integerProperty; } } public Map<String, String> getMap() { return map; } public String getKey() { return "key"; } public TestObject getObject() { return testObject; } public TestInterface getInterfaceObject() { return testObject; } public String getPropertyKey() { return propertyKey; } public void testEnhancedOgnl() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); Node expression = Ognl.compileExpression( context, this, "interfaceObject.property" ); Ognl.setValue( expression, context, this, "hello" ); assertEquals( "hello", getObject().getProperty() ); // Fails if an interface is defined, but succeeds if not context.clear(); expression = Ognl.compileExpression( context, this.getObject(), "property" ); Ognl.setValue( expression, context, this.getObject(), "hello" ); assertEquals( "hello", getObject().getProperty() ); } }
4,439
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/NullHandlerTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.OgnlRuntime; import org.apache.commons.ognl.test.objects.CorrectedObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class NullHandlerTest extends OgnlTestCase { private static final CorrectedObject CORRECTED = new CorrectedObject(); private static final Object[][] TESTS = { // NullHandler { CORRECTED, "stringValue", "corrected" }, { CORRECTED, "getStringValue()", "corrected" }, { CORRECTED, "#root.stringValue", "corrected" }, { CORRECTED, "#root.getStringValue()", "corrected" }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public NullHandlerTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } /* * =================================================================== Overridden methods * =================================================================== */ @Override @Before public void setUp() { super.setUp(); _compileExpressions = false; OgnlRuntime.setNullHandler( CorrectedObject.class, new CorrectedObjectNullHandler( "corrected" ) ); } @Test @Override public void runTest() throws Exception { super.runTest(); } }
4,440
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/PropertyArithmeticAndLogicalOperatorsTest.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.commons.ognl.test; import org.apache.commons.ognl.test.objects.Root; import org.apache.commons.ognl.test.objects.SimpleNumeric; import org.apache.commons.ognl.test.objects.TestModel; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; /** * */ @RunWith(value = Parameterized.class) public class PropertyArithmeticAndLogicalOperatorsTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final TestModel MODEL = new TestModel(); private static final SimpleNumeric NUMERIC = new SimpleNumeric(); private static final Object[][] TESTS = { { ROOT, "objectIndex > 0", Boolean.TRUE }, { ROOT, "false", Boolean.FALSE }, { ROOT, "!false || true", Boolean.TRUE }, { ROOT, "property.bean3.value >= 24", Boolean.TRUE }, { ROOT, "genericIndex-1", new Integer( 1 ) }, { ROOT, "((renderNavigation ? 0 : 1) + map.size) * theInt", new Integer( ( ( ROOT.getRenderNavigation() ? 0 : 1 ) + ROOT.getMap().size() ) * ROOT.getTheInt() ) }, { ROOT, "{theInt + 1}", Arrays.asList( new Integer( ROOT.getTheInt() + 1 ) ) }, { MODEL, "(unassignedCopyModel.optionCount > 0 && canApproveCopy) || entry.copy.size() > 0", Boolean.TRUE }, { ROOT, " !(printDelivery || @Boolean@FALSE)", Boolean.FALSE }, { ROOT, "(getIndexedProperty('nested').size - 1) > genericIndex", Boolean.FALSE }, { ROOT, "(getIndexedProperty('nested').size + 1) >= genericIndex", Boolean.TRUE }, { ROOT, "(getIndexedProperty('nested').size + 1) == genericIndex", Boolean.TRUE }, { ROOT, "(getIndexedProperty('nested').size + 1) < genericIndex", Boolean.FALSE }, { ROOT, "map.size * genericIndex", new Integer( ROOT.getMap().size() * ( (Integer) ROOT.getGenericIndex() ).intValue() ) }, { ROOT, "property == property", Boolean.TRUE }, { ROOT, "property.bean3.value % 2 == 0", Boolean.TRUE }, { ROOT, "genericIndex % 3 == 0", Boolean.FALSE }, { ROOT, "genericIndex % theInt == property.bean3.value", Boolean.FALSE }, { ROOT, "theInt / 100.0", ROOT.getTheInt() / 100.0 }, { ROOT, "@java.lang.Long@valueOf('100') == @java.lang.Long@valueOf('100')", Boolean.TRUE }, { NUMERIC, "budget - timeBilled", new Double( NUMERIC.getBudget() - NUMERIC.getTimeBilled() ) }, { NUMERIC, "(budget % tableSize) == 0", Boolean.TRUE } }; @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; tmp[3] = element[2]; if ( element.length == 5 ) { tmp[4] = element[3]; tmp[5] = element[4]; } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public PropertyArithmeticAndLogicalOperatorsTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,441
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/PropertyTest.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.commons.ognl.test; import org.apache.commons.ognl.test.objects.BaseBean; import org.apache.commons.ognl.test.objects.Bean2; import org.apache.commons.ognl.test.objects.FirstBean; import org.apache.commons.ognl.test.objects.PropertyHolder; import org.apache.commons.ognl.test.objects.Root; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @RunWith(value = Parameterized.class) public class PropertyTest extends OgnlTestCase { public static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat( "MM/dd/yyyy hh:mm a 'CST'" ); public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( "MM/dd/yyyy" ); public static final String VALUE = "foo"; private static final Root ROOT = new Root(); private static final BaseBean BEAN = new FirstBean(); private static final PropertyHolder PROPERTY = new PropertyHolder(); private static final Object[][] TESTS = { { ROOT, "testString != null && !false", Boolean.TRUE }, { ROOT, "!getRenderNavigation() and !getReadonly()", Boolean.TRUE }, { ROOT, "!bean2.pageBreakAfter", Boolean.TRUE }, { ROOT, "map", ROOT.getMap() }, { ROOT, "map.test", ROOT }, { ROOT, "map[\"test\"]", ROOT }, { ROOT, "map[\"te\" + \"st\"]", ROOT }, { ROOT, "map[(\"s\" + \"i\") + \"ze\"]", ROOT.getMap().get( Root.SIZE_STRING ) }, { ROOT, "map[\"size\"]", ROOT.getMap().get( Root.SIZE_STRING ) }, { ROOT, "map[@org.apache.commons.ognl.test.objects.Root@SIZE_STRING]", ROOT.getMap().get( Root.SIZE_STRING ) }, { ROOT, "stringValue != null && stringValue.length() > 0", Boolean.FALSE }, { ROOT, "indexedStringValue != null && indexedStringValue.length() > 0", Boolean.TRUE }, { ROOT.getMap(), "list", ROOT.getList() }, { ROOT, "map.array[0]", new Integer( ROOT.getArray()[0] ) }, { ROOT, "map.list[1]", ROOT.getList().get( 1 ) }, { ROOT, "map[^]", new Integer( 99 ) }, { ROOT, "map[$]", null }, { ROOT.getMap(), "array[$]", new Integer( ROOT.getArray()[ROOT.getArray().length - 1] ) }, { ROOT, "[\"map\"]", ROOT.getMap() }, { ROOT.getArray(), "length", new Integer( ROOT.getArray().length ) }, { ROOT, "getMap().list[|]", ROOT.getList().get( ROOT.getList().size() / 2 ) }, { ROOT, "map.(array[2] + size())", new Integer( ROOT.getArray()[2] + ROOT.getMap().size() ) }, { ROOT, "map.(#this)", ROOT.getMap() }, { ROOT, "map.(#this != null ? #this['size'] : null)", ROOT.getMap().get( Root.SIZE_STRING ) }, { ROOT, "map[^].(#this == null ? 'empty' : #this)", new Integer( 99 ) }, { ROOT, "map[$].(#this == null ? 'empty' : #this)", "empty" }, { ROOT, "map[$].(#root == null ? 'empty' : #root)", ROOT }, { ROOT, "((selected != null) && (currLocale.toString() == selected.toString())) ? 'first' : 'second'", "first" }, { ROOT, "{stringValue, getMap()}", Arrays.asList( ROOT.getStringValue(), ROOT.getMap() ) }, { ROOT, "{'stringValue', map[\"test\"].map[\"size\"]}", Arrays.asList( "stringValue", ROOT.getMap().get( "size" ) ) }, { ROOT, "property.bean3.value + '(this.checked)'", "100(this.checked)" }, { ROOT, "getIndexedProperty(property.bean3.map[\"bar\"])", ROOT.getArray() }, { ROOT, "getProperty().getBean3()", ( (Bean2) ROOT.getProperty() ).getBean3() }, { ROOT, "intValue", new Integer( 0 ), new Integer( 2 ), new Integer( 2 ) }, { ROOT, "! booleanValue", Boolean.TRUE }, { ROOT, "booleanValue", Boolean.FALSE, Boolean.TRUE, Boolean.TRUE }, { ROOT, "! disabled", new Boolean( false ) }, { ROOT, "disabled || readonly", Boolean.TRUE }, { ROOT, "property.bean3.value != null", Boolean.TRUE }, { ROOT, "\"background-color:blue; width:\" + (currentLocaleVerbosity / 2) + \"px\"", "background-color:blue; width:43px" }, { ROOT, "renderNavigation ? '' : 'noborder'", "noborder" }, { ROOT, "format('key', array)", "formatted" }, { ROOT, "format('key', intValue)", "formatted" }, { ROOT, "format('key', map.size)", "formatted" }, { ROOT, "'disableButton(this,\"' + map.get('button-testing') + '\");clearElement(&quot;testFtpMessage&quot;)'", "disableButton(this,'null');clearElement('testFtpMessage')" }, { ROOT.getMap(), "!disableWarning", Boolean.TRUE }, { ROOT.getMap(), "get('value').bean3.value", new Integer( ( (Bean2) ROOT.getMap().get( "value" ) ).getBean3().getValue() ) }, { ROOT.getMap(), "\"Tapestry\".toCharArray()[2]", new Character( 'p' ) }, { ROOT.getMap(), "nested.deep.last", Boolean.TRUE }, { ROOT, "'last ' + getCurrentClass(@org.apache.commons.ognl.test.PropertyTest@VALUE)", "last foo stop" }, { ROOT, "@org.apache.commons.ognl.test.PropertyTest@formatValue(property.millis, true, true)", formatValue( (int) ( (Bean2) ROOT.getProperty() ).getMillis(), true, true ) }, { ROOT, "nullObject || !readonly", Boolean.TRUE }, { ROOT, "testDate == null ? '-' : @org.apache.commons.ognl.test.PropertyTest@DATETIME_FORMAT.format(testDate)", DATETIME_FORMAT.format( ROOT.getTestDate() ) }, { ROOT, "disabled ? 'disabled' : 'othernot'", "disabled" }, { BEAN, "two.getMessage(active ? 'ACT' : 'INA')", "[ACT]" }, { BEAN, "hasChildren('aaa')", Boolean.TRUE }, { BEAN, "two.hasChildren('aa')", Boolean.FALSE }, { BEAN, "two.hasChildren('a')", Boolean.FALSE }, { ROOT, "sorted ? (readonly ? 'currentSortDesc' : 'currentSortAsc') : 'currentSortNone'", "currentSortAsc" }, { ROOT, "getAsset( (width?'Yes':'No')+'Icon' )", "YesIcon" }, { ROOT, "flyingMonkey", Boolean.TRUE }, { ROOT, "expiration == null ? '' : @org.apache.commons.ognl.test.PropertyTest@DATE_FORMAT.format(expiration)", "" }, { ROOT, "printDelivery ? 'javascript:toggle(' + bean2.id + ');' : ''", "javascript:toggle(1);" }, { ROOT, "openTransitionWin", Boolean.FALSE }, { ROOT, "b.methodOfB(a.methodOfA(b)-1)", new Integer( 0 ) }, { ROOT, "disabled", Boolean.TRUE }, { PROPERTY, "value", "" }, { PROPERTY, "search", "foo" } }; public static String formatValue( int millis, boolean b1, boolean b2 ) { return millis + "-formatted"; } /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; tmp[3] = element[2]; if ( element.length == 5 ) { tmp[4] = element[3]; tmp[5] = element[4]; } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public PropertyTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,442
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/QuotingTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class QuotingTest extends OgnlTestCase { private static final Object[][] TESTS = { // Quoting { null, "`c`", new Character( 'c' ) }, { null, "'s'", new Character( 's' ) }, { null, "'string'", "string" }, { null, "\"string\"", "string" }, { null, "'' + 'bar'", "bar" }, { null, "'yyyy\u539Add\u5EA6'", "yyyy\u539Add\u5EA6" } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public QuotingTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } @Test @Override public void runTest() throws Exception { super.runTest(); } }
4,443
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ProjectionSelectionTest.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.commons.ognl.test; import org.apache.commons.ognl.test.objects.Root; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @RunWith(value = Parameterized.class) public class ProjectionSelectionTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final Object[][] TESTS = { // Projection, selection { ROOT, "array.{class}", Arrays.asList( Integer.class, Integer.class, Integer.class, Integer.class ) }, { ROOT, "map.array.{? #this > 2 }", Arrays.asList( new Integer( 3 ), new Integer( 4 ) ) }, { ROOT, "map.array.{^ #this > 2 }", Arrays.asList( new Integer( 3 ) ) }, { ROOT, "map.array.{$ #this > 2 }", Arrays.asList( new Integer( 4 ) ) }, { ROOT, "map.array[*].{?true} instanceof java.util.Collection", Boolean.TRUE }, { null, "#fact=1, 30H.{? #fact = #fact * (#this+1), false }, #fact", new BigInteger( "265252859812191058636308480000000" ) }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; tmp[3] = element[2]; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public ProjectionSelectionTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,444
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/SetterWithConversionTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.test.objects.Root; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class SetterWithConversionTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final Object[][] TESTS = { // Property set with conversion { ROOT, "intValue", new Integer( 0 ), new Double( 6.5 ), new Integer( 6 ) }, { ROOT, "intValue", new Integer( 6 ), new Double( 1025.87645 ), new Integer( 1025 ) }, { ROOT, "intValue", new Integer( 1025 ), "654", new Integer( 654 ) }, { ROOT, "stringValue", null, new Integer( 25 ), "25" }, { ROOT, "stringValue", "25", new Float( 100.25 ), "100.25" }, { ROOT, "anotherStringValue", "foo", new Integer( 0 ), "0" }, { ROOT, "anotherStringValue", "0", new Double( 0.5 ), "0.5" }, { ROOT, "anotherIntValue", new Integer( 123 ), "5", new Integer( 5 ) }, { ROOT, "anotherIntValue", new Integer( 5 ), new Double( 100.25 ), new Integer( 100 ) }, // { ROOT, "anotherIntValue", new Integer(100), new String[] { "55" }, new Integer(55)}, // { ROOT, "yetAnotherIntValue", new Integer(46), new String[] { "55" }, new Integer(55)}, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for ( Object[] TEST : TESTS ) { Object[] tmp = new Object[6]; tmp[0] = TEST[1]; tmp[1] = TEST[0]; tmp[2] = TEST[1]; switch (TEST.length) { case 3: tmp[3] = TEST[2]; break; case 4: tmp[3] = TEST[2]; tmp[4] = TEST[3]; break; case 5: tmp[3] = TEST[2]; tmp[4] = TEST[3]; tmp[5] = TEST[4]; break; default: fail("don't understand TEST format with length " + TEST.length); } data.add(tmp); } return data; } /* * =================================================================== Constructors * =================================================================== */ public SetterWithConversionTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,445
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ClassMethodTest.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.commons.ognl.test; import org.apache.commons.ognl.test.objects.CorrectedObject; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; @RunWith(value = Parameterized.class) public class ClassMethodTest extends OgnlTestCase { private static final CorrectedObject CORRECTED = new CorrectedObject(); private static final Object[][] TESTS = { // Methods on Class { CORRECTED, "getClass().getName()", CORRECTED.getClass().getName() }, { CORRECTED, "getClass().getInterfaces()", CORRECTED.getClass().getInterfaces() }, { CORRECTED, "getClass().getInterfaces().length", new Integer( CORRECTED.getClass().getInterfaces().length ) }, { null, "@System@class.getInterfaces()", System.class.getInterfaces() }, { null, "@Class@class.getName()", Class.class.getName() }, { null, "@java.awt.image.ImageObserver@class.getName()", java.awt.image.ImageObserver.class.getName() }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; tmp[3] = element[2]; tmp[4] = null; tmp[5] = null; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public ClassMethodTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } @Before @Override public void setUp() { super.setUp(); _context.put( "x", "1" ); _context.put( "y", new BigDecimal( 1 ) ); } }
4,446
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/Performance.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.commons.ognl.test; import org.apache.commons.ognl.Ognl; import org.apache.commons.ognl.OgnlContext; import org.apache.commons.ognl.OgnlException; import org.apache.commons.ognl.SimpleNode; import org.apache.commons.ognl.test.objects.Bean1; import java.lang.reflect.Method; import java.text.DecimalFormat; import java.text.NumberFormat; public class Performance { private static int MAX_ITERATIONS = -1; private static boolean ITERATIONS_MODE; private static long MAX_TIME = -1L; private static boolean TIME_MODE; private static final NumberFormat FACTOR_FORMAT = new DecimalFormat( "0.000" ); private final String _name; private final OgnlContext _context = (OgnlContext) Ognl.createDefaultContext( null ); private final Bean1 _root = new Bean1(); private SimpleNode _expression; private SimpleNode _compiledExpression; private final Method _method; private int _iterations; private final String _expressionString; private boolean _isMvel; private long t0; private long t1; /* * =================================================================== Private static classes * =================================================================== */ private static class Results { int iterations; long time; boolean mvel; public Results( int iterations, long time, boolean mvel ) { this.iterations = iterations; this.time = time; this.mvel = mvel; } public String getFactor( Results otherResults ) { String ret; if ( TIME_MODE ) { float factor; if ( iterations < otherResults.iterations ) { factor = Math.max( (float) otherResults.iterations, (float) iterations ) / Math.min( (float) otherResults.iterations, (float) iterations ); } else { factor = Math.min( (float) otherResults.iterations, (float) iterations ) / Math.max( (float) otherResults.iterations, (float) iterations ); } ret = FACTOR_FORMAT.format( factor ); if ( iterations > otherResults.iterations ) ret += " times faster than "; else ret += " times slower than "; } else { float factor = Math.max( (float) otherResults.time, (float) time ) / Math.min( (float) otherResults.time, (float) time ); ret = FACTOR_FORMAT.format( factor ); if ( time < otherResults.time ) ret += " times faster than "; else ret += " times slower than "; } return ret; } } /* * =================================================================== Public static methods * =================================================================== */ public static void main( String[] args ) { for ( int i = 0; i < args.length; i++ ) { if ( args[i].equals( "-time" ) ) { TIME_MODE = true; MAX_TIME = Long.parseLong( args[++i] ); } else if ( args[i].equals( "-iterations" ) ) { ITERATIONS_MODE = true; MAX_ITERATIONS = Integer.parseInt( args[++i] ); } } if ( !TIME_MODE && !ITERATIONS_MODE ) { TIME_MODE = true; MAX_TIME = 1500; } try { Performance[] tests = new Performance[] { new Performance( "Constant", "100 + 20 * 5", "testConstantExpression" ), // new Performance("Constant", "100 + 20 * 5", "testConstantExpression", false), new Performance( "Single Property", "bean2", "testSinglePropertyExpression" ), new Performance( "Property Navigation", "bean2.bean3.value", "testPropertyNavigationExpression" ), /* * new Performance("Property Setting with context key", "bean2.bean3.nullValue", * "testPropertyNavigationSetting"), new Performance("Property Setting with context key", * "bean2.bean3.nullValue", "testPropertyNavigationSetting", true), */ new Performance( "Property Navigation and Comparison", "bean2.bean3.value <= 24", "testPropertyNavigationAndComparisonExpression" ), /* * new Performance("Property Navigation with Indexed Access", "bean2.bean3.indexedValue[25]", * "testIndexedPropertyNavigationExpression"), new * Performance("Property Navigation with Indexed Access", "bean2.bean3.indexedValue[25]", * "testIndexedPropertyNavigationExpression", true), */ new Performance( "Property Navigation with Map Access", "bean2.bean3.map['foo']", "testPropertyNavigationWithMapExpression" ), /* * new Performance("Property Navigation with Map value set", "bean2.bean3.map['foo']", * "testPropertyNavigationWithMapSetting"), new Performance("Property Navigation with Map value set", * "bean2.bean3.map['foo']", "testPropertyNavigationWithMapSetting", true) */ }; boolean timeMode = TIME_MODE; boolean iterMode = ITERATIONS_MODE; long maxTime = MAX_TIME; int maxIterations = MAX_ITERATIONS; // TIME_MODE = false; // ITERATIONS_MODE = true; // maxIterations = 1000; runTests( tests, false ); TIME_MODE = timeMode; ITERATIONS_MODE = iterMode; MAX_TIME = maxTime; MAX_ITERATIONS = maxIterations; System.out.println( "\n\n============================================================================\n" ); Thread.sleep( 2500 ); runTests( tests, true ); // Thread.sleep(2000); System.out.println( "\n\n============================================================================\n" ); // runTests(tests); } catch ( Exception ex ) { ex.printStackTrace(); } } static void runTests( Performance[] tests, boolean output ) throws Exception { for ( Performance perf : tests ) { try { Results javaResults = perf.testJava( ), interpretedResults = perf.testExpression( false ), compiledResults = perf.testExpression( true ); if ( !output ) { return; } System.out.println( ( compiledResults.mvel ? "MVEL" : "OGNL" ) + " " + perf.getName( ) + ": " + perf.getExpression( ) ); System.out.println( " java: " + javaResults.iterations + " iterations in " + javaResults.time + " ms" ); System.out.println( " compiled: " + compiledResults.iterations + " iterations in " + compiledResults.time + " ms (" + compiledResults.getFactor( javaResults ) + "java)" ); System.out.println( "interpreted: " + interpretedResults.iterations + " iterations in " + interpretedResults.time + " ms (" + interpretedResults.getFactor( javaResults ) + "java)" ); System.out.println( ); } catch ( OgnlException ex ) { ex.printStackTrace( ); } } } /* * =================================================================== Constructors * =================================================================== */ public Performance( String name, String expressionString, String javaMethodName ) throws Exception { this( name, expressionString, javaMethodName, false ); } public Performance( String name, String expressionString, String javaMethodName, boolean mvel ) throws Exception { _name = name; _isMvel = mvel; _expressionString = expressionString; try { _method = getClass().getMethod( javaMethodName ); } catch ( Exception ex ) { throw new OgnlException( "java method not found", ex ); } if ( !_isMvel ) { _expression = (SimpleNode) Ognl.parseExpression( expressionString ); _compiledExpression = (SimpleNode) Ognl.compileExpression( _context, _root, expressionString ); Ognl.getValue( _expression, _context, _root ); _context.put( "contextValue", "cvalue" ); } else { // _mvelCompiled = MVEL.compileExpression(expressionString); } } /* * =================================================================== Protected methods * =================================================================== */ protected void startTest() { _iterations = 0; t0 = t1 = System.currentTimeMillis(); } protected Results endTest() { return new Results( _iterations, t1 - t0, _isMvel ); } protected boolean done() { _iterations++; t1 = System.currentTimeMillis(); if ( TIME_MODE ) { return ( t1 - t0 ) >= MAX_TIME; } if ( ITERATIONS_MODE ) { return _iterations >= MAX_ITERATIONS; } throw new IllegalStateException( "no maximums specified" ); } /* * =================================================================== Public methods * =================================================================== */ public String getName() { return _name; } public String getExpression() { return _expressionString; } public Results testExpression( boolean compiled ) throws Exception { startTest(); do { if ( !_isMvel ) { if ( compiled ) Ognl.getValue( _compiledExpression.getAccessor(), _context, _root ); else Ognl.getValue( _expression, _context, _root ); } else { /* * if (compiled) MVEL.executeExpression(_mvelCompiled, _root); else MVEL.eval(_expressionString, _root); */ } } while ( !done() ); return endTest(); } public Results testJava() throws OgnlException { try { return (Results) _method.invoke( this ); } catch ( Exception ex ) { throw new OgnlException( "invoking java method '" + _method.getName() + "'", ex ); } } public Results testConstantExpression() throws OgnlException { startTest(); do { @SuppressWarnings( "unused" ) int result = 100 + 20 * 5; } while ( !done() ); return endTest(); } public Results testSinglePropertyExpression() throws OgnlException { startTest(); do { _root.getBean2(); } while ( !done() ); return endTest(); } public Results testPropertyNavigationExpression() throws OgnlException { startTest(); do { _root.getBean2().getBean3().getValue(); } while ( !done() ); return endTest(); } public Results testPropertyNavigationSetting() throws OgnlException { startTest(); do { _root.getBean2().getBean3().setNullValue( "a value" ); } while ( !done() ); return endTest(); } public Results testPropertyNavigationAndComparisonExpression() throws OgnlException { startTest(); do { @SuppressWarnings( "unused" ) boolean result = _root.getBean2().getBean3().getValue() < 24; } while ( !done() ); return endTest(); } public Results testIndexedPropertyNavigationExpression() throws OgnlException { startTest(); do { _root.getBean2().getBean3().getIndexedValue( 25 ); } while ( !done() ); return endTest(); } public Results testPropertyNavigationWithMapSetting() throws OgnlException { startTest(); do { _root.getBean2().getBean3().getMap().put( "bam", "bam" ); } while ( !done() ); return endTest(); } public Results testPropertyNavigationWithMapExpression() throws OgnlException { startTest(); do { _root.getBean2().getBean3().getMap().get( "foo" ); } while ( !done() ); return endTest(); } }
4,447
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/NumericConversionTest.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.commons.ognl.test; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import junit.framework.Assert; import org.apache.commons.ognl.OgnlException; import org.apache.commons.ognl.OgnlOps; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith( value = Parameterized.class ) public class NumericConversionTest extends OgnlTestCase { private static final Object[][] TESTS = { /* To Integer.class */ { "55", Integer.class, new Integer( 55 ) }, { new Integer( 55 ), Integer.class, new Integer( 55 ) }, { new Double( 55 ), Integer.class, new Integer( 55 ) }, { Boolean.TRUE, Integer.class, new Integer( 1 ) }, { new Byte( (byte) 55 ), Integer.class, new Integer( 55 ) }, { new Character( (char) 55 ), Integer.class, new Integer( 55 ) }, { new Short( (short) 55 ), Integer.class, new Integer( 55 ) }, { new Long( 55 ), Integer.class, new Integer( 55 ) }, { new Float( 55 ), Integer.class, new Integer( 55 ) }, { new BigInteger( "55" ), Integer.class, new Integer( 55 ) }, { new BigDecimal( "55" ), Integer.class, new Integer( 55 ) }, /* To Double.class */ { "55.1234", Double.class, new Double( 55.1234 ) }, { new Integer( 55 ), Double.class, new Double( 55 ) }, { new Double( 55.1234 ), Double.class, new Double( 55.1234 ) }, { Boolean.TRUE, Double.class, new Double( 1 ) }, { new Byte( (byte) 55 ), Double.class, new Double( 55 ) }, { new Character( (char) 55 ), Double.class, new Double( 55 ) }, { new Short( (short) 55 ), Double.class, new Double( 55 ) }, { new Long( 55 ), Double.class, new Double( 55 ) }, { new Float( 55.1234 ), Double.class, new Double( 55.1234 ), new Integer( 4 ) }, { new BigInteger( "55" ), Double.class, new Double( 55 ) }, { new BigDecimal( "55.1234" ), Double.class, new Double( 55.1234 ) }, /* To Boolean.class */ { "true", Boolean.class, Boolean.TRUE }, { new Integer( 55 ), Boolean.class, Boolean.TRUE }, { new Double( 55 ), Boolean.class, Boolean.TRUE }, { Boolean.TRUE, Boolean.class, Boolean.TRUE }, { new Byte( (byte) 55 ), Boolean.class, Boolean.TRUE }, { new Character( (char) 55 ), Boolean.class, Boolean.TRUE }, { new Short( (short) 55 ), Boolean.class, Boolean.TRUE }, { new Long( 55 ), Boolean.class, Boolean.TRUE }, { new Float( 55 ), Boolean.class, Boolean.TRUE }, { new BigInteger( "55" ), Boolean.class, Boolean.TRUE }, { new BigDecimal( "55" ), Boolean.class, Boolean.TRUE }, /* To Byte.class */ { "55", Byte.class, new Byte( (byte) 55 ) }, { new Integer( 55 ), Byte.class, new Byte( (byte) 55 ) }, { new Double( 55 ), Byte.class, new Byte( (byte) 55 ) }, { Boolean.TRUE, Byte.class, new Byte( (byte) 1 ) }, { new Byte( (byte) 55 ), Byte.class, new Byte( (byte) 55 ) }, { new Character( (char) 55 ), Byte.class, new Byte( (byte) 55 ) }, { new Short( (short) 55 ), Byte.class, new Byte( (byte) 55 ) }, { new Long( 55 ), Byte.class, new Byte( (byte) 55 ) }, { new Float( 55 ), Byte.class, new Byte( (byte) 55 ) }, { new BigInteger( "55" ), Byte.class, new Byte( (byte) 55 ) }, { new BigDecimal( "55" ), Byte.class, new Byte( (byte) 55 ) }, /* To Character.class */ { "55", Character.class, new Character( (char) 55 ) }, { new Integer( 55 ), Character.class, new Character( (char) 55 ) }, { new Double( 55 ), Character.class, new Character( (char) 55 ) }, { Boolean.TRUE, Character.class, new Character( (char) 1 ) }, { new Byte( (byte) 55 ), Character.class, new Character( (char) 55 ) }, { new Character( (char) 55 ), Character.class, new Character( (char) 55 ) }, { new Short( (short) 55 ), Character.class, new Character( (char) 55 ) }, { new Long( 55 ), Character.class, new Character( (char) 55 ) }, { new Float( 55 ), Character.class, new Character( (char) 55 ) }, { new BigInteger( "55" ), Character.class, new Character( (char) 55 ) }, { new BigDecimal( "55" ), Character.class, new Character( (char) 55 ) }, /* To Short.class */ { "55", Short.class, new Short( (short) 55 ) }, { new Integer( 55 ), Short.class, new Short( (short) 55 ) }, { new Double( 55 ), Short.class, new Short( (short) 55 ) }, { Boolean.TRUE, Short.class, new Short( (short) 1 ) }, { new Byte( (byte) 55 ), Short.class, new Short( (short) 55 ) }, { new Character( (char) 55 ), Short.class, new Short( (short) 55 ) }, { new Short( (short) 55 ), Short.class, new Short( (short) 55 ) }, { new Long( 55 ), Short.class, new Short( (short) 55 ) }, { new Float( 55 ), Short.class, new Short( (short) 55 ) }, { new BigInteger( "55" ), Short.class, new Short( (short) 55 ) }, { new BigDecimal( "55" ), Short.class, new Short( (short) 55 ) }, /* To Long.class */ { "55", Long.class, new Long( 55 ) }, { new Integer( 55 ), Long.class, new Long( 55 ) }, { new Double( 55 ), Long.class, new Long( 55 ) }, { Boolean.TRUE, Long.class, new Long( 1 ) }, { new Byte( (byte) 55 ), Long.class, new Long( 55 ) }, { new Character( (char) 55 ), Long.class, new Long( 55 ) }, { new Short( (short) 55 ), Long.class, new Long( 55 ) }, { new Long( 55 ), Long.class, new Long( 55 ) }, { new Float( 55 ), Long.class, new Long( 55 ) }, { new BigInteger( "55" ), Long.class, new Long( 55 ) }, { new BigDecimal( "55" ), Long.class, new Long( 55 ) }, /* To Float.class */ { "55.1234", Float.class, new Float( 55.1234 ) }, { new Integer( 55 ), Float.class, new Float( 55 ) }, { new Double( 55.1234 ), Float.class, new Float( 55.1234 ) }, { Boolean.TRUE, Float.class, new Float( 1 ) }, { new Byte( (byte) 55 ), Float.class, new Float( 55 ) }, { new Character( (char) 55 ), Float.class, new Float( 55 ) }, { new Short( (short) 55 ), Float.class, new Float( 55 ) }, { new Long( 55 ), Float.class, new Float( 55 ) }, { new Float( 55.1234 ), Float.class, new Float( 55.1234 ) }, { new BigInteger( "55" ), Float.class, new Float( 55 ) }, { new BigDecimal( "55.1234" ), Float.class, new Float( 55.1234 ) }, /* To BigInteger.class */ { "55", BigInteger.class, new BigInteger( "55" ) }, { new Integer( 55 ), BigInteger.class, new BigInteger( "55" ) }, { new Double( 55 ), BigInteger.class, new BigInteger( "55" ) }, { Boolean.TRUE, BigInteger.class, new BigInteger( "1" ) }, { new Byte( (byte) 55 ), BigInteger.class, new BigInteger( "55" ) }, { new Character( (char) 55 ), BigInteger.class, new BigInteger( "55" ) }, { new Short( (short) 55 ), BigInteger.class, new BigInteger( "55" ) }, { new Long( 55 ), BigInteger.class, new BigInteger( "55" ) }, { new Float( 55 ), BigInteger.class, new BigInteger( "55" ) }, { new BigInteger( "55" ), BigInteger.class, new BigInteger( "55" ) }, { new BigDecimal( "55" ), BigInteger.class, new BigInteger( "55" ) }, /* To BigDecimal.class */ { "55.1234", BigDecimal.class, new BigDecimal( "55.1234" ) }, { new Integer( 55 ), BigDecimal.class, new BigDecimal( "55" ) }, { new Double( 55.1234 ), BigDecimal.class, new BigDecimal( "55.1234" ), new Integer( 4 ) }, { Boolean.TRUE, BigDecimal.class, new BigDecimal( "1" ) }, { new Byte( (byte) 55 ), BigDecimal.class, new BigDecimal( "55" ) }, { new Character( (char) 55 ), BigDecimal.class, new BigDecimal( "55" ) }, { new Short( (short) 55 ), BigDecimal.class, new BigDecimal( "55" ) }, { new Long( 55 ), BigDecimal.class, new BigDecimal( "55" ) }, { new Float( 55.1234 ), BigDecimal.class, new BigDecimal( "55.1234" ), new Integer( 4 ) }, { new BigInteger( "55" ), BigDecimal.class, new BigDecimal( "55" ) }, { new BigDecimal( "55.1234" ), BigDecimal.class, new BigDecimal( "55.1234" ) }, }; private final Object value; private final Class<? extends Number> toClass; private final Object expectedValue; private final int scale; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[4]; tmp[0] = element[0]; tmp[1] = element[1]; tmp[2] = element[2]; tmp[3] = ( element.length > 3 ) ? ( (Integer) element[3] ).intValue() : -1 ; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public NumericConversionTest( Object value, Class<? extends Number> toClass, Object expectedValue, int scale ) { super( value + " [" + value.getClass().getName() + "] -> " + toClass.getName() + " == " + expectedValue + " [" + expectedValue.getClass().getName() + "]" + ( ( scale >= 0 ) ? ( " (to within " + scale + " decimal places)" ) : "" ), null, null, null, null, null ); this.value = value; this.toClass = toClass; this.expectedValue = expectedValue; this.scale = scale; } /* * =================================================================== Overridden methods * =================================================================== */ @Test @Override public void runTest() throws OgnlException { Object result; result = OgnlOps.convertValue( value, toClass ); if ( !isEqual( result, expectedValue ) ) { if ( scale >= 0 ) { double scalingFactor = Math.pow( 10, scale ), v1 = ( (Number) value ).doubleValue() * scalingFactor, v2 = ( (Number) expectedValue ).doubleValue() * scalingFactor; Assert.assertEquals((int) v1, (int) v2); } else { fail(); } } } }
4,448
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/IndexedPropertyTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.test.objects.Indexed; import org.apache.commons.ognl.test.objects.Root; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class IndexedPropertyTest extends OgnlTestCase { private static final Indexed INDEXED = new Indexed(); private static final Root ROOT = new Root(); private static final Object[][] TESTS = { // Indexed properties { INDEXED, "getValues", INDEXED.getValues() }, // gets String[] { INDEXED, "[\"values\"]", INDEXED.getValues() }, // String[] { INDEXED.getValues(), "[0]", INDEXED.getValues()[0] }, // "foo" { INDEXED, "getValues()[0]", INDEXED.getValues()[0] }, // "foo" directly from array { INDEXED, "values[0]", INDEXED.getValues( 0 ) }, // "foo" + "xxx" { INDEXED, "values[^]", INDEXED.getValues( 0 ) }, // "foo" + "xxx" { INDEXED, "values[|]", INDEXED.getValues( 1 ) }, // "bar" + "xxx" { INDEXED, "values[$]", INDEXED.getValues( 2 ) }, // "baz" + "xxx" { INDEXED, "values[1]", "bar" + "xxx", "xxxx" + "xxx", "xxxx" + "xxx" }, // set through setValues(int, String) { INDEXED, "values[1]", "xxxx" + "xxx" }, // getValues(int) again to check if setValues(int, String) was called { INDEXED, "setValues(2, \"xxxx\")", null }, // was "baz" -> "xxxx" { INDEXED, "getTitle(list.size)", "Title count 3" }, { INDEXED, "source.total", 1 }, { ROOT, "indexer.line[index]", "line:1" }, { INDEXED, "list[2].longValue()", (long) 3 }, { ROOT, "map.value.id", (long) 1 }, { INDEXED, "property['hoodak']", null, "random string", "random string" } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public IndexedPropertyTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,449
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/CompilingPropertyAccessor.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.commons.ognl.test; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.LoaderClassPath; import org.apache.commons.ognl.ObjectPropertyAccessor; import org.apache.commons.ognl.OgnlContext; import org.apache.commons.ognl.OgnlException; import org.apache.commons.ognl.OgnlRuntime; import org.apache.commons.ognl.enhance.ContextClassLoader; import org.apache.commons.ognl.enhance.EnhancedClassLoader; import org.apache.commons.ognl.test.util.NameFactory; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; /** * Implementation of PropertyAccessor that uses Javassist to compile a property accessor specifically tailored to the * property. */ public class CompilingPropertyAccessor extends ObjectPropertyAccessor { private static final NameFactory NAME_FACTORY = new NameFactory( "ognl.PropertyAccessor", "v" ); private static final Getter NOT_FOUND_GETTER = (context, target, propertyName) -> null; private static final Getter DEFAULT_GETTER = (context, target, propertyName) -> { try { return OgnlRuntime.getMethodValue( context, target, propertyName, true ); } catch ( Exception ex ) { throw new IllegalStateException( ex ); } }; private static final Map POOLS = new HashMap(); private static final Map LOADERS = new HashMap(); private static final java.util.IdentityHashMap PRIMITIVE_WRAPPER_CLASSES = new IdentityHashMap(); private final java.util.IdentityHashMap seenGetMethods = new java.util.IdentityHashMap(); static { PRIMITIVE_WRAPPER_CLASSES.put( Boolean.TYPE, Boolean.class ); PRIMITIVE_WRAPPER_CLASSES.put( Boolean.class, Boolean.TYPE ); PRIMITIVE_WRAPPER_CLASSES.put( Byte.TYPE, Byte.class ); PRIMITIVE_WRAPPER_CLASSES.put( Byte.class, Byte.TYPE ); PRIMITIVE_WRAPPER_CLASSES.put( Character.TYPE, Character.class ); PRIMITIVE_WRAPPER_CLASSES.put( Character.class, Character.TYPE ); PRIMITIVE_WRAPPER_CLASSES.put( Short.TYPE, Short.class ); PRIMITIVE_WRAPPER_CLASSES.put( Short.class, Short.TYPE ); PRIMITIVE_WRAPPER_CLASSES.put( Integer.TYPE, Integer.class ); PRIMITIVE_WRAPPER_CLASSES.put( Integer.class, Integer.TYPE ); PRIMITIVE_WRAPPER_CLASSES.put( Long.TYPE, Long.class ); PRIMITIVE_WRAPPER_CLASSES.put( Long.class, Long.TYPE ); PRIMITIVE_WRAPPER_CLASSES.put( Float.TYPE, Float.class ); PRIMITIVE_WRAPPER_CLASSES.put( Float.class, Float.TYPE ); PRIMITIVE_WRAPPER_CLASSES.put( Double.TYPE, Double.class ); PRIMITIVE_WRAPPER_CLASSES.put( Double.class, Double.TYPE ); } public static Class getPrimitiveWrapperClass( Class primitiveClass ) { return (Class) PRIMITIVE_WRAPPER_CLASSES.get( primitiveClass ); } public interface Getter { Object get( OgnlContext context, Object target, String propertyName ); } public static Getter generateGetter( OgnlContext context, String code ) throws OgnlException { String className = NAME_FACTORY.getNewClassName(); try { ClassPool pool = (ClassPool) POOLS.get( context.getClassResolver() ); EnhancedClassLoader loader = (EnhancedClassLoader) LOADERS.get( context.getClassResolver() ); CtClass newClass; CtClass ognlContextClass; CtClass objectClass; CtClass stringClass; CtMethod method; byte[] byteCode; Class compiledClass; if ( ( pool == null ) || ( loader == null ) ) { ClassLoader classLoader = new ContextClassLoader( OgnlContext.class.getClassLoader(), context ); pool = ClassPool.getDefault(); pool.insertClassPath( new LoaderClassPath( classLoader ) ); POOLS.put( context.getClassResolver(), pool ); loader = new EnhancedClassLoader( classLoader ); LOADERS.put( context.getClassResolver(), loader ); } newClass = pool.makeClass( className ); ognlContextClass = pool.get( OgnlContext.class.getName() ); objectClass = pool.get( Object.class.getName() ); stringClass = pool.get( String.class.getName() ); newClass.addInterface( pool.get( Getter.class.getName() ) ); method = new CtMethod( objectClass, "get", new CtClass[] { ognlContextClass, objectClass, stringClass }, newClass ); method.setBody( "{" + code + "}" ); newClass.addMethod( method ); byteCode = newClass.toBytecode(); compiledClass = loader.defineClass( className, byteCode ); return (Getter) compiledClass.newInstance(); } catch ( Throwable ex ) { throw new OgnlException( "Cannot create class", ex ); } } private Getter getGetter( OgnlContext context, Object target, String propertyName ) throws OgnlException { Getter result; Class targetClass = target.getClass(); Map propertyMap; if ( ( propertyMap = (Map) seenGetMethods.get( targetClass ) ) == null ) { propertyMap = new HashMap( 101 ); seenGetMethods.put( targetClass, propertyMap ); } if ( ( result = (Getter) propertyMap.get( propertyName ) ) == null ) { try { Method method = OgnlRuntime.getGetMethod( context, targetClass, propertyName ); if ( method != null ) { if ( Modifier.isPublic( method.getModifiers() ) ) { if ( method.getReturnType().isPrimitive() ) { propertyMap.put( propertyName, result = generateGetter( context, "java.lang.Object\t\tresult;\n" + targetClass.getName() + "\t" + "t0 = (" + targetClass.getName() + ")$2;\n" + "\n" + "try {\n" + " result = new " + getPrimitiveWrapperClass( method.getReturnType() ).getName() + "(t0." + method.getName() + "());\n" + "} catch (java.lang.Exception ex) {\n" + " throw new java.lang.RuntimeException(ex);\n" + "}\n" + "return result;" ) ); } else { propertyMap.put( propertyName, result = generateGetter( context, "java.lang.Object\t\tresult;\n" + targetClass.getName() + "\t" + "t0 = (" + targetClass.getName() + ")$2;\n" + "\n" + "try {\n" + " result = t0." + method.getName() + "();\n" + "} catch (java.lang.Exception ex) {\n" + " throw new java.lang.RuntimeException(ex);\n" + "}\n" + "return result;" ) ); } } else { propertyMap.put( propertyName, result = DEFAULT_GETTER ); } } else { propertyMap.put( propertyName, result = NOT_FOUND_GETTER ); } } catch ( Exception ex ) { throw new OgnlException( "getting getter", ex ); } } return result; } /** * Returns OgnlRuntime.NotFound if the property does not exist. */ public Object getPossibleProperty( Map context, Object target, String name ) throws OgnlException { Object result; OgnlContext ognlContext = (OgnlContext) context; if ( context.get( "_compile" ) != null ) { Getter getter = getGetter( ognlContext, target, name ); if ( getter != NOT_FOUND_GETTER ) { result = getter.get( ognlContext, target, name ); } else { try { result = OgnlRuntime.getFieldValue( ognlContext, target, name, true ); } catch ( Exception ex ) { throw new OgnlException( name, ex ); } } } else { result = super.getPossibleProperty( context, target, name ); } return result; } }
4,450
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/CorrectedObjectNullHandler.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.commons.ognl.test; import org.apache.commons.ognl.NullHandler; import java.util.Map; public class CorrectedObjectNullHandler extends Object implements NullHandler { private final String defaultValue; /* * =================================================================== Constructors * =================================================================== */ public CorrectedObjectNullHandler( String defaultValue ) { this.defaultValue = defaultValue; } /* * =================================================================== TypeConverter interface (overridden) * =================================================================== */ public Object nullMethodResult( Map context, Object target, String methodName, Object[] args ) { if ( methodName.equals( "getStringValue" ) ) { return defaultValue; } return null; } public Object nullPropertyValue( Map context, Object target, Object property ) { if ( property.equals( "stringValue" ) ) { return defaultValue; } return null; } }
4,451
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ArrayElementsTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.apache.commons.ognl.test.objects.Root; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class ArrayElementsTest extends OgnlTestCase { private static final String[] STRING_ARRAY = new String[] { "hello", "world" }; private static final int[] INT_ARRAY = new int[] { 10, 20 }; private static final Root ROOT = new Root(); private static final Object[][] TESTS = { // Array elements test { STRING_ARRAY, "length", 2 }, { STRING_ARRAY, "#root[1]", "world" }, { INT_ARRAY, "#root[1]", 20 }, { INT_ARRAY, "#root[1]", 20, "50", 50 }, { INT_ARRAY, "#root[1]", 50, new String[] { "50", "100" }, 50 }, { ROOT, "intValue", 0, new String[] { "50", "100" }, 50 }, { ROOT, "array", ROOT.getArray(), new String[] { "50", "100" }, new int[] { 50, 100 } }, { null, "\"{Hello}\".toCharArray()[6]", '}' }, { null, "\"Tapestry\".toCharArray()[2]", 'p' }, { null, "{'1','2','3'}", Arrays.asList( '1', '2', '3' ) }, { null, "{ true, !false }", Arrays.asList( Boolean.TRUE, Boolean.TRUE ) } }; /* * =================================================================== Private static methods * =================================================================== */ /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for ( Object[] TEST : TESTS ) { Object[] tmp = new Object[6]; tmp[0] = TEST[1]; tmp[1] = TEST[0]; tmp[2] = TEST[1]; switch ( TEST.length ) { case 3: tmp[3] = TEST[2]; break; case 4: tmp[3] = TEST[2]; tmp[4] = TEST[3]; break; case 5: tmp[3] = TEST[2]; tmp[4] = TEST[3]; tmp[5] = TEST[4]; break; default: fail( "don't understand TEST format with length" ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public ArrayElementsTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } /* * =================================================================== Overridden methods * =================================================================== */ @Override @Before public void setUp() { super.setUp(); /** * TypeConverter arrayConverter; * arrayConverter = new DefaultTypeConverter() { public Object convertValue(Map context, Object target, Member * member, String propertyName, Object value, Class toType) { if (value.getClass().isArray()) { if * (!toType.isArray()) { value = Array.get(value, 0); } } return super.convertValue(context, target, member, * propertyName, value, toType); } }; _context.setTypeConverter(arrayConverter); */ } }
4,452
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/OgnlTestCase.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.commons.ognl.test; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import org.apache.commons.ognl.Ognl; import org.apache.commons.ognl.OgnlContext; import org.apache.commons.ognl.SimpleNode; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public abstract class OgnlTestCase { protected OgnlContext _context; private final String _expressionString; private SimpleNode _expression; private final Object _expectedResult; private final Object _root; protected boolean _compileExpressions = true; private final boolean hasSetValue; private final Object setValue; private final boolean hasExpectedAfterSetResult; private final Object expectedAfterSetResult; /* * =================================================================== Public static methods * =================================================================== */ /** * Returns true if object1 is equal to object2 in either the sense that they are the same object or, if both are * non-null if they are equal in the <CODE>equals()</CODE> sense. */ public static boolean isEqual( Object object1, Object object2 ) { boolean result = false; if ( object1 == object2 ) { result = true; } else { if ( ( object1 != null ) && object1.getClass().isArray() ) { if ( ( object2 != null ) && object2.getClass().isArray() && ( object2.getClass() == object1.getClass() ) ) { result = ( Array.getLength( object1 ) == Array.getLength( object2 ) ); if ( result ) { for ( int i = 0, icount = Array.getLength( object1 ); result && ( i < icount ); i++ ) { result = isEqual( Array.get( object1, i ), Array.get( object2, i ) ); } } } } else { result = ( object1 != null ) && ( object2 != null ) && object1.equals( object2 ); } } return result; } /* * =================================================================== Constructors * =================================================================== */ public OgnlTestCase(String name, Object root, String expressionString, Object expectedResult) { this( name, root, expressionString, expectedResult, null, false, null, false); } public OgnlTestCase( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { this( name, root, expressionString, expectedResult, setValue, setValue != null, expectedAfterSetResult, expectedAfterSetResult != null ); } public OgnlTestCase( String name, Object root, String expressionString, Object expectedResult, Object setValue, boolean hasSetValue, Object expectedAfterSetResult, boolean hasExpectedAfterSetResult ) { this._root = root; this._expressionString = expressionString; this._expectedResult = expectedResult; this.hasExpectedAfterSetResult = hasExpectedAfterSetResult; this.expectedAfterSetResult = expectedAfterSetResult; this.hasSetValue = hasSetValue; this.setValue = setValue; } /* * =================================================================== Public methods * =================================================================== */ public String getExpressionDump( SimpleNode node ) { StringWriter writer = new StringWriter(); node.dump( new PrintWriter( writer ), " " ); return writer.toString(); } public String getExpressionString() { return _expressionString; } public SimpleNode getExpression() throws Exception { if ( _expression == null ) { _expression = (SimpleNode) Ognl.parseExpression( _expressionString ); } if ( _compileExpressions ) { _expression = (SimpleNode) Ognl.compileExpression( _context, _root, _expressionString ); } return _expression; } public Object getExpectedResult() { return _expectedResult; } public static void assertEquals( Object expected, Object actual ) { if ( expected != null && expected.getClass().isArray() && actual != null && actual.getClass().isArray() ) { Assert.assertEquals( Array.getLength( expected ), Array.getLength( actual ) ); int length = Array.getLength( expected ); for ( int i = 0; i < length; i++ ) { Object aexpected = Array.get( expected, i ); Object aactual = Array.get( actual, i ); if ( aexpected != null && aactual != null && Boolean.class.isAssignableFrom( aexpected.getClass() ) ) { Assert.assertEquals( aexpected.toString(), aactual.toString() ); } else OgnlTestCase.assertEquals( aexpected, aactual ); } } else if ( expected != null && actual != null && Character.class.isInstance( expected ) && Character.class.isInstance( actual ) ) { Assert.assertEquals( ( (Character) expected ).charValue(), ( (Character) actual ).charValue() ); } else { Assert.assertEquals( expected, actual ); } } /* * =================================================================== Overridden methods * =================================================================== */ @Test public void runTest() throws Exception { Object testedResult = null; try { SimpleNode expr; testedResult = _expectedResult; expr = getExpression(); assertEquals( _expectedResult, Ognl.getValue( expr, _context, _root ) ); if ( hasSetValue ) { testedResult = hasExpectedAfterSetResult ? expectedAfterSetResult : setValue; Ognl.setValue( expr, _context, _root, setValue ); assertEquals( testedResult, Ognl.getValue( expr, _context, _root ) ); } } catch ( Exception ex ) { if ( RuntimeException.class.isInstance( ex ) && ex.getCause() != null && Exception.class.isAssignableFrom( ex.getCause().getClass() ) ) { ex = (Exception) ex.getCause(); } if ( !(testedResult instanceof Class) ) { throw ex; } Assert.assertTrue( Exception.class.isAssignableFrom( (Class<?>) testedResult ) ); } } @Before public void setUp() { _context = (OgnlContext) Ognl.createDefaultContext( null ); } }
4,453
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ObjectIndexedTest.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.commons.ognl.test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.ognl.Ognl; import org.apache.commons.ognl.OgnlContext; import org.apache.commons.ognl.OgnlException; import org.apache.commons.ognl.OgnlRuntime; import org.apache.commons.ognl.SimpleNode; import org.junit.Before; public class ObjectIndexedTest extends TestCase { protected OgnlContext context; /* * =================================================================== Public static classes * =================================================================== */ public interface TestInterface { String getSunk( String index ); void setSunk( String index, String sunk ); } public static class Test1 extends Object implements TestInterface { public String getSunk( String index ) { return "foo"; } public void setSunk( String index, String sunk ) { /* do nothing */ } } public static class Test2 extends Test1 { public String getSunk( String index ) { return "foo"; } public void setSunk( String index, String sunk ) { /* do nothing */ } } public static class Test3 extends Test1 { public String getSunk( String index ) { return "foo"; } public void setSunk( String index, String sunk ) { /* do nothing */ } public String getSunk( Object index ) { return null; } } public static class Test4 extends Test1 { public String getSunk( String index ) { return "foo"; } public void setSunk( String index, String sunk ) { /* do nothing */ } public void setSunk( Object index, String sunk ) { /* do nothing */ } } public static class Test5 extends Test1 { public String getSunk( String index ) { return "foo"; } public void setSunk( String index, String sunk ) { /* do nothing */ } public String getSunk( Object index ) { return null; } public void setSunk( Object index, String sunk ) { /* do nothing */ } } /* * =================================================================== Public static methods * =================================================================== */ public static TestSuite suite() { return new TestSuite( ObjectIndexedTest.class ); } /* * =================================================================== Constructors * =================================================================== */ public ObjectIndexedTest() { } public ObjectIndexedTest( String name ) { super( name ); } /* * =================================================================== Public methods * =================================================================== */ public void testPropertyDescriptorReflection() throws Exception { OgnlRuntime.getPropertyDescriptor( java.util.AbstractList.class, "" ); OgnlRuntime.getPropertyDescriptor( java.util.AbstractSequentialList.class, "" ); OgnlRuntime.getPropertyDescriptor( java.lang.reflect.Array.class, "" ); OgnlRuntime.getPropertyDescriptor( java.util.ArrayList.class, "" ); OgnlRuntime.getPropertyDescriptor( java.util.BitSet.class, "" ); OgnlRuntime.getPropertyDescriptor( java.util.Calendar.class, "" ); OgnlRuntime.getPropertyDescriptor( java.lang.reflect.Field.class, "" ); OgnlRuntime.getPropertyDescriptor( java.util.LinkedList.class, "" ); OgnlRuntime.getPropertyDescriptor( java.util.List.class, "" ); OgnlRuntime.getPropertyDescriptor( java.util.Iterator.class, "" ); OgnlRuntime.getPropertyDescriptor( java.lang.ThreadLocal.class, "" ); OgnlRuntime.getPropertyDescriptor( java.net.URL.class, "" ); OgnlRuntime.getPropertyDescriptor( java.util.Vector.class, "" ); } public void testObjectIndexAccess() throws OgnlException { SimpleNode expression = (SimpleNode) Ognl.parseExpression( "#ka.sunk[#root]" ); context.put( "ka", new Test1() ); Ognl.getValue( expression, context, "aksdj" ); } public void testObjectIndexInSubclass() throws OgnlException { SimpleNode expression = (SimpleNode) Ognl.parseExpression( "#ka.sunk[#root]" ); context.put( "ka", new Test2() ); Ognl.getValue( expression, context, "aksdj" ); } public void testMultipleObjectIndexGetters() throws OgnlException { SimpleNode expression = (SimpleNode) Ognl.parseExpression( "#ka.sunk[#root]" ); context.put( "ka", new Test3() ); try { Ognl.getValue( expression, context, new Test3() ); fail(); } catch ( OgnlException ex ) { /* Should throw */ } } public void testMultipleObjectIndexSetters() throws OgnlException { SimpleNode expression = (SimpleNode) Ognl.parseExpression( "#ka.sunk[#root]" ); context.put( "ka", new Test4() ); try { Ognl.getValue( expression, context, "aksdj" ); fail(); } catch ( OgnlException ex ) { /* Should throw */ } } public void testMultipleObjectIndexMethodPairs() throws OgnlException { SimpleNode expression = (SimpleNode) Ognl.parseExpression( "#ka.sunk[#root]" ); context.put( "ka", new Test5() ); try { Ognl.getValue( expression, context, "aksdj" ); fail(); } catch ( OgnlException ex ) { /* Should throw */ } } /* * =================================================================== Overridden methods * =================================================================== */ @Override @Before protected void setUp() { context = (OgnlContext) Ognl.createDefaultContext( null ); } }
4,454
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/GenericsTest.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.commons.ognl.test; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.test.objects.BaseGeneric; import org.apache.commons.ognl.test.objects.GameGeneric; import org.apache.commons.ognl.test.objects.GameGenericObject; import org.apache.commons.ognl.test.objects.GenericRoot; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Tests java >= 1.5 generics support in ognl. */ @RunWith(value = Parameterized.class) public class GenericsTest extends OgnlTestCase { static GenericRoot ROOT = new GenericRoot(); static BaseGeneric<GameGenericObject, Long> GENERIC = new GameGeneric(); static Object[][] TESTS = { /* { ROOT, "cracker.param", null, new Integer(2), new Integer(2)}, */ { GENERIC, "ids", null, new Long[] { 1l, 101l }, new Long[] { 1l, 101l } }, /* { GENERIC, "ids", new Long[] {1l, 101l}, new String[] {"2", "34"}, new Long[]{2l, 34l}}, */ }; @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1] + " (" + element[2] + ")"; tmp[1] = element[0]; tmp[2] = element[1]; tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; data.add( tmp ); } return data; } public GenericsTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,455
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/SimpleNavigationChainTreeTest.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.commons.ognl.test; import static junit.framework.Assert.assertTrue; import java.util.ArrayList; import java.util.Collection; import junit.framework.Assert; import org.apache.commons.ognl.Ognl; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class SimpleNavigationChainTreeTest extends OgnlTestCase { private static final Object[][] TESTS = { { "name", Boolean.TRUE }, { "name[i]", Boolean.FALSE }, { "name + foo", Boolean.FALSE }, { "name.foo", Boolean.TRUE } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[0] + " (" + element[1] + ")"; tmp[1] = null; tmp[2] = element[0]; tmp[3] = element[1]; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public SimpleNavigationChainTreeTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } /* * =================================================================== Overridden methods * =================================================================== */ @Test @Override public void runTest() throws Exception { Assert.assertEquals(Ognl.isSimpleNavigationChain(getExpression(), _context), ((Boolean) getExpectedResult()).booleanValue()); } }
4,456
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/OperatorTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class OperatorTest extends OgnlTestCase { private static final Object[][] TESTS = { { null, "\"one\" > \"two\"", Boolean.FALSE }, { null, "\"one\" >= \"two\"", Boolean.FALSE }, { null, "\"one\" < \"two\"", Boolean.TRUE }, { null, "\"one\" <= \"two\"", Boolean.TRUE }, { null, "\"one\" == \"two\"", Boolean.FALSE }, { null, "\"o\" > \"o\"", Boolean.FALSE }, { null, "\"o\" gt \"o\"", Boolean.FALSE }, { null, "\"o\" >= \"o\"", Boolean.TRUE }, { null, "\"o\" gte \"o\"", Boolean.TRUE }, { null, "\"o\" < \"o\"", Boolean.FALSE }, { null, "\"o\" lt \"o\"", Boolean.FALSE }, { null, "\"o\" <= \"o\"", Boolean.TRUE }, { null, "\"o\" lte \"o\"", Boolean.TRUE }, { null, "\"o\" == \"o\"", Boolean.TRUE }, { null, "\"o\" eq \"o\"", Boolean.TRUE }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public OperatorTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,457
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/MethodTest.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.commons.ognl.test; import org.apache.commons.ognl.test.objects.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Collection; @RunWith(value = Parameterized.class) public class MethodTest extends OgnlTestCase { private static final Simple ROOT = new Simple(); private static final ListSource LIST = new ListSourceImpl(); private static final BaseGeneric<GameGenericObject, Long> GENERIC = new GameGeneric(); private static final Object[][] TESTS = { { "hashCode()", new Integer( ROOT.hashCode() ) }, { "getBooleanValue() ? \"here\" : \"\"", "" }, { "getValueIsTrue(!false) ? \"\" : \"here\" ", "" }, { "messages.format('ShowAllCount', new Object[]{one,two})", "foo" }, { "messages.format('ShowAllCount', one)", "first" }, { "getTestValue(@org.apache.commons.ognl.test.objects.SimpleEnum@ONE.value)", new Integer( 2 ) }, { "@org.apache.commons.ognl.test.MethodTest@getA().isProperty()", Boolean.FALSE }, { "isDisabled()", Boolean.TRUE }, { "isEditorDisabled()", Boolean.FALSE }, { LIST, "addValue(name)", Boolean.TRUE }, { "getDisplayValue(methodsTest.allowDisplay)", "test" }, { "isThisVarArgsWorking(three, rootValue)", Boolean.TRUE }, { GENERIC, "service.getFullMessageFor(value, null)", "Halo 3" } }; public static class A { public boolean isProperty() { return false; } } public static A getA() { return new A(); } /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; if ( element.length == 3 ) { tmp[0] = element[1] + " (" + element[2] + ")"; tmp[1] = element[0]; tmp[2] = element[1]; tmp[3] = element[2]; } else { tmp[0] = element[0] + " (" + element[1] + ")"; tmp[1] = ROOT; tmp[2] = element[0]; tmp[3] = element[1]; } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public MethodTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,458
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ASTPropertyTest.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.commons.ognl.test; import junit.framework.TestCase; import org.apache.commons.ognl.ASTChain; import org.apache.commons.ognl.ASTConst; import org.apache.commons.ognl.ASTProperty; import org.apache.commons.ognl.Ognl; import org.apache.commons.ognl.OgnlContext; import org.apache.commons.ognl.OgnlRuntime; import org.apache.commons.ognl.SimpleNode; import org.apache.commons.ognl.test.objects.BaseGeneric; import org.apache.commons.ognl.test.objects.GameGeneric; import org.apache.commons.ognl.test.objects.GameGenericObject; import org.apache.commons.ognl.test.objects.GenericRoot; import org.apache.commons.ognl.test.objects.Root; import java.util.List; import java.util.Map; import static org.apache.commons.ognl.test.OgnlTestCase.isEqual; /** * Tests functionality of {@link org.apache.commons.ognl.ASTProperty}. */ public class ASTPropertyTest extends TestCase { public void test_Get_Indexed_Property_Type() throws Exception { ASTProperty p = new ASTProperty( 0 ); p.setIndexedAccess( false ); ASTConst pRef = new ASTConst( 0 ); pRef.setValue( "nested" ); pRef.jjtSetParent( p ); p.jjtAddChild( pRef, 0 ); Map root = new Root().getMap(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); context.setCurrentNode( pRef ); assertEquals( root.getClass(), context.getCurrentType() ); assertNull(context.getPreviousType()); assertEquals( root, context.getCurrentObject() ); assertNull(context.getCurrentAccessor()); assertNull(context.getPreviousAccessor()); int type = p.getIndexedPropertyType( context, root ); assertEquals( OgnlRuntime.INDEXED_PROPERTY_NONE, type ); assertEquals( root.getClass(), context.getCurrentType() ); assertNull(context.getPreviousType()); assertNull(context.getCurrentAccessor()); assertNull(context.getPreviousAccessor()); } public void test_Get_Value_Body() throws Exception { ASTProperty p = new ASTProperty( 0 ); p.setIndexedAccess( false ); ASTConst pRef = new ASTConst( 0 ); pRef.setValue( "nested" ); pRef.jjtSetParent( p ); p.jjtAddChild( pRef, 0 ); Map root = new Root().getMap(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); context.setCurrentNode( pRef ); assertEquals( root.getClass(), context.getCurrentType() ); assertNull(context.getPreviousType()); assertEquals( root, context.getCurrentObject() ); assertNull(context.getCurrentAccessor()); assertNull(context.getPreviousAccessor()); Object value = p.getValue( context, root ); assertEquals( root.get( "nested" ), value ); assertEquals( root.getClass(), context.getCurrentType() ); assertNull(context.getPreviousType()); assertNull(context.getCurrentAccessor()); assertNull(context.getPreviousAccessor()); } public void test_Get_Source() throws Throwable { ASTProperty p = new ASTProperty( 0 ); p.setIndexedAccess( false ); ASTConst pRef = new ASTConst( 0 ); pRef.setValue( "nested" ); pRef.jjtSetParent( p ); p.jjtAddChild( pRef, 0 ); Map root = new Root().getMap(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); context.setCurrentNode( pRef ); assertEquals( ".get(\"nested\")", p.toGetSourceString( context, root ) ); assertEquals( Object.class, context.getCurrentType() ); assertEquals( Map.class, context.getCurrentAccessor() ); assertEquals( root.getClass(), context.getPreviousType() ); assertNull(context.getPreviousAccessor()); assertEquals( root.get( "nested" ), context.getCurrentObject() ); assert Map.class.isAssignableFrom( context.getCurrentAccessor() ); assertEquals( root.getClass(), context.getPreviousType() ); assertNull(context.getPreviousAccessor()); } public void test_Set_Source() throws Throwable { ASTProperty p = new ASTProperty( 0 ); p.setIndexedAccess( false ); ASTConst pRef = new ASTConst( 0 ); pRef.setValue( "nested" ); pRef.jjtSetParent( p ); p.jjtAddChild( pRef, 0 ); Map root = new Root().getMap(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); context.setCurrentNode( pRef ); assertEquals( ".put(\"nested\", $3)", p.toSetSourceString( context, root ) ); assertEquals( Object.class, context.getCurrentType() ); assertEquals( root.get( "nested" ), context.getCurrentObject() ); assert Map.class.isAssignableFrom( context.getCurrentAccessor() ); assertEquals( root.getClass(), context.getPreviousType() ); assertNull(context.getPreviousAccessor()); } public void test_Indexed_Object_Type() throws Throwable { // ASTChain chain = new ASTChain(0); ASTProperty listp = new ASTProperty( 0 ); listp.setIndexedAccess( false ); // listp.jjtSetParent(chain); ASTConst listc = new ASTConst( 0 ); listc.setValue( "list" ); listc.jjtSetParent( listp ); listp.jjtAddChild( listc, 0 ); // chain.jjtAddChild(listp, 0); ASTProperty p = new ASTProperty( 0 ); p.setIndexedAccess( true ); ASTProperty pindex = new ASTProperty( 0 ); ASTConst pRef = new ASTConst( 0 ); pRef.setValue( "genericIndex" ); pRef.jjtSetParent( pindex ); pindex.jjtAddChild( pRef, 0 ); p.jjtAddChild( pindex, 0 ); // chain.jjtAddChild(p, 1); Root root = new Root(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); context.setCurrentNode( listp ); assertEquals( ".getList()", listp.toGetSourceString( context, root ) ); assertEquals( List.class, context.getCurrentType() ); assertEquals( Root.class, context.getCurrentAccessor() ); assertNull(context.getPreviousAccessor()); assertEquals( root.getClass(), context.getPreviousType() ); assertEquals( root.getList(), context.getCurrentObject() ); // re test with chain context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); ASTChain chain = new ASTChain( 0 ); listp.jjtSetParent( chain ); chain.jjtAddChild( listp, 0 ); context.setCurrentNode( chain ); assertEquals( ".getList()", chain.toGetSourceString( context, root ) ); assertEquals( List.class, context.getCurrentType() ); assertEquals( Root.class, context.getCurrentAccessor() ); assertNull(context.getPreviousAccessor()); assertEquals( Root.class, context.getPreviousType() ); assertEquals( root.getList(), context.getCurrentObject() ); // test with only getIndex assertEquals( ".get(org.apache.commons.ognl.OgnlOps#getIntValue(((org.apache.commons.ognl.test.objects.Root)$2)..getGenericIndex().toString()))", p.toGetSourceString( context, root.getList() ) ); assertEquals( root.getArray(), context.getCurrentObject() ); assertEquals( Object.class, context.getCurrentType() ); } public void test_Complicated_List() throws Exception { Root root = new Root(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); SimpleNode node = (SimpleNode) Ognl.compileExpression( context, root, "{ new org.apache.commons.ognl.test.objects.MenuItem('Home', 'Main', " + "{ new org.apache.commons.ognl.test.objects.MenuItem('Help', 'Help'), " + "new org.apache.commons.ognl.test.objects.MenuItem('Contact', 'Contact') }), " // end // first // item + "new org.apache.commons.ognl.test.objects.MenuItem('UserList', getMessages().getMessage('menu.members')), " + "new org.apache.commons.ognl.test.objects.MenuItem('account/BetSlipList', getMessages().getMessage('menu.account'), " + "{ new org.apache.commons.ognl.test.objects.MenuItem('account/BetSlipList', 'My Bets'), " + "new org.apache.commons.ognl.test.objects.MenuItem('account/TransactionList', 'My Transactions') }), " + "new org.apache.commons.ognl.test.objects.MenuItem('About', 'About'), " + "new org.apache.commons.ognl.test.objects.MenuItem('admin/Admin', getMessages().getMessage('menu.admin'), " + "{ new org.apache.commons.ognl.test.objects.MenuItem('admin/AddEvent', 'Add event'), " + "new org.apache.commons.ognl.test.objects.MenuItem('admin/AddResult', 'Add result') })}" ); assertTrue( List.class.isAssignableFrom( node.getAccessor().get( context, root ).getClass() ) ); } public void test_Set_Chain_Indexed_Property() throws Exception { Root root = new Root(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); SimpleNode node = (SimpleNode) Ognl.parseExpression( "tab.searchCriteriaSelections[index1][index2]" ); node.setValue( context, root, Boolean.FALSE ); } public void test_Set_Generic_Property() throws Exception { GenericRoot root = new GenericRoot(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); SimpleNode node = (SimpleNode) Ognl.parseExpression( "cracker.param" ); node.setValue( context, root, "0" ); assertEquals( new Integer( 0 ), root.getCracker().getParam() ); node.setValue( context, root, "10" ); assertEquals( new Integer( 10 ), root.getCracker().getParam() ); } public void test_Get_Generic_Property() throws Exception { GenericRoot root = new GenericRoot(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); SimpleNode node = (SimpleNode) Ognl.parseExpression( "cracker.param" ); node.setValue( context, root, "0" ); assertEquals( new Integer( 0 ), node.getValue( context, root ) ); node.setValue( context, root, "10" ); assertEquals( new Integer( 10 ), node.getValue( context, root ) ); } public void test_Set_Get_Multiple_Generic_Types_Property() throws Exception { BaseGeneric<GameGenericObject, Long> root = new GameGeneric(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); SimpleNode node = (SimpleNode) Ognl.parseExpression( "ids" ); node.setValue( context, root, new String[] { "0", "20", "43" } ); isEqual( new Long[] { new Long( 0 ), new Long( 20 ), new Long( 43 ) }, root.getIds() ); isEqual( node.getValue( context, root ), root.getIds() ); } }
4,459
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/SimplePropertyTreeTest.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.commons.ognl.test; import static junit.framework.Assert.assertTrue; import java.util.ArrayList; import java.util.Collection; import junit.framework.Assert; import org.apache.commons.ognl.Ognl; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class SimplePropertyTreeTest extends OgnlTestCase { private static final Object[][] TESTS = { { "name", Boolean.TRUE }, { "foo", Boolean.TRUE }, { "name[i]", Boolean.FALSE }, { "name + foo", Boolean.FALSE }, { "name.foo", Boolean.FALSE }, { "name.foo.bar", Boolean.FALSE }, { "name.{? foo }", Boolean.FALSE }, { "name.( foo )", Boolean.FALSE } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[0] + " (" + element[1] + ")"; tmp[1] = null; tmp[2] = element[0]; tmp[3] = element[1]; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public SimplePropertyTreeTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } /* * =================================================================== Overridden methods * =================================================================== */ @Before @Override public void runTest() throws Exception { Assert.assertEquals(Ognl.isSimpleProperty(getExpression(), _context), ((Boolean) getExpectedResult()).booleanValue()); } }
4,460
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ASTMethodTest.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.commons.ognl.test; import junit.framework.TestCase; import org.apache.commons.ognl.*; import org.apache.commons.ognl.enhance.ExpressionCompiler; import org.apache.commons.ognl.test.objects.Bean2; import org.apache.commons.ognl.test.objects.Bean3; import org.apache.commons.ognl.test.objects.Root; import java.util.Map; /** * Tests {@link org.apache.commons.ognl.ASTMethod}. */ public class ASTMethodTest extends TestCase { public void test_Context_Types() throws Throwable { ASTMethod p = new ASTMethod( 0 ); p.setMethodName( "get" ); ASTConst pRef = new ASTConst( 0 ); pRef.setValue( "value" ); p.jjtAddChild( pRef, 0 ); Root root = new Root(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root.getMap() ); context.setCurrentObject( root.getMap() ); context.setCurrentType( root.getMap().getClass() ); assertEquals( p.toGetSourceString( context, root.getMap() ), ".get(\"value\")" ); assertEquals( context.getCurrentType(), Object.class ); assertEquals( root.getMap().get( "value" ), context.getCurrentObject() ); assert Map.class.isAssignableFrom( context.getCurrentAccessor() ); assert Map.class.isAssignableFrom( context.getPreviousType() ); assert context.getPreviousAccessor() == null; assertEquals( OgnlRuntime.getCompiler( context ).castExpression( context, p, ".get(\"value\")" ), ".get(\"value\")" ); assert context.get( ExpressionCompiler.PRE_CAST ) == null; // now test one context level further to see casting work properly on base object types ASTProperty prop = new ASTProperty( 0 ); ASTConst propRef = new ASTConst( 0 ); propRef.setValue( "bean3" ); prop.jjtAddChild( propRef, 0 ); Bean2 val = (Bean2) root.getMap().get( "value" ); assertEquals( prop.toGetSourceString( context, root.getMap().get( "value" ) ), ".getBean3()" ); assertEquals( context.getCurrentObject(), val.getBean3() ); assertEquals( context.getCurrentType(), Bean3.class ); assertEquals( context.getCurrentAccessor(), Bean2.class ); assertEquals( Object.class, context.getPreviousType() ); assert Map.class.isAssignableFrom( context.getPreviousAccessor() ); assertEquals( OgnlRuntime.getCompiler( context ).castExpression( context, prop, ".getBean3()" ), ").getBean3()" ); } }
4,461
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ContextVariableTest.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.commons.ognl.test; import org.apache.commons.ognl.test.objects.Simple; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Collection; @RunWith(value = Parameterized.class) public class ContextVariableTest extends OgnlTestCase { private static final Object ROOT = new Simple(); private static final Object[][] TESTS = { // Naming and referring to names { "#root", ROOT }, // Special root reference { "#this", ROOT }, // Special this reference { "#f=5, #s=6, #f + #s", new Integer( 11 ) }, { "#six=(#five=5, 6), #five + #six", new Integer( 11 ) }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[0] + " (" + element[1] + ")"; tmp[1] = ROOT; tmp[2] = element[0]; tmp[3] = element[1]; tmp[4] = null; tmp[5] = null; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public ContextVariableTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,462
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/MemberAccessTest.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.commons.ognl.test; import org.apache.commons.ognl.DefaultMemberAccess; import org.apache.commons.ognl.OgnlException; import org.apache.commons.ognl.test.objects.Simple; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Map; @RunWith(value = Parameterized.class) public class MemberAccessTest extends OgnlTestCase { private static final Simple ROOT = new Simple(); private static final Object[][] TESTS = { { "@Runtime@getRuntime()", OgnlException.class }, { "@System@getProperty('java.specification.version')", System.getProperty( "java.specification.version" ) }, { "bigIntValue", OgnlException.class }, { "bigIntValue", OgnlException.class, 25, OgnlException.class }, { "getBigIntValue()", OgnlException.class }, { "stringValue", ROOT.getStringValue() }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for ( Object[] TEST : TESTS ) { Object[] tmp = new Object[6]; tmp[0] = TEST[0] + " (" + TEST[1] + ")"; tmp[1] = ROOT; tmp[2] = TEST[0]; tmp[3] = TEST[1]; tmp[4] = null; tmp[5] = null; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public MemberAccessTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } /* * =================================================================== Overridden methods * =================================================================== */ @Override @Before public void setUp() { super.setUp(); /* Should allow access at all to the Simple class except for the bigIntValue property */ _context.setMemberAccess( new DefaultMemberAccess( false ) { @Override public boolean isAccessible( Map context, Object target, Member member, String propertyName ) { if ( target == Runtime.class ) { return false; } if ( target instanceof Simple ) { if ( propertyName != null ) { return !propertyName.equals( "bigIntValue" ) && super.isAccessible( context, target, member, propertyName ); } if ( member instanceof Method ) { return !member.getName().equals( "getBigIntValue" ) && !member.getName().equals( "setBigIntValue" ) && super.isAccessible( context, target, member, propertyName ); } } return super.isAccessible( context, target, member, propertyName ); } } ); } }
4,463
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ArrayCreationTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.ExpressionSyntaxException; import org.apache.commons.ognl.test.objects.Entry; import org.apache.commons.ognl.test.objects.Root; import org.apache.commons.ognl.test.objects.Simple; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class ArrayCreationTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final Object[][] TESTS = { // Array creation { ROOT, "new String[] { \"one\", \"two\" }", new String[] { "one", "two" } }, { ROOT, "new String[] { 1, 2 }", new String[] { "1", "2" } }, { ROOT, "new Integer[] { \"1\", 2, \"3\" }", new Integer[] { 1, 2, 3 } }, { ROOT, "new String[10]", new String[10] }, { ROOT, "new Object[4] { #root, #this }", ExpressionSyntaxException.class }, { ROOT, "new Object[4]", new Object[4] }, { ROOT, "new Object[] { #root, #this }", new Object[] { ROOT, ROOT } }, { ROOT, "new org.apache.commons.ognl.test.objects.Simple[] { new org.apache.commons.ognl.test.objects.Simple(), new org.apache.commons.ognl.test.objects.Simple(\"foo\", 1.0f, 2) }", new Simple[] { new Simple(), new Simple( "foo", 1.0f, 2 ) } }, { ROOT, "new org.apache.commons.ognl.test.objects.Simple[5]", new Simple[5] }, { ROOT, "new org.apache.commons.ognl.test.objects.Simple(new Object[5])", new Simple( new Object[5] ) }, { ROOT, "new org.apache.commons.ognl.test.objects.Simple(new String[5])", new Simple( new String[5] ) }, { ROOT, "objectIndex ? new org.apache.commons.ognl.test.objects.Entry[] { new org.apache.commons.ognl.test.objects.Entry(), new org.apache.commons.ognl.test.objects.Entry()} " + ": new org.apache.commons.ognl.test.objects.Entry[] { new org.apache.commons.ognl.test.objects.Entry(), new org.apache.commons.ognl.test.objects.Entry()} ", new Entry[] { new Entry(), new Entry() } } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for ( Object[] TEST : TESTS ) { Object[] tmp = new Object[6]; tmp[0] = TEST[1]; tmp[1] = TEST[0]; tmp[2] = TEST[1]; switch ( TEST.length ) { case 3: tmp[3] = TEST[2]; break; case 4: tmp[3] = TEST[2]; tmp[4] = TEST[3]; break; case 5: tmp[3] = TEST[2]; tmp[4] = TEST[3]; tmp[5] = TEST[4]; break; default: fail( "don't understand TEST format with length" ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public ArrayCreationTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,464
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/PrivateAccessorTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.DefaultMemberAccess; import org.apache.commons.ognl.test.objects.Root; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class PrivateAccessorTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final Object[][] TESTS = { // Using private get/set methods { ROOT, "getPrivateAccessorIntValue()", new Integer( 67 ) }, { ROOT, "privateAccessorIntValue", new Integer( 67 ) }, { ROOT, "privateAccessorIntValue", new Integer( 67 ), new Integer( 100 ) }, { ROOT, "privateAccessorIntValue2", new Integer( 67 ) }, { ROOT, "privateAccessorIntValue2", new Integer( 67 ), new Integer( 100 ) }, { ROOT, "privateAccessorIntValue3", new Integer( 67 ) }, { ROOT, "privateAccessorIntValue3", new Integer( 67 ), new Integer( 100 ) }, { ROOT, "privateAccessorBooleanValue", Boolean.TRUE }, { ROOT, "privateAccessorBooleanValue", Boolean.TRUE, Boolean.FALSE }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public PrivateAccessorTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } /* * =================================================================== Overridden methods * =================================================================== */ @Before @Override public void setUp() { super.setUp(); _context.setMemberAccess( new DefaultMemberAccess( true ) ); _compileExpressions = false; } @Test @Override public void runTest() throws Exception { super.runTest(); } }
4,465
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/MapCreationTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; import org.apache.commons.ognl.test.objects.Root; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class MapCreationTest extends OgnlTestCase { private static final Root ROOT = new Root(); private static final Map FOO_BAR_MAP_1; private static final Map FOO_BAR_MAP_2; private static final Map FOO_BAR_MAP_3; private static final Map FOO_BAR_MAP_4; private static final Map FOO_BAR_MAP_5; static { FOO_BAR_MAP_1 = new HashMap(); FOO_BAR_MAP_1.put( "foo", "bar" ); FOO_BAR_MAP_2 = new HashMap(); FOO_BAR_MAP_2.put( "foo", "bar" ); FOO_BAR_MAP_2.put( "bar", "baz" ); FOO_BAR_MAP_3 = new HashMap(); FOO_BAR_MAP_3.put( "foo", null ); FOO_BAR_MAP_3.put( "bar", "baz" ); FOO_BAR_MAP_4 = new LinkedHashMap(); FOO_BAR_MAP_4.put( "foo", "bar" ); FOO_BAR_MAP_4.put( "bar", "baz" ); FOO_BAR_MAP_5 = new TreeMap(); FOO_BAR_MAP_5.put( "foo", "bar" ); FOO_BAR_MAP_5.put( "bar", "baz" ); } private static final Object[][] TESTS = { // Map creation { ROOT, "#{ \"foo\" : \"bar\" }", FOO_BAR_MAP_1 }, { ROOT, "#{ \"foo\" : \"bar\", \"bar\" : \"baz\" }", FOO_BAR_MAP_2 }, { ROOT, "#{ \"foo\", \"bar\" : \"baz\" }", FOO_BAR_MAP_3 }, { ROOT, "#@java.util.LinkedHashMap@{ \"foo\" : \"bar\", \"bar\" : \"baz\" }", FOO_BAR_MAP_4 }, { ROOT, "#@java.util.TreeMap@{ \"foo\" : \"bar\", \"bar\" : \"baz\" }", FOO_BAR_MAP_5 }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public MapCreationTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,466
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/SetterTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.apache.commons.ognl.InappropriateExpressionException; import org.apache.commons.ognl.NoSuchPropertyException; import org.apache.commons.ognl.test.objects.Root; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class SetterTest extends OgnlTestCase { private static final Root ROOT = new Root(); static Set<String> _list = new HashSet<String>(); static { _list.add( "Test1" ); } private static final Object[][] TESTS = { // Setting values { ROOT.getMap(), "newValue", null, new Integer( 101 ) }, { ROOT, "settableList[0]", "foo", "quux" }, // absolute indexes { ROOT, "settableList[0]", "quux" }, { ROOT, "settableList[2]", "baz", "quux" }, { ROOT, "settableList[2]", "quux" }, { ROOT, "settableList[$]", "quux", "oompa" }, // special indexes { ROOT, "settableList[$]", "oompa" }, { ROOT, "settableList[^]", "quux", "oompa" }, { ROOT, "settableList[^]", "oompa" }, { ROOT, "settableList[|]", "bar", "oompa" }, { ROOT, "settableList[|]", "oompa" }, { ROOT, "map.newValue", new Integer( 101 ), new Integer( 555 ) }, { ROOT, "map", ROOT.getMap(), new HashMap<String, String>(), NoSuchPropertyException.class }, { ROOT.getMap(), "newValue2 || put(\"newValue2\",987), newValue2", new Integer( 987 ), new Integer( 1002 ) }, { ROOT, "map.(someMissingKey || newValue)", new Integer( 555 ), new Integer( 666 ) }, { ROOT.getMap(), "newValue || someMissingKey", new Integer( 666 ), new Integer( 666 ) }, // no setting happens! { ROOT, "map.(newValue && aKey)", null, new Integer( 54321 ) }, { ROOT, "map.(someMissingKey && newValue)", null, null }, // again, no setting { null, "0", new Integer( 0 ), null, InappropriateExpressionException.class }, // illegal for setting, no // property { ROOT, "map[0]=\"map.newValue\", map[0](#this)", new Integer( 666 ), new Integer( 888 ) }, { ROOT, "selectedList", null, _list, IllegalArgumentException.class }, { ROOT, "openTransitionWin", Boolean.FALSE, Boolean.TRUE } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public SetterTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } }
4,467
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/MethodWithConversionTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.test.objects.Simple; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class MethodWithConversionTest extends OgnlTestCase { private static final Simple SIMPLE = new Simple(); private static final Object[][] TESTS = { // Method call with conversion { SIMPLE, "setValues(new Integer(10), \"10.56\", new Double(34.225))", null }, { SIMPLE, "stringValue", "10" }, { SIMPLE, "stringValue", "10", new Character( 'x' ), "x" }, { SIMPLE, "setStringValue('x')", null }, // set by calling setStringValue() directly { SIMPLE, "floatValue", new Float( 10.56 ) }, { SIMPLE, "getValueIsTrue(rootValue)", Boolean.TRUE }, { SIMPLE, "messages.format('Testing', one, two, three)", "blah" } }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public MethodWithConversionTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } @Test @Override public void runTest() throws Exception { super.runTest(); } }
4,468
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/NestedMethodTest.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.commons.ognl.test; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.ognl.test.objects.Component; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class NestedMethodTest extends OgnlTestCase { private static final Component COMPONENT = new Component(); private static final Object[][] TESTS = { // Expression in a method call argument { COMPONENT, "toDisplay.pictureUrl", COMPONENT.getToDisplay().getPictureUrl() }, { COMPONENT, "page.createRelativeAsset(toDisplay.pictureUrl)", COMPONENT.getPage().createRelativeAsset( COMPONENT.getToDisplay().getPictureUrl() ) }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; switch ( element.length ) { case 3: tmp[3] = element[2]; break; case 4: tmp[3] = element[2]; tmp[4] = element[3]; break; case 5: tmp[3] = element[2]; tmp[4] = element[3]; tmp[5] = element[4]; break; default: fail( "don't understand TEST format with length " + element.length ); } data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public NestedMethodTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } @Test @Override public void runTest() throws Exception { super.runTest(); } }
4,469
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/ConstantTest.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.commons.ognl.test; import org.apache.commons.ognl.ExpressionSyntaxException; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @RunWith(value = Parameterized.class) public class ConstantTest extends OgnlTestCase { private static final Object[][] TESTS = { { "12345", new Integer( 12345 ) }, { "0x100", new Integer( 256 ) }, { "0xfE", new Integer( 254 ) }, { "01000", new Integer( 512 ) }, { "1234L", new Integer( 1234 ) }, { "12.34", new Double( 12.34 ) }, { ".1234", new Double( .12340000000000 ) }, { "12.34f", Double.valueOf( 12.34 ) }, { "12.", new Double( 12 ) }, { "12e+1d", new Double( 120 ) }, { "'x'", new Character( 'x' ) }, { "'\\n'", new Character( '\n' ) }, { "'\\u048c'", new Character( '\u048c' ) }, { "'\\47'", new Character( '\47' ) }, { "'\\367'", new Character( '\367' ) }, { "'\\367", ExpressionSyntaxException.class }, { "'\\x'", ExpressionSyntaxException.class }, { "\"hello world\"", "hello world" }, { "\"\\u00a0\\u0068ell\\'o\\\\\\n\\r\\f\\t\\b\\\"\\167orld\\\"\"", "\u00a0hell'o\\\n\r\f\t\b\"world\"" }, { "\"hello world", ExpressionSyntaxException.class }, { "\"hello\\x world\"", ExpressionSyntaxException.class }, { "null", null }, { "true", Boolean.TRUE }, { "false", Boolean.FALSE }, { "{ false, true, null, 0, 1. }", Arrays.asList( Boolean.FALSE, Boolean.TRUE, null, new Integer( 0 ), new Double( 1 ) ) }, { "'HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"'", "HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"" }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[0] + " (" + element[1] + ")"; tmp[1] = null; tmp[2] = element[0]; tmp[3] = element[1]; tmp[4] = null; tmp[5] = null; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public ConstantTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } @Before @Override public void setUp() { super.setUp(); _context.put( "x", "1" ); _context.put( "y", new BigDecimal( 1 ) ); } }
4,470
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/LambdaExpressionTest.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.commons.ognl.test; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @RunWith(value = Parameterized.class) public class LambdaExpressionTest extends OgnlTestCase { private static final Object[][] TESTS = { // Lambda expressions { null, "#a=:[33](20).longValue().{0}.toArray().length", new Integer( 33 ) }, { null, "#fact=:[#this<=1? 1 : #fact(#this-1) * #this], #fact(30)", new Integer( 1409286144 ) }, { null, "#fact=:[#this<=1? 1 : #fact(#this-1) * #this], #fact(30L)", new Long( -8764578968847253504L ) }, { null, "#fact=:[#this<=1? 1 : #fact(#this-1) * #this], #fact(30h)", new BigInteger( "265252859812191058636308480000000" ) }, { null, "#bump = :[ #this.{ #this + 1 } ], (#bump)({ 1, 2, 3 })", new ArrayList( Arrays.asList( new Integer( 2 ), new Integer( 3 ), new Integer( 4 ) ) ) }, { null, "#call = :[ \"calling \" + [0] + \" on \" + [1] ], (#call)({ \"x\", \"y\" })", "calling x on y" }, }; /* * =================================================================== Public static methods * =================================================================== */ @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(TESTS.length); for (Object[] element : TESTS) { Object[] tmp = new Object[6]; tmp[0] = element[1]; tmp[1] = element[0]; tmp[2] = element[1]; tmp[3] = element[2]; data.add( tmp ); } return data; } /* * =================================================================== Constructors * =================================================================== */ public LambdaExpressionTest( String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult ) { super( name, root, expressionString, expectedResult, setValue, expectedAfterSetResult ); } @Test @Override public void runTest() throws Exception { super.runTest(); } }
4,471
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/util/NameFactory.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.commons.ognl.test.util; public class NameFactory extends Object { private final String classBaseName; private int classNameCounter; private final String variableBaseName; private int variableNameCounter; /* * =================================================================== Constructors * =================================================================== */ public NameFactory( String classBaseName, String variableBaseName ) { this.classBaseName = classBaseName; this.variableBaseName = variableBaseName; } /* * =================================================================== Public methods * =================================================================== */ public String getNewClassName() { return classBaseName + classNameCounter++; } public String getNewVariableName() { return variableBaseName + variableNameCounter++; } }
4,472
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/util/EnhancedClassLoader.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.commons.ognl.test.util; public class EnhancedClassLoader extends ClassLoader { /* * =================================================================== Constructors * =================================================================== */ public EnhancedClassLoader( ClassLoader parentClassLoader ) { super( parentClassLoader ); } /* * =================================================================== Overridden methods * =================================================================== */ public Class<?> defineClass( String enhancedClassName, byte[] byteCode ) { return defineClass( enhancedClassName, byteCode, 0, byteCode.length ); } }
4,473
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/util/ContextClassLoader.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.commons.ognl.test.util; import org.apache.commons.ognl.OgnlContext; public class ContextClassLoader extends ClassLoader { private final OgnlContext context; /* * =================================================================== Constructors * =================================================================== */ public ContextClassLoader( ClassLoader parentClassLoader, OgnlContext context ) { super( parentClassLoader ); this.context = context; } /* * =================================================================== Overridden methods * =================================================================== */ protected Class<?> findClass( String name ) throws ClassNotFoundException { if ( ( context != null ) && ( context.getClassResolver() != null ) ) { return context.getClassResolver().classForName( name, context ); } return super.findClass( name ); } }
4,474
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/accessors/ListPropertyAccessorTest.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.commons.ognl.test.accessors; import org.apache.commons.ognl.ListPropertyAccessor; import org.apache.commons.ognl.Ognl; import org.apache.commons.ognl.OgnlContext; import org.apache.commons.ognl.enhance.ExpressionCompiler; import org.apache.commons.ognl.test.objects.ListSource; import org.apache.commons.ognl.test.objects.ListSourceImpl; import org.apache.commons.ognl.test.objects.Root; import org.junit.Test; import java.util.List; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; /** * Tests functionality of various built in object accessors. */ public class ListPropertyAccessorTest { @Test public void test_Get_Source_String_Number_Index() { ListPropertyAccessor pa = new ListPropertyAccessor(); Root root = new Root(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); context.setCurrentType( Integer.TYPE ); assertEquals( ".get(0)", pa.getSourceAccessor( context, root.getList(), "0" ) ); assertEquals( List.class, context.getCurrentAccessor() ); assertEquals( Object.class, context.getCurrentType() ); assertEquals( Integer.TYPE, context.getPreviousType() ); assertNull(context.getPreviousAccessor()); } @Test public void test_Get_Source_Object_Number_Index() { ListPropertyAccessor pa = new ListPropertyAccessor(); Root root = new Root(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( root ); context.setCurrentObject( root ); context.setCurrentType( Integer.class ); assertEquals( ".get(indexValue.intValue())", pa.getSourceAccessor( context, root.getList(), "indexValue" ) ); assertEquals( List.class, context.getCurrentAccessor() ); assertEquals( Object.class, context.getCurrentType() ); assertEquals( Integer.class, context.getPreviousType() ); assertNull(context.getPreviousAccessor()); } @Test public void test_List_To_Object_Property_Accessor_Read() throws Exception { ListPropertyAccessor pa = new ListPropertyAccessor(); ListSource list = new ListSourceImpl(); OgnlContext context = (OgnlContext) Ognl.createDefaultContext( null ); context.setRoot( list ); context.setCurrentObject( list ); assertEquals( ".getTotal()", pa.getSourceAccessor( context, list, "total" ) ); assertNull( context.get( ExpressionCompiler.PRE_CAST ) ); assertEquals( int.class, context.getCurrentType() ); assertEquals( ListSource.class, context.getCurrentAccessor() ); } }
4,475
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/TestClass.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.commons.ognl.test.objects; /** * */ public abstract class TestClass { }
4,476
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/BaseSyntheticObject.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.commons.ognl.test.objects; import java.util.ArrayList; import java.util.List; /** * Used to test OGNL-136 use of synthetic methods. */ public abstract class BaseSyntheticObject { protected List getList() { return new ArrayList(); } }
4,477
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/BaseObjectIndexed.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.commons.ognl.test.objects; import java.util.*; public class BaseObjectIndexed extends Object { private final Map attributes = new HashMap(); public BaseObjectIndexed() { } public Map getAttributes() { return attributes; } public Object getAttribute( String name ) { return attributes.get( name ); } public void setAttribute( String name, Object value ) { attributes.put( name, value ); } /* allow testing property name where types do not match */ public Object getOtherAttribute( String name ) { return null; } public void setOtherAttribute( Object someObject, Object foo ) { /* do nothing */ } /* test whether get only is found */ public Object getSecondaryAttribute( Object name ) { return attributes.get( name ); } }
4,478
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/Root.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.commons.ognl.test.objects; import org.apache.commons.ognl.DynamicSubscript; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; public class Root { public static final String SIZE_STRING = "size"; public static final int STATIC_INT = 23; private int[] array = { 1, 2, 3, 4 }; private final Map map = new HashMap( 23 ); private final MyMap myMap = new MyMapImpl(); private final List list = Arrays.asList( null, this, array ); private final List settableList = new ArrayList( Arrays.asList( "foo", "bar", "baz" ) ); private final int index = 1; private int intValue; private String stringValue; private final int yetAnotherIntValue = 46; private boolean privateAccessorBooleanValue = true; private int privateAccessorIntValue = 67; private int privateAccessorIntValue2 = 67; private int privateAccessorIntValue3 = 67; public String anotherStringValue = "foo"; public int anotherIntValue = 123; public int six = 6; private boolean _disabled; private Locale _selected = Locale.getDefault(); private final List<List<Boolean>> _booleanValues = new ArrayList<List<Boolean>>(); private final boolean[] _booleanArray = { true, false, true, true }; private List _list; private final int verbosity = 87; private final BeanProvider _beanProvider = new BeanProviderImpl(); private boolean _render; private Boolean _readOnly = Boolean.FALSE; private final Integer _objIndex = new Integer( 1 ); private final Object _genericObjIndex = new Integer( 2 ); private final Date _date = new Date(); private boolean _openWindow; private final ITreeContentProvider _contentProvider = new TreeContentProvider(); private final Indexed _indexed = new Indexed(); private SearchTab _tab = new SearchTab(); /* * =================================================================== Public static methods * =================================================================== */ public static int getStaticInt() { return STATIC_INT; } /* * =================================================================== Constructors * =================================================================== */ public Root() { } /* * =================================================================== Private methods * =================================================================== */ { map.put( "test", this ); map.put( "array", array ); map.put( "list", list ); map.put( "size", new Integer( 5000 ) ); map.put( DynamicSubscript.first, new Integer( 99 ) ); map.put( "baz", array ); map.put( "value", new Bean2() ); map.put( "bar", new Bean3() ); map.put( new Long( 82 ), "StringStuff=someValue" ); IFormComponent comp = new FormComponentImpl(); comp.setClientId( "formComponent" ); IForm form = new FormImpl(); form.setClientId( "form1" ); comp.setForm( form ); map.put( "comp", comp ); Map newMap = new HashMap(); Map chain = new HashMap(); newMap.put( "deep", chain ); chain.put( "last", Boolean.TRUE ); map.put( "nested", newMap ); /* make myMap identical */ myMap.putAll( map ); List<Boolean> bool1 = new ArrayList<Boolean>(); bool1.add( Boolean.TRUE ); bool1.add( Boolean.FALSE ); bool1.add( Boolean.TRUE ); _booleanValues.add( bool1 ); List<Boolean> bool2 = new ArrayList<Boolean>(); bool2.add( Boolean.TRUE ); bool2.add( Boolean.FALSE ); bool2.add( Boolean.TRUE ); _booleanValues.add( bool2 ); } private boolean isPrivateAccessorBooleanValue() { return privateAccessorBooleanValue; } private void setPrivateAccessorBooleanValue( boolean value ) { privateAccessorBooleanValue = value; } private int getPrivateAccessorIntValue() { return privateAccessorIntValue; } private void setPrivateAccessorIntValue( int value ) { privateAccessorIntValue = value; } /* * =================================================================== Protected methods * =================================================================== */ protected int getPrivateAccessorIntValue2() { return privateAccessorIntValue2; } protected void setPrivateAccessorIntValue2( int value ) { privateAccessorIntValue2 = value; } /* * =================================================================== Package protected methods * =================================================================== */ int getPrivateAccessorIntValue3() { return privateAccessorIntValue3; } void setPrivateAccessorIntValue3( int value ) { privateAccessorIntValue3 = value; } /* * =================================================================== Public methods * =================================================================== */ public int[] getArray() { return array; } public boolean[] getBooleanArray() { return _booleanArray; } public void setArray( int[] value ) { array = value; } public String format( String key, Object value ) { return format( key, new Object[] { value } ); } public String format( String key, Object[] value ) { return "formatted"; } public String getCurrentClass( String value ) { return value + " stop"; } public Messages getMessages() { return new Messages( map ); } public Map getMap() { return map; } public MyMap getMyMap() { return myMap; } public List getList() { return list; } public Object getAsset( String key ) { return key; } public List getSettableList() { return settableList; } public int getIndex() { return index; } public Integer getObjectIndex() { return _objIndex; } public Integer getNullIndex() { return null; } public Object getGenericIndex() { return _genericObjIndex; } public int getIntValue() { return intValue; } public void setIntValue( int value ) { intValue = value; } public int getTheInt() { return six; } public String getStringValue() { return stringValue; } public void setStringValue( String value ) { stringValue = value; } public String getIndexedStringValue() { return "array"; } public Object getNullObject() { return null; } public String getTestString() { return "wiggle"; } public Object getProperty() { return new Bean2(); } public Bean2 getBean2() { return new Bean2(); } public Object getIndexedProperty( String name ) { return myMap.get( name ); } public Indexed getIndexer() { return _indexed; } public BeanProvider getBeans() { return _beanProvider; } public boolean getBooleanValue() { return _disabled; } public void setBooleanValue( boolean value ) { _disabled = value; } public boolean getDisabled() { return _disabled; } public void setDisabled( boolean disabled ) { _disabled = disabled; } public Locale getSelected() { return _selected; } public void setSelected( Locale locale ) { _selected = locale; } public Locale getCurrLocale() { return Locale.getDefault(); } public int getCurrentLocaleVerbosity() { return verbosity; } public boolean getRenderNavigation() { return _render; } public void setSelectedList( List selected ) { _list = selected; } public List getSelectedList() { return _list; } public Boolean getReadonly() { return _readOnly; } public void setReadonly( Boolean value ) { _readOnly = value; } public Object getSelf() { return this; } public Date getTestDate() { return _date; } public String getWidth() { return "238px"; } public Long getTheLong() { return new Long( 4 ); } public boolean isSorted() { return true; } public TestClass getMyTest() { return new TestImpl(); } public ITreeContentProvider getContentProvider() { return _contentProvider; } public boolean isPrintDelivery() { return true; } public Long getCurrentDeliveryId() { return 1l; } public Boolean isFlyingMonkey() { return Boolean.TRUE; } public Boolean isDumb() { return Boolean.FALSE; } public Date getExpiration() { return null; } public Long getMapKey() { return new Long( 82 ); } public Object getArrayValue() { return new Object[] { new Integer( "2" ), new Integer( "2" ) }; } public List getResult() { List list = new ArrayList(); list.add( new Object[] { new Integer( "2" ), new Integer( "2" ) } ); list.add( new Object[] { new Integer( "2" ), new Integer( "2" ) } ); list.add( new Object[] { new Integer( "2" ), new Integer( "2" ) } ); return list; } public boolean isEditorDisabled() { return false; } public boolean isDisabled() { return true; } public boolean isOpenTransitionWin() { return _openWindow; } public void setOpenTransitionWin( boolean value ) { _openWindow = value; } public boolean isOk( SimpleEnum value, String otherValue ) { return true; } public List<List<Boolean>> getBooleanValues() { return _booleanValues; } public int getIndex1() { return 1; } public int getIndex2() { return 1; } public SearchTab getTab() { return _tab; } public void setTab( SearchTab tab ) { _tab = tab; } public static class A { public int methodOfA( B b ) { return 0; } public int getIntValue() { return 1; } } public static class B { public int methodOfB( int i ) { return 0; } } public A getA() { return new A(); } public B getB() { return new B(); } }
4,479
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/SearchCriteria.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.commons.ognl.test.objects; /** * Test for OGNL-131. */ public class SearchCriteria { String _displayName; public SearchCriteria( String name ) { _displayName = name; } public String getDisplayName() { return _displayName; } }
4,480
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/FormComponentImpl.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.commons.ognl.test.objects; /** * */ public class FormComponentImpl extends ComponentImpl implements IFormComponent { IForm _form; public IForm getForm() { return _form; } public void setForm( IForm form ) { _form = form; } }
4,481
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/CorrectedObject.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.commons.ognl.test.objects; public class CorrectedObject { public CorrectedObject() { } public void setStringValue( String value ) { } public String getStringValue() { return null; } public String getIndexedStringValue( String key ) { return null; } public void setIndexedStringValue( String key, String value ) { } }
4,482
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/GenericCracker.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.commons.ognl.test.objects; /** * */ public class GenericCracker implements Cracker<Integer> { Integer _param; public Integer getParam() { return _param; } public void setParam( Integer param ) { _param = param; } }
4,483
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/BaseBean.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.commons.ognl.test.objects; /** * Base class used to test inheritance class casting. */ public abstract class BaseBean { public abstract String getName(); public boolean getActive() { return true; } public boolean isActive2() { return true; } public Two getTwo() { return new Two(); } public String getMessage( String mes ) { return "[" + mes + "]"; } public boolean hasChildren( String name ) { return name.length() > 2; } }
4,484
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/IForm.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.commons.ognl.test.objects; /** * */ public interface IForm extends IComponent { }
4,485
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/IFormComponent.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.commons.ognl.test.objects; /** * */ public interface IFormComponent extends IComponent { String getClientId(); IForm getForm(); void setForm( IForm form ); }
4,486
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/SimpleNumeric.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.commons.ognl.test.objects; /** * Used for {@link org.apache.commons.ognl.test.PropertyArithmeticAndLogicalOperatorsTest}. */ public class SimpleNumeric { public double getBudget() { return 140; } public double getTimeBilled() { return 24.12; } public String getTableSize() { return "10"; } }
4,487
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/TestInherited2.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.commons.ognl.test.objects; /** * */ public class TestInherited2 implements Inherited { public String getMyString() { return "inherited2"; } }
4,488
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/Inherited.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.commons.ognl.test.objects; /** * */ public interface Inherited { String getMyString(); }
4,489
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/Cracker.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.commons.ognl.test.objects; import java.io.Serializable; /** * Generic test object. */ public interface Cracker<T extends Serializable> { T getParam(); void setParam( T param ); }
4,490
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/TestImpl.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.commons.ognl.test.objects; import java.util.HashMap; import java.util.Map; /** * */ public class TestImpl extends TestClass { public Map<String, String> getTheMap() { Map<String, String> map = new HashMap(); map.put( "key", "value" ); return map; } }
4,491
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/GenericServiceImpl.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.commons.ognl.test.objects; /** * */ public class GenericServiceImpl implements GenericService { public String getFullMessageFor( GameGenericObject game, Object... arguments ) { game.getHappy(); return game.getDisplayName(); } public String getFullMessageFor( PersonGenericObject person, Object... arguments ) { return person.getDisplayName(); } }
4,492
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/ITreeContentProvider.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.commons.ognl.test.objects; import java.util.Collection; /** * */ public interface ITreeContentProvider extends IContentProvider { Collection getChildren( Object parentElement ); boolean hasChildren( Object parentElement ); }
4,493
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/Bean1.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.commons.ognl.test.objects; public class Bean1 { private final Bean2 bean2 = new Bean2(); public Bean2 getBean2() { return bean2; } }
4,494
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/TreeContentProvider.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.commons.ognl.test.objects; import java.util.Collection; import java.util.Collections; import java.util.List; /** * */ public class TreeContentProvider implements ITreeContentProvider { public Collection getChildren( Object parentElement ) { return Collections.EMPTY_LIST; } public boolean hasChildren( Object parentElement ) { return true; } public List getElements() { return Collections.EMPTY_LIST; } }
4,495
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/Two.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.commons.ognl.test.objects; /** * */ public class Two { public String getMessage( String mes ) { return "[" + mes + "]"; } public boolean hasChildren( String name ) { return name.length() > 2; } }
4,496
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/OtherObjectIndexed.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.commons.ognl.test.objects; public class OtherObjectIndexed extends BaseObjectIndexed { public OtherObjectIndexed() { setAttribute( "foo", "bar" ); setAttribute( "bar", "baz" ); } }
4,497
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/SimpleEnum.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.commons.ognl.test.objects; /** * */ public enum SimpleEnum { ONE( 1 ); private final int _value; SimpleEnum( int value ) { _value = value; } public int getValue() { return _value; } }
4,498
0
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test
Create_ds/commons-ognl/src/test/java/org/apache/commons/ognl/test/objects/Component.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.commons.ognl.test.objects; public class Component extends Object { private URLStorage toDisplay = new URLStorage(); private Page page = new Page(); public static class URLStorage extends Object { private String pictureUrl = "http://www.picturespace.com/pictures/100"; public String getPictureUrl() { return pictureUrl; } public void setPictureUrl( String value ) { pictureUrl = value; } } public static class Page extends Object { public Object createRelativeAsset( String value ) { return "/toplevel/" + value; } } public Component() { } public Page getPage() { return page; } public void setPage( Page value ) { page = value; } public URLStorage getToDisplay() { return toDisplay; } public void setToDisplay( URLStorage value ) { toDisplay = value; } }
4,499