diff --git a/formatter.xml b/formatter.xml new file mode 100644 index 000000000..b5515c19e --- /dev/null +++ b/formatter.xml @@ -0,0 +1,291 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/DelegatingConversionService.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/DelegatingConversionService.java index b3ec428cd..15313730f 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/DelegatingConversionService.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/DelegatingConversionService.java @@ -1,3 +1,18 @@ +/* + * Copyright 2012-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springframework.data.rest.convert; import java.util.Stack; @@ -5,89 +20,91 @@ import java.util.Stack; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.core.convert.TypeDescriptor; +import org.springframework.util.Assert; /** * This {@link ConversionService} implementation delegates the actual conversion to the {@literal ConversionService} it * finds in its internal {@link Stack} that claims to be able to convert a given class. It will roll through the * {@literal ConversionService}s until it finds one that can convert the given type. - * + * * @author Jon Brisbin + * @authot Oliver Gierke */ public class DelegatingConversionService implements ConversionService { - private Stack conversionServices = new Stack(); + private final Stack conversionServices; - public DelegatingConversionService() { - } + public DelegatingConversionService(ConversionService... svcs) { - public DelegatingConversionService(ConversionService... svcs) { - addConversionServices(svcs); - } + this.conversionServices = new Stack(); - /** - * Add {@link ConversionService}s to the internal list of those to delegate to. - * - * @param svcs - * The ConversionServices to delegate to (in order). - * - * @return @this - */ - public DelegatingConversionService addConversionServices(ConversionService... svcs) { - for(ConversionService svc : svcs) { - conversionServices.add(svc); - } - return this; - } + for (ConversionService svc : svcs) { + Assert.notNull(svc); + conversionServices.add(svc); + } + } - /** - * Add a {@link ConversionService} to the internal list at a specific index for controlling the priority. - * - * @param atIndex - * Where in the stack to add this ConversionService. - * @param svc - * The ConversionService to add. - * - * @return - */ - public DelegatingConversionService addConversionService(int atIndex, ConversionService svc) { - conversionServices.add(atIndex, svc); - return this; - } + /* + * (non-Javadoc) + * @see org.springframework.core.convert.ConversionService#canConvert(java.lang.Class, java.lang.Class) + */ + @Override + public boolean canConvert(Class from, Class to) { - @Override public boolean canConvert(Class from, Class to) { - for(ConversionService svc : conversionServices) { - if(svc.canConvert(from, to)) { - return true; - } - } - return false; - } + for (ConversionService svc : conversionServices) { + if (svc.canConvert(from, to)) { + return true; + } + } - @Override public boolean canConvert(TypeDescriptor from, TypeDescriptor to) { - for(ConversionService svc : conversionServices) { - if(svc.canConvert(from, to)) { - return true; - } - } - return false; - } + return false; + } - @Override public T convert(Object o, Class type) { - for(ConversionService svc : conversionServices) { - if(svc.canConvert(o.getClass(), type)) { - return svc.convert(o, type); - } - } - throw new ConverterNotFoundException(TypeDescriptor.forObject(o), TypeDescriptor.valueOf(type)); - } + /* + * (non-Javadoc) + * @see org.springframework.core.convert.ConversionService#canConvert(org.springframework.core.convert.TypeDescriptor, org.springframework.core.convert.TypeDescriptor) + */ + @Override + public boolean canConvert(TypeDescriptor from, TypeDescriptor to) { - @Override public Object convert(Object o, TypeDescriptor from, TypeDescriptor to) { - for(ConversionService svc : conversionServices) { - if(svc.canConvert(from, to)) { - return svc.convert(o, from, to); - } - } - throw new ConverterNotFoundException(from, to); - } + for (ConversionService svc : conversionServices) { + if (svc.canConvert(from, to)) { + return true; + } + } + return false; + } + + /* + * (non-Javadoc) + * @see org.springframework.core.convert.ConversionService#convert(java.lang.Object, java.lang.Class) + */ + @Override + public T convert(Object o, Class type) { + + for (ConversionService svc : conversionServices) { + if (svc.canConvert(o.getClass(), type)) { + return svc.convert(o, type); + } + } + + throw new ConverterNotFoundException(TypeDescriptor.forObject(o), TypeDescriptor.valueOf(type)); + } + + /* + * (non-Javadoc) + * @see org.springframework.core.convert.ConversionService#convert(java.lang.Object, org.springframework.core.convert.TypeDescriptor, org.springframework.core.convert.TypeDescriptor) + */ + @Override + public Object convert(Object o, TypeDescriptor from, TypeDescriptor to) { + + for (ConversionService svc : conversionServices) { + if (svc.canConvert(from, to)) { + return svc.convert(o, from, to); + } + } + + throw new ConverterNotFoundException(from, to); + } } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/ISO8601DateConverter.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/ISO8601DateConverter.java index 98a547003..0e17aa8dc 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/ISO8601DateConverter.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/ISO8601DateConverter.java @@ -1,3 +1,18 @@ +/* + * Copyright 2012-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springframework.data.rest.convert; import java.text.DateFormat; @@ -15,62 +30,81 @@ import org.springframework.core.convert.converter.Converter; /** * @author Jon Brisbin */ -public class ISO8601DateConverter implements ConditionalGenericConverter, - Converter { +public class ISO8601DateConverter implements ConditionalGenericConverter, Converter { - public static final ConditionalGenericConverter INSTANCE = new ISO8601DateConverter(); + public static final ConditionalGenericConverter INSTANCE = new ISO8601DateConverter(); - private static final Set CONVERTIBLE_PAIRS = new HashSet(); + private static final Set CONVERTIBLE_PAIRS = new HashSet(); - static { - CONVERTIBLE_PAIRS.add(new ConvertiblePair(String.class, Date.class)); - CONVERTIBLE_PAIRS.add(new ConvertiblePair(Date.class, String.class)); - } + static { + CONVERTIBLE_PAIRS.add(new ConvertiblePair(String.class, Date.class)); + CONVERTIBLE_PAIRS.add(new ConvertiblePair(Date.class, String.class)); + } - @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - if(String.class.isAssignableFrom(sourceType.getType())) { - return Date.class.isAssignableFrom(targetType.getType()); - } + /* + * (non-Javadoc) + * @see org.springframework.core.convert.converter.ConditionalConverter#matches(org.springframework.core.convert.TypeDescriptor, org.springframework.core.convert.TypeDescriptor) + */ + @Override + public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - return Date.class.isAssignableFrom(sourceType.getType()) - && String.class.isAssignableFrom(targetType.getType()); - } + if (String.class.isAssignableFrom(sourceType.getType())) { + return Date.class.isAssignableFrom(targetType.getType()); + } - @Override public Set getConvertibleTypes() { - return CONVERTIBLE_PAIRS; - } + return Date.class.isAssignableFrom(sourceType.getType()) && String.class.isAssignableFrom(targetType.getType()); + } - @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - DateFormat dateFmt = iso8601DateFormat(); - if(String.class.isAssignableFrom(sourceType.getType())) { - return dateFmt.format(source); - } else { - try { - return dateFmt.parse(source.toString()); - } catch(ParseException e) { - throw new ConversionFailedException(sourceType, targetType, source, e); - } - } - } + /* + * (non-Javadoc) + * @see org.springframework.core.convert.converter.GenericConverter#getConvertibleTypes() + */ + @Override + public Set getConvertibleTypes() { + return CONVERTIBLE_PAIRS; + } - @Override public Date convert(String[] source) { - if(source.length > 0) { - try { - return iso8601DateFormat().parse(source[0]); - } catch(ParseException e) { - throw new ConversionFailedException( - TypeDescriptor.valueOf(String[].class), - TypeDescriptor.valueOf(Date.class), - source[0], - new IllegalArgumentException("Source does not conform to ISO8601 date format (YYYY-MM-DDTHH:MM:SS-0000") - ); - } - } - return null; - } + /* + * (non-Javadoc) + * @see org.springframework.core.convert.converter.GenericConverter#convert(java.lang.Object, org.springframework.core.convert.TypeDescriptor, org.springframework.core.convert.TypeDescriptor) + */ + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - private DateFormat iso8601DateFormat() { - return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - } + DateFormat dateFmt = iso8601DateFormat(); + if (String.class.isAssignableFrom(sourceType.getType())) { + return dateFmt.format(source); + } + + try { + return dateFmt.parse(source.toString()); + } catch (ParseException e) { + throw new ConversionFailedException(sourceType, targetType, source, e); + } + } + + /* + * (non-Javadoc) + * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object) + */ + @Override + public Date convert(String[] source) { + + if (source.length == 0) { + return null; + } + + try { + return iso8601DateFormat().parse(source[0]); + } catch (ParseException e) { + throw new ConversionFailedException(TypeDescriptor.valueOf(String[].class), TypeDescriptor.valueOf(Date.class), + source[0], new IllegalArgumentException( + "Source does not conform to ISO8601 date format (YYYY-MM-DDTHH:MM:SS-0000")); + } + } + + private DateFormat iso8601DateFormat() { + return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + } } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/UUIDConverter.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/UUIDConverter.java index 5b2ccf31a..e1cf1a071 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/UUIDConverter.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/UUIDConverter.java @@ -1,3 +1,18 @@ +/* + * Copyright 2012-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springframework.data.rest.convert; import java.util.HashSet; @@ -9,38 +24,51 @@ import org.springframework.core.convert.converter.ConditionalGenericConverter; /** * For converting a {@link UUID} into a {@link String}. - * + * * @author Jon Brisbin */ public class UUIDConverter implements ConditionalGenericConverter { - public static final UUIDConverter INSTANCE = new UUIDConverter(); - private static final Set CONVERTIBLE_PAIRS = new HashSet(); + public static final UUIDConverter INSTANCE = new UUIDConverter(); + private static final Set CONVERTIBLE_PAIRS = new HashSet(); - static { - CONVERTIBLE_PAIRS.add(new ConvertiblePair(String.class, UUID.class)); - CONVERTIBLE_PAIRS.add(new ConvertiblePair(UUID.class, String.class)); - } + static { + CONVERTIBLE_PAIRS.add(new ConvertiblePair(String.class, UUID.class)); + CONVERTIBLE_PAIRS.add(new ConvertiblePair(UUID.class, String.class)); + } - @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - if(String.class.isAssignableFrom(sourceType.getType())) { - return UUID.class.isAssignableFrom(targetType.getType()); - } + /* + * (non-Javadoc) + * @see org.springframework.core.convert.converter.ConditionalConverter#matches(org.springframework.core.convert.TypeDescriptor, org.springframework.core.convert.TypeDescriptor) + */ + @Override + public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { + if (String.class.isAssignableFrom(sourceType.getType())) { + return UUID.class.isAssignableFrom(targetType.getType()); + } - return UUID.class.isAssignableFrom(sourceType.getType()) - && String.class.isAssignableFrom(targetType.getType()); - } + return UUID.class.isAssignableFrom(sourceType.getType()) && String.class.isAssignableFrom(targetType.getType()); + } - @Override public Set getConvertibleTypes() { - return CONVERTIBLE_PAIRS; - } - - @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - if(String.class.isAssignableFrom(sourceType.getType())) { - return UUID.fromString(source.toString()); - } else { - return source.toString(); - } - } + /* + * (non-Javadoc) + * @see org.springframework.core.convert.converter.GenericConverter#getConvertibleTypes() + */ + @Override + public Set getConvertibleTypes() { + return CONVERTIBLE_PAIRS; + } + /* + * (non-Javadoc) + * @see org.springframework.core.convert.converter.GenericConverter#convert(java.lang.Object, org.springframework.core.convert.TypeDescriptor, org.springframework.core.convert.TypeDescriptor) + */ + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + if (String.class.isAssignableFrom(sourceType.getType())) { + return UUID.fromString(source.toString()); + } else { + return source.toString(); + } + } } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/package-info.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/package-info.java index 2a539f0cc..c79336930 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/package-info.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/convert/package-info.java @@ -2,3 +2,4 @@ * {@link org.springframework.core.convert.ConversionService} and {@link org.springframework.core.convert.converter.Converter} integration for Spring Data REST. */ package org.springframework.data.rest.convert; + diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/package-info.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/package-info.java index ba9ee30c4..ab46b12e2 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/package-info.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/package-info.java @@ -2,3 +2,4 @@ * Core components used across Spring Data REST. */ package org.springframework.data.rest.core; + diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/MapUtils.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/MapUtils.java index c5c33203a..fc85c546a 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/MapUtils.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/MapUtils.java @@ -38,14 +38,14 @@ public abstract class MapUtils { * @return */ public static Map> toMap(MultiValueMap map) { - + Assert.notNull(map, "Given map must not be null!"); Map> result = new LinkedHashMap>(map.size()); for (Entry> entry : map.entrySet()) { result.put(entry.getKey(), entry.getValue()); } - + return result; } } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/UriUtils.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/UriUtils.java index 4739be5d7..c7cb057d2 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/UriUtils.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/UriUtils.java @@ -1,210 +1,25 @@ package org.springframework.data.rest.core.util; import java.net.URI; -import java.util.List; -import java.util.Stack; -import org.springframework.util.StringUtils; import org.springframework.web.util.UriComponentsBuilder; /** * Helper methods for dealing with URIs. - * - * @author Jon Brisbin + * + * @author Jon Brisbin */ public abstract class UriUtils { - private UriUtils() { - } - - /** - * Is the given {@link URI} based on the "base" {@link URI}? - *

e.g. given a base URI of {@literal http://localhost:8080/data} and a URI of {@code - * http://localhost:8080/data/person}, this method would report the baseUri being a valid base of the given URI. - *

- * - * @param baseUri - * {@link URI} to check. - * @param uri - * {@link URI} against which to compare the base. - * - * @return {@literal true} if the baseUri is valid against the given {@link URI}, {@literal false} otherwise. - */ - public static boolean validBaseUri(URI baseUri, URI uri) { - String path = UriUtils.path(baseUri.relativize(uri)); - return !StringUtils.hasText(path) || path.charAt(0) != '/'; - } - - /** - * Execute the given {@link Function} for each segment in the {@link URI}. - *

e.g. given a URI of {@literal http://localhost:8080/data/person/1} and a base URI of {@code - * http://localhost:8080/data}, this method will explode the URI into it's components, as compared to the base URI. - * The result would be: the given handler gets called twice, once passing a relative {@link URI} of "person" and a - * second time passing a relative {@link URI} of "1". - *

- * - * @param baseUri - * base {@link URI} - * @param uri - * {@link URI} to explode and iterate over. - * @param handler - * {@link Function} to call for each segment of the URI's path. - * @param - * Return type of the handler. - * - * @return Handler return value, or possibly {@literal null}. - */ - public static V foreach(URI baseUri, URI uri, Function handler) { - List uris = explode(baseUri, uri); - V v = null; - for(URI u : uris) { - v = handler.apply(u); - } - return v; - } - - /** - * Explode the given {@link URI} into its component parts, as compared to the base {@link URI}. - *

Given a base URI of {@literal http://localhost:8080/data}, exploding the URI {@code - * http://localhost:8080/data/person/1} strips the first part of the URI, leaving {@literal person/1}. This results - * in - * a {@link Stack} of relative {@link URI}s of size 2--one for "person" and one for "1".

- * - * @param baseUri - * base {@link URI} - * @param uri - * {@link URI} to explode - * - * @return {@link Stack} of relative {@link URI}s. - */ - public static Stack explode(URI baseUri, URI uri) { - Stack uris = new Stack(); - if(StringUtils.hasText(uri.getPath())) { - URI relativeUri = baseUri.relativize(uri); - if(StringUtils.hasText(relativeUri.getPath())) { - for(String part : relativeUri.getPath().split("/")) { - uris.add(URI.create(part + (StringUtils.hasText(uri.getQuery()) ? "?" + uri.getQuery() : ""))); - } - } - } - return uris; - } - - /** - * Merge the components of these {@link URI}s into a single URI. Useful for combining a relative URI with a base URI - * and coming up with a full absolute URI. - *

e.g. merging base URI {@literal http://localhost:8080/data} and relative uri {@literal person/1?name=John+Doe} - * would result in an absolute URI of {@literal http://localhost:8080/data/person/1?name=John+Doe}

- * - * @param baseUri - * base {@link URI} - * @param uris - * {@link URI}s to merge - * - * @return {@link URI} that is the combination of all the given (possibly relative, possibly absolute) URIs. - */ - public static URI merge(URI baseUri, URI... uris) { - StringBuilder query = new StringBuilder(); - - UriComponentsBuilder ub = UriComponentsBuilder.fromUri(baseUri); - for(URI uri : uris) { - String s = uri.getScheme(); - if(null != s) { - ub.scheme(s); - } - - s = uri.getUserInfo(); - if(null != s) { - ub.userInfo(s); - } - - s = uri.getHost(); - if(null != s) { - ub.host(s); - } - - int i = uri.getPort(); - if(i > 0) { - ub.port(i); - } - - s = uri.getPath(); - if(null != s) { - if(!uri.isAbsolute() && StringUtils.hasText(s)) { - ub.pathSegment(s); - } else { - ub.path(s); - } - } - - s = uri.getQuery(); - if(null != s) { - if(query.length() > 0) { - query.append("&"); - } - query.append(s); - } - - s = uri.getFragment(); - if(null != s) { - ub.fragment(s); - } - } - - if(query.length() > 0) { - ub.query(query.toString()); - } - - return ub.build().toUri(); - } - - /** - * Just the path portion of the {@link URI}, but with any trailing slash "/" removed. - * - * @param uri - * path URI - * - * @return the path portion of the URI, but with any trailing slash removed - */ - public static String path(URI uri) { - if(null == uri) { - return null; - } - String s = uri.getPath(); - if(s.endsWith("/")) { - return s.substring(0, s.length() - 1); - } else { - return s; - } - } - - /** - * The very last segment of the {@link URI}. - * - * @param baseUri - * base {@link URI} - * @param uri - * {@link URI} to explode - * - * @return Relative {@link URI} that is the last segment of the path for the given URI. - */ - public static URI tail(URI baseUri, URI uri) { - Stack uris = explode(baseUri, uri); - return uris.size() > 0 ? uris.get(Math.max(uris.size() - 1, 0)) : null; - } - - /** - * Create a new {@link URI} out of the components. - * - * @param baseUri - * The base URI these path segments are relative to. - * @param pathSegments - * The path segments to add to the given base URI. - * - * @return A new URI built from the given base URI and additional path segments. - */ - public static URI buildUri(URI baseUri, String... pathSegments) { - return UriComponentsBuilder.fromUri(baseUri).pathSegment(pathSegments).build().toUri(); - } + /** + * Create a new {@link URI} out of the components. + * + * @param baseUri The base URI these path segments are relative to. + * @param pathSegments The path segments to add to the given base URI. + * @return A new URI built from the given base URI and additional path segments. + */ + public static URI buildUri(URI baseUri, String... pathSegments) { + return UriComponentsBuilder.fromUri(baseUri).pathSegment(pathSegments).build().toUri(); + } } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/package-info.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/package-info.java index 91a1bbf41..0acebd7b7 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/package-info.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/package-info.java @@ -2,3 +2,4 @@ * Spring Data REST */ package org.springframework.data.rest; + diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/convert/DelegatingConversionServiceUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/convert/DelegatingConversionServiceUnitTests.java index 480922b2e..4d2b38710 100644 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/convert/DelegatingConversionServiceUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/convert/DelegatingConversionServiceUnitTests.java @@ -1,7 +1,23 @@ +/* + * Copyright 2012-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springframework.data.rest.convert; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; +import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; import java.util.UUID; @@ -16,48 +32,53 @@ import org.springframework.core.convert.ConversionService; import org.springframework.format.support.DefaultFormattingConversionService; /** - * Tests to ensure the {@link DelegatingConversionService} properly delegates conversions to the {@link - * org.springframework.core.convert.ConversionService} that is appropriate for the given source and return types. - * + * Tests to ensure the {@link DelegatingConversionService} properly delegates conversions to the + * {@link org.springframework.core.convert.ConversionService} that is appropriate for the given source and return types. + * * @author Jon Brisbin * @author Oliver Gierke */ @RunWith(MockitoJUnitRunner.class) public class DelegatingConversionServiceUnitTests { - private static final UUID RANDOM_UUID = UUID.fromString("9deccfd7-f892-4e26-a4d5-c92893392e78"); + private static final UUID RANDOM_UUID = UUID.fromString("9deccfd7-f892-4e26-a4d5-c92893392e78"); - @Mock ConversionService conversionService; - DelegatingConversionService delegatingConversionService; + @Mock ConversionService conversionService; + DelegatingConversionService delegatingConversionService; - @Before - public void setup() { + @Before + public void setup() { - DefaultFormattingConversionService cs = new DefaultFormattingConversionService(false); - cs.addConverter(UUIDConverter.INSTANCE); + DefaultFormattingConversionService cs = new DefaultFormattingConversionService(false); + cs.addConverter(UUIDConverter.INSTANCE); - delegatingConversionService = new DelegatingConversionService(conversionService, cs); - - when(conversionService.canConvert(String.class, UUID.class)).thenReturn(false); - when(conversionService.canConvert(UUID.class, String.class)).thenReturn(false); - } + delegatingConversionService = new DelegatingConversionService(conversionService, cs); - @Test - public void shouldDelegateToProperConversionService() throws Exception { - assertThat(delegatingConversionService.canConvert(String.class, UUID.class), is(true)); - assertThat(delegatingConversionService.convert(RANDOM_UUID.toString(), UUID.class), is(RANDOM_UUID)); - verifyConversionService(); - } + when(conversionService.canConvert(String.class, UUID.class)).thenReturn(false); + when(conversionService.canConvert(UUID.class, String.class)).thenReturn(false); + } - @Test - public void shouldConvertUUIDToString() throws Exception { - assertThat(delegatingConversionService.canConvert(UUID.class, String.class), is(true)); - assertThat(delegatingConversionService.convert(RANDOM_UUID, String.class), is(RANDOM_UUID.toString())); - verifyConversionService(); - } + @Test + public void shouldDelegateToProperConversionService() { - private void verifyConversionService() { - verify(conversionService, times(0)).convert(Matchers.any(String.class), eq(UUID.class)); - verify(conversionService, times(0)).convert(Matchers.any(UUID.class), eq(String.class)); - } + assertThat(delegatingConversionService.canConvert(String.class, UUID.class), is(true)); + assertThat(delegatingConversionService.convert(RANDOM_UUID.toString(), UUID.class), is(RANDOM_UUID)); + + verifyConversionService(); + } + + @Test + public void shouldConvertUUIDToString() { + + assertThat(delegatingConversionService.canConvert(UUID.class, String.class), is(true)); + assertThat(delegatingConversionService.convert(RANDOM_UUID, String.class), is(RANDOM_UUID.toString())); + + verifyConversionService(); + } + + private void verifyConversionService() { + + verify(conversionService, times(0)).convert(Matchers.any(String.class), eq(UUID.class)); + verify(conversionService, times(0)).convert(Matchers.any(UUID.class), eq(String.class)); + } } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/UriUtilsUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/UriUtilsUnitTests.java index 2c9be61fb..77b5686a2 100644 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/UriUtilsUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/UriUtilsUnitTests.java @@ -1,92 +1,44 @@ +/* + * Copyright 2012-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springframework.data.rest.core.util; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import java.util.Stack; import org.junit.Test; /** * Tests to verify that {@link UriUtils} can manipulate {@link URI}s. - * + * * @author Jon Brisbin */ public class UriUtilsUnitTests { - private static final String BASE_URI_STR = "http://localhost:8080/data"; - private static final URI BASE_URI = URI.create(BASE_URI_STR); + private static final String BASE_URI_STR = "http://localhost:8080/data"; + private static final URI BASE_URI = URI.create(BASE_URI_STR); - private static final String PERSON_2LVL_STR = BASE_URI_STR + "/person/1"; - private static final URI PERSON_2LVL_URI = URI.create(PERSON_2LVL_STR); + private static final String PERSON_2LVL_STR = BASE_URI_STR + "/person/1"; + private static final URI PERSON_2LVL_URI = URI.create(PERSON_2LVL_STR); - @Test - public void shouldValidateBaseURI() throws Exception { - URI uri = new URI(BASE_URI + "/person/1"); - - assertThat(UriUtils.validBaseUri(BASE_URI, uri), is(true)); - } - - @Test - public void shouldIterateOverPathElements() throws Exception { - final List paths = new ArrayList(); - Function fn = new Function() { - @Override public Void apply(URI uri) { - paths.add(uri.getPath()); - return null; - } - }; - - UriUtils.foreach(BASE_URI, PERSON_2LVL_URI, fn); - - assertThat(paths, hasSize(2)); - assertThat(paths, contains("person", "1")); - } - - @Test - public void shouldExplodeRelativeURI() throws Exception { - Stack uris = UriUtils.explode(BASE_URI, PERSON_2LVL_URI); - - assertThat(uris, hasSize(2)); - assertThat(uris, contains(URI.create("person"), URI.create("1"))); - } - - @Test - public void shouldMergeDifferentURIsIntoOne() throws Exception { - String qrystr = "?queryParam=testValue"; - - URI uriWithQuery = URI.create(qrystr); - URI uriWithPath = URI.create("person/1"); - - URI uri = UriUtils.merge(BASE_URI, uriWithPath, uriWithQuery); - - assertThat(uri.toString(), is(PERSON_2LVL_STR + qrystr)); - } - - @Test - public void shouldStripTrailingSlashFromPath() throws Exception { - URI uri = URI.create("person/"); - - String path = UriUtils.path(uri); - - assertThat(path, is("person")); - } - - @Test - public void shouldStripTheLastPathSegmentFromAURI() throws Exception { - URI uri = UriUtils.tail(BASE_URI, PERSON_2LVL_URI); - - assertThat(uri, is(URI.create("1"))); - } - - @Test - public void shouldBuildURIFromPathSegments() throws Exception { - URI uri = UriUtils.buildUri(BASE_URI, "person", "1"); - - assertThat(uri, is(PERSON_2LVL_URI)); - } + @Test + public void shouldBuildURIFromPathSegments() throws Exception { + URI uri = UriUtils.buildUri(BASE_URI, "person", "1"); + assertThat(uri, is(PERSON_2LVL_URI)); + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/RepositoryRestConfiguration.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/RepositoryRestConfiguration.java index e1e6305f0..0d85b3f15 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/RepositoryRestConfiguration.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/RepositoryRestConfiguration.java @@ -30,22 +30,22 @@ import org.springframework.util.Assert; @SuppressWarnings("deprecation") public class RepositoryRestConfiguration { - private URI baseUri = null; - private int defaultPageSize = 20; - private int maxPageSize = 1000; - private String pageParamName = "page"; - private String limitParamName = "limit"; - private String sortParamName = "sort"; - private MediaType defaultMediaType = MediaType.APPLICATION_JSON; - private boolean returnBodyOnCreate = false; - private boolean returnBodyOnUpdate = false; - private List> exposeIdsFor = new ArrayList>(); - private ResourceMappingConfiguration domainMappings = new ResourceMappingConfiguration(); - private ResourceMappingConfiguration repoMappings = new ResourceMappingConfiguration(); + private URI baseUri = null; + private int defaultPageSize = 20; + private int maxPageSize = 1000; + private String pageParamName = "page"; + private String limitParamName = "limit"; + private String sortParamName = "sort"; + private MediaType defaultMediaType = MediaType.APPLICATION_JSON; + private boolean returnBodyOnCreate = false; + private boolean returnBodyOnUpdate = false; + private List> exposeIdsFor = new ArrayList>(); + private ResourceMappingConfiguration domainMappings = new ResourceMappingConfiguration(); + private ResourceMappingConfiguration repoMappings = new ResourceMappingConfiguration(); /** * The base URI against which the exporter should calculate its links. - * + * * @return The base URI. */ public URI getBaseUri() { @@ -54,9 +54,8 @@ public class RepositoryRestConfiguration { /** * The base URI against which the exporter should calculate its links. - * - * @param baseUri - * The base URI. + * + * @param baseUri The base URI. */ public RepositoryRestConfiguration setBaseUri(URI baseUri) { Assert.notNull(baseUri, "The baseUri cannot be null."); @@ -66,7 +65,7 @@ public class RepositoryRestConfiguration { /** * Get the default size of {@link org.springframework.data.domain.Pageable}s. Default is 20. - * + * * @return The default page size. */ public int getDefaultPageSize() { @@ -75,10 +74,8 @@ public class RepositoryRestConfiguration { /** * Set the default size of {@link org.springframework.data.domain.Pageable}s. - * - * @param defaultPageSize - * The default page size. - * + * + * @param defaultPageSize The default page size. * @return {@literal this} */ public RepositoryRestConfiguration setDefaultPageSize(int defaultPageSize) { @@ -89,7 +86,7 @@ public class RepositoryRestConfiguration { /** * Get the maximum size of pages. - * + * * @return Maximum page size. */ public int getMaxPageSize() { @@ -98,10 +95,8 @@ public class RepositoryRestConfiguration { /** * Set the maximum size of pages. - * - * @param maxPageSize - * Maximum page size. - * + * + * @param maxPageSize Maximum page size. * @return {@literal this} */ public RepositoryRestConfiguration setMaxPageSize(int maxPageSize) { @@ -112,7 +107,7 @@ public class RepositoryRestConfiguration { /** * Get the name of the URL query string parameter that indicates what page to return. Default is 'page'. - * + * * @return Name of the query parameter used to indicate the page number to return. */ public String getPageParamName() { @@ -121,10 +116,8 @@ public class RepositoryRestConfiguration { /** * Set the name of the URL query string parameter that indicates what page to return. - * - * @param pageParamName - * Name of the query parameter used to indicate the page number to return. - * + * + * @param pageParamName Name of the query parameter used to indicate the page number to return. * @return {@literal this} */ public RepositoryRestConfiguration setPageParamName(String pageParamName) { @@ -136,7 +129,7 @@ public class RepositoryRestConfiguration { /** * Get the name of the URL query string parameter that indicates how many results to return at once. Default is * 'limit'. - * + * * @return Name of the query parameter used to indicate the maximum number of entries to return at a time. */ public String getLimitParamName() { @@ -145,10 +138,9 @@ public class RepositoryRestConfiguration { /** * Set the name of the URL query string parameter that indicates how many results to return at once. - * - * @param limitParamName - * Name of the query parameter used to indicate the maximum number of entries to return at a time. - * + * + * @param limitParamName Name of the query parameter used to indicate the maximum number of entries to return at a + * time. * @return {@literal this} */ public RepositoryRestConfiguration setLimitParamName(String limitParamName) { @@ -159,7 +151,7 @@ public class RepositoryRestConfiguration { /** * Get the name of the URL query string parameter that indicates what direction to sort results. Default is 'sort'. - * + * * @return Name of the query string parameter used to indicate what field to sort on. */ public String getSortParamName() { @@ -168,10 +160,8 @@ public class RepositoryRestConfiguration { /** * Set the name of the URL query string parameter that indicates what direction to sort results. - * - * @param sortParamName - * Name of the query string parameter used to indicate what field to sort on. - * + * + * @param sortParamName Name of the query string parameter used to indicate what field to sort on. * @return {@literal this} */ public RepositoryRestConfiguration setSortParamName(String sortParamName) { @@ -182,7 +172,7 @@ public class RepositoryRestConfiguration { /** * Get the {@link MediaType} to use as a default when none is specified. - * + * * @return Default content type if none has been specified. */ public MediaType getDefaultMediaType() { @@ -191,10 +181,8 @@ public class RepositoryRestConfiguration { /** * Set the {@link MediaType} to use as a default when none is specified. - * - * @param defaultMediaType - * Default content type if none has been specified. - * + * + * @param defaultMediaType Default content type if none has been specified. * @return {@literal this} */ public RepositoryRestConfiguration setDefaultMediaType(MediaType defaultMediaType) { @@ -204,7 +192,7 @@ public class RepositoryRestConfiguration { /** * Whether to return a response body after creating an entity. - * + * * @return {@literal true} to return a body on create, {@literal false} otherwise. */ public boolean isReturnBodyOnCreate() { @@ -213,10 +201,8 @@ public class RepositoryRestConfiguration { /** * Set whether to return a response body after creating an entity. - * - * @param returnBodyOnCreate - * {@literal true} to return a body on create, {@literal false} otherwise. - * + * + * @param returnBodyOnCreate {@literal true} to return a body on create, {@literal false} otherwise. * @return {@literal this} */ public RepositoryRestConfiguration setReturnBodyOnCreate(boolean returnBodyOnCreate) { @@ -226,7 +212,7 @@ public class RepositoryRestConfiguration { /** * Whether to return a response body after updating an entity. - * + * * @return {@literal true} to return a body on update, {@literal false} otherwise. */ public boolean isReturnBodyOnUpdate() { @@ -235,9 +221,8 @@ public class RepositoryRestConfiguration { /** * Sets whether to return a response body after updating an entity. - * + * * @param returnBodyOnUpdate - * * @return */ public RepositoryRestConfiguration setReturnBodyOnUpdate(boolean returnBodyOnUpdate) { @@ -247,10 +232,8 @@ public class RepositoryRestConfiguration { /** * Start configuration a {@link ResourceMapping} for a specific domain type. - * - * @param domainType - * The {@link Class} of the domain type to configure a mapping for. - * + * + * @param domainType The {@link Class} of the domain type to configure a mapping for. * @return A new {@link ResourceMapping} for configuring how a domain type is mapped. */ public ResourceMapping setResourceMappingForDomainType(Class domainType) { @@ -259,10 +242,8 @@ public class RepositoryRestConfiguration { /** * Get the {@link ResourceMapping} for a specific domain type. - * - * @param domainType - * The {@link Class} of the domain type. - * + * + * @param domainType The {@link Class} of the domain type. * @return A {@link ResourceMapping} for that domain type or {@literal null} if none exists. */ public ResourceMapping getResourceMappingForDomainType(Class domainType) { @@ -271,10 +252,8 @@ public class RepositoryRestConfiguration { /** * Whether there is a {@link ResourceMapping} for the given domain type. - * - * @param domainType - * The domain type to find a {@link ResourceMapping} for. - * + * + * @param domainType The domain type to find a {@link ResourceMapping} for. * @return {@literal true} if a {@link ResourceMapping} exists for this domain class, {@literal false} otherwise. */ public boolean hasResourceMappingForDomainType(Class domainType) { @@ -283,7 +262,7 @@ public class RepositoryRestConfiguration { /** * Get the {@link ResourceMappingConfiguration} that is currently configured. - * + * * @return */ public ResourceMappingConfiguration getDomainTypesResourceMappingConfiguration() { @@ -292,10 +271,8 @@ public class RepositoryRestConfiguration { /** * Start configuration a {@link ResourceMapping} for a specific repository interface. - * - * @param repositoryInterface - * The {@link Class} of the repository interface to configure a mapping for. - * + * + * @param repositoryInterface The {@link Class} of the repository interface to configure a mapping for. * @return A new {@link ResourceMapping} for configuring how a repository interface is mapped. */ public ResourceMapping setResourceMappingForRepository(Class repositoryInterface) { @@ -304,10 +281,8 @@ public class RepositoryRestConfiguration { /** * Get the {@link ResourceMapping} for a specific repository interface. - * - * @param repositoryInterface - * The {@link Class} of the repository interface. - * + * + * @param repositoryInterface The {@link Class} of the repository interface. * @return A {@link ResourceMapping} for that repository interface or {@literal null} if none exists. */ public ResourceMapping getResourceMappingForRepository(Class repositoryInterface) { @@ -316,9 +291,8 @@ public class RepositoryRestConfiguration { /** * Whether there is a {@link ResourceMapping} configured for this {@literal Repository} class. - * + * * @param repositoryInterface - * * @return */ public boolean hasResourceMappingForRepository(Class repositoryInterface) { @@ -327,7 +301,7 @@ public class RepositoryRestConfiguration { public ResourceMapping findRepositoryMappingForPath(String path) { Class type = repoMappings.findTypeForPath(path); - if(null == type) { + if (null == type) { return null; } return repoMappings.getResourceMappingFor(type); @@ -335,10 +309,8 @@ public class RepositoryRestConfiguration { /** * Should we expose the ID property for this domain type? - * - * @param domainType - * The domain type we may need to expose the ID for. - * + * + * @param domainType The domain type we may need to expose the ID for. * @return {@literal true} is the ID is to be exposed, {@literal false} otherwise. */ public boolean isIdExposedFor(Class domainType) { @@ -347,10 +319,8 @@ public class RepositoryRestConfiguration { /** * Set the list of domain types for which we will expose the ID value as a normal property. - * - * @param domainTypes - * Array of types to expose IDs for. - * + * + * @param domainTypes Array of types to expose IDs for. * @return {@literal this} */ public RepositoryRestConfiguration exposeIdsFor(Class... domainTypes) { diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/ResourceMapping.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/ResourceMapping.java index a799727d3..74c0c83d4 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/ResourceMapping.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/ResourceMapping.java @@ -26,101 +26,97 @@ import java.util.Map; @Deprecated public class ResourceMapping { - private String rel; - private String path; - private boolean exported = true; - private final Map resourceMappings = new HashMap(); + private String rel; + private String path; + private boolean exported = true; + private final Map resourceMappings = new HashMap(); - public ResourceMapping() { - } + public ResourceMapping() {} - public ResourceMapping(Class type) { - rel = findRel(type); - path = findPath(type); - exported = findExported(type); - } + public ResourceMapping(Class type) { + rel = findRel(type); + path = findPath(type); + exported = findExported(type); + } - public ResourceMapping(String rel, String path) { - this.rel = rel; - this.path = path; - } + public ResourceMapping(String rel, String path) { + this.rel = rel; + this.path = path; + } - public ResourceMapping(String rel, String path, boolean exported) { - this.rel = rel; - this.path = path; - this.exported = exported; - } + public ResourceMapping(String rel, String path, boolean exported) { + this.rel = rel; + this.path = path; + this.exported = exported; + } - public String getRel() { - return rel; - } + public String getRel() { + return rel; + } - public ResourceMapping setRel(String rel) { - this.rel = rel; - return this; - } + public ResourceMapping setRel(String rel) { + this.rel = rel; + return this; + } - public String getPath() { - return path; - } + public String getPath() { + return path; + } - public ResourceMapping setPath(String path) { - this.path = path; - return this; - } + public ResourceMapping setPath(String path) { + this.path = path; + return this; + } - public boolean isExported() { - return exported; - } + public boolean isExported() { + return exported; + } - public ResourceMapping setExported(boolean exported) { - this.exported = exported; - return this; - } + public ResourceMapping setExported(boolean exported) { + this.exported = exported; + return this; + } - public ResourceMapping addResourceMappings(Map mappings) { - if(null == mappings) { - return this; - } + public ResourceMapping addResourceMappings(Map mappings) { + if (null == mappings) { + return this; + } - resourceMappings.putAll(mappings); - return this; - } + resourceMappings.putAll(mappings); + return this; + } - public ResourceMapping addResourceMappingFor(String name) { - ResourceMapping rm = new ResourceMapping(); - resourceMappings.put(name, rm); - return rm; - } + public ResourceMapping addResourceMappingFor(String name) { + ResourceMapping rm = new ResourceMapping(); + resourceMappings.put(name, rm); + return rm; + } - public ResourceMapping getResourceMappingFor(String name) { - return resourceMappings.get(name); - } + public ResourceMapping getResourceMappingFor(String name) { + return resourceMappings.get(name); + } - public boolean hasResourceMappingFor(String name) { - return resourceMappings.containsKey(name); - } + public boolean hasResourceMappingFor(String name) { + return resourceMappings.containsKey(name); + } - public Map getResourceMappings() { - return resourceMappings; - } + public Map getResourceMappings() { + return resourceMappings; + } - public String getNameForPath(String path) { - for(Map.Entry mapping : resourceMappings.entrySet()) { - if(mapping.getValue().getPath().equals(path)) { - return mapping.getKey(); - } - } - return path; - } + public String getNameForPath(String path) { + for (Map.Entry mapping : resourceMappings.entrySet()) { + if (mapping.getValue().getPath().equals(path)) { + return mapping.getKey(); + } + } + return path; + } - @Override public String toString() { - return "ResourceMapping{" + - "rel='" + rel + '\'' + - ", path='" + path + '\'' + - ", exported=" + exported + - ", resourceMappings=" + resourceMappings + - '}'; - } + @Override + public String toString() { + return "ResourceMapping{" + "rel='" + rel + '\'' + ", path='" + path + '\'' + ", exported=" + exported + + ", resourceMappings=" + resourceMappings + '}'; + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/ResourceMappingConfiguration.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/ResourceMappingConfiguration.java index 4d2d7ac9c..9dd745107 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/ResourceMappingConfiguration.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/config/ResourceMappingConfiguration.java @@ -21,41 +21,41 @@ import java.util.Map; /** * Manages the {@link ResourceMapping} configurations for any resources being exported. This includes domain entities * and repositories. - * + * * @author Jon Brisbin */ @SuppressWarnings("deprecation") public class ResourceMappingConfiguration { - private final Map, ResourceMapping> resourceMappings = new HashMap, ResourceMapping>(); + private final Map, ResourceMapping> resourceMappings = new HashMap, ResourceMapping>(); - public ResourceMapping setResourceMappingFor(Class type) { - ResourceMapping rm = resourceMappings.get(type); - if(null == rm) { - rm = new ResourceMapping(type); - resourceMappings.put(type, rm); - } - return rm; - } + public ResourceMapping setResourceMappingFor(Class type) { + ResourceMapping rm = resourceMappings.get(type); + if (null == rm) { + rm = new ResourceMapping(type); + resourceMappings.put(type, rm); + } + return rm; + } - public ResourceMapping getResourceMappingFor(Class type) { - return resourceMappings.get(type); - } + public ResourceMapping getResourceMappingFor(Class type) { + return resourceMappings.get(type); + } - public boolean hasResourceMappingFor(Class type) { - return resourceMappings.containsKey(type); - } + public boolean hasResourceMappingFor(Class type) { + return resourceMappings.containsKey(type); + } - public Class findTypeForPath(String path) { - if(null == path) { - return null; - } - for(Map.Entry, ResourceMapping> entry : resourceMappings.entrySet()) { - if(path.equals(entry.getValue().getPath())) { - return entry.getKey(); - } - } - return null; - } + public Class findTypeForPath(String path) { + if (null == path) { + return null; + } + for (Map.Entry, ResourceMapping> entry : resourceMappings.entrySet()) { + if (path.equals(entry.getValue().getPath())) { + return entry.getKey(); + } + } + return null; + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/RepositoryConstraintViolationException.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/RepositoryConstraintViolationException.java index 86c13e6bb..864920e2f 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/RepositoryConstraintViolationException.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/RepositoryConstraintViolationException.java @@ -5,22 +5,22 @@ import org.springframework.validation.Errors; /** * Exception that is thrown when a Spring {@link org.springframework.validation.Validator} throws an error. - * + * * @author Jon Brisbin */ public class RepositoryConstraintViolationException extends DataIntegrityViolationException { private static final long serialVersionUID = -4789377071564956366L; - + private final Errors errors; - public RepositoryConstraintViolationException(Errors errors) { - super("Validation failed"); - this.errors = errors; - } + public RepositoryConstraintViolationException(Errors errors) { + super("Validation failed"); + this.errors = errors; + } - public Errors getErrors() { - return errors; - } + public Errors getErrors() { + return errors; + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/UriDomainClassConverter.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/UriDomainClassConverter.java index 41f9f37ba..d2a842110 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/UriDomainClassConverter.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/UriDomainClassConverter.java @@ -15,58 +15,51 @@ import org.springframework.data.rest.repository.support.RepositoryInformationSup /** * A {@link ConditionalGenericConverter} that can convert a {@link URI} domain entity. - * + * * @author Jon Brisbin */ -public class UriDomainClassConverter - extends RepositoryInformationSupport - implements ConditionalGenericConverter, - InitializingBean { +public class UriDomainClassConverter extends RepositoryInformationSupport implements ConditionalGenericConverter, + InitializingBean { - private static TypeDescriptor STRING_TYPE = TypeDescriptor.valueOf(String.class); + private static TypeDescriptor STRING_TYPE = TypeDescriptor.valueOf(String.class); - @Autowired - private DomainClassConverter domainClassConverter; - private Set convertiblePairs = new HashSet(); + @Autowired private DomainClassConverter domainClassConverter; + private Set convertiblePairs = new HashSet(); - @Override public void afterPropertiesSet() throws Exception { - for(Class domainType : repositories) { - convertiblePairs.add(new ConvertiblePair(URI.class, domainType)); - } - } + @Override + public void afterPropertiesSet() throws Exception { + for (Class domainType : repositories) { + convertiblePairs.add(new ConvertiblePair(URI.class, domainType)); + } + } - @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - return URI.class.isAssignableFrom(sourceType.getType()) - && (null != repositories.getPersistentEntity(targetType.getType())); - } + @Override + public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { + return URI.class.isAssignableFrom(sourceType.getType()) + && (null != repositories.getPersistentEntity(targetType.getType())); + } - @Override public Set getConvertibleTypes() { - return convertiblePairs; - } + @Override + public Set getConvertibleTypes() { + return convertiblePairs; + } - @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - PersistentEntity entity = repositories.getPersistentEntity(targetType.getType()); - if(null == entity || !domainClassConverter.matches(STRING_TYPE, targetType)) { - throw new ConversionFailedException( - sourceType, - targetType, - source, - new IllegalArgumentException("No PersistentEntity information available for " + targetType.getType()) - ); - } + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + PersistentEntity entity = repositories.getPersistentEntity(targetType.getType()); + if (null == entity || !domainClassConverter.matches(STRING_TYPE, targetType)) { + throw new ConversionFailedException(sourceType, targetType, source, new IllegalArgumentException( + "No PersistentEntity information available for " + targetType.getType())); + } - URI uri = (URI)source; - String[] parts = uri.getPath().split("/"); - if(parts.length < 2) { - throw new ConversionFailedException( - sourceType, - targetType, - source, - new IllegalArgumentException("Cannot resolve URI " + uri + ". Is it local or remote? Only local URIs are resolvable.") - ); - } + URI uri = (URI) source; + String[] parts = uri.getPath().split("/"); + if (parts.length < 2) { + throw new ConversionFailedException(sourceType, targetType, source, new IllegalArgumentException( + "Cannot resolve URI " + uri + ". Is it local or remote? Only local URIs are resolvable.")); + } - return domainClassConverter.convert(parts[parts.length - 1], STRING_TYPE, targetType); - } + return domainClassConverter.convert(parts[parts.length - 1], STRING_TYPE, targetType); + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/ValidationErrors.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/ValidationErrors.java index 35eb99f3c..46b311a8e 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/ValidationErrors.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/ValidationErrors.java @@ -16,71 +16,73 @@ import org.springframework.validation.ObjectError; /** * An {@link Errors} implementation for use in the events mechanism of Spring Data REST. - * + * * @author Jon Brisbin */ public class ValidationErrors extends AbstractErrors { private static final long serialVersionUID = 8141826537389141361L; - - private String name; - private Object entity; - private PersistentEntity persistentEntity; - private List globalErrors = new ArrayList(); - private List fieldErrors = new ArrayList(); - public ValidationErrors(String name, Object entity, PersistentEntity persistentEntity) { - this.name = name; - this.entity = entity; - this.persistentEntity = persistentEntity; - } + private String name; + private Object entity; + private PersistentEntity persistentEntity; + private List globalErrors = new ArrayList(); + private List fieldErrors = new ArrayList(); - @Override public String getObjectName() { - return name; - } + public ValidationErrors(String name, Object entity, PersistentEntity persistentEntity) { + this.name = name; + this.entity = entity; + this.persistentEntity = persistentEntity; + } - @Override public void reject(String errorCode, Object[] errorArgs, String defaultMessage) { - globalErrors.add(new ObjectError(name, new String[]{errorCode}, errorArgs, defaultMessage)); - } + @Override + public String getObjectName() { + return name; + } - @Override public void rejectValue(String field, String errorCode, Object[] errorArgs, String defaultMessage) { - fieldErrors.add(new FieldError(name, - field, - getFieldValue(field), - true, - new String[]{errorCode}, - errorArgs, - defaultMessage)); - } + @Override + public void reject(String errorCode, Object[] errorArgs, String defaultMessage) { + globalErrors.add(new ObjectError(name, new String[] { errorCode }, errorArgs, defaultMessage)); + } - @Override public void addAllErrors(Errors errors) { - globalErrors.addAll(errors.getAllErrors()); - } + @Override + public void rejectValue(String field, String errorCode, Object[] errorArgs, String defaultMessage) { + fieldErrors.add(new FieldError(name, field, getFieldValue(field), true, new String[] { errorCode }, errorArgs, + defaultMessage)); + } - @Override public List getGlobalErrors() { - return globalErrors; - } + @Override + public void addAllErrors(Errors errors) { + globalErrors.addAll(errors.getAllErrors()); + } - @Override public List getFieldErrors() { - return fieldErrors; - } + @Override + public List getGlobalErrors() { + return globalErrors; + } - @Override public Object getFieldValue(String field) { - PersistentProperty prop = persistentEntity != null ? persistentEntity.getPersistentProperty(field) : null; - if(null == prop) { - return null; - } + @Override + public List getFieldErrors() { + return fieldErrors; + } - Method getter = prop.getGetter(); - if(null != getter) { - return invokeMethod(getter, entity); - } - Field fld = prop.getField(); - if(null != fld) { - return getField(fld, entity); - } + @Override + public Object getFieldValue(String field) { + PersistentProperty prop = persistentEntity != null ? persistentEntity.getPersistentProperty(field) : null; + if (null == prop) { + return null; + } - return null; - } + Method getter = prop.getGetter(); + if (null != getter) { + return invokeMethod(getter, entity); + } + Field fld = prop.getField(); + if (null != fld) { + return getField(fld, entity); + } + + return null; + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/ConvertWith.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/ConvertWith.java index a71a1dfb5..479e3a95c 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/ConvertWith.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/ConvertWith.java @@ -11,11 +11,11 @@ import org.springframework.core.convert.converter.Converter; /** * @author Jon Brisbin */ -@Target({ElementType.PARAMETER}) +@Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface ConvertWith { - Class> value(); + Class> value(); } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/Description.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/Description.java index d78c6f4f0..0409c1270 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/Description.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/Description.java @@ -8,12 +8,8 @@ import java.lang.annotation.Target; /** * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.FIELD, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface Description { - String value(); + String value(); } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterCreate.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterCreate.java index ec9ec9683..e36d8f5a1 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterCreate.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterCreate.java @@ -9,10 +9,7 @@ import java.lang.annotation.Target; /** * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface HandleAfterCreate { diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterDelete.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterDelete.java index b484f5579..c54d758d9 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterDelete.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterDelete.java @@ -8,17 +8,14 @@ import java.lang.annotation.Target; /** * Denotes a component that should handle the {@literal afterDelete} event. - * + * * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface HandleAfterDelete { - Class[] value() default {}; + Class[] value() default {}; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterLinkDelete.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterLinkDelete.java index e8f22c458..70de41b3a 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterLinkDelete.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterLinkDelete.java @@ -8,17 +8,14 @@ import java.lang.annotation.Target; /** * Denotes a component that should handle the {@literal afterLinkDelete} event. - * + * * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface HandleAfterLinkDelete { - Class[] value() default {}; + Class[] value() default {}; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterLinkSave.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterLinkSave.java index dcc73e21c..662ba64a8 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterLinkSave.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterLinkSave.java @@ -8,17 +8,14 @@ import java.lang.annotation.Target; /** * Denotes a component that should handle the {@literal afterLinkSave} event. - * + * * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface HandleAfterLinkSave { - Class[] value() default {}; + Class[] value() default {}; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterSave.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterSave.java index 467de4827..cdf67c483 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterSave.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleAfterSave.java @@ -8,17 +8,14 @@ import java.lang.annotation.Target; /** * Denotes a component that should handle the {@literal afterSave} event. - * + * * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface HandleAfterSave { - Class[] value() default {}; + Class[] value() default {}; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeCreate.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeCreate.java index 06cd5850d..7c7c7fa1b 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeCreate.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeCreate.java @@ -9,10 +9,7 @@ import java.lang.annotation.Target; /** * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface HandleBeforeCreate { diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeDelete.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeDelete.java index be175c323..7ea568d94 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeDelete.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeDelete.java @@ -8,17 +8,14 @@ import java.lang.annotation.Target; /** * Denotes a component that should handle the {@literal beforeDelete} event. - * + * * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface HandleBeforeDelete { - Class[] value() default {}; + Class[] value() default {}; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeLinkDelete.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeLinkDelete.java index eeb8edf2c..c9a5da9c4 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeLinkDelete.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeLinkDelete.java @@ -8,17 +8,14 @@ import java.lang.annotation.Target; /** * Denotes a component that should handle the {@literal beforeLinkDelete} event. - * + * * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface HandleBeforeLinkDelete { - Class[] value() default {}; + Class[] value() default {}; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeLinkSave.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeLinkSave.java index 705151d63..00929e3ec 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeLinkSave.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeLinkSave.java @@ -8,17 +8,14 @@ import java.lang.annotation.Target; /** * Denotes a component that should handle the {@literal beforeLinkSave} event. - * + * * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface HandleBeforeLinkSave { - Class[] value() default {}; + Class[] value() default {}; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeSave.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeSave.java index 20a419b27..c53b334e4 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeSave.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/HandleBeforeSave.java @@ -8,17 +8,14 @@ import java.lang.annotation.Target; /** * Denotes a component that should handle the {@literal beforeSave} event. - * + * * @author Jon Brisbin */ -@Target({ - ElementType.TYPE, - ElementType.METHOD - }) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface HandleBeforeSave { - Class[] value() default {}; + Class[] value() default {}; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/RepositoryEventHandler.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/RepositoryEventHandler.java index 7b95301ca..4c66e8eaf 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/RepositoryEventHandler.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/RepositoryEventHandler.java @@ -8,17 +8,17 @@ import java.lang.annotation.Target; /** * Advertises classes annotated with this that they are event handlers. - * + * * @author Jon Brisbin */ -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface RepositoryEventHandler { - /** - * The list of {@link org.springframework.context.ApplicationEvent} classes this event handler cares about. - */ - Class[] value() default {}; + /** + * The list of {@link org.springframework.context.ApplicationEvent} classes this event handler cares about. + */ + Class[] value() default {}; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/RestResource.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/RestResource.java index 303d5cad4..a6585711e 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/RestResource.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/annotation/RestResource.java @@ -9,37 +9,33 @@ import java.lang.annotation.Target; /** * Annotate a {@link org.springframework.data.repository.Repository} with this to influence how it is exported and what * the value of the {@literal rel} attribute will be in links. - * + * * @author Jon Brisbin */ -@Target({ - ElementType.FIELD, - ElementType.METHOD, - ElementType.TYPE - }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface RestResource { - /** - * Flag indicating whether this resource is exported at all. - * - * @return {@literal true} if the resource is to be exported, {@literal false} otherwise. - */ - boolean exported() default true; + /** + * Flag indicating whether this resource is exported at all. + * + * @return {@literal true} if the resource is to be exported, {@literal false} otherwise. + */ + boolean exported() default true; - /** - * The path segment under which this resource is to be exported. - * - * @return A valid path segment. - */ - String path() default ""; + /** + * The path segment under which this resource is to be exported. + * + * @return A valid path segment. + */ + String path() default ""; - /** - * The rel value to use when generating links to this resource. - * - * @return A valid rel value. - */ - String rel() default ""; + /** + * The rel value to use when generating links to this resource. + * + * @return A valid rel value. + */ + String rel() default ""; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AbstractRepositoryEventListener.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AbstractRepositoryEventListener.java index 31c333eeb..fb646f130 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AbstractRepositoryEventListener.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AbstractRepositoryEventListener.java @@ -8,147 +8,125 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; /** - * Abstract class that listens for generic {@link RepositoryEvent}s and dispatches them to a specific - * method based on the event type. - * + * Abstract class that listens for generic {@link RepositoryEvent}s and dispatches them to a specific method based on + * the event type. + * * @author Jon Brisbin */ public abstract class AbstractRepositoryEventListener implements ApplicationListener, - ApplicationContextAware { + ApplicationContextAware { private final Class INTERESTED_TYPE = resolveTypeArgument(getClass(), AbstractRepositoryEventListener.class); protected ApplicationContext applicationContext; - @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } - @SuppressWarnings({"unchecked"}) - @Override public final void onApplicationEvent(RepositoryEvent event) { + @SuppressWarnings({ "unchecked" }) + @Override + public final void onApplicationEvent(RepositoryEvent event) { Class srcType = event.getSource().getClass(); - if(null != INTERESTED_TYPE && !INTERESTED_TYPE.isAssignableFrom(srcType)) { + if (null != INTERESTED_TYPE && !INTERESTED_TYPE.isAssignableFrom(srcType)) { return; } - if(event instanceof BeforeSaveEvent) { - onBeforeSave((T)event.getSource()); - } else if(event instanceof BeforeCreateEvent) { - onBeforeCreate((T)event.getSource()); - } else if(event instanceof AfterCreateEvent) { - onAfterCreate((T)event.getSource()); - } else if(event instanceof AfterSaveEvent) { - onAfterSave((T)event.getSource()); - } else if(event instanceof BeforeLinkSaveEvent) { - onBeforeLinkSave((T)event.getSource(), ((BeforeLinkSaveEvent)event).getLinked()); - } else if(event instanceof AfterLinkSaveEvent) { - onAfterLinkSave((T)event.getSource(), ((AfterLinkSaveEvent)event).getLinked()); - } else if(event instanceof BeforeLinkDeleteEvent) { - onBeforeLinkDelete((T)event.getSource(), ((BeforeLinkDeleteEvent)event).getLinked()); - } else if(event instanceof AfterLinkDeleteEvent) { - onAfterLinkDelete((T)event.getSource(), ((AfterLinkDeleteEvent)event).getLinked()); - } else if(event instanceof BeforeDeleteEvent) { - onBeforeDelete((T)event.getSource()); - } else if(event instanceof AfterDeleteEvent) { - onAfterDelete((T)event.getSource()); + if (event instanceof BeforeSaveEvent) { + onBeforeSave((T) event.getSource()); + } else if (event instanceof BeforeCreateEvent) { + onBeforeCreate((T) event.getSource()); + } else if (event instanceof AfterCreateEvent) { + onAfterCreate((T) event.getSource()); + } else if (event instanceof AfterSaveEvent) { + onAfterSave((T) event.getSource()); + } else if (event instanceof BeforeLinkSaveEvent) { + onBeforeLinkSave((T) event.getSource(), ((BeforeLinkSaveEvent) event).getLinked()); + } else if (event instanceof AfterLinkSaveEvent) { + onAfterLinkSave((T) event.getSource(), ((AfterLinkSaveEvent) event).getLinked()); + } else if (event instanceof BeforeLinkDeleteEvent) { + onBeforeLinkDelete((T) event.getSource(), ((BeforeLinkDeleteEvent) event).getLinked()); + } else if (event instanceof AfterLinkDeleteEvent) { + onAfterLinkDelete((T) event.getSource(), ((AfterLinkDeleteEvent) event).getLinked()); + } else if (event instanceof BeforeDeleteEvent) { + onBeforeDelete((T) event.getSource()); + } else if (event instanceof AfterDeleteEvent) { + onAfterDelete((T) event.getSource()); } } /** * Override this method if you are interested in {@literal beforeCreate} events. - * - * @param entity - * The entity being created. + * + * @param entity The entity being created. */ - protected void onBeforeCreate(T entity) { - } + protected void onBeforeCreate(T entity) {} /** * Override this method if you are interested in {@literal afterCreate} events. - * - * @param entity - * The entity that was created. + * + * @param entity The entity that was created. */ - protected void onAfterCreate(T entity) { - } + protected void onAfterCreate(T entity) {} /** * Override this method if you are interested in {@literal beforeSave} events. - * - * @param entity - * The entity being saved. + * + * @param entity The entity being saved. */ - protected void onBeforeSave(T entity) { - } + protected void onBeforeSave(T entity) {} /** * Override this method if you are interested in {@literal afterSave} events. - * - * @param entity - * The entity that was just saved. + * + * @param entity The entity that was just saved. */ - protected void onAfterSave(T entity) { - } + protected void onAfterSave(T entity) {} /** * Override this method if you are interested in {@literal beforeLinkSave} events. - * - * @param parent - * The parent entity to which the child object is linked. - * @param linked - * The linked, child entity. + * + * @param parent The parent entity to which the child object is linked. + * @param linked The linked, child entity. */ - protected void onBeforeLinkSave(T parent, Object linked) { - } + protected void onBeforeLinkSave(T parent, Object linked) {} /** * Override this method if you are interested in {@literal afterLinkSave} events. - * - * @param parent - * The parent entity to which the child object is linked. - * @param linked - * The linked, child entity. + * + * @param parent The parent entity to which the child object is linked. + * @param linked The linked, child entity. */ - protected void onAfterLinkSave(T parent, Object linked) { - } + protected void onAfterLinkSave(T parent, Object linked) {} /** * Override this method if you are interested in {@literal beforeLinkDelete} events. - * - * @param parent - * The parent entity to which the child object is linked. - * @param linked - * The linked, child entity. + * + * @param parent The parent entity to which the child object is linked. + * @param linked The linked, child entity. */ - protected void onBeforeLinkDelete(T parent, Object linked) { - } + protected void onBeforeLinkDelete(T parent, Object linked) {} /** * Override this method if you are interested in {@literal afterLinkDelete} events. - * - * @param parent - * The parent entity to which the child object is linked. - * @param linked - * The linked, child entity. + * + * @param parent The parent entity to which the child object is linked. + * @param linked The linked, child entity. */ - protected void onAfterLinkDelete(T parent, Object linked) { - } + protected void onAfterLinkDelete(T parent, Object linked) {} /** * Override this method if you are interested in {@literal beforeDelete} events. - * - * @param entity - * The entity that is being deleted. + * + * @param entity The entity that is being deleted. */ - protected void onBeforeDelete(T entity) { - } + protected void onBeforeDelete(T entity) {} /** * Override this method if you are interested in {@literal afterDelete} events. - * - * @param entity - * The entity that was just deleted. + * + * @param entity The entity that was just deleted. */ - protected void onAfterDelete(T entity) { - } + protected void onAfterDelete(T entity) {} } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterCreateEvent.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterCreateEvent.java index de3f61ce8..3490aa020 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterCreateEvent.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterCreateEvent.java @@ -2,11 +2,11 @@ package org.springframework.data.rest.repository.context; /** * Event that is emitted after a new entity is saved. - * + * * @author Jon Brisbin */ public class AfterCreateEvent extends RepositoryEvent { - + private static final long serialVersionUID = -7673953693485678403L; public AfterCreateEvent(Object source) { diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterDeleteEvent.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterDeleteEvent.java index 255e5ec36..5f6b44f4c 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterDeleteEvent.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterDeleteEvent.java @@ -2,14 +2,14 @@ package org.springframework.data.rest.repository.context; /** * Emitted after the entity is deleted from the repository. - * + * * @author Jon Brisbin */ public class AfterDeleteEvent extends RepositoryEvent { - + private static final long serialVersionUID = -6090615345948638970L; public AfterDeleteEvent(Object source) { - super(source); - } + super(source); + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterLinkDeleteEvent.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterLinkDeleteEvent.java index 7c9a9c303..fdb264854 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterLinkDeleteEvent.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterLinkDeleteEvent.java @@ -2,7 +2,7 @@ package org.springframework.data.rest.repository.context; /** * Emitted after a link to a related object is deleted from the parent. - * + * * @author Jon Brisbin */ public class AfterLinkDeleteEvent extends LinkSaveEvent { @@ -10,6 +10,6 @@ public class AfterLinkDeleteEvent extends LinkSaveEvent { private static final long serialVersionUID = 3887575011761146290L; public AfterLinkDeleteEvent(Object source, Object linked) { - super(source, linked); - } + super(source, linked); + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterLinkSaveEvent.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterLinkSaveEvent.java index 5ce117558..58cbc3c48 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterLinkSaveEvent.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterLinkSaveEvent.java @@ -2,14 +2,14 @@ package org.springframework.data.rest.repository.context; /** * Emitted after saving a linked object to its parent in the repository. - * + * * @author Jon Brisbin */ public class AfterLinkSaveEvent extends LinkSaveEvent { - + private static final long serialVersionUID = 261522353893713633L; public AfterLinkSaveEvent(Object source, Object child) { - super(source, child); - } + super(source, child); + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterSaveEvent.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterSaveEvent.java index 21db5b160..57d606006 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterSaveEvent.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AfterSaveEvent.java @@ -2,14 +2,14 @@ package org.springframework.data.rest.repository.context; /** * Emitted after a save to the repository. - * + * * @author Jon Brisbin */ public class AfterSaveEvent extends RepositoryEvent { - + private static final long serialVersionUID = 8568843338617401903L; public AfterSaveEvent(Object source) { - super(source); - } + super(source); + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AnnotatedHandlerBeanPostProcessor.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AnnotatedHandlerBeanPostProcessor.java index 14027896e..c7e163f07 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AnnotatedHandlerBeanPostProcessor.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/context/AnnotatedHandlerBeanPostProcessor.java @@ -31,126 +31,119 @@ import org.springframework.util.ReflectionUtils; /** * @author Jon Brisbin */ -public class AnnotatedHandlerBeanPostProcessor implements ApplicationListener, - BeanPostProcessor { +public class AnnotatedHandlerBeanPostProcessor implements ApplicationListener, BeanPostProcessor { - private static final Logger LOG = LoggerFactory.getLogger( - AnnotatedHandlerBeanPostProcessor.class); + private static final Logger LOG = LoggerFactory.getLogger(AnnotatedHandlerBeanPostProcessor.class); private final MultiValueMap, EventHandlerMethod> handlerMethods = new LinkedMultiValueMap, AnnotatedHandlerBeanPostProcessor.EventHandlerMethod>(); - @Override public void onApplicationEvent(RepositoryEvent event) { + @Override + public void onApplicationEvent(RepositoryEvent event) { Class eventType = event.getClass(); - if(!handlerMethods.containsKey(eventType)) { + if (!handlerMethods.containsKey(eventType)) { return; } - for(EventHandlerMethod handlerMethod : handlerMethods.get(eventType)) { + for (EventHandlerMethod handlerMethod : handlerMethods.get(eventType)) { try { Object src = event.getSource(); - if(!ClassUtils.isAssignable(handlerMethod.targetType, src.getClass())) { + if (!ClassUtils.isAssignable(handlerMethod.targetType, src.getClass())) { continue; } List params = new ArrayList(); params.add(src); - if(event instanceof BeforeLinkSaveEvent) { - params.add(((BeforeLinkSaveEvent)event).getLinked()); - } else if(event instanceof AfterLinkSaveEvent) { - params.add(((AfterLinkSaveEvent)event).getLinked()); + if (event instanceof BeforeLinkSaveEvent) { + params.add(((BeforeLinkSaveEvent) event).getLinked()); + } else if (event instanceof AfterLinkSaveEvent) { + params.add(((AfterLinkSaveEvent) event).getLinked()); } - if(LOG.isDebugEnabled()) { + if (LOG.isDebugEnabled()) { LOG.debug("Invoking " + event.getClass().getSimpleName() + " handler for " + event.getSource()); } handlerMethod.method.invoke(handlerMethod.handler, params.toArray()); - } catch(Exception e) { + } catch (Exception e) { throw new IllegalStateException(e); } } } - @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } - @Override public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException { + @Override + public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException { final Class beanType = bean.getClass(); RepositoryEventHandler typeAnno = AnnotationUtils.findAnnotation(beanType, RepositoryEventHandler.class); - if(null == typeAnno) { + if (null == typeAnno) { return bean; } Class[] targetTypes = typeAnno.value(); - if(targetTypes.length == 0) { - targetTypes = new Class[]{null}; + if (targetTypes.length == 0) { + targetTypes = new Class[] { null }; } - for(final Class targetType : targetTypes) { - ReflectionUtils.doWithMethods( - beanType, - new ReflectionUtils.MethodCallback() { - @Override public void doWith(Method method) - throws IllegalArgumentException, IllegalAccessException { - inspect(targetType, bean, method, HandleBeforeCreate.class, BeforeCreateEvent.class); - inspect(targetType, bean, method, HandleAfterCreate.class, AfterCreateEvent.class); - inspect(targetType, bean, method, HandleBeforeSave.class, BeforeSaveEvent.class); - inspect(targetType, bean, method, HandleAfterSave.class, AfterSaveEvent.class); - inspect(targetType, bean, method, HandleBeforeLinkSave.class, BeforeLinkSaveEvent.class); - inspect(targetType, bean, method, HandleAfterLinkSave.class, AfterLinkSaveEvent.class); - inspect(targetType, bean, method, HandleBeforeDelete.class, BeforeDeleteEvent.class); - inspect(targetType, bean, method, HandleAfterDelete.class, AfterDeleteEvent.class); - inspect(targetType, bean, method, HandleBeforeLinkDelete.class, BeforeLinkDeleteEvent.class); - inspect(targetType, bean, method, HandleAfterLinkDelete.class, AfterLinkDeleteEvent.class); - } - }, - new ReflectionUtils.MethodFilter() { - @Override public boolean matches(Method method) { - return (!method.isSynthetic() - && !method.isBridge() - && method.getDeclaringClass() != Object.class - && !method.getName().contains("$")); - } - } - ); + for (final Class targetType : targetTypes) { + ReflectionUtils.doWithMethods(beanType, new ReflectionUtils.MethodCallback() { + @Override + public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + inspect(targetType, bean, method, HandleBeforeCreate.class, BeforeCreateEvent.class); + inspect(targetType, bean, method, HandleAfterCreate.class, AfterCreateEvent.class); + inspect(targetType, bean, method, HandleBeforeSave.class, BeforeSaveEvent.class); + inspect(targetType, bean, method, HandleAfterSave.class, AfterSaveEvent.class); + inspect(targetType, bean, method, HandleBeforeLinkSave.class, BeforeLinkSaveEvent.class); + inspect(targetType, bean, method, HandleAfterLinkSave.class, AfterLinkSaveEvent.class); + inspect(targetType, bean, method, HandleBeforeDelete.class, BeforeDeleteEvent.class); + inspect(targetType, bean, method, HandleAfterDelete.class, AfterDeleteEvent.class); + inspect(targetType, bean, method, HandleBeforeLinkDelete.class, BeforeLinkDeleteEvent.class); + inspect(targetType, bean, method, HandleAfterLinkDelete.class, AfterLinkDeleteEvent.class); + } + }, new ReflectionUtils.MethodFilter() { + @Override + public boolean matches(Method method) { + return (!method.isSynthetic() && !method.isBridge() && method.getDeclaringClass() != Object.class && !method + .getName().contains("$")); + } + }); } return bean; } - private void inspect(Class targetType, - Object handler, - Method method, - Class annoType, - Class eventType) { + private void inspect(Class targetType, Object handler, Method method, Class annoType, + Class eventType) { T anno = method.getAnnotation(annoType); - if(null != anno) { + if (null != anno) { try { Class[] targetTypes; - if(null == targetType) { - targetTypes = (Class[])anno.getClass().getMethod("value", new Class[0]).invoke(anno); + if (null == targetType) { + targetTypes = (Class[]) anno.getClass().getMethod("value", new Class[0]).invoke(anno); } else { - targetTypes = new Class[]{targetType}; + targetTypes = new Class[] { targetType }; } - for(Class type : targetTypes) { + for (Class type : targetTypes) { EventHandlerMethod m = new EventHandlerMethod(type, handler, method); - if(LOG.isDebugEnabled()) { + if (LOG.isDebugEnabled()) { LOG.debug("Annotated handler method found: " + m); } handlerMethods.add(eventType, m); } - } catch(NoSuchMethodException e) { - if(LOG.isDebugEnabled()) { + } catch (NoSuchMethodException e) { + if (LOG.isDebugEnabled()) { LOG.debug(e.getMessage(), e); } - } catch(InvocationTargetException e) { - if(LOG.isDebugEnabled()) { + } catch (InvocationTargetException e) { + if (LOG.isDebugEnabled()) { LOG.debug(e.getMessage(), e); } - } catch(IllegalAccessException e) { - if(LOG.isDebugEnabled()) { + } catch (IllegalAccessException e) { + if (LOG.isDebugEnabled()) { LOG.debug(e.getMessage(), e); } } @@ -159,8 +152,8 @@ public class AnnotatedHandlerBeanPostProcessor implements ApplicationListener targetType; - final Method method; - final Object handler; + final Method method; + final Object handler; private EventHandlerMethod(Class targetType, Object handler, Method method) { this.targetType = targetType; @@ -168,12 +161,9 @@ public class AnnotatedHandlerBeanPostProcessor implements ApplicationListener> ANNOTATIONS_TO_FIND = Arrays.asList( - HandleBeforeSave.class, - HandleAfterSave.class, - HandleBeforeDelete.class, - HandleAfterDelete.class, - HandleBeforeLinkSave.class, - HandleAfterLinkSave.class, - HandleBeforeLinkDelete.class, - HandleAfterLinkDelete.class - ); - @Autowired - private Repositories repositories; + private static final Logger LOG = LoggerFactory.getLogger(ValidatingRepositoryEventListener.class); + @SuppressWarnings({ "unchecked" }) private static final List> ANNOTATIONS_TO_FIND = Arrays + .asList(HandleBeforeSave.class, HandleAfterSave.class, HandleBeforeDelete.class, HandleAfterDelete.class, + HandleBeforeLinkSave.class, HandleAfterLinkSave.class, HandleBeforeLinkDelete.class, + HandleAfterLinkDelete.class); + @Autowired private Repositories repositories; private MultiValueMap validators = new LinkedMultiValueMap(); - @Override public void afterPropertiesSet() throws Exception { - if(validators.size() == 0) { - for(Map.Entry entry : beansOfTypeIncludingAncestors(applicationContext, - Validator.class).entrySet()) { + @Override + public void afterPropertiesSet() throws Exception { + if (validators.size() == 0) { + for (Map.Entry entry : beansOfTypeIncludingAncestors(applicationContext, Validator.class) + .entrySet()) { String name = null; Validator v = entry.getValue(); - if(entry.getKey().contains("Save")) { + if (entry.getKey().contains("Save")) { name = entry.getKey().substring(0, entry.getKey().indexOf("Save") + 4); - } else if(entry.getKey().contains("Create")) { + } else if (entry.getKey().contains("Create")) { name = entry.getKey().substring(0, entry.getKey().indexOf("Create") + 6); - } else if(entry.getKey().contains("Delete")) { + } else if (entry.getKey().contains("Delete")) { name = entry.getKey().substring(0, entry.getKey().indexOf("Delete") + 6); } else { - for(Class annoType : ANNOTATIONS_TO_FIND) { - if(findAnnotation(v.getClass(), annoType) != null) { + for (Class annoType : ANNOTATIONS_TO_FIND) { + if (findAnnotation(v.getClass(), annoType) != null) { name = uncapitalize(annoType.getSimpleName().substring(6)); } } } - if(null != name) { + if (null != name) { this.validators.add(name, v); } } @@ -91,7 +82,7 @@ public class ValidatingRepositoryEventListener /** * Get a Map of {@link Validator}s that are assigned to the various {@link RepositoryEvent}s. - * + * * @return Validators assigned to events. */ public Map> getValidators() { @@ -100,14 +91,12 @@ public class ValidatingRepositoryEventListener /** * Assign a Map of {@link Validator}s that are assigned to the various {@link RepositoryEvent}s. - * - * @param validators - * A Map of Validators to wire. - * + * + * @param validators A Map of Validators to wire. * @return @this */ public ValidatingRepositoryEventListener setValidators(Map> validators) { - for(Map.Entry> entry : validators.entrySet()) { + for (Map.Entry> entry : validators.entrySet()) { this.validators.put(entry.getKey(), new ArrayList(entry.getValue())); } return this; @@ -115,12 +104,9 @@ public class ValidatingRepositoryEventListener /** * Add a {@link Validator} that will be triggered on the given event. - * - * @param event - * The event to listen for. - * @param validator - * The Validator to execute when that event fires. - * + * + * @param event The event to listen for. + * @param validator The Validator to execute when that event fires. * @return @this */ public ValidatingRepositoryEventListener addValidator(String event, Validator validator) { @@ -128,57 +114,63 @@ public class ValidatingRepositoryEventListener return this; } - @Override protected void onBeforeCreate(Object entity) { + @Override + protected void onBeforeCreate(Object entity) { validate("beforeCreate", entity); } - @Override protected void onAfterCreate(Object entity) { + @Override + protected void onAfterCreate(Object entity) { validate("afterCreate", entity); } - @Override protected void onBeforeSave(Object entity) { + @Override + protected void onBeforeSave(Object entity) { validate("beforeSave", entity); } - @Override protected void onAfterSave(Object entity) { + @Override + protected void onAfterSave(Object entity) { validate("afterSave", entity); } - @Override protected void onBeforeLinkSave(Object parent, Object linked) { + @Override + protected void onBeforeLinkSave(Object parent, Object linked) { validate("beforeLinkSave", parent); } - @Override protected void onAfterLinkSave(Object parent, Object linked) { + @Override + protected void onAfterLinkSave(Object parent, Object linked) { validate("afterLinkSave", parent); } - @Override protected void onBeforeDelete(Object entity) { + @Override + protected void onBeforeDelete(Object entity) { validate("beforeDelete", entity); } - @Override protected void onAfterDelete(Object entity) { + @Override + protected void onAfterDelete(Object entity) { validate("afterDelete", entity); } private Errors validate(String event, Object o) { Errors errors = null; - if(null != o) { + if (null != o) { Class domainType = o.getClass(); - errors = new ValidationErrors(domainType.getSimpleName(), - o, - repositories.getPersistentEntity(domainType)); + errors = new ValidationErrors(domainType.getSimpleName(), o, repositories.getPersistentEntity(domainType)); Collection validators = this.validators.get(event); - if(null != validators) { - for(Validator v : validators) { - if(v.supports(o.getClass())) { + if (null != validators) { + for (Validator v : validators) { + if (v.supports(o.getClass())) { LOG.debug(event + ": " + o + " with " + v); ValidationUtils.invokeValidator(v, o, errors); } } } - if(errors.getErrorCount() > 0) { + if (errors.getErrorCount() > 0) { throw new RepositoryConstraintViolationException(errors); } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/CrudMethod.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/CrudMethod.java index 94de6d692..4ea224cea 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/CrudMethod.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/CrudMethod.java @@ -3,78 +3,69 @@ package org.springframework.data.rest.repository.invoke; import java.lang.reflect.Method; /** - * Represents one of the CRUD methods supported by {@link org.springframework.data.repository.PagingAndSortingRepository} - * or {@link org.springframework.data.repository.CrudRepository}. - * + * Represents one of the CRUD methods supported by + * {@link org.springframework.data.repository.PagingAndSortingRepository} or + * {@link org.springframework.data.repository.CrudRepository}. + * * @author Jon Brisbin */ public enum CrudMethod { - COUNT, - DELETE_ALL, - DELETE_ONE, - DELETE_SOME, - FIND_ALL, - FIND_ONE, - FIND_SOME, - SAVE_ONE, - SAVE_SOME; + COUNT, DELETE_ALL, DELETE_ONE, DELETE_SOME, FIND_ALL, FIND_ONE, FIND_SOME, SAVE_ONE, SAVE_SOME; - /** - * Get an enum from a {@link Method}. Narrow down overridden methods by looking for {@link Iterable} in the first - * parameter, which tells us it is a '_SOME' type. - * - * @param m - * The CRUD method from the repository interface. - * - * @return An enum representing which CRUD operation this method represents. - */ - public static CrudMethod fromMethod(Method m) { - String s = m.getName(); - Class[] paramTypes = m.getParameterTypes(); - boolean some = (paramTypes.length > 0 && Iterable.class.isAssignableFrom(paramTypes[0])); - if("count".equals(s)) { - return COUNT; - } else if("delete".equals(s)) { - return (some ? DELETE_SOME : DELETE_ONE); - } else if("deleteAll".equals(s)) { - return DELETE_ALL; - } else if("findAll".equals(s)) { - return (some ? FIND_SOME : FIND_ALL); - } else if("findOne".equals(s)) { - return FIND_ONE; - } else if("save".equals(s)) { - return (some ? SAVE_SOME : SAVE_ONE); - } else { - return null; - } - } + /** + * Get an enum from a {@link Method}. Narrow down overridden methods by looking for {@link Iterable} in the first + * parameter, which tells us it is a '_SOME' type. + * + * @param m The CRUD method from the repository interface. + * @return An enum representing which CRUD operation this method represents. + */ + public static CrudMethod fromMethod(Method m) { + String s = m.getName(); + Class[] paramTypes = m.getParameterTypes(); + boolean some = (paramTypes.length > 0 && Iterable.class.isAssignableFrom(paramTypes[0])); + if ("count".equals(s)) { + return COUNT; + } else if ("delete".equals(s)) { + return (some ? DELETE_SOME : DELETE_ONE); + } else if ("deleteAll".equals(s)) { + return DELETE_ALL; + } else if ("findAll".equals(s)) { + return (some ? FIND_SOME : FIND_ALL); + } else if ("findOne".equals(s)) { + return FIND_ONE; + } else if ("save".equals(s)) { + return (some ? SAVE_SOME : SAVE_ONE); + } else { + return null; + } + } - /** - * Turn this enum into a method name. - * - * @return The method name as a string. - */ - public String toMethodName() { - switch(this) { - case COUNT: - return "count"; - case DELETE_ALL: - return "deleteAll"; - case DELETE_ONE: - case DELETE_SOME: - return "delete"; - case FIND_ALL: - case FIND_SOME: - return "findAll"; - case FIND_ONE: - return "findOne"; - case SAVE_ONE: - case SAVE_SOME: - return "save"; - default: - return null; - } - } + /** + * Turn this enum into a method name. + * + * @return The method name as a string. + */ + public String toMethodName() { + switch (this) { + case COUNT: + return "count"; + case DELETE_ALL: + return "deleteAll"; + case DELETE_ONE: + case DELETE_SOME: + return "delete"; + case FIND_ALL: + case FIND_SOME: + return "findAll"; + case FIND_ONE: + return "findOne"; + case SAVE_ONE: + case SAVE_SOME: + return "save"; + default: + return null; + } + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/MethodParameterConversionService.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/MethodParameterConversionService.java index d9c37d7e1..e6134e8fb 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/MethodParameterConversionService.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/MethodParameterConversionService.java @@ -9,49 +9,48 @@ import org.springframework.data.rest.repository.annotation.ConvertWith; import org.springframework.util.Assert; /** - * A special conversion service that can convert {@link MethodParameter}s and their values to a target type, taking - * into account any specific conversion instructions annotated on the parameter with {@link ConvertWith}. - * + * A special conversion service that can convert {@link MethodParameter}s and their values to a target type, taking into + * account any specific conversion instructions annotated on the parameter with {@link ConvertWith}. + * * @author Jon Brisbin */ public class MethodParameterConversionService { - private final ConversionService delegateConversionService; + private final ConversionService delegateConversionService; - public MethodParameterConversionService(ConversionService delegateConversionService) { - Assert.notNull(delegateConversionService, "Delegate ConversionService cannot be null."); - this.delegateConversionService = delegateConversionService; - } + public MethodParameterConversionService(ConversionService delegateConversionService) { + Assert.notNull(delegateConversionService, "Delegate ConversionService cannot be null."); + this.delegateConversionService = delegateConversionService; + } - public boolean canConvert(Class sourceType, MethodParameter param) { - return canConvert(TypeDescriptor.valueOf(sourceType), param); - } + public boolean canConvert(Class sourceType, MethodParameter param) { + return canConvert(TypeDescriptor.valueOf(sourceType), param); + } - public boolean canConvert(TypeDescriptor sourceType, MethodParameter param) { - return (delegateConversionService.canConvert(sourceType, new TypeDescriptor(param)) - || param.hasParameterAnnotation(ConvertWith.class)); - } + public boolean canConvert(TypeDescriptor sourceType, MethodParameter param) { + return (delegateConversionService.canConvert(sourceType, new TypeDescriptor(param)) || param + .hasParameterAnnotation(ConvertWith.class)); + } - public T convert(Object source, MethodParameter param) { - return convert(source, TypeDescriptor.forObject(source), param); - } + public T convert(Object source, MethodParameter param) { + return convert(source, TypeDescriptor.forObject(source), param); + } - @SuppressWarnings({"unchecked"}) - public T convert(Object source, TypeDescriptor sourceType, MethodParameter param) { - TypeDescriptor targetType = new TypeDescriptor(param); + @SuppressWarnings({ "unchecked" }) + public T convert(Object source, TypeDescriptor sourceType, MethodParameter param) { + TypeDescriptor targetType = new TypeDescriptor(param); - try { - if(param.hasParameterAnnotation(ConvertWith.class)) { - Converter converter = (Converter)param.getParameterAnnotation(ConvertWith.class) - .value() - .newInstance(); - return converter.convert(source); - } else { - return (T)delegateConversionService.convert(source, sourceType, targetType); - } - } catch(Exception e) { - throw new ConversionFailedException(sourceType, targetType, source, e); - } - } + try { + if (param.hasParameterAnnotation(ConvertWith.class)) { + Converter converter = (Converter) param.getParameterAnnotation(ConvertWith.class).value() + .newInstance(); + return converter.convert(source); + } else { + return (T) delegateConversionService.convert(source, sourceType, targetType); + } + } catch (Exception e) { + throw new ConversionFailedException(sourceType, targetType, source, e); + } + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethod.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethod.java index 5de1fc153..0f3a9581a 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethod.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethod.java @@ -14,101 +14,101 @@ import org.springframework.data.rest.repository.support.Methods; /** * An abstraction to encapsulate metadata about a repository method. - * + * * @author Jon Brisbin */ public class RepositoryMethod { - private Method method; - private List methodParameters = new ArrayList(); - private List paramNames = new ArrayList(); - private boolean pageable = false; - private boolean sortable = false; + private Method method; + private List methodParameters = new ArrayList(); + private List paramNames = new ArrayList(); + private boolean pageable = false; + private boolean sortable = false; - public RepositoryMethod(Method method) { - this.method = method; + public RepositoryMethod(Method method) { + this.method = method; - Class[] paramTypes = method.getParameterTypes(); - String[] paramNames = Methods.NAME_DISCOVERER.getParameterNames(method); - if(null == paramNames) { - paramNames = new String[paramTypes.length]; - } + Class[] paramTypes = method.getParameterTypes(); + String[] paramNames = Methods.NAME_DISCOVERER.getParameterNames(method); + if (null == paramNames) { + paramNames = new String[paramTypes.length]; + } - Annotation[][] paramAnnos = method.getParameterAnnotations(); - for(int i = 0; i < paramAnnos.length; i++) { - if(paramAnnos[i].length > 0) { - for(Annotation anno : paramAnnos[i]) { - if(Param.class.isAssignableFrom(anno.getClass())) { - Param p = (Param)anno; - paramNames[i] = p.value(); - break; - } - } - } - if(null == paramNames[i]) { - paramNames[i] = "arg" + i; - } - } + Annotation[][] paramAnnos = method.getParameterAnnotations(); + for (int i = 0; i < paramAnnos.length; i++) { + if (paramAnnos[i].length > 0) { + for (Annotation anno : paramAnnos[i]) { + if (Param.class.isAssignableFrom(anno.getClass())) { + Param p = (Param) anno; + paramNames[i] = p.value(); + break; + } + } + } + if (null == paramNames[i]) { + paramNames[i] = "arg" + i; + } + } - int idx = 0; - for(Class type : paramTypes) { - if(Pageable.class.isAssignableFrom(type)) { - pageable = true; - } - if(Sort.class.isAssignableFrom(type)) { - sortable = true; - } - methodParameters.add(new MethodParameter(method, idx)); - idx++; - } + int idx = 0; + for (Class type : paramTypes) { + if (Pageable.class.isAssignableFrom(type)) { + pageable = true; + } + if (Sort.class.isAssignableFrom(type)) { + sortable = true; + } + methodParameters.add(new MethodParameter(method, idx)); + idx++; + } - Collections.addAll(this.paramNames, paramNames); - } + Collections.addAll(this.paramNames, paramNames); + } - /** - * Get the method parameter types. - * - * @return Array of parameter types. - */ - public List getParameters() { - return methodParameters; - } + /** + * Get the method parameter types. + * + * @return Array of parameter types. + */ + public List getParameters() { + return methodParameters; + } - /** - * Get the method parameter names. - * - * @return Array of parameter names. - */ - public List getParameterNames() { - return paramNames; - } + /** + * Get the method parameter names. + * + * @return Array of parameter names. + */ + public List getParameterNames() { + return paramNames; + } - /** - * Get the reflected {@link Method} to invoke. - * - * @return The {@link Method} to invoke. - */ - public Method getMethod() { - return method; - } + /** + * Get the reflected {@link Method} to invoke. + * + * @return The {@link Method} to invoke. + */ + public Method getMethod() { + return method; + } - /** - * Flag denoting whether this repository method returns a {@link org.springframework.data.domain.Page} result or not. - * - * @return {@literal true} if this method returns a {@link org.springframework.data.domain.Page}, {@literal false} - * otherwise. - */ - public boolean isPageable() { - return pageable; - } + /** + * Flag denoting whether this repository method returns a {@link org.springframework.data.domain.Page} result or not. + * + * @return {@literal true} if this method returns a {@link org.springframework.data.domain.Page}, {@literal false} + * otherwise. + */ + public boolean isPageable() { + return pageable; + } - /** - * Flag denoting whether this repository method accepts sorting information. - * - * @return {@literal true} if this method accepts a {@link Sort}, {@literal false} otherwise. - */ - public boolean isSortable() { - return sortable; - } + /** + * Flag denoting whether this repository method accepts sorting information. + * + * @return {@literal true} if this method accepts a {@link Sort}, {@literal false} otherwise. + */ + public boolean isSortable() { + return sortable; + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethodInvoker.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethodInvoker.java index 3f35409ca..28e97e6bd 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethodInvoker.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethodInvoker.java @@ -27,7 +27,7 @@ public class RepositoryMethodInvoker implements PagingAndSortingRepository queryMethods = new HashMap(); private final ConversionService conversionService; - + private RepositoryMethod saveOne; private RepositoryMethod saveSome; private RepositoryMethod findOne; @@ -42,18 +42,17 @@ public class RepositoryMethodInvoker implements PagingAndSortingRepository repoType = repoInfo.getRepositoryInterface(); doWithMethods(repoType, new MethodCallback() { - @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + @Override + public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { boolean exported = ResourceMappingUtils.findExported(method); - if(!exported) { + if (!exported) { return; } String name = method.getName(); @@ -65,31 +64,31 @@ public class RepositoryMethodInvoker implements PagingAndSortingRepository S save(S entity) { - return (S)invokeMethod(saveOne.getMethod(), repository, entity); + @SuppressWarnings({ "unchecked" }) + @Override + public S save(S entity) { + return (S) invokeMethod(saveOne.getMethod(), repository, entity); } public boolean hasSaveOne() { return null != saveOne; } - @SuppressWarnings({"unchecked"}) - @Override public Iterable save(Iterable entities) { - return (Iterable)invokeMethod(saveSome.getMethod(), repository, entities); + @SuppressWarnings({ "unchecked" }) + @Override + public Iterable save(Iterable entities) { + return (Iterable) invokeMethod(saveSome.getMethod(), repository, entities); } public boolean hasSaveSome() { return null != saveSome; } - @Override public Object findOne(Serializable serializable) { + @Override + public Object findOne(Serializable serializable) { return invokeMethod(findOne.getMethod(), repository, serializable); } @@ -124,51 +126,57 @@ public class RepositoryMethodInvoker implements PagingAndSortingRepository findAll() { - return (Iterable)invokeMethod(findAll.getMethod(), repository); + @SuppressWarnings({ "unchecked" }) + @Override + public Iterable findAll() { + return (Iterable) invokeMethod(findAll.getMethod(), repository); } public boolean hasFindAll() { return null != findAll; } - @SuppressWarnings({"unchecked"}) - @Override public Iterable findAll(Iterable serializables) { - return (Iterable)invokeMethod(findSome.getMethod(), repository, serializables); + @SuppressWarnings({ "unchecked" }) + @Override + public Iterable findAll(Iterable serializables) { + return (Iterable) invokeMethod(findSome.getMethod(), repository, serializables); } public boolean hasFindSome() { return null != findSome; } - @SuppressWarnings({"unchecked"}) - @Override public Iterable findAll(Sort sort) { - return (Iterable)invokeMethod(findAllSorted.getMethod(), repository, sort); + @SuppressWarnings({ "unchecked" }) + @Override + public Iterable findAll(Sort sort) { + return (Iterable) invokeMethod(findAllSorted.getMethod(), repository, sort); } public boolean hasFindAllSorted() { return null != findAllSorted; } - @SuppressWarnings({"unchecked"}) - @Override public Page findAll(Pageable pageable) { - return (Page)invokeMethod(findAllPaged.getMethod(), repository, pageable); + @SuppressWarnings({ "unchecked" }) + @Override + public Page findAll(Pageable pageable) { + return (Page) invokeMethod(findAllPaged.getMethod(), repository, pageable); } public boolean hasFindAllPageable() { return null != findAllPaged; } - @Override public void delete(Serializable serializable) { + @Override + public void delete(Serializable serializable) { invokeMethod(deleteOneById.getMethod(), repository, serializable); } @@ -176,15 +184,17 @@ public class RepositoryMethodInvoker implements PagingAndSortingRepository entities) { + @Override + public void delete(Iterable entities) { invokeMethod(deleteSome.getMethod(), repository, entities); } @@ -200,7 +211,8 @@ public class RepositoryMethodInvoker implements PagingAndSortingRepository rawParameters) { return invokeQueryMethod(method, foo(method, pageable, rawParameters)); } - + private Object[] foo(RepositoryMethod repoMethod, Pageable pageable, Map rawParameters) { - + List methodParams = repoMethod.getParameters(); - + if (methodParams.isEmpty()) { return new Object[0]; } - + Object[] paramValues = new Object[methodParams.size()]; - - - for(int i = 0; i < paramValues.length; i++) { + + for (int i = 0; i < paramValues.length; i++) { MethodParameter param = methodParams.get(i); Class targetType = param.getParameterType(); - if(Pageable.class.isAssignableFrom(targetType)) { + if (Pageable.class.isAssignableFrom(targetType)) { paramValues[i] = pageable; - } else if(Sort.class.isAssignableFrom(targetType)) { + } else if (Sort.class.isAssignableFrom(targetType)) { paramValues[i] = pageable.getSort(); } else { String paramName = repoMethod.getParameterNames().get(i); String[] queryParamVals = rawParameters.get(paramName); - if(null == queryParamVals) { - if(paramName.startsWith("arg")) { + if (null == queryParamVals) { + if (paramName.startsWith("arg")) { throw new IllegalArgumentException("No @Param annotation found on query method " - + repoMethod.getMethod().getName() - + " for parameter " + param.getParameterName()); + + repoMethod.getMethod().getName() + " for parameter " + param.getParameterName()); } else { - throw new IllegalArgumentException("No query parameter specified for " - + repoMethod.getMethod().getName() + " param '" - + paramName + "'"); + throw new IllegalArgumentException("No query parameter specified for " + repoMethod.getMethod().getName() + + " param '" + paramName + "'"); } } paramValues[i] = conversionService.convert(queryParamVals, targetType); } } - - + return paramValues; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethodResponse.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethodResponse.java index 9582b2f67..32fa77998 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethodResponse.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryMethodResponse.java @@ -11,96 +11,94 @@ import org.springframework.hateoas.Link; /** * JSON-serializable response for returns that have a mix of results and links. Also used in responses that have just * links (in that case, 'results' will be an empty array). - * + * * @author Jon Brisbin */ public class RepositoryMethodResponse { - @JsonProperty("results") - private List results = new ArrayList(); - @JsonProperty("links") - private List links = new ArrayList(); - private long totalCount = 0; - private int totalPages = 1; - private int currentPage = 1; + @JsonProperty("results") private List results = new ArrayList(); + @JsonProperty("links") private List links = new ArrayList(); + private long totalCount = 0; + private int totalPages = 1; + private int currentPage = 1; - public RepositoryMethodResponse addLink(Link l) { - links.add(l); - return this; - } + public RepositoryMethodResponse addLink(Link l) { + links.add(l); + return this; + } - public RepositoryMethodResponse addResult(Object obj) { - results.add(obj); - return this; - } + public RepositoryMethodResponse addResult(Object obj) { + results.add(obj); + return this; + } - public RepositoryMethodResponse addAllResults(Iterator results) { - if(null == results) { - return this; - } + public RepositoryMethodResponse addAllResults(Iterator results) { + if (null == results) { + return this; + } - while(results.hasNext()) { - addResult(results.next()); - } + while (results.hasNext()) { + addResult(results.next()); + } - return this; - } + return this; + } - public List getResults() { - return results; - } + public List getResults() { + return results; + } - public boolean hasResults() { - return (results.size() > 0); - } + public boolean hasResults() { + return (results.size() > 0); + } - public RepositoryMethodResponse setResults(List results) { - if(null == results) { - this.results = Collections.emptyList(); - } else { - this.results = results; - } - return this; - } + public RepositoryMethodResponse setResults(List results) { + if (null == results) { + this.results = Collections.emptyList(); + } else { + this.results = results; + } + return this; + } - public List getLinks() { - return links; - } + public List getLinks() { + return links; + } - public RepositoryMethodResponse setLinks(List links) { - if(null == links) { - this.links = Collections.emptyList(); - } else { - this.links = links; - } - return this; - } + public RepositoryMethodResponse setLinks(List links) { + if (null == links) { + this.links = Collections.emptyList(); + } else { + this.links = links; + } + return this; + } - public long getTotalCount() { - return totalCount; - } + public long getTotalCount() { + return totalCount; + } - public RepositoryMethodResponse setTotalCount(long totalCount) { - this.totalCount = totalCount; - return this; - } + public RepositoryMethodResponse setTotalCount(long totalCount) { + this.totalCount = totalCount; + return this; + } - public int getTotalPages() { - return totalPages; - } + public int getTotalPages() { + return totalPages; + } - public RepositoryMethodResponse setTotalPages(int totalPages) { - this.totalPages = totalPages; - return this; - } + public RepositoryMethodResponse setTotalPages(int totalPages) { + this.totalPages = totalPages; + return this; + } - public int getCurrentPage() { - return currentPage; - } + public int getCurrentPage() { + return currentPage; + } - public RepositoryMethodResponse setCurrentPage(int currentPage) { - this.currentPage = currentPage; - return this; - } + public RepositoryMethodResponse setCurrentPage(int currentPage) { + this.currentPage = currentPage; + return this; + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryQueryMethod.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryQueryMethod.java index 85a721d48..30d373c53 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryQueryMethod.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/invoke/RepositoryQueryMethod.java @@ -10,72 +10,70 @@ import org.springframework.util.Assert; /** * Represents a query method on a repository interface. - * + * * @author Jon Brisbin */ public class RepositoryQueryMethod { - private Method method; - private Class[] paramTypes; - private String[] paramNames; + private Method method; + private Class[] paramTypes; + private String[] paramNames; - public RepositoryQueryMethod(Method method) { - this.method = method; - paramTypes = method.getParameterTypes(); - paramNames = new String[paramTypes.length]; - if(null == paramNames) { - paramNames = new String[paramTypes.length]; - } - Annotation[][] paramAnnos = method.getParameterAnnotations(); - for(int i = 0; i < paramAnnos.length; i++) { - if(paramAnnos[i].length == 0) { - continue; - } + public RepositoryQueryMethod(Method method) { + this.method = method; + paramTypes = method.getParameterTypes(); + paramNames = new String[paramTypes.length]; + if (null == paramNames) { + paramNames = new String[paramTypes.length]; + } + Annotation[][] paramAnnos = method.getParameterAnnotations(); + for (int i = 0; i < paramAnnos.length; i++) { + if (paramAnnos[i].length == 0) { + continue; + } - for(Annotation anno : paramAnnos[i]) { - if(Param.class.isAssignableFrom(anno.getClass())) { - Param p = (Param)anno; - paramNames[i] = p.value(); - break; - } - } + for (Annotation anno : paramAnnos[i]) { + if (Param.class.isAssignableFrom(anno.getClass())) { + Param p = (Param) anno; + paramNames[i] = p.value(); + break; + } + } - if(Pageable.class.isAssignableFrom(paramTypes[i]) - || Sort.class.isAssignableFrom(paramTypes[i])) { - continue; - } + if (Pageable.class.isAssignableFrom(paramTypes[i]) || Sort.class.isAssignableFrom(paramTypes[i])) { + continue; + } - Assert.notNull(paramNames[i], - "No @Param('name') was provided for parameter " + (i + 1) + " of type " + paramTypes[i] - + " on " + (method.getDeclaringClass().getName() + "." + method.getName())); - } - } + Assert.notNull(paramNames[i], "No @Param('name') was provided for parameter " + (i + 1) + " of type " + + paramTypes[i] + " on " + (method.getDeclaringClass().getName() + "." + method.getName())); + } + } - /** - * The method's parameter types. - * - * @return - */ - public Class[] paramTypes() { - return paramTypes; - } + /** + * The method's parameter types. + * + * @return + */ + public Class[] paramTypes() { + return paramTypes; + } - /** - * The parameter names as pulled from the {@link Param} annotations. - * - * @return - */ - public String[] paramNames() { - return paramNames; - } + /** + * The parameter names as pulled from the {@link Param} annotations. + * + * @return + */ + public String[] paramNames() { + return paramNames; + } - /** - * The {@link Method} to invoke. - * - * @return - */ - public Method method() { - return method; - } + /** + * The {@link Method} to invoke. + * + * @return + */ + public Method method() { + return method; + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/CollectionResourceMapping.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/CollectionResourceMapping.java index a91cd5e20..bc534d649 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/CollectionResourceMapping.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/CollectionResourceMapping.java @@ -17,7 +17,7 @@ package org.springframework.data.rest.repository.mapping; /** * A custom resource mapping for collection resources. - * + * * @author Oliver Gierke */ public interface CollectionResourceMapping extends ResourceMapping { diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/CollectionResourceMappingBuilder.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/CollectionResourceMappingBuilder.java index 5dc8cd992..39df2ff71 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/CollectionResourceMappingBuilder.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/CollectionResourceMappingBuilder.java @@ -17,92 +17,91 @@ package org.springframework.data.rest.repository.mapping; import org.springframework.util.Assert; - class CollectionResourceMappingBuilder implements InternalMappingBuilder { - + private final CollectionResourceMapping mapping; - + public CollectionResourceMappingBuilder(CollectionResourceMapping mapping) { this.mapping = mapping; } - + /* * (non-Javadoc) * @see org.springframework.data.rest.repository.mapping.InternalMappingBuilder#withCollectionRel(java.lang.String) */ public CollectionResourceMappingBuilder withCollectionRel(String rel) { - - SimpleCollectionResourceMapping newMapping = new SimpleCollectionResourceMapping(rel != null ? rel : mapping.getRel(), - mapping.getSingleResourceRel(), mapping.getPath(), mapping.isExported()); + + SimpleCollectionResourceMapping newMapping = new SimpleCollectionResourceMapping(rel != null ? rel + : mapping.getRel(), mapping.getSingleResourceRel(), mapping.getPath(), mapping.isExported()); return new CollectionResourceMappingBuilder(newMapping); } - + /* * (non-Javadoc) * @see org.springframework.data.rest.repository.mapping.InternalMappingBuilder#withSingleRel(java.lang.String) */ @Override public CollectionResourceMappingBuilder withSingleRel(String rel) { - + SimpleCollectionResourceMapping newMapping = new SimpleCollectionResourceMapping(mapping.getRel(), rel != null ? rel : mapping.getSingleResourceRel(), mapping.getPath(), mapping.isExported()); - + return new CollectionResourceMappingBuilder(newMapping); } - + /* * (non-Javadoc) * @see org.springframework.data.rest.repository.mapping.InternalMappingBuilder#withPath(java.lang.String) */ @Override public CollectionResourceMappingBuilder withPath(String path) { - + SimpleCollectionResourceMapping newMapping = new SimpleCollectionResourceMapping(mapping.getRel(), mapping.getSingleResourceRel(), path != null ? path : mapping.getPath(), mapping.isExported()); - + return new CollectionResourceMappingBuilder(newMapping); } - + /* * (non-Javadoc) * @see org.springframework.data.rest.repository.mapping.InternalMappingBuilder#withExposed(java.lang.Boolean) */ @Override public CollectionResourceMappingBuilder withExposed(Boolean exported) { - + SimpleCollectionResourceMapping newMapping = new SimpleCollectionResourceMapping(mapping.getRel(), mapping.getSingleResourceRel(), mapping.getPath(), exported != null ? exported : mapping.isExported()); - + return new CollectionResourceMappingBuilder(newMapping); } - + /* * (non-Javadoc) * @see org.springframework.data.rest.repository.mapping.InternalMappingBuilder#merge(org.springframework.data.rest.repository.mapping.CollectionResourceMapping) */ @Override public InternalMappingBuilder merge(CollectionResourceMapping mapping) { - + if (mapping == null) { return this; } - + return withCollectionRel(mapping.getRel()). // withSingleRel(mapping.getSingleResourceRel()). // withPath(mapping.getPath()). // withExposed(mapping.isExported()); } - + /* * (non-Javadoc) * @see org.springframework.data.rest.repository.mapping.InternalMappingBuilder#getMapping() */ @Override public CollectionResourceMapping getMapping() { - + Assert.hasText(mapping.getRel(), "Rel must not be null or empty!"); - + return mapping; } @@ -112,4 +111,4 @@ class CollectionResourceMappingBuilder implements InternalMappingBuilder { public Boolean isExported() { return mapping.isExported(); } -} \ No newline at end of file +} diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/InternalMappingBuilder.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/InternalMappingBuilder.java index 42f4b422b..c313997be 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/InternalMappingBuilder.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/InternalMappingBuilder.java @@ -21,6 +21,6 @@ package org.springframework.data.rest.repository.mapping; interface InternalMappingBuilder extends MappingBuilder { InternalMappingBuilder merge(CollectionResourceMapping mapping); - + CollectionResourceMapping getMapping(); } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/MappingBuilder.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/MappingBuilder.java index b7c33a985..0122d9443 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/MappingBuilder.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/MappingBuilder.java @@ -17,7 +17,7 @@ package org.springframework.data.rest.repository.mapping; /** * SPI to allow users to register - * + * * @author Oliver Gierke */ public interface MappingBuilder { diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/RepositoryAwareResourceInformation.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/RepositoryAwareResourceInformation.java index d42753c8f..e6d8ed983 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/RepositoryAwareResourceInformation.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/RepositoryAwareResourceInformation.java @@ -49,7 +49,7 @@ public class RepositoryAwareResourceInformation implements ResourceMetadata { this.provider = provider; this.repositoryInterface = repositoryInterface; } - + public boolean isPrimary() { return AnnotationUtils.findAnnotation(repositoryInterface.getRepositoryInterface(), Primary.class) != null; } @@ -71,7 +71,7 @@ public class RepositoryAwareResourceInformation implements ResourceMetadata { public ResourceMapping getMappingFor(PersistentProperty property) { return provider.getMappingFor(property); } - + /* * (non-Javadoc) * @see org.springframework.data.rest.repository.mapping.ResourceMetadataProvider#hasMappingFor(org.springframework.data.mapping.PersistentProperty) diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMapping.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMapping.java index f93e0c3a3..d9363c708 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMapping.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMapping.java @@ -21,19 +21,19 @@ package org.springframework.data.rest.repository.mapping; * @author Oliver Gierke */ public interface ResourceMapping { - + public static ResourceMapping NO_MAPPING = new ResourceMapping() { - + @Override public Boolean isExported() { return false; } - + @Override public String getRel() { return null; } - + @Override public String getPath() { return null; diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMappingFactory.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMappingFactory.java index e98cb59fa..262c158c5 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMappingFactory.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMappingFactory.java @@ -47,7 +47,7 @@ public class ResourceMappingFactory { if (type != typeToInspect) { mapping = mapping.merge(discoverConfig(type)); } - + for (CollectionResourceMapping externalMapping : manualMapping) { mapping = mapping.merge(externalMapping); } @@ -56,7 +56,7 @@ public class ResourceMappingFactory { } private static Class getTypeToInspect(Class type) { - + if (!RepositoriesUtils.isRepositoryInterface(type)) { return type; } @@ -69,8 +69,9 @@ public class ResourceMappingFactory { String path = StringUtils.uncapitalize(domainType.getSimpleName()); String defaultCollectionRel = relProvider.getCollectionResourceRelFor(domainType); String defaultSingleRel = relProvider.getSingleResourceRelFor(domainType); - - CollectionResourceMapping mapping = new SimpleCollectionResourceMapping(defaultCollectionRel, defaultSingleRel, path, true); + + CollectionResourceMapping mapping = new SimpleCollectionResourceMapping(defaultCollectionRel, defaultSingleRel, + path, true); return new CollectionResourceMappingBuilder(mapping); } @@ -82,19 +83,19 @@ public class ResourceMappingFactory { if (resource == null) { return null; } - + return new AnnotationResourceMapping(resource); } - + /** * {@link CollectionResourceMapping} based on an {@link RestResource} annotation. - * + * * @author Oliver Gierke */ private static class AnnotationResourceMapping implements CollectionResourceMapping { - + private final RestResource annotation; - + /** * Creates a new {@link AnnotationResourceMapping} for the given {@link RestResource}. * @@ -129,7 +130,7 @@ public class ResourceMappingFactory { */ @Override public String getSingleResourceRel() { - + String rel = getRel(); return rel == null ? null : String.format("%s.%s", rel, rel); } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMappings.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMappings.java index 4ca06ef2c..24d530a25 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMappings.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMappings.java @@ -25,8 +25,8 @@ import org.springframework.data.repository.core.RepositoryInformation; import org.springframework.data.repository.support.Repositories; import org.springframework.data.rest.config.RepositoryRestConfiguration; import org.springframework.data.rest.repository.support.RepositoriesUtils; -import org.springframework.data.rest.repository.support.SimpleRelProvider; import org.springframework.hateoas.RelProvider; +import org.springframework.hateoas.core.EvoInflectorRelProvider; import org.springframework.util.Assert; /** @@ -53,7 +53,7 @@ public class ResourceMappings implements ResourceMetadataProvider, Iterable property); } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMetadataProvider.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMetadataProvider.java index ec3dedb08..148c4f584 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMetadataProvider.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/ResourceMetadataProvider.java @@ -18,12 +18,11 @@ package org.springframework.data.rest.repository.mapping; import org.springframework.data.mapping.PersistentProperty; /** - * * @author Oliver Gierke */ public interface ResourceMetadataProvider { boolean isMapped(PersistentProperty property); - + ResourceMapping getMappingFor(PersistentProperty property); } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/SimpleCollectionResourceMapping.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/SimpleCollectionResourceMapping.java index 2f3d5227e..b92911a88 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/SimpleCollectionResourceMapping.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/mapping/SimpleCollectionResourceMapping.java @@ -15,9 +15,8 @@ */ package org.springframework.data.rest.repository.mapping; - public class SimpleCollectionResourceMapping implements CollectionResourceMapping { - + private final String collectionRel; private final String singleRel; private final String path; @@ -26,9 +25,9 @@ public class SimpleCollectionResourceMapping implements CollectionResourceMappin public SimpleCollectionResourceMapping(String relsAndPath) { this(relsAndPath, relsAndPath, relsAndPath, true); } - + public SimpleCollectionResourceMapping(String collectionRel, String singleRel, String path, Boolean exported) { - + this.collectionRel = collectionRel; this.singleRel = singleRel; this.path = path; @@ -50,7 +49,7 @@ public class SimpleCollectionResourceMapping implements CollectionResourceMappin public String getSingleResourceRel() { return singleRel; } - + /* * (non-Javadoc) * @see org.springframework.data.rest.repository.mapping.CollectionResourceMapping#getPath() @@ -66,4 +65,4 @@ public class SimpleCollectionResourceMapping implements CollectionResourceMappin public Boolean isExported() { return exported; } -} \ No newline at end of file +} diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/DomainObjectMerger.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/DomainObjectMerger.java index 89d40e3a8..ecd2346ff 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/DomainObjectMerger.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/DomainObjectMerger.java @@ -15,43 +15,43 @@ import org.springframework.data.repository.support.Repositories; */ public class DomainObjectMerger { - private final Repositories repositories; - private final ConversionService conversionService; + private final Repositories repositories; + private final ConversionService conversionService; - @Autowired - public DomainObjectMerger(Repositories repositories, - ConversionService conversionService) { - this.repositories = repositories; - this.conversionService = conversionService; - } + @Autowired + public DomainObjectMerger(Repositories repositories, ConversionService conversionService) { + this.repositories = repositories; + this.conversionService = conversionService; + } - @SuppressWarnings({"unchecked", "rawtypes"}) - public void merge(Object from, Object target) { - if(null == from || null == target) { - return; - } - final BeanWrapper fromWrapper = BeanWrapper.create(from, conversionService); - final BeanWrapper targetWrapper = BeanWrapper.create(target, conversionService); - - PersistentEntity entity = repositories.getPersistentEntity(target.getClass()); - entity.doWithProperties(new PropertyHandler() { - @Override public void doWithPersistentProperty(PersistentProperty persistentProperty) { - Object fromVal = fromWrapper.getProperty(persistentProperty); - if(null != fromVal && !fromVal.equals(targetWrapper.getProperty(persistentProperty))) { - targetWrapper.setProperty(persistentProperty, fromVal); - } - } - }); - entity.doWithAssociations(new AssociationHandler() { - @Override public void doWithAssociation(Association association) { - PersistentProperty persistentProperty = association.getInverse(); - Object fromVal = fromWrapper.getProperty(persistentProperty); - if(null != fromVal && !fromVal.equals(targetWrapper.getProperty(persistentProperty))) { - targetWrapper.setProperty(persistentProperty, fromVal); - } - } - }); - } + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void merge(Object from, Object target) { + if (null == from || null == target) { + return; + } + final BeanWrapper fromWrapper = BeanWrapper.create(from, conversionService); + final BeanWrapper targetWrapper = BeanWrapper.create(target, conversionService); + PersistentEntity entity = repositories.getPersistentEntity(target.getClass()); + entity.doWithProperties(new PropertyHandler() { + @Override + public void doWithPersistentProperty(PersistentProperty persistentProperty) { + Object fromVal = fromWrapper.getProperty(persistentProperty); + if (null != fromVal && !fromVal.equals(targetWrapper.getProperty(persistentProperty))) { + targetWrapper.setProperty(persistentProperty, fromVal); + } + } + }); + entity.doWithAssociations(new AssociationHandler() { + @Override + public void doWithAssociation(Association association) { + PersistentProperty persistentProperty = association.getInverse(); + Object fromVal = fromWrapper.getProperty(persistentProperty); + if (null != fromVal && !fromVal.equals(targetWrapper.getProperty(persistentProperty))) { + targetWrapper.setProperty(persistentProperty, fromVal); + } + } + }); + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/Methods.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/Methods.java index 48c8919c5..2b9335220 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/Methods.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/Methods.java @@ -10,19 +10,15 @@ import org.springframework.util.ReflectionUtils; */ public abstract class Methods { - private Methods() { - } + private Methods() {} - public static final ReflectionUtils.MethodFilter USER_METHODS = - new ReflectionUtils.MethodFilter() { - @Override public boolean matches(Method method) { - return (!method.isSynthetic() - && !method.isBridge() - && method.getDeclaringClass() != Object.class - && !method.getName().contains("$")); - } - }; - public static final LocalVariableTableParameterNameDiscoverer NAME_DISCOVERER = - new LocalVariableTableParameterNameDiscoverer(); + public static final ReflectionUtils.MethodFilter USER_METHODS = new ReflectionUtils.MethodFilter() { + @Override + public boolean matches(Method method) { + return (!method.isSynthetic() && !method.isBridge() && method.getDeclaringClass() != Object.class && !method + .getName().contains("$")); + } + }; + public static final LocalVariableTableParameterNameDiscoverer NAME_DISCOVERER = new LocalVariableTableParameterNameDiscoverer(); } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoriesUtils.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoriesUtils.java index c9d399b67..65bc655d5 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoriesUtils.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoriesUtils.java @@ -23,20 +23,19 @@ import org.springframework.data.repository.core.support.AnnotationRepositoryMeta import org.springframework.data.repository.core.support.DefaultRepositoryMetadata; /** - * * @author Oliver Gierke */ public class RepositoriesUtils { public static Class getDomainType(Class repositoryType) { - + if (!isRepositoryInterface(repositoryType)) { return null; } - + return getMetadataFor(repositoryType).getDomainType(); } - + public static boolean isRepositoryInterface(Class type) { return Repository.class.isAssignableFrom(type) || AnnotationUtils.findAnnotation(type, RepositoryDefinition.class) != null; diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoryInformationSupport.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoryInformationSupport.java index 54fe4c215..169ba8027 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoryInformationSupport.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoryInformationSupport.java @@ -22,56 +22,57 @@ import org.springframework.util.MultiValueMap; @SuppressWarnings("deprecation") public abstract class RepositoryInformationSupport { - protected Repositories repositories; - protected RepositoryRestConfiguration config; - protected MultiValueMap, RepositoryMethod> repositoryMethods = new LinkedMultiValueMap, RepositoryMethod>(); + protected Repositories repositories; + protected RepositoryRestConfiguration config; + protected MultiValueMap, RepositoryMethod> repositoryMethods = new LinkedMultiValueMap, RepositoryMethod>(); - public Repositories getRepositories() { - return repositories; - } + public Repositories getRepositories() { + return repositories; + } - @Autowired - public void setRepositories(Repositories repositories) { - this.repositories = repositories; - for(Class domainType : repositories) { - final RepositoryInformation repoInfo = repositories.getRepositoryInformationFor(domainType); - doWithMethods(repoInfo.getRepositoryInterface(), new MethodCallback() { - @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - repositoryMethods.add(repoInfo.getRepositoryInterface(), new RepositoryMethod(method)); - } - }); - } - } + @Autowired + public void setRepositories(Repositories repositories) { + this.repositories = repositories; + for (Class domainType : repositories) { + final RepositoryInformation repoInfo = repositories.getRepositoryInformationFor(domainType); + doWithMethods(repoInfo.getRepositoryInterface(), new MethodCallback() { + @Override + public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + repositoryMethods.add(repoInfo.getRepositoryInterface(), new RepositoryMethod(method)); + } + }); + } + } - public RepositoryRestConfiguration getConfig() { - return config; - } + public RepositoryRestConfiguration getConfig() { + return config; + } - @Autowired - public void setConfig(RepositoryRestConfiguration config) { - this.config = config; - } + @Autowired + public void setConfig(RepositoryRestConfiguration config) { + this.config = config; + } - protected RepositoryInformation findRepositoryInfoFor(String pathSegment) { - if(!hasText(pathSegment)) { - return null; - } - for(Class domainType : repositories) { - RepositoryInformation repoInfo = findRepositoryInfoFor(domainType); + protected RepositoryInformation findRepositoryInfoFor(String pathSegment) { + if (!hasText(pathSegment)) { + return null; + } + for (Class domainType : repositories) { + RepositoryInformation repoInfo = findRepositoryInfoFor(domainType); ResourceMapping mapping = getResourceMapping(config, repoInfo); - if(pathSegment.equals(mapping.getPath()) && mapping.isExported()) { - return repoInfo; - } - } - return null; - } + if (pathSegment.equals(mapping.getPath()) && mapping.isExported()) { + return repoInfo; + } + } + return null; + } - protected RepositoryInformation findRepositoryInfoFor(Class domainType) { - PersistentEntity entity = repositories.getPersistentEntity(domainType); - if(null != entity) { - return repositories.getRepositoryInformationFor(domainType); - } - return null; - } + protected RepositoryInformation findRepositoryInfoFor(Class domainType) { + PersistentEntity entity = repositories.getPersistentEntity(domainType); + if (null != entity) { + return repositories.getRepositoryInformationFor(domainType); + } + return null; + } } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoryRelProvider.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoryRelProvider.java index f24efed1f..0117f8174 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoryRelProvider.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/RepositoryRelProvider.java @@ -19,22 +19,21 @@ import org.springframework.data.rest.repository.mapping.ResourceMappings; import org.springframework.hateoas.RelProvider; /** - * * @author Oliver Gierke */ public class RepositoryRelProvider implements RelProvider { private final ResourceMappings mappings; - + /** * @param repositories * @param config */ public RepositoryRelProvider(ResourceMappings mappings) { - + this.mappings = mappings; } - + /* * (non-Javadoc) * @see org.springframework.hateoas.RelProvider#getCollectionResourceRelFor(java.lang.Class) @@ -43,7 +42,7 @@ public class RepositoryRelProvider implements RelProvider { public String getCollectionResourceRelFor(Class type) { return mappings.getMappingFor(type).getRel(); } - + /* * (non-Javadoc) * @see org.springframework.hateoas.RelProvider#getSingleResourceRelFor(java.lang.Class) @@ -52,7 +51,7 @@ public class RepositoryRelProvider implements RelProvider { public String getSingleResourceRelFor(Class type) { return mappings.getMappingFor(type).getSingleResourceRel(); } - + /* * (non-Javadoc) * @see org.springframework.plugin.core.Plugin#supports(java.lang.Object) diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/ResourceMappingUtils.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/ResourceMappingUtils.java index 2f55c271e..fea187694 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/ResourceMappingUtils.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/ResourceMappingUtils.java @@ -67,7 +67,7 @@ public abstract class ResourceMappingUtils { public static String formatRel(RepositoryRestConfiguration config, RepositoryInformation repoInfo, PersistentProperty persistentProperty) { - + if (persistentProperty == null) { return null; } @@ -81,9 +81,9 @@ public abstract class ResourceMappingUtils { } public static String findPath(Class type) { - + RestResource anno = findAnnotation(type, RestResource.class); - + if (anno != null) { if (hasTextExceptSlash(anno.path())) { return removeLeadingSlash(anno.path()); @@ -94,9 +94,9 @@ public abstract class ResourceMappingUtils { } public static String findPath(Method method) { - + RestResource anno = findAnnotation(method, RestResource.class); - + if (anno != null) { if (hasTextExceptSlash(anno.path())) { return removeLeadingSlash(anno.path()); diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/ResourceStringUtils.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/ResourceStringUtils.java index 827a5b9d6..a021f832d 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/ResourceStringUtils.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/ResourceStringUtils.java @@ -53,11 +53,11 @@ public class ResourceStringUtils { } boolean hasLeadingSlash = startsWithSlash(path); - + if (path.length() == 1) { return hasLeadingSlash ? "" : path; } - + return hasLeadingSlash ? path.substring(1) : path; } diff --git a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/SimpleRelProvider.java b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/SimpleRelProvider.java index 162d59964..a7ffae5c8 100644 --- a/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/SimpleRelProvider.java +++ b/spring-data-rest-repository/src/main/java/org/springframework/data/rest/repository/support/SimpleRelProvider.java @@ -19,7 +19,6 @@ import org.springframework.hateoas.RelProvider; import org.springframework.util.StringUtils; /** - * * @author Oliver Gierke */ public class SimpleRelProvider implements RelProvider { diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/config/ResourceMappingUnitTests.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/config/ResourceMappingUnitTests.java index ef0894744..339c68b93 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/config/ResourceMappingUnitTests.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/config/ResourceMappingUnitTests.java @@ -35,89 +35,84 @@ import org.springframework.data.rest.repository.support.SimpleRelProvider; /** * Ensure the {@link ResourceMapping} components convey the correct information. - * + * * @author Jon Brisbin */ @SuppressWarnings("deprecation") public class ResourceMappingUnitTests { - + ResourceMappingFactory factory = new ResourceMappingFactory(new SimpleRelProvider()); - @Test - public void shouldDetectDefaultRelAndPath() throws Exception { - - ResourceMapping newMapping = factory.getMappingForType(PlainPersonRepository.class); - - assertThat(newMapping.getRel(), is("person")); - assertThat(newMapping.getPath(), is("person")); - assertThat(newMapping.isExported(), is(true)); - } + @Test + public void shouldDetectDefaultRelAndPath() throws Exception { - @Test - public void shouldDetectAnnotatedRelAndPath() throws Exception { - - ResourceMapping newMapping = factory.getMappingForType(AnnotatedPersonRepository.class); - - assertThat(newMapping.getRel(), is("people")); - assertThat(newMapping.getPath(), is("person")); - assertThat(newMapping.isExported(), is(false)); - } - - @Test - public void shouldDetectPathAndRemoveLeadingSlashIfAny() { + ResourceMapping newMapping = factory.getMappingForType(PlainPersonRepository.class); + + assertThat(newMapping.getRel(), is("person")); + assertThat(newMapping.getPath(), is("person")); + assertThat(newMapping.isExported(), is(true)); + } + + @Test + public void shouldDetectAnnotatedRelAndPath() throws Exception { + + ResourceMapping newMapping = factory.getMappingForType(AnnotatedPersonRepository.class); + + assertThat(newMapping.getRel(), is("people")); + assertThat(newMapping.getPath(), is("person")); + assertThat(newMapping.isExported(), is(false)); + } + + @Test + public void shouldDetectPathAndRemoveLeadingSlashIfAny() { org.springframework.data.rest.config.ResourceMapping mapping = new org.springframework.data.rest.config.ResourceMapping( - findRel(AnnotatedWithLeadingSlashPersonRepository.class), - findPath(AnnotatedWithLeadingSlashPersonRepository.class), - findExported(AnnotatedWithLeadingSlashPersonRepository.class) - ); + findRel(AnnotatedWithLeadingSlashPersonRepository.class), + findPath(AnnotatedWithLeadingSlashPersonRepository.class), + findExported(AnnotatedWithLeadingSlashPersonRepository.class)); - // The rel attribute defaults to class name - assertThat(mapping.getRel(), is("annotatedWithLeadingSlashPerson")); - assertThat(mapping.getPath(), is("people")); - // The exported defaults to true - assertThat(mapping.isExported(), is(true)); - } + // The rel attribute defaults to class name + assertThat(mapping.getRel(), is("annotatedWithLeadingSlashPerson")); + assertThat(mapping.getPath(), is("people")); + // The exported defaults to true + assertThat(mapping.isExported(), is(true)); + } - @Test - public void shouldDetectPathAndRemoveLeadingSlashIfAnyOnMethod() throws Exception { - Method method = AnnotatedWithLeadingSlashPersonRepository.class.getMethod("findByFirstName", String.class, Pageable.class); - org.springframework.data.rest.config.ResourceMapping mapping = new org.springframework.data.rest.config.ResourceMapping( - findRel(method), - findPath(method), - findExported(method) - ); + @Test + public void shouldDetectPathAndRemoveLeadingSlashIfAnyOnMethod() throws Exception { + Method method = AnnotatedWithLeadingSlashPersonRepository.class.getMethod("findByFirstName", String.class, + Pageable.class); + org.springframework.data.rest.config.ResourceMapping mapping = new org.springframework.data.rest.config.ResourceMapping( + findRel(method), findPath(method), findExported(method)); - // The rel attribute defaults to class name - assertThat(mapping.getRel(), is("findByFirstName")); - assertThat(mapping.getPath(), is("firstname")); - // The exported defaults to true - assertThat(mapping.isExported(), is(true)); - } + // The rel attribute defaults to class name + assertThat(mapping.getRel(), is("findByFirstName")); + assertThat(mapping.getPath(), is("firstname")); + // The exported defaults to true + assertThat(mapping.isExported(), is(true)); + } - @Test - public void shouldReturnDefaultIfPathContainsOnlySlashTextOnMethod() throws Exception { - Method method = AnnotatedWithLeadingSlashPersonRepository.class.getMethod("findByLastName", String.class, Pageable.class); - org.springframework.data.rest.config.ResourceMapping mapping = new org.springframework.data.rest.config.ResourceMapping( - findRel(method), - findPath(method), - findExported(method) - ); + @Test + public void shouldReturnDefaultIfPathContainsOnlySlashTextOnMethod() throws Exception { + Method method = AnnotatedWithLeadingSlashPersonRepository.class.getMethod("findByLastName", String.class, + Pageable.class); + org.springframework.data.rest.config.ResourceMapping mapping = new org.springframework.data.rest.config.ResourceMapping( + findRel(method), findPath(method), findExported(method)); - // The rel defaults to method name - assertThat(mapping.getRel(), is("findByLastName")); - // The path contains only a leading slash therefore defaults to method name - assertThat(mapping.getPath(), is("findByLastName")); - // The exported defaults to true - assertThat(mapping.isExported(), is(true)); - } - - @RestResource(path = "/people") - interface AnnotatedWithLeadingSlashPersonRepository { + // The rel defaults to method name + assertThat(mapping.getRel(), is("findByLastName")); + // The path contains only a leading slash therefore defaults to method name + assertThat(mapping.getPath(), is("findByLastName")); + // The exported defaults to true + assertThat(mapping.isExported(), is(true)); + } - @RestResource(path = "/firstname") - Page findByFirstName(@Param("firstName") String firstName, Pageable pageable); + @RestResource(path = "/people") + interface AnnotatedWithLeadingSlashPersonRepository { - @RestResource(path = " / ") - Page findByLastName(@Param("lastName") String firstName, Pageable pageable); - } + @RestResource(path = "/firstname") + Page findByFirstName(@Param("firstName") String firstName, Pageable pageable); + + @RestResource(path = " / ") + Page findByLastName(@Param("lastName") String firstName, Pageable pageable); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/RepositoryRestConfigurationIntegrationTests.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/RepositoryRestConfigurationIntegrationTests.java index 9f333deb7..4bca09de7 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/RepositoryRestConfigurationIntegrationTests.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/RepositoryRestConfigurationIntegrationTests.java @@ -14,7 +14,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Tests to check that {@link ResourceMapping}s are handled correctly. - * + * * @author Jon Brisbin */ @RunWith(SpringJUnit4ClassRunner.class) @@ -22,17 +22,16 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @SuppressWarnings("deprecation") public class RepositoryRestConfigurationIntegrationTests { - @Autowired - RepositoryRestConfiguration config; + @Autowired RepositoryRestConfiguration config; - @Test - public void shouldProvideResourceMappingForConfiguredRepository() throws Exception { + @Test + public void shouldProvideResourceMappingForConfiguredRepository() throws Exception { ResourceMapping mapping = config.getResourceMappingForRepository(ConfiguredPersonRepository.class); - assertThat(mapping, notNullValue()); - assertThat(mapping.getRel(), is("people")); - assertThat(mapping.getPath(), is("people")); - assertThat(mapping.isExported(), is(false)); - } + assertThat(mapping, notNullValue()); + assertThat(mapping.getRel(), is("people")); + assertThat(mapping.getPath(), is("people")); + assertThat(mapping.isExported(), is(false)); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/RepositoryTestsConfig.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/RepositoryTestsConfig.java index abb8da9f4..613710462 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/RepositoryTestsConfig.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/RepositoryTestsConfig.java @@ -18,47 +18,44 @@ import org.springframework.format.support.DefaultFormattingConversionService; * @author Jon Brisbin */ @Configuration -@Import({JpaRepositoryConfig.class}) +@Import({ JpaRepositoryConfig.class }) public class RepositoryTestsConfig { - @Autowired - private ApplicationContext appCtx; + @Autowired private ApplicationContext appCtx; - @Bean public Repositories repositories() { - return new Repositories(appCtx); - } + @Bean + public Repositories repositories() { + return new Repositories(appCtx); + } - @SuppressWarnings("deprecation") - @Bean public RepositoryRestConfiguration config() { - RepositoryRestConfiguration config = new RepositoryRestConfiguration(); + @SuppressWarnings("deprecation") + @Bean + public RepositoryRestConfiguration config() { + RepositoryRestConfiguration config = new RepositoryRestConfiguration(); - config.setResourceMappingForDomainType(Person.class) - .setRel("person"); + config.setResourceMappingForDomainType(Person.class).setRel("person"); - config.setResourceMappingForRepository(ConfiguredPersonRepository.class) - .setRel("people") - .setPath("people") - .setExported(false); + config.setResourceMappingForRepository(ConfiguredPersonRepository.class).setRel("people").setPath("people") + .setExported(false); - config.setResourceMappingForRepository(PersonRepository.class) - .setRel("people") - .setPath("people") - .addResourceMappingFor("findByFirstName") - .setRel("firstname") - .setPath("firstname"); + config.setResourceMappingForRepository(PersonRepository.class).setRel("people").setPath("people") + .addResourceMappingFor("findByFirstName").setRel("firstname").setPath("firstname"); - return config; - } + return config; + } - @Bean public DefaultFormattingConversionService defaultConversionService() { - return new DefaultFormattingConversionService(); - } + @Bean + public DefaultFormattingConversionService defaultConversionService() { + return new DefaultFormattingConversionService(); + } - @Bean public DomainClassConverter domainClassConverter() { - return new DomainClassConverter(defaultConversionService()); - } + @Bean + public DomainClassConverter domainClassConverter() { + return new DomainClassConverter(defaultConversionService()); + } - @Bean public UriDomainClassConverter uriDomainClassConverter() { - return new UriDomainClassConverter(); - } + @Bean + public UriDomainClassConverter uriDomainClassConverter() { + return new UriDomainClassConverter(); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/RepositoryEventIntegrationTests.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/RepositoryEventIntegrationTests.java index bba736f13..520ddcbb0 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/RepositoryEventIntegrationTests.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/RepositoryEventIntegrationTests.java @@ -12,17 +12,15 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Tests around the {@link org.springframework.context.ApplicationEvent} handling abstractions. - * + * * @author Jon Brisbin */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RepositoryEventTestsConfig.class) public class RepositoryEventIntegrationTests { - @Autowired - ApplicationContext appCtx; - @Autowired - PersonRepository people; + @Autowired ApplicationContext appCtx; + @Autowired PersonRepository people; Person person; @Before diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/RepositoryEventTestsConfig.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/RepositoryEventTestsConfig.java index 798d90777..61d8e4ba9 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/RepositoryEventTestsConfig.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/RepositoryEventTestsConfig.java @@ -11,19 +11,22 @@ import org.springframework.data.rest.repository.domain.jpa.PersonBeforeSaveHandl * @author Jon Brisbin */ @Configuration -@Import({RepositoryTestsConfig.class}) +@Import({ RepositoryTestsConfig.class }) public class RepositoryEventTestsConfig { - @Bean public PersonBeforeSaveHandler personBeforeSaveHandler() { - return new PersonBeforeSaveHandler(); - } + @Bean + public PersonBeforeSaveHandler personBeforeSaveHandler() { + return new PersonBeforeSaveHandler(); + } - @Bean public AnnotatedPersonEventHandler beforeSaveHandler() { - return new AnnotatedPersonEventHandler(); - } + @Bean + public AnnotatedPersonEventHandler beforeSaveHandler() { + return new AnnotatedPersonEventHandler(); + } - @Bean public AnnotatedHandlerBeanPostProcessor annotatedHandlerBeanPostProcessor() { - return new AnnotatedHandlerBeanPostProcessor(); - } + @Bean + public AnnotatedHandlerBeanPostProcessor annotatedHandlerBeanPostProcessor() { + return new AnnotatedHandlerBeanPostProcessor(); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/ValidatorIntegrationTests.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/ValidatorIntegrationTests.java index 02241f192..8c0b501f2 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/ValidatorIntegrationTests.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/ValidatorIntegrationTests.java @@ -11,19 +11,18 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Tests to check the {@link org.springframework.validation.Validator} integration. - * + * * @author Jon Brisbin */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = ValidatorTestsConfig.class) public class ValidatorIntegrationTests { - @Autowired - ApplicationContext appCtx; + @Autowired ApplicationContext appCtx; - @Test(expected = RepositoryConstraintViolationException.class) - public void shouldValidateLastName() throws Exception { - appCtx.publishEvent(new BeforeSaveEvent(new Person())); - } + @Test(expected = RepositoryConstraintViolationException.class) + public void shouldValidateLastName() throws Exception { + appCtx.publishEvent(new BeforeSaveEvent(new Person())); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/ValidatorTestsConfig.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/ValidatorTestsConfig.java index b4cb7595d..4a6080c87 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/ValidatorTestsConfig.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/context/ValidatorTestsConfig.java @@ -9,11 +9,12 @@ import org.springframework.data.rest.repository.RepositoryTestsConfig; * @author Jon Brisbin */ @Configuration -@Import({RepositoryTestsConfig.class}) +@Import({ RepositoryTestsConfig.class }) public class ValidatorTestsConfig { - @Bean public ValidatingRepositoryEventListener validatingListener() { - return new ValidatingRepositoryEventListener(); - } + @Bean + public ValidatingRepositoryEventListener validatingListener() { + return new ValidatingRepositoryEventListener(); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/AnnotatedPersonRepository.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/AnnotatedPersonRepository.java index f7000630c..32f30d441 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/AnnotatedPersonRepository.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/AnnotatedPersonRepository.java @@ -6,10 +6,9 @@ import org.springframework.data.rest.repository.annotation.RestResource; /** * A repository to manage {@link org.springframework.data.rest.repository.domain.jpa.Person}s. - * + * * @author Jon Brisbin */ @RestResource(rel = "people", exported = false) @NoRepositoryBean -public interface AnnotatedPersonRepository extends CrudRepository { -} +public interface AnnotatedPersonRepository extends CrudRepository {} diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/ConfiguredPersonRepository.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/ConfiguredPersonRepository.java index 19d6b8b5d..d4566fa99 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/ConfiguredPersonRepository.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/ConfiguredPersonRepository.java @@ -5,9 +5,8 @@ import org.springframework.data.repository.NoRepositoryBean; /** * A repository to manage {@link Person}s. - * + * * @author Jon Brisbin */ @NoRepositoryBean -public interface ConfiguredPersonRepository extends CrudRepository { -} +public interface ConfiguredPersonRepository extends CrudRepository {} diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/JpaRepositoryConfig.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/JpaRepositoryConfig.java index 22513ef2b..607742005 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/JpaRepositoryConfig.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/JpaRepositoryConfig.java @@ -45,39 +45,44 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement public class JpaRepositoryConfig { - @Bean public MessageSource messageSource() { - ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); - ms.setBasename("org.springframework.data.rest.repository.ValidationErrors"); - return ms; - } + @Bean + public MessageSource messageSource() { + ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); + ms.setBasename("org.springframework.data.rest.repository.ValidationErrors"); + return ms; + } - @Bean public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - return builder.setType(EmbeddedDatabaseType.HSQL).build(); - } + @Bean + public DataSource dataSource() { + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); + return builder.setType(EmbeddedDatabaseType.HSQL).build(); + } - @Bean public EntityManagerFactory entityManagerFactory() { - HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - vendorAdapter.setDatabase(Database.HSQL); - vendorAdapter.setGenerateDdl(true); + @Bean + public EntityManagerFactory entityManagerFactory() { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + vendorAdapter.setDatabase(Database.HSQL); + vendorAdapter.setGenerateDdl(true); - LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); - factory.setJpaVendorAdapter(vendorAdapter); - factory.setPackagesToScan(getClass().getPackage().getName()); - factory.setDataSource(dataSource()); + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(vendorAdapter); + factory.setPackagesToScan(getClass().getPackage().getName()); + factory.setDataSource(dataSource()); - factory.afterPropertiesSet(); + factory.afterPropertiesSet(); - return factory.getObject(); - } + return factory.getObject(); + } - @Bean public JpaDialect jpaDialect() { - return new HibernateJpaDialect(); - } + @Bean + public JpaDialect jpaDialect() { + return new HibernateJpaDialect(); + } - @Bean public PlatformTransactionManager transactionManager() { - JpaTransactionManager txManager = new JpaTransactionManager(); - txManager.setEntityManagerFactory(entityManagerFactory()); - return txManager; - } + @Bean + public PlatformTransactionManager transactionManager() { + JpaTransactionManager txManager = new JpaTransactionManager(); + txManager.setEntityManagerFactory(entityManagerFactory()); + return txManager; + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/Person.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/Person.java index 84c85d16f..4d2d0c80a 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/Person.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/Person.java @@ -13,70 +13,68 @@ import javax.persistence.PrePersist; /** * An entity that represents a person. - * + * * @author Jon Brisbin */ @Entity public class Person { - @Id @GeneratedValue private Long id; - private String firstName; - private String lastName; - @OneToMany - private List siblings = Collections.emptyList(); - private Date created; + @Id @GeneratedValue private Long id; + private String firstName; + private String lastName; + @OneToMany private List siblings = Collections.emptyList(); + private Date created; - public Person() { - } + public Person() {} - public Person(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } + public Person(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public Person addSibling(Person p) { - if(siblings == Collections.EMPTY_LIST) { - siblings = new ArrayList(); - } - siblings.add(p); - return this; - } + public Person addSibling(Person p) { + if (siblings == Collections.EMPTY_LIST) { + siblings = new ArrayList(); + } + siblings.add(p); + return this; + } - public List getSiblings() { - return siblings; - } + public List getSiblings() { + return siblings; + } - public void setSiblings(List siblings) { - this.siblings = siblings; - } + public void setSiblings(List siblings) { + this.siblings = siblings; + } - public Date getCreated() { - return created; - } + public Date getCreated() { + return created; + } - @PrePersist - private void prePersist() { - this.created = Calendar.getInstance().getTime(); - } + @PrePersist + private void prePersist() { + this.created = Calendar.getInstance().getTime(); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonBeforeSaveHandler.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonBeforeSaveHandler.java index 529423ab6..16c0ffe50 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonBeforeSaveHandler.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonBeforeSaveHandler.java @@ -6,7 +6,8 @@ import org.springframework.data.rest.repository.context.AbstractRepositoryEventL * @author Jon Brisbin */ public class PersonBeforeSaveHandler extends AbstractRepositoryEventListener { - @Override protected void onBeforeSave(Person person) { - throw new RuntimeException(); - } + @Override + protected void onBeforeSave(Person person) { + throw new RuntimeException(); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonLoader.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonLoader.java index b34b6903b..9c2eb3691 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonLoader.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonLoader.java @@ -10,10 +10,10 @@ import org.springframework.stereotype.Component; @Component public class PersonLoader implements InitializingBean { - @Autowired - PersonRepository people; + @Autowired PersonRepository people; - @Override public void afterPropertiesSet() throws Exception { - people.save(new Person("John", "Doe")); - } + @Override + public void afterPropertiesSet() throws Exception { + people.save(new Person("John", "Doe")); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonNameValidator.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonNameValidator.java index fa3deeb58..61729a072 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonNameValidator.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonNameValidator.java @@ -10,22 +10,24 @@ import org.springframework.validation.Validator; /** * A test {@link Validator} that checks for non-blank names. - * + * * @author Jon Brisbin */ @Component @HandleBeforeSave public class PersonNameValidator implements Validator { - @Override public boolean supports(Class clazz) { - return isAssignable(clazz, Person.class); - } + @Override + public boolean supports(Class clazz) { + return isAssignable(clazz, Person.class); + } - @Override public void validate(Object target, Errors errors) { - Person p = (Person)target; - if(!hasText(p.getLastName())) { - errors.rejectValue("lastName", "blank", "Last name cannot be blank"); - } - } + @Override + public void validate(Object target, Errors errors) { + Person p = (Person) target; + if (!hasText(p.getLastName())) { + errors.rejectValue("lastName", "blank", "Last name cannot be blank"); + } + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonRepository.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonRepository.java index 7733c07b1..68d9cfeea 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonRepository.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PersonRepository.java @@ -13,22 +13,19 @@ import org.springframework.data.rest.repository.annotation.RestResource; /** * A repository to manage {@link Person}s. - * + * * @author Jon Brisbin */ @RestResource(rel = "people", path = "people") public interface PersonRepository extends PagingAndSortingRepository { - @RestResource(rel = "firstname", path = "firstname") - public Page findByFirstName(@Param("firstName") String firstName, Pageable pageable); + @RestResource(rel = "firstname", path = "firstname") + public Page findByFirstName(@Param("firstName") String firstName, Pageable pageable); - public Page findByCreatedGreaterThan(@Param("date") Date date, Pageable pageable); + public Page findByCreatedGreaterThan(@Param("date") Date date, Pageable pageable); - @Query("select p from Person p where p.created > :date") - public Page findByCreatedUsingISO8601Date(@Param("date") - @ConvertWith( - ISO8601DateConverter.class) - Date date, - Pageable pageable); + @Query("select p from Person p where p.created > :date") + public Page findByCreatedUsingISO8601Date(@Param("date") @ConvertWith(ISO8601DateConverter.class) Date date, + Pageable pageable); } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PlainPersonRepository.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PlainPersonRepository.java index f9d49feda..168eecacd 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PlainPersonRepository.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/jpa/PlainPersonRepository.java @@ -5,9 +5,8 @@ import org.springframework.data.repository.NoRepositoryBean; /** * A repository to manage {@link Person}s. - * + * * @author Jon Brisbin */ @NoRepositoryBean -public interface PlainPersonRepository extends CrudRepository { -} +public interface PlainPersonRepository extends CrudRepository {} diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/MongoDbRepositoryConfig.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/MongoDbRepositoryConfig.java index de49b7fdd..cb7ade123 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/MongoDbRepositoryConfig.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/MongoDbRepositoryConfig.java @@ -15,16 +15,18 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie * @author Jon Brisbin */ @Configuration -@ComponentScan(basePackageClasses = {MongoDbRepositoryConfig.class}) +@ComponentScan(basePackageClasses = { MongoDbRepositoryConfig.class }) @EnableMongoRepositories public class MongoDbRepositoryConfig { - @Bean public MongoDbFactory mongoDbFactory() throws UnknownHostException { - return new SimpleMongoDbFactory(new Mongo("localhost"), "spring-data-rest"); - } + @Bean + public MongoDbFactory mongoDbFactory() throws UnknownHostException { + return new SimpleMongoDbFactory(new Mongo("localhost"), "spring-data-rest"); + } - @Bean public MongoTemplate mongoTemplate() throws UnknownHostException { - return new MongoTemplate(mongoDbFactory()); - } + @Bean + public MongoTemplate mongoTemplate() throws UnknownHostException { + return new MongoTemplate(mongoDbFactory()); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/Profile.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/Profile.java index f07561666..f08fb49af 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/Profile.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/Profile.java @@ -9,39 +9,38 @@ import org.springframework.data.mongodb.core.mapping.Document; @Document public class Profile { - @Id private String id; - private String name; - private String type; + @Id private String id; + private String name; + private String type; - public Profile() { - } + public Profile() {} - public Profile(String id, String name, String type) { - this.id = id; - this.name = name; - this.type = type; - } + public Profile(String id, String name, String type) { + this.id = id; + this.name = name; + this.type = type; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Profile setName(String name) { - this.name = name; - return this; - } + public Profile setName(String name) { + this.name = name; + return this; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public Profile setType(String type) { - this.type = type; - return this; - } + public Profile setType(String type) { + this.type = type; + return this; + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/ProfileLoader.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/ProfileLoader.java index c1edbeb54..0ed111568 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/ProfileLoader.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/ProfileLoader.java @@ -10,11 +10,11 @@ import org.springframework.stereotype.Component; @Component public class ProfileLoader implements InitializingBean { - @Autowired - private ProfileRepository profiles; + @Autowired private ProfileRepository profiles; - @Override public void afterPropertiesSet() throws Exception { - profiles.save(new Profile("jdoe", "jdoe", "account")); - } + @Override + public void afterPropertiesSet() throws Exception { + profiles.save(new Profile("jdoe", "jdoe", "account")); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/ProfileRepository.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/ProfileRepository.java index 737bbf8e2..e4253d27e 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/ProfileRepository.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/domain/mongodb/ProfileRepository.java @@ -5,8 +5,7 @@ import org.springframework.data.repository.CrudRepository; /** * Repository for managing {@link Profile}s in MongoDB. - * + * * @author Jon Brisbin */ -public interface ProfileRepository extends CrudRepository { -} +public interface ProfileRepository extends CrudRepository {} diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/invoke/MethodParameterConversionServiceUnitTests.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/invoke/MethodParameterConversionServiceUnitTests.java index 88cf92e6a..cba3b18ad 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/invoke/MethodParameterConversionServiceUnitTests.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/invoke/MethodParameterConversionServiceUnitTests.java @@ -21,50 +21,48 @@ import org.springframework.format.support.DefaultFormattingConversionService; */ public class MethodParameterConversionServiceUnitTests { - static final SimpleDateFormat ISO8601_FMT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - static final String[] DATE_S = new String[]{"2010-01-01T12:00:00-0600"}; - static final Date DATE_D; + static final SimpleDateFormat ISO8601_FMT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + static final String[] DATE_S = new String[] { "2010-01-01T12:00:00-0600" }; + static final Date DATE_D; - static { - try { - DATE_D = ISO8601_FMT.parse(DATE_S[0]); - } catch(ParseException e) { - throw new IllegalStateException(e); - } - } + static { + try { + DATE_D = ISO8601_FMT.parse(DATE_S[0]); + } catch (ParseException e) { + throw new IllegalStateException(e); + } + } - MethodParameter findByCreatedGreaterThan; - MethodParameter findByCreatedUsingISO8601Date; + MethodParameter findByCreatedGreaterThan; + MethodParameter findByCreatedUsingISO8601Date; - @Before - public void setup() throws NoSuchMethodException { - findByCreatedGreaterThan = new MethodParameter(PersonRepository.class.getMethod("findByCreatedGreaterThan", - Date.class, - Pageable.class), 0); - findByCreatedUsingISO8601Date = new MethodParameter(PersonRepository.class.getMethod("findByCreatedUsingISO8601Date", - Date.class, - Pageable.class), 0); - } + @Before + public void setup() throws NoSuchMethodException { + findByCreatedGreaterThan = new MethodParameter(PersonRepository.class.getMethod("findByCreatedGreaterThan", + Date.class, Pageable.class), 0); + findByCreatedUsingISO8601Date = new MethodParameter(PersonRepository.class.getMethod( + "findByCreatedUsingISO8601Date", Date.class, Pageable.class), 0); + } - @SuppressWarnings({"deprecation"}) - @Test - public void shouldConvertDateParameterUsingDefaultConverter() throws Exception { - ConfigurableConversionService cs = new DefaultFormattingConversionService(); - MethodParameterConversionService conversionService = new MethodParameterConversionService(cs); + @SuppressWarnings({ "deprecation" }) + @Test + public void shouldConvertDateParameterUsingDefaultConverter() throws Exception { + ConfigurableConversionService cs = new DefaultFormattingConversionService(); + MethodParameterConversionService conversionService = new MethodParameterConversionService(cs); - String dateStr = "01/01/2010"; - assertThat(conversionService.canConvert(String.class, findByCreatedGreaterThan), is(true)); - assertThat((Date)conversionService.convert(dateStr, findByCreatedGreaterThan), is(new Date(dateStr))); - } + String dateStr = "01/01/2010"; + assertThat(conversionService.canConvert(String.class, findByCreatedGreaterThan), is(true)); + assertThat((Date) conversionService.convert(dateStr, findByCreatedGreaterThan), is(new Date(dateStr))); + } - @Test - public void shouldConvertDateParameterUsingSpecificConverter() throws Exception { - ConfigurableConversionService cs = new DefaultFormattingConversionService(); - cs.addConverter(ISO8601DateConverter.INSTANCE); - MethodParameterConversionService conversionService = new MethodParameterConversionService(cs); + @Test + public void shouldConvertDateParameterUsingSpecificConverter() throws Exception { + ConfigurableConversionService cs = new DefaultFormattingConversionService(); + cs.addConverter(ISO8601DateConverter.INSTANCE); + MethodParameterConversionService conversionService = new MethodParameterConversionService(cs); - assertThat(conversionService.canConvert(String.class, findByCreatedUsingISO8601Date), is(true)); - assertThat((Date)conversionService.convert(DATE_S, findByCreatedUsingISO8601Date), is(DATE_D)); - } + assertThat(conversionService.canConvert(String.class, findByCreatedUsingISO8601Date), is(true)); + assertThat((Date) conversionService.convert(DATE_S, findByCreatedUsingISO8601Date), is(DATE_D)); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/invoke/RepositoryMethodUnitTests.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/invoke/RepositoryMethodUnitTests.java index 9db7c9173..fd133573c 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/invoke/RepositoryMethodUnitTests.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/invoke/RepositoryMethodUnitTests.java @@ -17,57 +17,55 @@ import org.springframework.util.ReflectionUtils; /** * Tests to verify the integrity of the {@link RepositoryMethod} abstraction. - * + * * @author Jon Brisbin */ public class RepositoryMethodUnitTests { - Map methods = new HashMap(); - RepositoryMethod method; + Map methods = new HashMap(); + RepositoryMethod method; - @Before - public void setup() { - doWithMethods(PersonRepository.class, - new ReflectionUtils.MethodCallback() { - @Override public void doWith(Method method) throws IllegalArgumentException, - IllegalAccessException { - String name = method.getName(); - RepositoryMethod repoMethod = new RepositoryMethod(method); - methods.put(name, repoMethod); - } - }, - Methods.USER_METHODS); - method = methods.get("findByFirstName"); - } + @Before + public void setup() { + doWithMethods(PersonRepository.class, new ReflectionUtils.MethodCallback() { + @Override + public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + String name = method.getName(); + RepositoryMethod repoMethod = new RepositoryMethod(method); + methods.put(name, repoMethod); + } + }, Methods.USER_METHODS); + method = methods.get("findByFirstName"); + } - @Test - public void shouldFindSimpleQueryMethods() throws Exception { - assertThat(method, notNullValue()); - } + @Test + public void shouldFindSimpleQueryMethods() throws Exception { + assertThat(method, notNullValue()); + } - @Test - public void shouldFindPageableInformationOnMethod() throws Exception { - assertThat(method, notNullValue()); - assertThat(method.isPageable(), is(true)); - } + @Test + public void shouldFindPageableInformationOnMethod() throws Exception { + assertThat(method, notNullValue()); + assertThat(method.isPageable(), is(true)); + } - @Test - public void shouldNotFindSortInformationOnMethod() throws Exception { - assertThat(method, notNullValue()); - assertThat(method.isSortable(), is(false)); - } + @Test + public void shouldNotFindSortInformationOnMethod() throws Exception { + assertThat(method, notNullValue()); + assertThat(method.isSortable(), is(false)); + } - @Test - public void shouldProvideParameterClassTypes() throws Exception { - assertThat(method, notNullValue()); - assertThat(method.getParameters().get(0).getParameterType(), is(typeCompatibleWith(String.class))); - assertThat(method.getParameters().get(1).getParameterType(), is(typeCompatibleWith(Pageable.class))); - } + @Test + public void shouldProvideParameterClassTypes() throws Exception { + assertThat(method, notNullValue()); + assertThat(method.getParameters().get(0).getParameterType(), is(typeCompatibleWith(String.class))); + assertThat(method.getParameters().get(1).getParameterType(), is(typeCompatibleWith(Pageable.class))); + } - @Test - public void shouldProvideParameterNames() throws Exception { - assertThat(method, notNullValue()); - assertThat(method.getParameterNames(), contains("firstName", "arg1")); - } + @Test + public void shouldProvideParameterNames() throws Exception { + assertThat(method, notNullValue()); + assertThat(method.getParameterNames(), contains("firstName", "arg1")); + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/RepositoryAwareResourceMappingFactoryUnitTests.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/RepositoryAwareResourceMappingFactoryUnitTests.java index bb20dbb96..5c2c7a2eb 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/RepositoryAwareResourceMappingFactoryUnitTests.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/RepositoryAwareResourceMappingFactoryUnitTests.java @@ -23,38 +23,37 @@ import org.springframework.data.rest.repository.annotation.RestResource; import org.springframework.data.rest.repository.support.SimpleRelProvider; /** - * * @author Oliver Gierke */ public class RepositoryAwareResourceMappingFactoryUnitTests { ResourceMappingFactory factory = new ResourceMappingFactory(new SimpleRelProvider()); - + @Test public void foo() { - + CollectionResourceMapping mapping = factory.getMappingForType(Person.class); assertThat(mapping.getPath(), is("person")); assertThat(mapping.getRel(), is("person")); assertThat(mapping.getSingleResourceRel(), is("person.person")); } - + @Test public void honorsAnnotatedMapping() { - + CollectionResourceMapping mapping = factory.getMappingForType(AnnotatedPerson.class); assertThat(mapping.getPath(), is("bar")); assertThat(mapping.getRel(), is("foo")); assertThat(mapping.getSingleResourceRel(), is("foo.foo")); assertThat(mapping.isExported(), is(false)); } - + static class Person { - + } - + @RestResource(path = "bar", rel = "foo", exported = false) static class AnnotatedPerson { - + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/ResourceMappingFactoryUnitTests.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/ResourceMappingFactoryUnitTests.java index a6ec726d4..8552cafe9 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/ResourceMappingFactoryUnitTests.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/ResourceMappingFactoryUnitTests.java @@ -24,67 +24,66 @@ import org.springframework.data.rest.repository.annotation.RestResource; import org.springframework.data.rest.repository.support.SimpleRelProvider; /** - * * @author Oliver Gierke */ public class ResourceMappingFactoryUnitTests { ResourceMappingFactory factory = new ResourceMappingFactory(new SimpleRelProvider()); - + @Test public void foo() { - + CollectionResourceMapping mapping = factory.getMappingForType(Person.class); assertThat(mapping.getPath(), is("person")); assertThat(mapping.getRel(), is("person")); assertThat(mapping.getSingleResourceRel(), is("person.person")); } - + @Test public void honorsAnnotatedMapping() { - + CollectionResourceMapping mapping = factory.getMappingForType(AnnotatedPerson.class); assertThat(mapping.getPath(), is("bar")); assertThat(mapping.getRel(), is("foo")); assertThat(mapping.getSingleResourceRel(), is("foo.foo")); assertThat(mapping.isExported(), is(false)); } - + @Test public void honorsAnnotatedsMapping() { - + CollectionResourceMapping mapping = factory.getMappingForType(PersonRepository.class); assertThat(mapping.getPath(), is("bar")); assertThat(mapping.getRel(), is("foo")); assertThat(mapping.getSingleResourceRel(), is("foo.foo")); assertThat(mapping.isExported(), is(false)); } - + @Test public void repositoryAnnotationTrumpsDomainTypeMapping() { - + CollectionResourceMapping mapping = factory.getMappingForType(AnnotatedAnnotatedPersonRepository.class); assertThat(mapping.getPath(), is("trumpsAll")); assertThat(mapping.getRel(), is("foo")); assertThat(mapping.getSingleResourceRel(), is("foo.foo")); assertThat(mapping.isExported(), is(true)); } - + static class Person { - + } - + @RestResource(path = "bar", rel = "foo", exported = false) static class AnnotatedPerson { - + } - + interface PersonRepository extends Repository { - + } - + @RestResource(path = "trumpsAll") interface AnnotatedAnnotatedPersonRepository extends Repository { - + } } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/ResourceMappingsIntegrationTest.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/ResourceMappingsIntegrationTest.java index 2ac4a4e94..79334ed91 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/ResourceMappingsIntegrationTest.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/mapping/ResourceMappingsIntegrationTest.java @@ -46,14 +46,14 @@ public class ResourceMappingsIntegrationTest { @Before public void setUp() { - + Repositories repositories = new Repositories(factory); this.mappings = new ResourceMappings(new RepositoryRestConfiguration(), repositories); } @Test public void foo() { - + assertThat(mappings, is(Matchers. iterableWithSize(2))); assertThat(mappings.getMappingFor(Person.class).isExported(), is(true)); } diff --git a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/support/ResourceStringUtilsTest.java b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/support/ResourceStringUtilsTest.java index 814e9fc9c..80077a6e9 100644 --- a/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/support/ResourceStringUtilsTest.java +++ b/spring-data-rest-repository/src/test/java/org/springframework/data/rest/repository/support/ResourceStringUtilsTest.java @@ -39,7 +39,7 @@ public class ResourceStringUtilsTest { final boolean hasText; public ResourceStringUtilsTest(String testDescription, String actual, String expected, boolean hasText) { - + this.actual = actual; this.expected = expected; this.hasText = hasText; diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/AbstractRepositoryRestController.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/AbstractRepositoryRestController.java index d531c994c..54975e272 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/AbstractRepositoryRestController.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/AbstractRepositoryRestController.java @@ -58,7 +58,7 @@ import org.springframework.web.bind.annotation.ResponseBody; */ @SuppressWarnings({ "rawtypes", "deprecation" }) class AbstractRepositoryRestController implements MessageSourceAware, InitializingBean { - + private static final Logger LOG = LoggerFactory.getLogger(AbstractRepositoryRestController.class); private final PersistentEntityResourceAssembler perAssembler; @@ -69,8 +69,9 @@ class AbstractRepositoryRestController implements MessageSourceAware, Initializi private MessageSource messageSource; private PagedResourcesAssembler assembler; - public AbstractRepositoryRestController(PagedResourcesAssembler assembler, PersistentEntityResourceAssembler entityResourceAssembler) { - + public AbstractRepositoryRestController(PagedResourcesAssembler assembler, + PersistentEntityResourceAssembler entityResourceAssembler) { + this.assembler = assembler; this.perAssembler = entityResourceAssembler; } @@ -86,13 +87,13 @@ class AbstractRepositoryRestController implements MessageSourceAware, Initializi @Override public void afterPropertiesSet() throws Exception { - - // FIXME: - -// if (null != txMgr) { -// txTmpl = new TransactionTemplate(txMgr); -// txTmpl.afterPropertiesSet(); -// } + + // FIXME: + + // if (null != txMgr) { + // txTmpl = new TransactionTemplate(txMgr); + // txTmpl.afterPropertiesSet(); + // } } @ExceptionHandler({ NullPointerException.class }) @@ -139,7 +140,7 @@ class AbstractRepositoryRestController implements MessageSourceAware, Initializi @ResponseBody public ResponseEntity handleRepositoryConstraintViolationException(Locale locale, RepositoryConstraintViolationException rcve) { - + return response(null, new RepositoryConstraintViolationExceptionMessage(rcve, messageSource, locale), HttpStatus.BAD_REQUEST); } @@ -205,7 +206,7 @@ class AbstractRepositoryRestController implements MessageSourceAware, Initializi @SuppressWarnings({ "unchecked" }) protected Resources resultToResources(Object result, Link baseLink) { - + if (result instanceof Page) { Page page = (Page) result; return entitiesToResources(page, baseLink, assembler); @@ -225,7 +226,6 @@ class AbstractRepositoryRestController implements MessageSourceAware, Initializi return assembler.toResource(page, perAssembler, baseLink); } - protected Resources> entitiesToResources(Iterable entities) { List> resources = new ArrayList>(); diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/BaseUriMethodArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/BaseUriMethodArgumentResolver.java index c4a18d660..080101b58 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/BaseUriMethodArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/BaseUriMethodArgumentResolver.java @@ -33,30 +33,28 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; */ public class BaseUriMethodArgumentResolver implements HandlerMethodArgumentResolver { - private final RepositoryRestConfiguration config; + private final RepositoryRestConfiguration config; - public BaseUriMethodArgumentResolver(RepositoryRestConfiguration config) { - this.config = config; - } + public BaseUriMethodArgumentResolver(RepositoryRestConfiguration config) { + this.config = config; + } - @Override public boolean supportsParameter(MethodParameter parameter) { - return (null != parameter.getParameterAnnotation(BaseURI.class) - && parameter.getParameterType() == URI.class); - } + @Override + public boolean supportsParameter(MethodParameter parameter) { + return (null != parameter.getParameterAnnotation(BaseURI.class) && parameter.getParameterType() == URI.class); + } - @Override - public URI resolveArgument(MethodParameter parameter, - ModelAndViewContainer mavContainer, - NativeWebRequest webRequest, - WebDataBinderFactory binderFactory) throws Exception { - HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); + @Override + public URI resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { + HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); - // Use configured URI if there is one or set the current one as the default if not. - if(null == config.getBaseUri()) { - URI baseUri = ServletUriComponentsBuilder.fromServletMapping(servletRequest).build().toUri(); - config.setBaseUri(baseUri); - } + // Use configured URI if there is one or set the current one as the default if not. + if (null == config.getBaseUri()) { + URI baseUri = ServletUriComponentsBuilder.fromServletMapping(servletRequest).build().toUri(); + config.setBaseUri(baseUri); + } - return config.getBaseUri(); - } + return config.getBaseUri(); + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ControllerUtils.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ControllerUtils.java index fd6cd033f..23580ffa2 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ControllerUtils.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ControllerUtils.java @@ -25,11 +25,10 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; /** - * * @author Oliver Gierke */ public class ControllerUtils { - + public static final Resource EMPTY_RESOURCE = new Resource(Collections.emptyList()); public static final Resources> EMPTY_RESOURCES = new Resources>( Collections.> emptyList()); @@ -38,12 +37,12 @@ public class ControllerUtils { public static > ResponseEntity> toResponseEntity(HttpHeaders headers, R resource, HttpStatus status) { - + HttpHeaders hdrs = new HttpHeaders(); if (null != headers) { hdrs.putAll(headers); } - + return new ResponseEntity>(resource, hdrs, status); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssembler.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssembler.java index 993562425..a82c833ab 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssembler.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssembler.java @@ -25,14 +25,13 @@ import org.springframework.hateoas.ResourceAssembler; import org.springframework.util.Assert; /** - * * @author Oliver Gierke */ public class PersistentEntityResourceAssembler implements ResourceAssembler> { private final Repositories repositories; private final EntityLinks entityLinks; - + /** * Creates a new {@link PersistentEntityResourceAssembler}. * @@ -40,10 +39,10 @@ public class PersistentEntityResourceAssembler implements ResourceAssembler implements ResourceAssembler toResource(T instance) { PersistentEntity entity = repositories.getPersistentEntity(instance.getClass()); - + PersistentEntityResource resource = PersistentEntityResource.wrap(entity, instance); resource.add(getSelfLinkFor(instance)); return resource; } - + public Link getSelfLinkFor(Object instance) { - + PersistentEntity entity = repositories.getPersistentEntity(instance.getClass()); - + BeanWrapper wrapper = BeanWrapper.create(instance, null); Object id = wrapper.getProperty(entity.getIdProperty()); - + return entityLinks.linkForSingleResource(entity.getType(), id).withSelfRel(); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceHandlerMethodArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceHandlerMethodArgumentResolver.java index c43d6da8b..c053142f4 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceHandlerMethodArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceHandlerMethodArgumentResolver.java @@ -18,41 +18,38 @@ import org.springframework.web.method.support.ModelAndViewContainer; */ public class PersistentEntityResourceHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { - @Autowired - private RepositoryRestRequestHandlerMethodArgumentResolver repoRequestResolver; - private final List> messageConverters; + @Autowired private RepositoryRestRequestHandlerMethodArgumentResolver repoRequestResolver; + private final List> messageConverters; - public PersistentEntityResourceHandlerMethodArgumentResolver(List> messageConverters) { - this.messageConverters = messageConverters; - } + public PersistentEntityResourceHandlerMethodArgumentResolver(List> messageConverters) { + this.messageConverters = messageConverters; + } - @Override public boolean supportsParameter(MethodParameter parameter) { - return PersistentEntityResource.class.isAssignableFrom(parameter.getParameterType()); - } + @Override + public boolean supportsParameter(MethodParameter parameter) { + return PersistentEntityResource.class.isAssignableFrom(parameter.getParameterType()); + } - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - public Object resolveArgument(MethodParameter parameter, - ModelAndViewContainer mavContainer, - NativeWebRequest webRequest, - WebDataBinderFactory binderFactory) throws Exception { - RepositoryRestRequest repoRequest = (RepositoryRestRequest)repoRequestResolver.resolveArgument(parameter, - mavContainer, - webRequest, - binderFactory); + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { + RepositoryRestRequest repoRequest = (RepositoryRestRequest) repoRequestResolver.resolveArgument(parameter, + mavContainer, webRequest, binderFactory); - final ServletServerHttpRequest request = new ServletServerHttpRequest(webRequest.getNativeRequest(HttpServletRequest.class)); - for(HttpMessageConverter converter : messageConverters) { - Class domainType = repoRequest.getPersistentEntity().getType(); - if(!converter.canRead(domainType, request.getHeaders().getContentType())) { - continue; - } + final ServletServerHttpRequest request = new ServletServerHttpRequest( + webRequest.getNativeRequest(HttpServletRequest.class)); + for (HttpMessageConverter converter : messageConverters) { + Class domainType = repoRequest.getPersistentEntity().getType(); + if (!converter.canRead(domainType, request.getHeaders().getContentType())) { + continue; + } - Object obj = converter.read(domainType, request); + Object obj = converter.read(domainType, request); return new PersistentEntityResource(repoRequest.getPersistentEntity(), obj); - } + } - return null; - } + return null; + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryController.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryController.java index d03584d16..a7737cebb 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryController.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryController.java @@ -42,7 +42,7 @@ public class RepositoryController extends AbstractRepositoryRestController { @Autowired public RepositoryController(Repositories repositories, RepositoryRestConfiguration config, EntityLinks entityLinks, PagedResourcesAssembler assembler, PersistentEntityResourceAssembler perAssembler) { - + super(assembler, perAssembler); this.repositories = repositories; diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryEntityController.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryEntityController.java index 009ed92ec..44ec00290 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryEntityController.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryEntityController.java @@ -71,8 +71,7 @@ import org.springframework.web.bind.annotation.ResponseBody; */ @RestController @SuppressWarnings("deprecation") -class RepositoryEntityController extends AbstractRepositoryRestController implements - ApplicationEventPublisherAware { +class RepositoryEntityController extends AbstractRepositoryRestController implements ApplicationEventPublisherAware { private static final String BASE_MAPPING = "/{repository}"; @@ -81,7 +80,7 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem private final RepositoryRestConfiguration config; private final DomainClassConverter converter; private final ConversionService conversionService; - + private final TransactionOperations txOperations; private ApplicationEventPublisher publisher; @@ -91,7 +90,7 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem @Autowired public RepositoryEntityController(Repositories repositories, RepositoryRestConfiguration config, EntityLinks entityLinks, PagedResourcesAssembler assembler, - PersistentEntityResourceAssembler perAssembler, DomainClassConverter converter, + PersistentEntityResourceAssembler perAssembler, DomainClassConverter converter, @Qualifier("defaultConversionService") ConversionService conversionService) { super(assembler, perAssembler); @@ -101,7 +100,7 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem this.config = config; this.converter = converter; this.conversionService = conversionService; - + this.txOperations = null; } @@ -203,7 +202,7 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem } /** - * {@code GET /{repository}/{id}} + * {@code GET / repository}/{id}} * * @param repoRequest * @param id @@ -231,7 +230,7 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem } /** - * {@code PUT /{repository}/{id}} - Updates an existing entity or creates one at exactly that place. + * {@code PUT / repository}/{id}} - Updates an existing entity or creates one at exactly that place. * * @param repoRequest * @param incoming @@ -244,7 +243,7 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem @ResponseBody public ResponseEntity> updateEntity(RepositoryRestRequest repoRequest, PersistentEntityResource incoming, @PathVariable String id) throws ResourceNotFoundException { - + RepositoryMethodInvoker repoMethodInvoker = repoRequest.getRepositoryMethodInvoker(); if (null == repoMethodInvoker || !repoMethodInvoker.hasSaveOne() || !repoMethodInvoker.hasFindOne()) { throw new NoSuchMethodError(); @@ -308,15 +307,15 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem } } }; - + // FIXME - + if (txOperations != null) { txOperations.execute(callback); } else { callback.doInTransaction(null); } - + publisher.publishEvent(new AfterDeleteEvent(domainObj)); return new ResponseEntity(HttpStatus.NO_CONTENT); diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryInformationHandlerMethodArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryInformationHandlerMethodArgumentResolver.java index a2790c05e..3efbcb7fc 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryInformationHandlerMethodArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryInformationHandlerMethodArgumentResolver.java @@ -35,31 +35,29 @@ import org.springframework.web.util.UrlPathHelper; public class RepositoryInformationHandlerMethodArgumentResolver extends RepositoryInformationSupport implements HandlerMethodArgumentResolver { - @Override - public boolean supportsParameter(MethodParameter parameter) { - return isAssignable(parameter.getParameterType(), RepositoryInformation.class); - } + @Override + public boolean supportsParameter(MethodParameter parameter) { + return isAssignable(parameter.getParameterType(), RepositoryInformation.class); + } - @Override - public RepositoryInformation resolveArgument(MethodParameter parameter, - ModelAndViewContainer mavContainer, - NativeWebRequest webRequest, - WebDataBinderFactory binderFactory) throws Exception { - - HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); - String requestUri = new UrlPathHelper().getLookupPathForRequest(request); - - if(requestUri.startsWith("/")) { - requestUri = requestUri.substring(1); - } + @Override + public RepositoryInformation resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { - String[] parts = requestUri.split("/"); - - if(parts.length == 0) { - // Root request - return null; - } + HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); + String requestUri = new UrlPathHelper().getLookupPathForRequest(request); - return findRepositoryInfoFor(parts[0]); - } + if (requestUri.startsWith("/")) { + requestUri = requestUri.substring(1); + } + + String[] parts = requestUri.split("/"); + + if (parts.length == 0) { + // Root request + return null; + } + + return findRepositoryInfoFor(parts[0]); + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java index 47d3fa037..0eac5aaca 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java @@ -62,11 +62,12 @@ import org.springframework.web.bind.annotation.ResponseBody; * @author Oliver Gierke */ @RestController -@SuppressWarnings({"unchecked", "deprecation"}) -public class RepositoryPropertyReferenceController extends AbstractRepositoryRestController implements ApplicationEventPublisherAware { - +@SuppressWarnings({ "unchecked", "deprecation" }) +public class RepositoryPropertyReferenceController extends AbstractRepositoryRestController implements + ApplicationEventPublisherAware { + private static final String BASE_MAPPING = "/{repository}/{id}/{property}"; - + private final Repositories repositories; private final RepositoryRestConfiguration config; private final PersistentEntityResourceAssembler perAssembler; @@ -78,15 +79,15 @@ public class RepositoryPropertyReferenceController extends AbstractRepositoryRes public RepositoryPropertyReferenceController(Repositories repositories, RepositoryRestConfiguration config, DomainClassConverter domainClassConverter, PagedResourcesAssembler assembler, PersistentEntityResourceAssembler perAssembler) { - + super(assembler, perAssembler); - + this.repositories = repositories; this.perAssembler = perAssembler; this.config = config; this.converter = domainClassConverter; } - + /* * (non-Javadoc) * @see org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) @@ -96,84 +97,71 @@ public class RepositoryPropertyReferenceController extends AbstractRepositoryRes this.publisher = applicationEventPublisher; } - @RequestMapping( - value = BASE_MAPPING, - method = RequestMethod.GET, - produces = { - "application/json", - "application/x-spring-data-verbose+json" - } - ) + @RequestMapping(value = BASE_MAPPING, method = RequestMethod.GET, produces = { "application/json", + "application/x-spring-data-verbose+json" }) @ResponseBody public ResponseEntity> followPropertyReference(final RepositoryRestRequest repoRequest, - @PathVariable String id, - @PathVariable String property) - throws ResourceNotFoundException, NoSuchMethodException { + @PathVariable String id, @PathVariable String property) throws ResourceNotFoundException, NoSuchMethodException { final HttpHeaders headers = new HttpHeaders(); Function> handler = new Function>() { - @Override public Resource apply(ReferencedProperty prop) { - - if(null == prop.propertyValue) { + @Override + public Resource apply(ReferencedProperty prop) { + + if (null == prop.propertyValue) { throw new ResourceNotFoundException(); } - - if(prop.property.isCollectionLike()) { - + + if (prop.property.isCollectionLike()) { + List> resources = new ArrayList>(); - - for(Object obj : ((Iterable) prop.propertyValue)) { + + for (Object obj : ((Iterable) prop.propertyValue)) { resources.add(perAssembler.toResource(obj)); } return new Resource(resources); - - } else if(prop.property.isMap()) { - + + } else if (prop.property.isMap()) { + Map> resources = new HashMap>(); - - for(Map.Entry entry : ((Map) prop.propertyValue).entrySet()) { + + for (Map.Entry entry : ((Map) prop.propertyValue).entrySet()) { resources.put(entry.getKey(), perAssembler.toResource(entry.getValue())); } return new Resource(resources); - + } else { - + PersistentEntityResource resource = perAssembler.toResource(prop.propertyValue); headers.set("Content-Location", resource.getId().getHref()); return resource; } } }; - Resource responseResource = doWithReferencedProperty(repoRequest, - id, - property, - handler); + Resource responseResource = doWithReferencedProperty(repoRequest, id, property, handler); return ControllerUtils.toResponseEntity(headers, responseResource, HttpStatus.OK); } - @RequestMapping( - value = BASE_MAPPING, - method = RequestMethod.DELETE - ) + @RequestMapping(value = BASE_MAPPING, method = RequestMethod.DELETE) @ResponseBody public ResponseEntity> deletePropertyReference(final RepositoryRestRequest repoRequest, - @PathVariable String id, - @PathVariable String property) - throws ResourceNotFoundException, NoSuchMethodException, HttpRequestMethodNotSupportedException { + @PathVariable String id, @PathVariable String property) throws ResourceNotFoundException, NoSuchMethodException, + HttpRequestMethodNotSupportedException { final RepositoryMethodInvoker repoMethodInvoker = repoRequest.getRepositoryMethodInvoker(); - if(!repoMethodInvoker.hasDeleteOne()) { + if (!repoMethodInvoker.hasDeleteOne()) { throw new NoSuchMethodException(); } Function> handler = new Function>() { - @Override public Resource apply(ReferencedProperty prop) { - if(null == prop.propertyValue) { + @Override + public Resource apply(ReferencedProperty prop) { + if (null == prop.propertyValue) { return null; } - if(prop.property.isCollectionLike()) { + if (prop.property.isCollectionLike()) { throw new IllegalArgumentException(new HttpRequestMethodNotSupportedException("DELETE")); - } else if(prop.property.isMap()) { + } else if (prop.property.isMap()) { throw new IllegalArgumentException(new HttpRequestMethodNotSupportedException("DELETE")); } else { prop.wrapper.setProperty(prop.property, null); @@ -186,62 +174,50 @@ public class RepositoryPropertyReferenceController extends AbstractRepositoryRes } }; try { - doWithReferencedProperty(repoRequest, - id, - property, - handler); - } catch(IllegalArgumentException iae) { - if(iae.getCause() instanceof HttpRequestMethodNotSupportedException) { - throw (HttpRequestMethodNotSupportedException)iae.getCause(); + doWithReferencedProperty(repoRequest, id, property, handler); + } catch (IllegalArgumentException iae) { + if (iae.getCause() instanceof HttpRequestMethodNotSupportedException) { + throw (HttpRequestMethodNotSupportedException) iae.getCause(); } } return ControllerUtils.toResponseEntity(null, EMPTY_RESOURCE, HttpStatus.NO_CONTENT); } - @RequestMapping( - value = BASE_MAPPING + "/{propertyId}", - method = RequestMethod.GET, - produces = { - "application/json", - "application/x-spring-data-verbose+json", - "application/x-spring-data-compact+json", - "text/uri-list" - } - ) + @RequestMapping(value = BASE_MAPPING + "/{propertyId}", method = RequestMethod.GET, produces = { "application/json", + "application/x-spring-data-verbose+json", "application/x-spring-data-compact+json", "text/uri-list" }) @ResponseBody public ResponseEntity> followPropertyReference(final RepositoryRestRequest repoRequest, - @PathVariable String id, - @PathVariable String property, - final @PathVariable String propertyId) + @PathVariable String id, @PathVariable String property, final @PathVariable String propertyId) throws ResourceNotFoundException, NoSuchMethodException { final HttpHeaders headers = new HttpHeaders(); Function> handler = new Function>() { - @Override public Resource apply(ReferencedProperty prop) { - if(null == prop.propertyValue) { + @Override + public Resource apply(ReferencedProperty prop) { + if (null == prop.propertyValue) { throw new ResourceNotFoundException(); } - if(prop.property.isCollectionLike()) { - for(Object obj : ((Iterable)prop.propertyValue)) { - + if (prop.property.isCollectionLike()) { + for (Object obj : ((Iterable) prop.propertyValue)) { + BeanWrapper propValWrapper = BeanWrapper.create(obj, null); String sId = propValWrapper.getProperty(prop.entity.getIdProperty()).toString(); - - if(propertyId.equals(sId)) { - + + if (propertyId.equals(sId)) { + PersistentEntityResource resource = perAssembler.toResource(obj); headers.set("Content-Location", resource.getId().getHref()); return resource; } } - } else if(prop.property.isMap()) { - for(Map.Entry entry : ((Map)prop.propertyValue).entrySet()) { - + } else if (prop.property.isMap()) { + for (Map.Entry entry : ((Map) prop.propertyValue).entrySet()) { + BeanWrapper propValWrapper = BeanWrapper.create(entry.getValue(), null); String sId = propValWrapper.getProperty(prop.entity.getIdProperty()).toString(); - - if(propertyId.equals(sId)) { - + + if (propertyId.equals(sId)) { + PersistentEntityResource resource = perAssembler.toResource(entry.getValue()); headers.set("Content-Location", resource.getId().getHref()); return resource; @@ -253,26 +229,18 @@ public class RepositoryPropertyReferenceController extends AbstractRepositoryRes throw new IllegalArgumentException(new ResourceNotFoundException()); } }; - + Resource responseResource = doWithReferencedProperty(repoRequest, id, property, handler); return ControllerUtils.toResponseEntity(headers, responseResource, HttpStatus.OK); } - @RequestMapping( - value = BASE_MAPPING, - method = RequestMethod.GET, - produces = { - "application/x-spring-data-compact+json", - "text/uri-list" - } - ) + @RequestMapping(value = BASE_MAPPING, method = RequestMethod.GET, produces = { + "application/x-spring-data-compact+json", "text/uri-list" }) @ResponseBody public ResponseEntity> followPropertyReferenceCompact(RepositoryRestRequest repoRequest, - @PathVariable String id, - @PathVariable String property) - throws ResourceNotFoundException, NoSuchMethodException { + @PathVariable String id, @PathVariable String property) throws ResourceNotFoundException, NoSuchMethodException { ResponseEntity> response = followPropertyReference(repoRequest, id, property); - if(response.getStatusCode() != HttpStatus.OK) { + if (response.getStatusCode() != HttpStatus.OK) { return response; } @@ -281,32 +249,25 @@ public class RepositoryPropertyReferenceController extends AbstractRepositoryRes String propName = entityMapping.getNameForPath(property); ResourceMapping propMapping = entityMapping.getResourceMappingFor(entityMapping.getNameForPath(property)); PersistentProperty persistentProp = repoRequest.getPersistentEntity().getPersistentProperty(propName); - Class propType = (persistentProp.isCollectionLike() || persistentProp.isMap() - ? persistentProp.getComponentType() - : persistentProp.getType()); + Class propType = (persistentProp.isCollectionLike() || persistentProp.isMap() ? persistentProp + .getComponentType() : persistentProp.getType()); ResourceMapping propRepoMapping = getResourceMapping(config, repositories.getRepositoryInformationFor(propType)); - String propRel = String.format("%s.%s.%s.%s", - repoMapping.getRel(), - entityMapping.getRel(), - (null != propMapping ? propMapping.getRel() : property), - propRepoMapping.getRel()); + String propRel = String.format("%s.%s.%s.%s", repoMapping.getRel(), entityMapping.getRel(), + (null != propMapping ? propMapping.getRel() : property), propRepoMapping.getRel()); Resource resource = response.getBody(); List links = new ArrayList(); - URI entityBaseUri = buildUri(repoRequest.getBaseUri(), - repoMapping.getPath(), - id, - property); + URI entityBaseUri = buildUri(repoRequest.getBaseUri(), repoMapping.getPath(), id, property); - if(resource.getContent() instanceof Iterable) { - for(Resource res : (Iterable>)resource.getContent()) { + if (resource.getContent() instanceof Iterable) { + for (Resource res : (Iterable>) resource.getContent()) { Link propLink = propertyReferenceLink(res, entityBaseUri, propRel); links.add(propLink); } - } else if(resource.getContent() instanceof Map) { - for(Map.Entry> entry : ((Map>)resource.getContent()).entrySet()) { + } else if (resource.getContent() instanceof Map) { + for (Map.Entry> entry : ((Map>) resource.getContent()).entrySet()) { Link l = new Link(entry.getValue().getLink("self").getHref(), entry.getKey().toString()); links.add(l); } @@ -317,56 +278,45 @@ public class RepositoryPropertyReferenceController extends AbstractRepositoryRes return ControllerUtils.toResponseEntity(null, new Resource(EMPTY_RESOURCE_LIST, links), HttpStatus.OK); } - @RequestMapping( - value = BASE_MAPPING, - method = { - RequestMethod.POST, - RequestMethod.PUT - }, - consumes = { - "application/json", - "application/x-spring-data-compact+json", - "text/uri-list" - } - ) + @RequestMapping(value = BASE_MAPPING, method = { RequestMethod.POST, RequestMethod.PUT }, consumes = { + "application/json", "application/x-spring-data-compact+json", "text/uri-list" }) @ResponseBody public ResponseEntity> createPropertyReference(final RepositoryRestRequest repoRequest, - final @RequestBody Resource incoming, - @PathVariable String id, - @PathVariable String property) + final @RequestBody Resource incoming, @PathVariable String id, @PathVariable String property) throws ResourceNotFoundException, NoSuchMethodException { final RepositoryMethodInvoker repoMethodInvoker = repoRequest.getRepositoryMethodInvoker(); - if(!repoMethodInvoker.hasSaveOne()) { + if (!repoMethodInvoker.hasSaveOne()) { throw new NoSuchMethodException(); } Function> handler = new Function>() { - @Override public Resource apply(ReferencedProperty prop) { - if(prop.property.isCollectionLike()) { + @Override + public Resource apply(ReferencedProperty prop) { + if (prop.property.isCollectionLike()) { Collection coll = new ArrayList(); - if("POST".equals(repoRequest.getRequest().getMethod())) { - coll.addAll((Collection)prop.propertyValue); + if ("POST".equals(repoRequest.getRequest().getMethod())) { + coll.addAll((Collection) prop.propertyValue); } - for(Link l : incoming.getLinks()) { + for (Link l : incoming.getLinks()) { Object propVal = loadPropertyValue(prop.propertyType, l.getHref()); coll.add(propVal); } prop.wrapper.setProperty(prop.property, coll); - } else if(prop.property.isMap()) { + } else if (prop.property.isMap()) { Map m = new HashMap(); - if("POST".equals(repoRequest.getRequest().getMethod())) { - m.putAll((Map)prop.propertyValue); + if ("POST".equals(repoRequest.getRequest().getMethod())) { + m.putAll((Map) prop.propertyValue); } - for(Link l : incoming.getLinks()) { + for (Link l : incoming.getLinks()) { Object propVal = loadPropertyValue(prop.propertyType, l.getHref()); m.put(l.getRel(), propVal); } prop.wrapper.setProperty(prop.property, m); } else { - if("POST".equals(repoRequest.getRequest().getMethod())) { + if ("POST".equals(repoRequest.getRequest().getMethod())) { throw new IllegalStateException( "Cannot POST a reference to this singular property since the property type is not a List or a Map."); } - if(incoming.getLinks().size() != 1) { + if (incoming.getLinks().size() != 1) { throw new IllegalArgumentException( "Must send only 1 link to update a property reference that isn't a List or a Map."); } @@ -380,49 +330,42 @@ public class RepositoryPropertyReferenceController extends AbstractRepositoryRes return null; } }; - doWithReferencedProperty(repoRequest, - id, - property, - handler); + doWithReferencedProperty(repoRequest, id, property, handler); return ControllerUtils.toResponseEntity(null, EMPTY_RESOURCE, HttpStatus.CREATED); } - @RequestMapping( - value = BASE_MAPPING + "/{propertyId}", - method = RequestMethod.DELETE - ) + @RequestMapping(value = BASE_MAPPING + "/{propertyId}", method = RequestMethod.DELETE) @ResponseBody public ResponseEntity> deletePropertyReferenceId(final RepositoryRestRequest repoRequest, - @PathVariable String id, - @PathVariable String property, - final @PathVariable String propertyId) + @PathVariable String id, @PathVariable String property, final @PathVariable String propertyId) throws ResourceNotFoundException, NoSuchMethodException { final RepositoryMethodInvoker repoMethodInvoker = repoRequest.getRepositoryMethodInvoker(); - if(!repoMethodInvoker.hasDeleteOne()) { + if (!repoMethodInvoker.hasDeleteOne()) { throw new NoSuchMethodException(); } Function> handler = new Function>() { - @Override public Resource apply(ReferencedProperty prop) { - if(null == prop.propertyValue) { + @Override + public Resource apply(ReferencedProperty prop) { + if (null == prop.propertyValue) { return null; } - if(prop.property.isCollectionLike()) { + if (prop.property.isCollectionLike()) { Collection coll = new ArrayList(); - for(Object obj : (Collection) prop.propertyValue) { + for (Object obj : (Collection) prop.propertyValue) { BeanWrapper propValWrapper = BeanWrapper.create(obj, null); String s = propValWrapper.getProperty(prop.entity.getIdProperty()).toString(); - if(!propertyId.equals(s)) { + if (!propertyId.equals(s)) { coll.add(obj); } } prop.wrapper.setProperty(prop.property, coll); - } else if(prop.property.isMap()) { + } else if (prop.property.isMap()) { Map m = new HashMap(); - for(Map.Entry entry : ((Map)prop.propertyValue).entrySet()) { + for (Map.Entry entry : ((Map) prop.propertyValue).entrySet()) { BeanWrapper propValWrapper = BeanWrapper.create(entry.getValue(), null); String s = propValWrapper.getProperty(prop.entity.getIdProperty()).toString(); - if(!propertyId.equals(s)) { + if (!propertyId.equals(s)) { m.put(entry.getKey(), entry.getValue()); } } @@ -437,17 +380,12 @@ public class RepositoryPropertyReferenceController extends AbstractRepositoryRes return null; } }; - doWithReferencedProperty(repoRequest, - id, - property, - handler); + doWithReferencedProperty(repoRequest, id, property, handler); return ControllerUtils.toResponseEntity(null, EMPTY_RESOURCE, HttpStatus.NO_CONTENT); } - private Link propertyReferenceLink(Resource resource, - URI baseUri, - String rel) { + private Link propertyReferenceLink(Resource resource, URI baseUri, String rel) { Link selfLink = resource.getLink("self"); String objId = selfLink.getHref().substring(selfLink.getHref().lastIndexOf('/') + 1); return new Link(buildUri(baseUri, objId).toString(), rel); @@ -455,60 +393,51 @@ public class RepositoryPropertyReferenceController extends AbstractRepositoryRes private Object loadPropertyValue(Class type, String href) { String id = href.substring(href.lastIndexOf('/') + 1); - return converter.convert(id, - STRING_TYPE, - TypeDescriptor.valueOf(type)); + return converter.convert(id, STRING_TYPE, TypeDescriptor.valueOf(type)); } - private Resource doWithReferencedProperty(RepositoryRestRequest repoRequest, - String id, - String propertyPath, - Function> handler) - throws ResourceNotFoundException, NoSuchMethodException { + private Resource doWithReferencedProperty(RepositoryRestRequest repoRequest, String id, String propertyPath, + Function> handler) throws ResourceNotFoundException, NoSuchMethodException { RepositoryMethodInvoker repoMethodInvoker = repoRequest.getRepositoryMethodInvoker(); - if(!repoMethodInvoker.hasFindOne()) { + if (!repoMethodInvoker.hasFindOne()) { throw new NoSuchMethodException(); } Object domainObj = converter.convert(id, STRING_TYPE, TypeDescriptor.valueOf(repoRequest.getPersistentEntity().getType())); - - if(null == domainObj) { + + if (null == domainObj) { throw new ResourceNotFoundException(); } String propertyName = repoRequest.getPersistentEntityResourceMapping().getNameForPath(propertyPath); PersistentProperty prop = repoRequest.getPersistentEntity().getPersistentProperty(propertyName); - if(null == prop) { + if (null == prop) { throw new ResourceNotFoundException(); } BeanWrapper wrapper = BeanWrapper.create(domainObj, null); Object propVal = wrapper.getProperty(prop); - return handler.apply(new ReferencedProperty(prop, - propVal, - wrapper)); + return handler.apply(new ReferencedProperty(prop, propVal, wrapper)); } private class ReferencedProperty { - + final PersistentEntity entity; final PersistentProperty property; final Class propertyType; final Object propertyValue; - final BeanWrapperwrapper; + final BeanWrapper wrapper; + + private ReferencedProperty(PersistentProperty property, Object propertyValue, BeanWrapper wrapper) { - private ReferencedProperty(PersistentProperty property, - Object propertyValue, - BeanWrapper wrapper) { - this.property = property; this.propertyValue = propertyValue; this.wrapper = wrapper; - if(property.isCollectionLike()) { + if (property.isCollectionLike()) { this.propertyType = property.getComponentType(); - } else if(property.isMap()) { + } else if (property.isMap()) { this.propertyType = property.getMapValueType(); } else { this.propertyType = property.getType(); diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestDispatcherServlet.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestDispatcherServlet.java index e10472090..083d281e5 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestDispatcherServlet.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestDispatcherServlet.java @@ -7,12 +7,11 @@ import org.springframework.web.servlet.DispatcherServlet; /** * Special {@link DispatcherServlet} subclass that certain exporter components can recognize. - * + * * @author Jon Brisbin */ public class RepositoryRestDispatcherServlet extends DispatcherServlet { - private static final long serialVersionUID = 5761346441984290240L; public RepositoryRestDispatcherServlet() { diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerAdapter.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerAdapter.java index ce8be574d..ae17361ea 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerAdapter.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerAdapter.java @@ -10,32 +10,34 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl /** * {@link RequestMappingHandlerAdapter} implementation that adds a couple argument resolvers for controller method - * parameters used in the REST exporter controller. Also only looks for handler methods in the Spring Data REST - * provided controller classes to help isolate this handler adapter from other handler adapters the user might have - * configured in their Spring MVC context. - * + * parameters used in the REST exporter controller. Also only looks for handler methods in the Spring Data REST provided + * controller classes to help isolate this handler adapter from other handler adapters the user might have configured in + * their Spring MVC context. + * * @author Jon Brisbin */ public class RepositoryRestHandlerAdapter extends ResourceProcessorInvokingHandlerAdapter { - @Autowired - private List argumentResolvers; + @Autowired private List argumentResolvers; - @Override public void afterPropertiesSet() { + @Override + public void afterPropertiesSet() { setCustomArgumentResolvers(argumentResolvers); super.afterPropertiesSet(); } - @Override public int getOrder() { + @Override + public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } - @Override protected boolean supportsInternal(HandlerMethod handlerMethod) { + @Override + protected boolean supportsInternal(HandlerMethod handlerMethod) { Class controllerType = handlerMethod.getBeanType(); return (RepositoryController.class.isAssignableFrom(controllerType) || RepositoryEntityController.class.isAssignableFrom(controllerType) - || RepositoryPropertyReferenceController.class.isAssignableFrom(controllerType) - || RepositorySearchController.class.isAssignableFrom(controllerType)); + || RepositoryPropertyReferenceController.class.isAssignableFrom(controllerType) || RepositorySearchController.class + .isAssignableFrom(controllerType)); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMapping.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMapping.java index 51f9cba70..75f33a246 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMapping.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMapping.java @@ -21,22 +21,19 @@ import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; /** - * {@link RequestMappingHandlerMapping} implementation that will only find a handler method if a {@link - * org.springframework.data.repository.Repository} is exported under that URL path segment. Also ensures the {@link - * OpenEntityManagerInViewInterceptor} is registered in the application context. The OEMIVI is required for the REST - * exporter to function properly. - * + * {@link RequestMappingHandlerMapping} implementation that will only find a handler method if a + * {@link org.springframework.data.repository.Repository} is exported under that URL path segment. Also ensures the + * {@link OpenEntityManagerInViewInterceptor} is registered in the application context. The OEMIVI is required for the + * REST exporter to function properly. + * * @author Jon Brisbin */ public class RepositoryRestHandlerMapping extends RequestMappingHandlerMapping { - @Autowired - private Repositories repositories; - @Autowired - private RepositoryRestConfiguration config; - @Autowired(required = false) - private JpaHelper jpaHelper; - + @Autowired private Repositories repositories; + @Autowired private RepositoryRestConfiguration config; + @Autowired(required = false) private JpaHelper jpaHelper; + private final ResourceMappings mappings; public RepositoryRestHandlerMapping(ResourceMappings mappings) { @@ -45,26 +42,25 @@ public class RepositoryRestHandlerMapping extends RequestMappingHandlerMapping { } @Override - protected HandlerMethod lookupHandlerMethod(String lookupPath, - HttpServletRequest origRequest) throws Exception { + protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest origRequest) throws Exception { String acceptType = origRequest.getHeader("Accept"); - if(null == acceptType) { + if (null == acceptType) { acceptType = config.getDefaultMediaType().toString(); } List acceptHeaderTypes = MediaType.parseMediaTypes(acceptType); List acceptableTypes = new ArrayList(); - for(MediaType mt : acceptHeaderTypes) { - if(("*".equals(mt.getType()) && ("*".equals(mt.getSubtype())) - || ("application".equals(mt.getType()) && "*".equals(mt.getSubtype())))) { + for (MediaType mt : acceptHeaderTypes) { + if (("*".equals(mt.getType()) && ("*".equals(mt.getSubtype())) || ("application".equals(mt.getType()) && "*" + .equals(mt.getSubtype())))) { mt = config.getDefaultMediaType(); } - if(!acceptableTypes.contains(mt)) { + if (!acceptableTypes.contains(mt)) { acceptableTypes.add(mt); } } - if(acceptableTypes.size() > 1) { + if (acceptableTypes.size() > 1) { acceptType = collectionToDelimitedString(acceptableTypes, ","); - } else if(acceptableTypes.size() == 1) { + } else if (acceptableTypes.size() == 1) { acceptType = acceptableTypes.get(0).toString(); } else { acceptType = config.getDefaultMediaType().toString(); @@ -73,19 +69,19 @@ public class RepositoryRestHandlerMapping extends RequestMappingHandlerMapping { HttpServletRequest request = new DefaultAcceptTypeHttpServletRequest(origRequest, acceptType); String requestUri = lookupPath; - if(requestUri.startsWith("/")) { + if (requestUri.startsWith("/")) { requestUri = requestUri.substring(1); } - if(!hasText(requestUri)) { + if (!hasText(requestUri)) { return super.lookupHandlerMethod(lookupPath, request); } String[] parts = requestUri.split("/"); - if(parts.length == 0) { + if (parts.length == 0) { // Root request return super.lookupHandlerMethod(lookupPath, request); } - - for(Class domainType : repositories) { + + for (Class domainType : repositories) { if (mappings.exportsMappingFor(domainType)) { return super.lookupHandlerMethod(lookupPath, request); } @@ -94,13 +90,15 @@ public class RepositoryRestHandlerMapping extends RequestMappingHandlerMapping { return null; } - @Override protected boolean isHandler(Class beanType) { + @Override + protected boolean isHandler(Class beanType) { return AnnotationUtils.findAnnotation(beanType, RestController.class) != null; } - @Override protected void extendInterceptors(List interceptors) { - if(null != jpaHelper) { - for(Object o : jpaHelper.getInterceptors()) { + @Override + protected void extendInterceptors(List interceptors) { + if (null != jpaHelper) { + for (Object o : jpaHelper.getInterceptors()) { interceptors.add(o); } } @@ -109,14 +107,14 @@ public class RepositoryRestHandlerMapping extends RequestMappingHandlerMapping { private static class DefaultAcceptTypeHttpServletRequest extends HttpServletRequestWrapper { private final String defaultAcceptType; - private DefaultAcceptTypeHttpServletRequest(HttpServletRequest request, - String defaultAcceptType) { + private DefaultAcceptTypeHttpServletRequest(HttpServletRequest request, String defaultAcceptType) { super(request); this.defaultAcceptType = defaultAcceptType; } - @Override public String getHeader(String name) { - if("accept".equals(name.toLowerCase())) { + @Override + public String getHeader(String name) { + if ("accept".equals(name.toLowerCase())) { return defaultAcceptType; } else { return super.getHeader(name); diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestRequest.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestRequest.java index 63b7d3a24..af942ffc4 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestRequest.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestRequest.java @@ -37,25 +37,21 @@ import org.springframework.hateoas.Link; @SuppressWarnings("deprecation") class RepositoryRestRequest { - private final HttpServletRequest request; - private final URI baseUri; - private final ResourceMapping repoMapping; - private final Link repoLink; - private final Object repository; - private final RepositoryMethodInvoker repoMethodInvoker; - private final PersistentEntity persistentEntity; - private final ResourceMapping entityMapping; + private final HttpServletRequest request; + private final URI baseUri; + private final ResourceMapping repoMapping; + private final Link repoLink; + private final Object repository; + private final RepositoryMethodInvoker repoMethodInvoker; + private final PersistentEntity persistentEntity; + private final ResourceMapping entityMapping; - public RepositoryRestRequest(RepositoryRestConfiguration config, - Repositories repositories, - HttpServletRequest request, - URI baseUri, - RepositoryInformation repoInfo, - ConversionService conversionService) { + public RepositoryRestRequest(RepositoryRestConfiguration config, Repositories repositories, + HttpServletRequest request, URI baseUri, RepositoryInformation repoInfo, ConversionService conversionService) { this.request = request; this.baseUri = baseUri; this.repoMapping = getResourceMapping(config, repoInfo); - if(null == repoMapping || !repoMapping.isExported()) { + if (null == repoMapping || !repoMapping.isExported()) { this.repoLink = null; this.repository = null; this.repoMethodInvoker = null; diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestRequestHandlerMethodArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestRequestHandlerMethodArgumentResolver.java index f9896504f..ff6c9499b 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestRequestHandlerMethodArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestRequestHandlerMethodArgumentResolver.java @@ -34,37 +34,32 @@ import org.springframework.web.method.support.ModelAndViewContainer; * @author Oliver Gierke */ public class RepositoryRestRequestHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { - + private final ConversionService conversionService; - - @Autowired - private RepositoryRestConfiguration config; - @Autowired - private Repositories repositories; - @Autowired - private RepositoryInformationHandlerMethodArgumentResolver repoInfoResolver; - @Autowired - private BaseUriMethodArgumentResolver baseUriResolver; - - public RepositoryRestRequestHandlerMethodArgumentResolver(ConversionService conversionService) { + + @Autowired private RepositoryRestConfiguration config; + @Autowired private Repositories repositories; + @Autowired private RepositoryInformationHandlerMethodArgumentResolver repoInfoResolver; + @Autowired private BaseUriMethodArgumentResolver baseUriResolver; + + public RepositoryRestRequestHandlerMethodArgumentResolver(ConversionService conversionService) { this.conversionService = conversionService; - } + } - @Override - public boolean supportsParameter(MethodParameter parameter) { - return RepositoryRestRequest.class.isAssignableFrom(parameter.getParameterType()); - } + @Override + public boolean supportsParameter(MethodParameter parameter) { + return RepositoryRestRequest.class.isAssignableFrom(parameter.getParameterType()); + } + + @Override + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { - @Override - public Object resolveArgument(MethodParameter parameter, - ModelAndViewContainer mavContainer, - NativeWebRequest webRequest, - WebDataBinderFactory binderFactory) throws Exception { - URI baseUri = (URI) baseUriResolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory); RepositoryInformation repoInfo = repoInfoResolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory); - return new RepositoryRestRequest(config, repositories, webRequest.getNativeRequest(HttpServletRequest.class), baseUri, repoInfo, conversionService); - } + return new RepositoryRestRequest(config, repositories, webRequest.getNativeRequest(HttpServletRequest.class), + baseUri, repoInfo, conversionService); + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositorySearchController.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositorySearchController.java index 268fa0eb2..2f1684966 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositorySearchController.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositorySearchController.java @@ -57,41 +57,32 @@ import org.springframework.web.bind.annotation.ResponseBody; class RepositorySearchController extends AbstractRepositoryRestController { private static final String BASE_MAPPING = "/{repository}/search"; - + private final Repositories repositories; private final RepositoryRestConfiguration config; - + @Autowired - public RepositorySearchController(Repositories repositories, - RepositoryRestConfiguration config, - PagedResourcesAssembler assembler, - PersistentEntityResourceAssembler perAssembler) { - + public RepositorySearchController(Repositories repositories, RepositoryRestConfiguration config, + PagedResourcesAssembler assembler, PersistentEntityResourceAssembler perAssembler) { + super(assembler, perAssembler); this.repositories = repositories; this.config = config; } - @RequestMapping( - value = BASE_MAPPING, - method = RequestMethod.GET, - produces = { - "application/json", - "application/x-spring-data-compact+json" - } - ) + @RequestMapping(value = BASE_MAPPING, method = RequestMethod.GET, produces = { "application/json", + "application/x-spring-data-compact+json" }) @ResponseBody public Resource list(RepositoryRestRequest repoRequest) throws ResourceNotFoundException { List links = new ArrayList(); - links.addAll(queryMethodLinks(repoRequest.getBaseUri(), - repoRequest.getPersistentEntity().getType())); - if(links.isEmpty()) { + links.addAll(queryMethodLinks(repoRequest.getBaseUri(), repoRequest.getPersistentEntity().getType())); + if (links.isEmpty()) { throw new ResourceNotFoundException(); } return new Resource(Collections.emptyList(), links); } - + protected List queryMethodLinks(URI baseUri, Class domainType) { List links = new ArrayList(); RepositoryInformation repoInfo = repositories.getRepositoryInformationFor(domainType); @@ -110,81 +101,63 @@ class RepositorySearchController extends AbstractRepositoryRestController { return links; } - @RequestMapping( - value = BASE_MAPPING + "/{method}", - method = RequestMethod.GET, - produces = { - "application/json", - "application/x-spring-data-verbose+json" - } - ) + @RequestMapping(value = BASE_MAPPING + "/{method}", method = RequestMethod.GET, produces = { "application/json", + "application/x-spring-data-verbose+json" }) @ResponseBody - public ResourceSupport query(final RepositoryRestRequest repoRequest, - @PathVariable String repository, - @PathVariable String method, Pageable pageable) - throws ResourceNotFoundException { + public ResourceSupport query(final RepositoryRestRequest repoRequest, @PathVariable String repository, + @PathVariable String method, Pageable pageable) throws ResourceNotFoundException { RepositoryMethodInvoker repoMethodInvoker = repoRequest.getRepositoryMethodInvoker(); - if(repoMethodInvoker.getQueryMethods().isEmpty()) { + if (repoMethodInvoker.getQueryMethods().isEmpty()) { throw new ResourceNotFoundException(); } ResourceMapping repoMapping = repoRequest.getRepositoryResourceMapping(); String methodName = repoMapping.getNameForPath(method); RepositoryMethod repoMethod = repoMethodInvoker.getQueryMethods().get(methodName); - if(null == repoMethod) { - for(RepositoryMethod queryMethod : repoMethodInvoker.getQueryMethods().values()) { + if (null == repoMethod) { + for (RepositoryMethod queryMethod : repoMethodInvoker.getQueryMethods().values()) { String path = findPath(queryMethod.getMethod()); - if(path.equals(method)) { + if (path.equals(method)) { repoMethod = queryMethod; break; } } - if(null == repoMethod) { + if (null == repoMethod) { throw new ResourceNotFoundException(); } } - - + Map rawParameters = repoRequest.getRequest().getParameterMap(); Object result = repoMethodInvoker.invokeQueryMethod(repoMethod, pageable, rawParameters); - + Link baseLink = linkTo(methodOn(RepositorySearchController.class). // queryCompact(repoRequest, repository, methodName, pageable)).withSelfRel(); return resultToResources(result, baseLink); } - @RequestMapping( - value = BASE_MAPPING +"/{method}", - method = RequestMethod.GET, - produces = { - "application/x-spring-data-compact+json" - } - ) + @RequestMapping(value = BASE_MAPPING + "/{method}", method = RequestMethod.GET, + produces = { "application/x-spring-data-compact+json" }) @ResponseBody - public ResourceSupport queryCompact(RepositoryRestRequest repoRequest, - @PathVariable String repository, - @PathVariable String method, - Pageable pageable) - throws ResourceNotFoundException { + public ResourceSupport queryCompact(RepositoryRestRequest repoRequest, @PathVariable String repository, + @PathVariable String method, Pageable pageable) throws ResourceNotFoundException { List links = new ArrayList(); ResourceSupport resource = query(repoRequest, repository, method, pageable); links.addAll(resource.getLinks()); - if(resource instanceof Resources && ((Resources) resource).getContent() != null) { - for(Object obj : ((Resources) resource).getContent()) { - if(null != obj && obj instanceof Resource) { - Resource res = (Resource)obj; + if (resource instanceof Resources && ((Resources) resource).getContent() != null) { + for (Object obj : ((Resources) resource).getContent()) { + if (null != obj && obj instanceof Resource) { + Resource res = (Resource) obj; links.add(resourceLink(repoRequest, res)); } } - } else if(resource instanceof Resource) { + } else if (resource instanceof Resource) { Resource res = (Resource) resource; links.add(resourceLink(repoRequest, res)); } - return new Resource(EMPTY_RESOURCE_LIST, links); } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceNotFoundException.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceNotFoundException.java index 33b1fad65..5333d07c8 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceNotFoundException.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceNotFoundException.java @@ -2,7 +2,7 @@ package org.springframework.data.rest.webmvc; /** * Indicates a resource was not found. - * + * * @author Jon Brisbin */ public class ResourceNotFoundException extends RuntimeException { @@ -10,14 +10,14 @@ public class ResourceNotFoundException extends RuntimeException { private static final long serialVersionUID = 7992904489502842099L; public ResourceNotFoundException() { - super("Resource not found"); - } + super("Resource not found"); + } - public ResourceNotFoundException(String message) { - super(message); - } + public ResourceNotFoundException(String message) { + super(message); + } - public ResourceNotFoundException(String message, Throwable cause) { - super(message, cause); - } + public ResourceNotFoundException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceProcessorHandlerMethodReturnValueHandler.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceProcessorHandlerMethodReturnValueHandler.java index 7f940651d..413d13a61 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceProcessorHandlerMethodReturnValueHandler.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceProcessorHandlerMethodReturnValueHandler.java @@ -44,21 +44,21 @@ import static org.springframework.data.util.ClassTypeInformation.from; /** * {@link HandlerMethodReturnValueHandler} to post-process the objects returned from controller methods using the * configured {@link ResourceProcessor}s. - * + * * @author Oliver Gierke */ public class ResourceProcessorHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler { - private static final TypeInformation RESOURCE_TYPE = from(Resource.class); + private static final TypeInformation RESOURCE_TYPE = from(Resource.class); private static final TypeInformation RESOURCES_TYPE = from(Resources.class); - private static final Field CONTENT_FIELD = ReflectionUtils.findField(Resources.class, "content"); + private static final Field CONTENT_FIELD = ReflectionUtils.findField(Resources.class, "content"); static { ReflectionUtils.makeAccessible(CONTENT_FIELD); } private final HandlerMethodReturnValueHandler delegate; - private final List processors; + private final List processors; private boolean rootLinksAsHeaders = false; /** @@ -66,13 +66,13 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler * delegate calls to {@link #handleReturnValue(Object, MethodParameter, ModelAndViewContainer, NativeWebRequest)} to. * Will consider the given {@link ResourceProcessor} to post-process the controller methods return value to before * invoking the delegate. - * - * @param delegate the {@link HandlerMethodReturnValueHandler} to evenually delegate calls to, must not be {@literal - * null}. + * + * @param delegate the {@link HandlerMethodReturnValueHandler} to evenually delegate calls to, must not be + * {@literal null}. * @param processors the {@link ResourceProcessor}s to be considered, must not be {@literal null}. */ public ResourceProcessorHandlerMethodReturnValueHandler(HandlerMethodReturnValueHandler delegate, - List> processors) { + List> processors) { Assert.notNull(delegate, "Delegate must not be null!"); Assert.notNull(processors, "ResourceProcessors must not be null!"); @@ -97,7 +97,7 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler Collections.sort(this.processors, AnnotationAwareOrderComparator.INSTANCE); } - + /** * @param rootLinksAsHeaders the rootLinksAsHeaders to set */ @@ -120,7 +120,7 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler */ @Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, - NativeWebRequest webRequest) throws Exception { + NativeWebRequest webRequest) throws Exception { Object value = returnValue; @@ -174,7 +174,7 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler /** * Invokes all registered {@link ResourceProcessor}s registered for the given {@link TypeInformation}. - * + * * @param value the object to process * @param targetType * @return @@ -194,10 +194,11 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler } /** - * Re-wraps the result of the post-processing work into an {@link HttpEntity} or {@link ResponseEntity} if the original - * value was one of those two types. Copies headers and status code from the original value but uses the new body. - * - * @param newBody the post-processed value. + * Re-wraps the result of the post-processing work into an {@link HttpEntity} or {@link ResponseEntity} if the + * original value was one of those two types. Copies headers and status code from the original value but uses the new + * body. + * + * @param newBody the post-processed value. * @param originalValue the original input value. * @return */ @@ -206,7 +207,7 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler if (!(originalValue instanceof HttpEntity)) { return newBody; } - + HttpEntity entity = null; if (originalValue instanceof ResponseEntity) { @@ -216,18 +217,18 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler HttpEntity source = (HttpEntity) originalValue; entity = new HttpEntity(newBody, source.getHeaders()); } - + return addLinksToHeaderWrapper(entity); } - + private HttpEntity addLinksToHeaderWrapper(HttpEntity entity) { - + return rootLinksAsHeaders ? HeaderLinksResponseEntity.wrap(entity) : entity; } /** * Returns whether the given value is a resource (i.e. implements {@link Resource) or {@link Resources}). - * + * * @param value * @return */ @@ -236,9 +237,9 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler } /** - * Interface to unify interaction with {@link ResourceProcessor}s. The {@link Ordered} rank should be determined by the - * underlying processor. - * + * Interface to unify interaction with {@link ResourceProcessor}s. The {@link Ordered} rank should be determined by + * the underlying processor. + * * @author Oliver Gierke */ private interface ProcessorWrapper extends Ordered { @@ -246,17 +247,17 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler /** * Returns whether the underlying processor supports the given {@link TypeInformation}. It might also aditionally * inspect the object that would eventually be handed to the processor. - * + * * @param typeInformation the type of object to be post processed, will never be {@literal null}. - * @param value the object that would be passed into the processor eventually, can be {@literal null}. + * @param value the object that would be passed into the processor eventually, can be {@literal null}. * @return */ boolean supports(TypeInformation typeInformation, Object value); /** - * Performs the actual invocation of the processor. Implementations can be sure {@link #supports(TypeInformation, - * Object)} has been called before and returned {@literal true}. - * + * Performs the actual invocation of the processor. Implementations can be sure + * {@link #supports(TypeInformation, Object)} has been called before and returned {@literal true}. + * * @param object */ Object invokeProcessor(Object object); @@ -264,17 +265,17 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler /** * Default implementation of {@link ProcessorWrapper} to generically deal with {@link ResourceSupport} types. - * + * * @author Oliver Gierke */ private static class DefaultProcessorWrapper implements ProcessorWrapper { private final ResourceProcessor processor; - private final TypeInformation targetType; + private final TypeInformation targetType; /** * Creates a ne {@link DefaultProcessorWrapper} with the given {@link ResourceProcessor}. - * + * * @param processor must not be {@literal null}. */ public DefaultProcessorWrapper(ResourceProcessor processor) { @@ -315,7 +316,7 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler /** * Returns the target type the underlying {@link ResourceProcessor} wants to get invoked for. - * + * * @return the targetType */ public TypeInformation getTargetType() { @@ -326,14 +327,14 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler /** * {@link ProcessorWrapper} to deal with {@link ResourceProcessor}s for {@link Resource}s. Will fall back to peeking * into the {@link Resource}'s content for type resolution. - * + * * @author Oliver Gierke */ private static class ResourceProcessorWrapper extends DefaultProcessorWrapper { /** * Creates a new {@link ResourceProcessorWrapper} for the given {@link ResourceProcessor}. - * + * * @param processor must not be {@literal null}. */ public ResourceProcessorWrapper(ResourceProcessor processor) { @@ -355,11 +356,11 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler } /** - * Returns whether the given {@link Resource} matches the given target {@link TypeInformation}. We inspect the {@link - * Resource}'s value to determine the match. - * + * Returns whether the given {@link Resource} matches the given target {@link TypeInformation}. We inspect the + * {@link Resource}'s value to determine the match. + * * @param resource - * @param target must not be {@literal null}. + * @param target must not be {@literal null}. * @return whether the given {@link Resource} can be assigned to the given target {@link TypeInformation} */ private static boolean isValueTypeMatch(Resource resource, TypeInformation target) { @@ -382,14 +383,14 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler /** * {@link ProcessorWrapper} for {@link ResourceProcessor}s targeting {@link Resources}. Will peek into the content of * the {@link Resources} for type matching decisions if needed. - * + * * @author Oliver Gierke */ private static class ResourcesProcessorWrapper extends DefaultProcessorWrapper { /** * Creates a new {@link ResourcesProcessorWrapper} for the given {@link ResourceProcessor}. - * + * * @param processor must not be {@literal null}. */ public ResourcesProcessorWrapper(ResourceProcessor processor) { @@ -411,11 +412,11 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler } /** - * Returns whether the given {@link Resources} instance matches the given {@link TypeInformation}. We predict this by - * inspecting the first element of the content of the {@link Resources}. - * + * Returns whether the given {@link Resources} instance matches the given {@link TypeInformation}. We predict this + * by inspecting the first element of the content of the {@link Resources}. + * * @param resources the {@link Resources} to inspect. - * @param target that target {@link TypeInformation}. + * @param target that target {@link TypeInformation}. * @return */ private static boolean isValueTypeMatch(Resources resources, TypeInformation target) { @@ -444,7 +445,7 @@ public class ResourceProcessorHandlerMethodReturnValueHandler implements Handler /** * Helper extension of {@link AnnotationAwareOrderComparator} to make {@link #getOrder(Object)} public to allow it * being used in a standalone fashion. - * + * * @author Oliver Gierke */ private static class CustomOrderAwareComparator extends AnnotationAwareOrderComparator { diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceProcessorInvokingHandlerAdapter.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceProcessorInvokingHandlerAdapter.java index b3e448b35..2654d602b 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceProcessorInvokingHandlerAdapter.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceProcessorInvokingHandlerAdapter.java @@ -30,63 +30,59 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl /** * Special {@link RequestMappingHandlerAdapter} that tweaks the {@link HandlerMethodReturnValueHandlerComposite} to be - * proxied by a {@link ResourceProcessorHandlerMethodReturnValueHandler} which will invoke the {@link - * ResourceProcessor}s - * found in the application context and eventually delegate to the originally configured + * proxied by a {@link ResourceProcessorHandlerMethodReturnValueHandler} which will invoke the {@link ResourceProcessor} + * s found in the application context and eventually delegate to the originally configured * {@link HandlerMethodReturnValueHandler}. *

- * This is a separate component as it might make sense to deploy it in a standalone SpringMVC application to enable - * post + * This is a separate component as it might make sense to deploy it in a standalone SpringMVC application to enable post * processing. It would actually make most sense in Spring HATEOAS project. - * + * * @author Oliver Gierke */ public class ResourceProcessorInvokingHandlerAdapter extends RequestMappingHandlerAdapter { - @Autowired(required = false) - private List> resourcesProcessors = new ArrayList>(); + @Autowired(required = false) private List> resourcesProcessors = new ArrayList>(); - /** - * Empty constructor to setup a {@link ResourceProcessorInvokingHandlerAdapter}. - */ - public ResourceProcessorInvokingHandlerAdapter() { + /** + * Empty constructor to setup a {@link ResourceProcessorInvokingHandlerAdapter}. + */ + public ResourceProcessorInvokingHandlerAdapter() { - } + } - /** - * Copy constructor to copy configuration of {@link HttpMessageConverter}s, {@link WebBindingInitializer}, custom - * {@link HandlerMethodArgumentResolver}s and custom {@link HandlerMethodReturnValueHandler}s. - * - * @param original - * must not be {@literal null}. - */ - public ResourceProcessorInvokingHandlerAdapter(RequestMappingHandlerAdapter original) { + /** + * Copy constructor to copy configuration of {@link HttpMessageConverter}s, {@link WebBindingInitializer}, custom + * {@link HandlerMethodArgumentResolver}s and custom {@link HandlerMethodReturnValueHandler}s. + * + * @param original must not be {@literal null}. + */ + public ResourceProcessorInvokingHandlerAdapter(RequestMappingHandlerAdapter original) { - Assert.notNull(original); + Assert.notNull(original); - setMessageConverters(original.getMessageConverters()); - setWebBindingInitializer(original.getWebBindingInitializer()); - setCustomArgumentResolvers(original.getCustomArgumentResolvers()); - setCustomReturnValueHandlers(original.getCustomReturnValueHandlers()); - } + setMessageConverters(original.getMessageConverters()); + setWebBindingInitializer(original.getWebBindingInitializer()); + setCustomArgumentResolvers(original.getCustomArgumentResolvers()); + setCustomReturnValueHandlers(original.getCustomReturnValueHandlers()); + } - /* - * (non-Javadoc) - * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#afterPropertiesSet() - */ - @Override - public void afterPropertiesSet() { + /* + * (non-Javadoc) + * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#afterPropertiesSet() + */ + @Override + public void afterPropertiesSet() { - super.afterPropertiesSet(); + super.afterPropertiesSet(); - // Retrieve actual handlers to use as delegate - HandlerMethodReturnValueHandlerComposite oldHandlers = getReturnValueHandlers(); + // Retrieve actual handlers to use as delegate + HandlerMethodReturnValueHandlerComposite oldHandlers = getReturnValueHandlers(); - // Set up ResourceProcessingHandlerMethodResolver to delegate to originally configured ones - List newHandlers = new ArrayList(); - newHandlers.add(new ResourceProcessorHandlerMethodReturnValueHandler(oldHandlers, resourcesProcessors)); + // Set up ResourceProcessingHandlerMethodResolver to delegate to originally configured ones + List newHandlers = new ArrayList(); + newHandlers.add(new ResourceProcessorHandlerMethodReturnValueHandler(oldHandlers, resourcesProcessors)); - // Configure the new handler to be used - this.setReturnValueHandlers(newHandlers); - } + // Configure the new handler to be used + this.setReturnValueHandlers(newHandlers); + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ServerHttpRequestMethodArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ServerHttpRequestMethodArgumentResolver.java index aace3c21f..cb4082a9a 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ServerHttpRequestMethodArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ServerHttpRequestMethodArgumentResolver.java @@ -15,16 +15,15 @@ import org.springframework.web.method.support.ModelAndViewContainer; */ public class ServerHttpRequestMethodArgumentResolver implements HandlerMethodArgumentResolver { - @Override public boolean supportsParameter(MethodParameter parameter) { - return ClassUtils.isAssignable(parameter.getParameterType(), ServletServerHttpRequest.class); - } + @Override + public boolean supportsParameter(MethodParameter parameter) { + return ClassUtils.isAssignable(parameter.getParameterType(), ServletServerHttpRequest.class); + } - @Override - public Object resolveArgument(MethodParameter parameter, - ModelAndViewContainer mavContainer, - NativeWebRequest webRequest, - WebDataBinderFactory binderFactory) throws Exception { - return new ServletServerHttpRequest((HttpServletRequest)webRequest.getNativeRequest()); - } + @Override + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { + return new ServletServerHttpRequest((HttpServletRequest) webRequest.getNativeRequest()); + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/annotation/BaseURI.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/annotation/BaseURI.java index b4b92c0a1..c2d280f71 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/annotation/BaseURI.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/annotation/BaseURI.java @@ -7,10 +7,10 @@ import java.lang.annotation.Target; /** * Marker annotation to denote which {@link java.net.URI} parameter should be resolved to the request base URI. - * + * * @author Jon Brisbin */ -@Target({ElementType.PARAMETER}) +@Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface BaseURI { } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.java index c72f11177..b2db542fe 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.java @@ -84,7 +84,8 @@ import com.fasterxml.jackson.databind.SerializationFeature; * @author Oliver Gierke */ @Configuration -@ComponentScan(basePackageClasses = RestController.class, includeFilters = @Filter(RestController.class), useDefaultFilters = false) +@ComponentScan(basePackageClasses = RestController.class, includeFilters = @Filter(RestController.class), + useDefaultFilters = false) @ImportResource("classpath*:META-INF/spring-data-rest/**/*.xml") public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebConfiguration { @@ -103,7 +104,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon @Bean @Qualifier public DefaultFormattingConversionService defaultConversionService() { - + DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(); conversionService.addConverter(UUIDConverter.INSTANCE); conversionService.addConverter(ISO8601DateConverter.INSTANCE); diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/convert/UriListHttpMessageConverter.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/convert/UriListHttpMessageConverter.java index 075d6a0c5..3b46199fc 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/convert/UriListHttpMessageConverter.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/convert/UriListHttpMessageConverter.java @@ -23,51 +23,51 @@ import org.springframework.http.converter.HttpMessageNotWritableException; */ public class UriListHttpMessageConverter implements HttpMessageConverter> { - private static final List MEDIA_TYPES = new ArrayList(); + private static final List MEDIA_TYPES = new ArrayList(); - static { - MEDIA_TYPES.add(MediaType.parseMediaType("text/uri-list")); - } + static { + MEDIA_TYPES.add(MediaType.parseMediaType("text/uri-list")); + } - @Override public boolean canRead(Class clazz, MediaType mediaType) { - if(null == mediaType) { - return false; - } - return Resource.class.isAssignableFrom(clazz) && mediaType.getSubtype().contains("uri-list"); - } + @Override + public boolean canRead(Class clazz, MediaType mediaType) { + if (null == mediaType) { + return false; + } + return Resource.class.isAssignableFrom(clazz) && mediaType.getSubtype().contains("uri-list"); + } - @Override public boolean canWrite(Class clazz, MediaType mediaType) { - return canRead(clazz, mediaType); - } + @Override + public boolean canWrite(Class clazz, MediaType mediaType) { + return canRead(clazz, mediaType); + } - @Override public List getSupportedMediaTypes() { - return MEDIA_TYPES; - } + @Override + public List getSupportedMediaTypes() { + return MEDIA_TYPES; + } - @Override public Resource read(Class> clazz, - HttpInputMessage inputMessage) - throws IOException, - HttpMessageNotReadableException { - List links = new ArrayList(); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputMessage.getBody())); - String line; - while(null != (line = reader.readLine())) { - links.add(new Link(line)); - } - return new Resource(Collections.emptyList(), links); - } + @Override + public Resource read(Class> clazz, HttpInputMessage inputMessage) throws IOException, + HttpMessageNotReadableException { + List links = new ArrayList(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputMessage.getBody())); + String line; + while (null != (line = reader.readLine())) { + links.add(new Link(line)); + } + return new Resource(Collections.emptyList(), links); + } - @Override public void write(Resource resource, - MediaType contentType, - HttpOutputMessage outputMessage) - throws IOException, - HttpMessageNotWritableException { - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputMessage.getBody())); - for(Link link : resource.getLinks()) { - writer.write(link.getHref()); - writer.newLine(); - } - writer.flush(); - } + @Override + public void write(Resource resource, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, + HttpMessageNotWritableException { + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputMessage.getBody())); + for (Link link : resource.getLinks()) { + writer.write(link.getHref()); + writer.newLine(); + } + writer.flush(); + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/Jackson2DatatypeHelper.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/Jackson2DatatypeHelper.java index 6be7fa07c..26cad384c 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/Jackson2DatatypeHelper.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/Jackson2DatatypeHelper.java @@ -8,40 +8,35 @@ import org.springframework.util.ClassUtils; /** * Helper class to register datatype modules based on their presence in the classpath. - * + * * @author Jon Brisbin */ public class Jackson2DatatypeHelper { - private static final Logger LOG = LoggerFactory.getLogger(Jackson2DatatypeHelper.class); + private static final Logger LOG = LoggerFactory.getLogger(Jackson2DatatypeHelper.class); private static final boolean IS_HIBERNATE4_MODULE_AVAILABLE = ClassUtils.isPresent( - "com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module", - Jackson2DatatypeHelper.class.getClassLoader() - ); - private static final boolean IS_JODA_MODULE_AVAILABLE = ClassUtils.isPresent( - "com.fasterxml.jackson.datatype.joda.JodaModule", - Jackson2DatatypeHelper.class.getClassLoader() - ); + "com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module", Jackson2DatatypeHelper.class.getClassLoader()); + private static final boolean IS_JODA_MODULE_AVAILABLE = ClassUtils.isPresent( + "com.fasterxml.jackson.datatype.joda.JodaModule", Jackson2DatatypeHelper.class.getClassLoader()); public static void configureObjectMapper(ObjectMapper mapper) { // Hibernate types - if(IS_HIBERNATE4_MODULE_AVAILABLE) { + if (IS_HIBERNATE4_MODULE_AVAILABLE) { try { - mapper.registerModule((Module)Class.forName("com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module") - .newInstance()); - } catch(Throwable t) { - if(LOG.isDebugEnabled()) { + mapper.registerModule((Module) Class.forName("com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module") + .newInstance()); + } catch (Throwable t) { + if (LOG.isDebugEnabled()) { LOG.debug(t.getMessage(), t); } } } // JODA time - if(IS_JODA_MODULE_AVAILABLE) { + if (IS_JODA_MODULE_AVAILABLE) { try { - mapper.registerModule((Module)Class.forName("com.fasterxml.jackson.datatype.joda.JodaModule") - .newInstance()); - } catch(Throwable t) { - if(LOG.isDebugEnabled()) { + mapper.registerModule((Module) Class.forName("com.fasterxml.jackson.datatype.joda.JodaModule").newInstance()); + } catch (Throwable t) { + if (LOG.isDebugEnabled()) { LOG.debug(t.getMessage(), t); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/JsonSchema.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/JsonSchema.java index ed059f7f3..5b1fab7a5 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/JsonSchema.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/JsonSchema.java @@ -13,84 +13,82 @@ import org.springframework.hateoas.Resource; */ public class JsonSchema extends Resource> { - private final String name; - @SuppressWarnings("unused") - private final String description; + private final String name; + @SuppressWarnings("unused") private final String description; - public JsonSchema(String name, String description) { - super(new HashMap()); - this.name = name; - this.description = description; - } + public JsonSchema(String name, String description) { + super(new HashMap()); + this.name = name; + this.description = description; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - @JsonProperty("properties") - @Override public Map getContent() { - return super.getContent(); - } + @JsonProperty("properties") + @Override + public Map getContent() { + return super.getContent(); + } - public JsonSchema addProperty(String name, Property property) { - getContent().put(name, property); - return this; - } + public JsonSchema addProperty(String name, Property property) { + getContent().put(name, property); + return this; + } - public boolean isArrayProperty(String name) { - return (getContent().containsKey(name) && getContent().get(name) instanceof ArrayProperty); - } + public boolean isArrayProperty(String name) { + return (getContent().containsKey(name) && getContent().get(name) instanceof ArrayProperty); + } - public ArrayProperty getArrayProperty(String name) { - return (ArrayProperty)getContent().get(name); - } + public ArrayProperty getArrayProperty(String name) { + return (ArrayProperty) getContent().get(name); + } - public static class Property { - private final String type; - private final String description; - private final boolean required; + public static class Property { + private final String type; + private final String description; + private final boolean required; - public Property(String type, String description, boolean required) { - this.type = type; - this.description = description; - this.required = required; - } + public Property(String type, String description, boolean required) { + this.type = type; + this.description = description; + this.required = required; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public boolean isRequired() { - return required; - } - } + public boolean isRequired() { + return required; + } + } - public static class ArrayProperty extends Property { - private List items = new ArrayList(); + public static class ArrayProperty extends Property { + private List items = new ArrayList(); - public ArrayProperty(String type, - String description, - boolean required) { - super(type, description, required); - } + public ArrayProperty(String type, String description, boolean required) { + super(type, description, required); + } - public List getItems() { - return items; - } + public List getItems() { + return items; + } - public ArrayProperty setItems(List items) { - this.items = items; - return this; - } + public ArrayProperty setItems(List items) { + this.items = items; + return this; + } - public

ArrayProperty addItem(P item) { - this.items.add(item); - return this; - } - } + public

ArrayProperty addItem(P item) { + this.items.add(item); + return this; + } + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2Module.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2Module.java index 1abd88089..cc53ad348 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2Module.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2Module.java @@ -53,57 +53,53 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer; public class PersistentEntityJackson2Module extends SimpleModule implements InitializingBean { private static final long serialVersionUID = -7289265674870906323L; - private static final Logger LOG = LoggerFactory.getLogger(PersistentEntityJackson2Module.class); + private static final Logger LOG = LoggerFactory.getLogger(PersistentEntityJackson2Module.class); private static final TypeDescriptor URI_TYPE = TypeDescriptor.valueOf(URI.class); - @Autowired - private Repositories repositories; - @Autowired - private RepositoryRestConfiguration config; - @Autowired - private UriDomainClassConverter uriDomainClassConverter; + @Autowired private Repositories repositories; + @Autowired private RepositoryRestConfiguration config; + @Autowired private UriDomainClassConverter uriDomainClassConverter; private final ResourceMappings mappings; public PersistentEntityJackson2Module(ResourceMappings resourceMappings) { - + super(new Version(1, 1, 0, "BUILD-SNAPSHOT", "org.springframework.data.rest", "jackson-module")); - + this.mappings = resourceMappings; addSerializer(new ResourceSerializer()); } - public static boolean maybeAddAssociationLink(RepositoryLinkBuilder builder, - ResourceMappings mappings, - PersistentProperty persistentProperty, - List links) { - + public static boolean maybeAddAssociationLink(RepositoryLinkBuilder builder, ResourceMappings mappings, + PersistentProperty persistentProperty, List links) { + Assert.isTrue(persistentProperty.isAssociation(), "PersistentProperty must be an association!"); ResourceMetadata metadata = mappings.getMappingFor(persistentProperty.getOwner().getType()); - + if (!metadata.isManaged(persistentProperty)) { return false; } - + metadata = mappings.getMappingFor(persistentProperty.getActualType()); - - if(metadata.isExported()) { - + + if (metadata.isExported()) { + String propertyRel = String.format("%s.%s", metadata.getSingleResourceRel(), persistentProperty.getName()); links.add(builder.slash(persistentProperty.getName()).withRel(propertyRel)); - + // This is an association. We added a Link. return true; - } - + } + // This is not an association. No Link was added. return false; } - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override public void afterPropertiesSet() throws Exception { - for(Class domainType : repositories) { + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public void afterPropertiesSet() throws Exception { + for (Class domainType : repositories) { PersistentEntity pe = repositories.getPersistentEntity(domainType); - if(null == pe) { - if(LOG.isWarnEnabled()) { + if (null == pe) { + if (LOG.isWarnEnabled()) { LOG.warn("The domain class {} does not have PersistentEntity metadata.", domainType.getName()); } } else { @@ -122,47 +118,46 @@ public class PersistentEntityJackson2Module extends SimpleModule implements Init this.persistentEntity = persistentEntity; } - @SuppressWarnings({"unchecked", "incomplete-switch", "null", "unused"}) - @Override public T deserialize(JsonParser jp, - DeserializationContext ctxt) throws IOException, - JsonProcessingException { + @SuppressWarnings({ "unchecked", "incomplete-switch", "null", "unused" }) + @Override + public T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Object entity = instantiateClass(getValueClass()); - BeanWrapper wrapper = BeanWrapper.create(entity, null); - + BeanWrapper wrapper = BeanWrapper.create(entity, null); + ResourceMetadata metadata = mappings.getMappingFor(getValueClass()); - for(JsonToken tok = jp.nextToken(); tok != JsonToken.END_OBJECT; tok = jp.nextToken()) { + for (JsonToken tok = jp.nextToken(); tok != JsonToken.END_OBJECT; tok = jp.nextToken()) { String name = jp.getCurrentName(); - switch(tok) { + switch (tok) { case FIELD_NAME: { - if("href".equals(name)) { + if ("href".equals(name)) { URI uri = URI.create(jp.nextTextValue()); TypeDescriptor entityType = TypeDescriptor.forObject(entity); - if(uriDomainClassConverter.matches(URI_TYPE, entityType)) { + if (uriDomainClassConverter.matches(URI_TYPE, entityType)) { entity = uriDomainClassConverter.convert(uri, URI_TYPE, entityType); } continue; } - if("rel".equals(name)) { + if ("rel".equals(name)) { // rel is currently ignored continue; } PersistentProperty persistentProperty = persistentEntity.getPersistentProperty(name); - if(null == persistentProperty) { + if (null == persistentProperty) { continue; } Object val = null; - if("links".equals(name)) { - if((tok = jp.nextToken()) == JsonToken.START_ARRAY) { - while((tok = jp.nextToken()) != JsonToken.END_ARRAY) { + if ("links".equals(name)) { + if ((tok = jp.nextToken()) == JsonToken.START_ARRAY) { + while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) { // Advance past the links } - } else if(tok == JsonToken.VALUE_NULL) { + } else if (tok == JsonToken.VALUE_NULL) { // skip null value } else { throw new HttpMessageNotReadableException( @@ -171,44 +166,44 @@ public class PersistentEntityJackson2Module extends SimpleModule implements Init continue; } - if(null == persistentProperty) { + if (null == persistentProperty) { // do nothing continue; } // Try and read the value of this attribute. // The method of doing that varies based on the type of the property. - if(persistentProperty.isCollectionLike()) { + if (persistentProperty.isCollectionLike()) { Class> ctype = (Class>) persistentProperty.getType(); Collection c = (Collection) wrapper.getProperty(persistentProperty); - if(null == c || c == Collections.EMPTY_LIST || c == Collections.EMPTY_SET) { - if(Collection.class.isAssignableFrom(ctype)) { + if (null == c || c == Collections.EMPTY_LIST || c == Collections.EMPTY_SET) { + if (Collection.class.isAssignableFrom(ctype)) { c = new ArrayList(); - } else if(Set.class.isAssignableFrom(ctype)) { + } else if (Set.class.isAssignableFrom(ctype)) { c = new HashSet(); } } - if((tok = jp.nextToken()) == JsonToken.START_ARRAY) { - while((tok = jp.nextToken()) != JsonToken.END_ARRAY) { + if ((tok = jp.nextToken()) == JsonToken.START_ARRAY) { + while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) { Object cval = jp.readValueAs(persistentProperty.getComponentType()); c.add(cval); } val = c; - } else if(tok == JsonToken.VALUE_NULL) { + } else if (tok == JsonToken.VALUE_NULL) { val = null; } else { throw new HttpMessageNotReadableException("Cannot read a JSON " + tok + " as a Collection."); } - } else if(persistentProperty.isMap()) { - Class> mtype = (Class>)persistentProperty.getType(); + } else if (persistentProperty.isMap()) { + Class> mtype = (Class>) persistentProperty.getType(); Map m = (Map) wrapper.getProperty(persistentProperty); - if(null == m || m == Collections.EMPTY_MAP) { + if (null == m || m == Collections.EMPTY_MAP) { m = new HashMap(); } - if((tok = jp.nextToken()) == JsonToken.START_OBJECT) { + if ((tok = jp.nextToken()) == JsonToken.START_OBJECT) { do { name = jp.getCurrentName(); // TODO resolve domain object from URI @@ -216,16 +211,16 @@ public class PersistentEntityJackson2Module extends SimpleModule implements Init Object mval = jp.readValueAs(persistentProperty.getMapValueType()); m.put(name, mval); - } while((tok = jp.nextToken()) != JsonToken.END_OBJECT); + } while ((tok = jp.nextToken()) != JsonToken.END_OBJECT); val = m; - } else if(tok == JsonToken.VALUE_NULL) { + } else if (tok == JsonToken.VALUE_NULL) { val = null; } else { throw new HttpMessageNotReadableException("Cannot read a JSON " + tok + " as a Map."); } } else { - if((tok = jp.nextToken()) != JsonToken.VALUE_NULL) { + if ((tok = jp.nextToken()) != JsonToken.VALUE_NULL) { val = jp.readValueAs(persistentProperty.getType()); } } @@ -237,7 +232,7 @@ public class PersistentEntityJackson2Module extends SimpleModule implements Init } } - return (T)entity; + return (T) entity; } } @@ -248,12 +243,11 @@ public class PersistentEntityJackson2Module extends SimpleModule implements Init super(PersistentEntityResource.class); } - @SuppressWarnings({"unchecked"}) - @Override public void serialize(final PersistentEntityResource resource, - final JsonGenerator jgen, - final SerializerProvider provider) throws IOException, - JsonGenerationException { - if(LOG.isDebugEnabled()) { + @SuppressWarnings({ "unchecked" }) + @Override + public void serialize(final PersistentEntityResource resource, final JsonGenerator jgen, + final SerializerProvider provider) throws IOException, JsonGenerationException { + if (LOG.isDebugEnabled()) { LOG.debug("Serializing PersistentEntity " + resource.getPersistentEntity()); } @@ -274,14 +268,16 @@ public class PersistentEntityJackson2Module extends SimpleModule implements Init jgen.writeStartObject(); try { entity.doWithProperties(new PropertyHandler() { - @Override public void doWithPersistentProperty(PersistentProperty property) { - - boolean idAvailableAndShallNotBeExposed = property.isIdProperty() && !config.isIdExposedFor(entity.getType()); - - if(idAvailableAndShallNotBeExposed) { + @Override + public void doWithPersistentProperty(PersistentProperty property) { + + boolean idAvailableAndShallNotBeExposed = property.isIdProperty() + && !config.isIdExposedFor(entity.getType()); + + if (idAvailableAndShallNotBeExposed) { return; } - + if (property.isEntity() && maybeAddAssociationLink(builder, mappings, property, links)) { return; } @@ -290,7 +286,7 @@ public class PersistentEntityJackson2Module extends SimpleModule implements Init Object propertyValue = wrapper.getProperty(property); try { jgen.writeObjectField(property.getName(), propertyValue); - } catch(IOException e) { + } catch (IOException e) { throw new IllegalStateException(e); } } @@ -298,14 +294,15 @@ public class PersistentEntityJackson2Module extends SimpleModule implements Init // Add associations as links entity.doWithAssociations(new AssociationHandler() { - @Override public void doWithAssociation(Association association) { - + @Override + public void doWithAssociation(Association association) { + PersistentProperty property = association.getInverse(); - - if(!mappings.isMapped(property)) { + + if (!mappings.isMapped(property)) { return; } - + if (maybeAddAssociationLink(builder, mappings, property, links)) { return; } @@ -313,20 +310,20 @@ public class PersistentEntityJackson2Module extends SimpleModule implements Init Object propertyValue = wrapper.getProperty(property); try { jgen.writeObjectField(property.getName(), propertyValue); - } catch(IOException e) { + } catch (IOException e) { throw new IllegalStateException(e); } } }); jgen.writeArrayFieldStart("links"); - for(Link l : links) { + for (Link l : links) { jgen.writeObject(l); } jgen.writeEndArray(); - } catch(IllegalStateException e) { - throw (IOException)e.getCause(); + } catch (IllegalStateException e) { + throw (IOException) e.getCause(); } finally { jgen.writeEndObject(); } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverter.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverter.java index cda9ebc1b..28465b8ca 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverter.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverter.java @@ -29,89 +29,90 @@ import org.springframework.hateoas.Link; /** * @author Jon Brisbin */ -public class PersistentEntityToJsonSchemaConverter - extends RepositoryInformationSupport - implements ConditionalGenericConverter, - InitializingBean { +public class PersistentEntityToJsonSchemaConverter extends RepositoryInformationSupport implements + ConditionalGenericConverter, InitializingBean { - private static final TypeDescriptor STRING_TYPE = TypeDescriptor.valueOf(String.class); - private static final TypeDescriptor SCHEMA_TYPE = TypeDescriptor.valueOf(JsonSchema.class); - private Set convertiblePairs = new HashSet(); - private ResourceMappings mappings; + private static final TypeDescriptor STRING_TYPE = TypeDescriptor.valueOf(String.class); + private static final TypeDescriptor SCHEMA_TYPE = TypeDescriptor.valueOf(JsonSchema.class); + private Set convertiblePairs = new HashSet(); + private ResourceMappings mappings; - @Override public void afterPropertiesSet() throws Exception { - - for(Class domainType : repositories) { - convertiblePairs.add(new ConvertiblePair(domainType, JsonSchema.class)); - } - - this.mappings = new ResourceMappings(config, repositories); - } + @Override + public void afterPropertiesSet() throws Exception { - @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - return (Class.class.isAssignableFrom(sourceType.getType()) && JsonSchema.class.isAssignableFrom(targetType.getType())); - } + for (Class domainType : repositories) { + convertiblePairs.add(new ConvertiblePair(domainType, JsonSchema.class)); + } + this.mappings = new ResourceMappings(config, repositories); + } - @Override public Set getConvertibleTypes() { - return convertiblePairs; - } + @Override + public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { + return (Class.class.isAssignableFrom(sourceType.getType()) && JsonSchema.class.isAssignableFrom(targetType + .getType())); + } - public JsonSchema convert(Class domainType) { - return (JsonSchema)convert(domainType, STRING_TYPE, SCHEMA_TYPE); - } + @Override + public Set getConvertibleTypes() { + return convertiblePairs; + } - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - - PersistentEntity persistentEntity = repositories.getPersistentEntity((Class)source); - final ResourceMetadata metadata = mappings.getMappingFor(persistentEntity.getClass()); - String entityDesc = persistentEntity.getType().isAnnotationPresent(Description.class) - ? ((Description)persistentEntity.getType().getAnnotation(Description.class)).value() - : null; - - final JsonSchema jsonSchema = new JsonSchema(persistentEntity.getName(), entityDesc); - persistentEntity.doWithProperties(new PropertyHandler() { - @Override public void doWithPersistentProperty(PersistentProperty persistentProperty) { - Class propertyType = persistentProperty.getType(); - String type = uncapitalize(propertyType.getSimpleName()); - boolean notNull = (persistentProperty.getField().isAnnotationPresent(Nonnull.class) - || persistentProperty.getGetter().isAnnotationPresent(Nonnull.class)) - || (persistentProperty.getField().isAnnotationPresent(NotNull.class) - || persistentProperty.getGetter().isAnnotationPresent(NotNull.class)); - String desc = persistentProperty.getField().isAnnotationPresent(Description.class) - ? persistentProperty.getField().getAnnotation(Description.class).value() - : persistentProperty.getGetter().isAnnotationPresent(Description.class) - ? persistentProperty.getGetter().getAnnotation(Description.class).value() - : null; + public JsonSchema convert(Class domainType) { + return (JsonSchema) convert(domainType, STRING_TYPE, SCHEMA_TYPE); + } - JsonSchema.Property property; - if(persistentProperty.isCollectionLike()) { - property = new JsonSchema.ArrayProperty("array", desc, notNull); - } else { - property = new JsonSchema.Property(type, desc, notNull); - } - jsonSchema.addProperty(persistentProperty.getName(), property); - } - }); + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - final List links = new ArrayList(); - - persistentEntity.doWithAssociations(new AssociationHandler() { - @Override public void doWithAssociation(Association association) { - PersistentProperty persistentProperty = association.getInverse(); - if(!metadata.isMapped(persistentProperty)) { - return; - } - - RepositoryLinkBuilder builder = new RepositoryLinkBuilder(metadata, config.getBaseUri()).slash("{id}"); + PersistentEntity persistentEntity = repositories.getPersistentEntity((Class) source); + final ResourceMetadata metadata = mappings.getMappingFor(persistentEntity.getClass()); + String entityDesc = persistentEntity.getType().isAnnotationPresent(Description.class) ? ((Description) persistentEntity + .getType().getAnnotation(Description.class)).value() : null; + + final JsonSchema jsonSchema = new JsonSchema(persistentEntity.getName(), entityDesc); + persistentEntity.doWithProperties(new PropertyHandler() { + @Override + public void doWithPersistentProperty(PersistentProperty persistentProperty) { + Class propertyType = persistentProperty.getType(); + String type = uncapitalize(propertyType.getSimpleName()); + boolean notNull = (persistentProperty.getField().isAnnotationPresent(Nonnull.class) || persistentProperty + .getGetter().isAnnotationPresent(Nonnull.class)) + || (persistentProperty.getField().isAnnotationPresent(NotNull.class) || persistentProperty.getGetter() + .isAnnotationPresent(NotNull.class)); + String desc = persistentProperty.getField().isAnnotationPresent(Description.class) ? persistentProperty + .getField().getAnnotation(Description.class).value() : persistentProperty.getGetter().isAnnotationPresent( + Description.class) ? persistentProperty.getGetter().getAnnotation(Description.class).value() : null; + + JsonSchema.Property property; + if (persistentProperty.isCollectionLike()) { + property = new JsonSchema.ArrayProperty("array", desc, notNull); + } else { + property = new JsonSchema.Property(type, desc, notNull); + } + jsonSchema.addProperty(persistentProperty.getName(), property); + } + }); + + final List links = new ArrayList(); + + persistentEntity.doWithAssociations(new AssociationHandler() { + @Override + public void doWithAssociation(Association association) { + PersistentProperty persistentProperty = association.getInverse(); + if (!metadata.isMapped(persistentProperty)) { + return; + } + + RepositoryLinkBuilder builder = new RepositoryLinkBuilder(metadata, config.getBaseUri()).slash("{id}"); maybeAddAssociationLink(builder, mappings, persistentProperty, links); - } - }); - - jsonSchema.add(links); + } + }); - return jsonSchema; - } + jsonSchema.add(links); + + return jsonSchema; + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/BaseUriLinkBuilder.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/BaseUriLinkBuilder.java index 7b272c013..10b9a2126 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/BaseUriLinkBuilder.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/BaseUriLinkBuilder.java @@ -10,20 +10,22 @@ import org.springframework.web.util.UriComponentsBuilder; */ public class BaseUriLinkBuilder extends LinkBuilderSupport { - public BaseUriLinkBuilder(UriComponentsBuilder builder) { - super(builder); - } + public BaseUriLinkBuilder(UriComponentsBuilder builder) { + super(builder); + } - public static BaseUriLinkBuilder create(URI baseUri) { - return new BaseUriLinkBuilder(UriComponentsBuilder.fromUri(baseUri)); - } + public static BaseUriLinkBuilder create(URI baseUri) { + return new BaseUriLinkBuilder(UriComponentsBuilder.fromUri(baseUri)); + } - @Override protected BaseUriLinkBuilder getThis() { - return this; - } + @Override + protected BaseUriLinkBuilder getThis() { + return this; + } - @Override protected BaseUriLinkBuilder createNewInstance(UriComponentsBuilder builder) { - return new BaseUriLinkBuilder(builder); - } + @Override + protected BaseUriLinkBuilder createNewInstance(UriComponentsBuilder builder) { + return new BaseUriLinkBuilder(builder); + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ConstraintViolationExceptionMessage.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ConstraintViolationExceptionMessage.java index 3a23b63d8..862428ca1 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ConstraintViolationExceptionMessage.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ConstraintViolationExceptionMessage.java @@ -14,26 +14,24 @@ import org.springframework.context.MessageSource; */ public class ConstraintViolationExceptionMessage { - private final ConstraintViolationException cve; - private final List messages = new ArrayList(); + private final ConstraintViolationException cve; + private final List messages = new ArrayList(); - public ConstraintViolationExceptionMessage(ConstraintViolationException cve, - MessageSource msgSrc, - Locale locale) { - this.cve = cve; - for(ConstraintViolation cv : cve.getConstraintViolations()) { - messages.add(new ConstraintViolationMessage(cv, msgSrc, locale)); - } - } + public ConstraintViolationExceptionMessage(ConstraintViolationException cve, MessageSource msgSrc, Locale locale) { + this.cve = cve; + for (ConstraintViolation cv : cve.getConstraintViolations()) { + messages.add(new ConstraintViolationMessage(cv, msgSrc, locale)); + } + } - @JsonProperty("cause") - public String getCause() { - return cve.getMessage(); - } + @JsonProperty("cause") + public String getCause() { + return cve.getMessage(); + } - @JsonProperty("messages") - public List getMessages() { - return messages; - } + @JsonProperty("messages") + public List getMessages() { + return messages; + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ConstraintViolationMessage.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ConstraintViolationMessage.java index d80038854..4227925c1 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ConstraintViolationMessage.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ConstraintViolationMessage.java @@ -10,26 +10,19 @@ import org.springframework.context.MessageSource; /** * A helper class to encapsulate {@link ConstraintViolation} errors. - * + * * @author Jon Brisbin */ public class ConstraintViolationMessage { private final ConstraintViolation violation; - private final String message; + private final String message; - public ConstraintViolationMessage(ConstraintViolation violation, - MessageSource msgSrc, - Locale locale) { + public ConstraintViolationMessage(ConstraintViolation violation, MessageSource msgSrc, Locale locale) { this.violation = violation; this.message = msgSrc.getMessage(violation.getMessageTemplate(), - new Object[]{ - violation.getLeafBean().getClass().getSimpleName(), - violation.getPropertyPath().toString(), - violation.getInvalidValue() - }, - violation.getMessage(), - locale); + new Object[] { violation.getLeafBean().getClass().getSimpleName(), violation.getPropertyPath().toString(), + violation.getInvalidValue() }, violation.getMessage(), locale); } @JsonProperty("entity") diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ExceptionMessage.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ExceptionMessage.java index c9661a8d8..e358e555d 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ExceptionMessage.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ExceptionMessage.java @@ -4,29 +4,28 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * A helper that renders an {@link Exception} JSON-friendly. - * + * * @author Jon Brisbin */ public class ExceptionMessage { - private final Throwable exception; + private final Throwable exception; - public ExceptionMessage(Throwable exception) { - this.exception = exception; - } + public ExceptionMessage(Throwable exception) { + this.exception = exception; + } - @JsonProperty("message") - public String getMessage() { - return exception.getMessage(); - } + @JsonProperty("message") + public String getMessage() { + return exception.getMessage(); + } - @JsonProperty("cause") - public ExceptionMessage getCause() { - if(null != exception.getCause()) { - return new ExceptionMessage(exception.getCause()); - } - return null; - } + @JsonProperty("cause") + public ExceptionMessage getCause() { + if (null != exception.getCause()) { + return new ExceptionMessage(exception.getCause()); + } + return null; + } } - diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/HttpRequestUtils.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/HttpRequestUtils.java index 5a1a75100..03238268c 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/HttpRequestUtils.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/HttpRequestUtils.java @@ -7,37 +7,33 @@ import org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet; /** * Helper class to HttpServletRequest helpers. - * + * * @author Jon Brisbin */ public abstract class HttpRequestUtils { - /** - * Strip a servlet registration mapping from the request URI. - * - * @param requestUri - * The request URI to strip. - * @param ctx - * The servlet context in which to search for registration mappings. - * - * @return The stripped request URI. - */ - public static String stripRegistrationMapping(String requestUri, - ServletContext ctx) { - for(ServletRegistration reg : ctx.getServletRegistrations().values()) { - if(reg.getClassName().equals(RepositoryRestDispatcherServlet.class.getName()) - || reg.getName().equals("rest-exporter")) { - for(String mapping : reg.getMappings()) { - if(mapping.contains("*")) { - mapping = mapping.substring(0, mapping.indexOf('*')); - } - if(requestUri.startsWith(mapping)) { - return requestUri.replaceAll(mapping, ""); - } - } - } - } - return requestUri; - } + /** + * Strip a servlet registration mapping from the request URI. + * + * @param requestUri The request URI to strip. + * @param ctx The servlet context in which to search for registration mappings. + * @return The stripped request URI. + */ + public static String stripRegistrationMapping(String requestUri, ServletContext ctx) { + for (ServletRegistration reg : ctx.getServletRegistrations().values()) { + if (reg.getClassName().equals(RepositoryRestDispatcherServlet.class.getName()) + || reg.getName().equals("rest-exporter")) { + for (String mapping : reg.getMappings()) { + if (mapping.contains("*")) { + mapping = mapping.substring(0, mapping.indexOf('*')); + } + if (requestUri.startsWith(mapping)) { + return requestUri.replaceAll(mapping, ""); + } + } + } + } + return requestUri; + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/JpaHelper.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/JpaHelper.java index 5daa56b20..4c5a926da 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/JpaHelper.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/JpaHelper.java @@ -19,13 +19,12 @@ public class JpaHelper implements BeanFactoryAware { private List interceptor = new ArrayList(); - @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - (ListableBeanFactory)beanFactory, - EntityManagerFactory.class - ); - for(String s : beanNames) { - EntityManagerFactory emf = (EntityManagerFactory)beanFactory.getBean(s); + @Override + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory, + EntityManagerFactory.class); + for (String s : beanNames) { + EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(s); OpenEntityManagerInViewInterceptor omivi = new OpenEntityManagerInViewInterceptor(); omivi.setEntityManagerFactory(emf); interceptor.add(omivi); diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryConstraintViolationExceptionMessage.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryConstraintViolationExceptionMessage.java index ea0bcbf75..c15129754 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryConstraintViolationExceptionMessage.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryConstraintViolationExceptionMessage.java @@ -17,28 +17,22 @@ public class RepositoryConstraintViolationExceptionMessage { private final List errors = new ArrayList(); public RepositoryConstraintViolationExceptionMessage(RepositoryConstraintViolationException violationException, - MessageSource msgSrc, - Locale locale) { + MessageSource msgSrc, Locale locale) { - for(FieldError fe : violationException.getErrors().getFieldErrors()) { + for (FieldError fe : violationException.getErrors().getFieldErrors()) { List args = new ArrayList(); args.add(fe.getObjectName()); args.add(fe.getField()); args.add(fe.getRejectedValue()); - if(null != fe.getArguments()) { - for(Object o : fe.getArguments()) { + if (null != fe.getArguments()) { + for (Object o : fe.getArguments()) { args.add(o); } } - String msg = msgSrc.getMessage(fe.getCode(), - args.toArray(), - fe.getDefaultMessage(), - locale); - this.errors.add(new ValidationError(fe.getObjectName(), - msg, - String.format("%s", fe.getRejectedValue()), - fe.getField())); + String msg = msgSrc.getMessage(fe.getCode(), args.toArray(), fe.getDefaultMessage(), locale); + this.errors.add(new ValidationError(fe.getObjectName(), msg, String.format("%s", fe.getRejectedValue()), fe + .getField())); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinks.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinks.java index ec997b7d0..cd7d98c5d 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinks.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinks.java @@ -22,9 +22,9 @@ public class RepositoryEntityLinks extends AbstractEntityLinks { @Autowired public RepositoryEntityLinks(Repositories repositories, ResourceMappings mappings, RepositoryRestConfiguration config) { - + Assert.notNull(repositories, "Repositories must not be null!"); - + this.repositories = repositories; this.mappings = mappings; this.config = config; @@ -45,7 +45,7 @@ public class RepositoryEntityLinks extends AbstractEntityLinks { */ @Override public LinkBuilder linkFor(Class type) { - + ResourceMetadata metadata = mappings.getMappingFor(type); return new RepositoryLinkBuilder(metadata, config.getBaseUri()); } @@ -65,7 +65,7 @@ public class RepositoryEntityLinks extends AbstractEntityLinks { */ @Override public Link linkToCollectionResource(Class type) { - + ResourceMetadata metadata = mappings.getMappingFor(type); return linkFor(type).withRel(metadata.getRel()); } @@ -76,7 +76,7 @@ public class RepositoryEntityLinks extends AbstractEntityLinks { */ @Override public Link linkToSingleResource(Class type, Object id) { - + ResourceMetadata metadata = mappings.getMappingFor(type); return linkFor(type).slash(id).withRel(metadata.getSingleResourceRel()); } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryLinkBuilder.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryLinkBuilder.java index 92b32132a..a67e35feb 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryLinkBuilder.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryLinkBuilder.java @@ -40,8 +40,9 @@ public class RepositoryLinkBuilder extends LinkBuilderSupport property) { - + String propName = property.getName(); - + if (metadata.isManaged(property)) { return slash(metadata.getMappingFor(property).getPath()); } else { return slash(propName); } } - + public Link withResourceRel() { return withRel(metadata.getRel()); } @@ -78,7 +79,7 @@ public class RepositoryLinkBuilder extends LinkBuilderSupport handleValidationException(RuntimeException ex, - MessageSource msgsrc, - Locale locale) { + public ResponseEntity handleValidationException(RuntimeException ex, MessageSource msgsrc, Locale locale) { Assert.isAssignable(ConstraintViolationException.class, ex.getClass()); - return new ResponseEntity( - new ConstraintViolationExceptionMessage((ConstraintViolationException)ex, - msgsrc, - locale), - HttpStatus.BAD_REQUEST + return new ResponseEntity(new ConstraintViolationExceptionMessage( + (ConstraintViolationException) ex, msgsrc, locale), HttpStatus.BAD_REQUEST ); } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AbstractWebIntegrationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AbstractWebIntegrationTests.java index b9c1bc9fa..bdd120ac8 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AbstractWebIntegrationTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AbstractWebIntegrationTests.java @@ -74,39 +74,33 @@ public abstract class AbstractWebIntegrationTests { protected MockHttpServletResponse request(String href) throws Exception { return request(href, MediaType.APPLICATION_JSON); } - + protected ResultActions follow(Link link) throws Exception { - return mvc.perform(get(link.getHref())); - } - + return mvc.perform(get(link.getHref())); + } + protected List discover(String rel) throws Exception { - return discover(new Link("/"), rel); - } - + return discover(new Link("/"), rel); + } + protected Link discoverUnique(String rel) throws Exception { - + List discover = discover(rel); assertThat(discover, hasSize(1)); return discover.get(0); } - protected List discover(Link root, String rel) throws Exception { - String s = mvc - .perform(get(root.getHref())) - .andExpect(status().isOk()) - .andExpect(hasLinkWithRel(rel)) - .andReturn().getResponse().getContentAsString(); - return links.findLinksWithRel(rel, s); - } - - protected Link discoverUnique(Link root, String rel) throws Exception { - String s = mvc - .perform(get(root.getHref())) - .andExpect(status().isOk()) - .andExpect(hasLinkWithRel(rel)) - .andReturn().getResponse().getContentAsString(); - return links.findLinkWithRel(rel, s); - } + protected List discover(Link root, String rel) throws Exception { + String s = mvc.perform(get(root.getHref())).andExpect(status().isOk()).andExpect(hasLinkWithRel(rel)).andReturn() + .getResponse().getContentAsString(); + return links.findLinksWithRel(rel, s); + } + + protected Link discoverUnique(Link root, String rel) throws Exception { + String s = mvc.perform(get(root.getHref())).andExpect(status().isOk()).andExpect(hasLinkWithRel(rel)).andReturn() + .getResponse().getContentAsString(); + return links.findLinkWithRel(rel, s); + } protected Link assertHasLinkWithRel(String rel, MockHttpServletResponse response) throws Exception { @@ -140,13 +134,13 @@ public abstract class AbstractWebIntegrationTests { @Test public void exposesRootResource() throws Exception { - + ResultActions actions = mvc.perform(get("/")).andExpect(status().isOk()); - + for (String rel : expectedRootLinkRels()) { actions.andExpect(hasLinkWithRel(rel)); } } - + protected abstract Iterable expectedRootLinkRels(); } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/CustomMethodArgumentResolverTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/CustomMethodArgumentResolverTests.java index fc3cc3a57..e732c93be 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/CustomMethodArgumentResolverTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/CustomMethodArgumentResolverTests.java @@ -47,83 +47,55 @@ public class CustomMethodArgumentResolverTests { static { try { - BASE_URI = MethodParameter.forMethodOrConstructor( - Methods.class.getDeclaredMethod("baseUri", URI.class), - 0 - ); + BASE_URI = MethodParameter.forMethodOrConstructor(Methods.class.getDeclaredMethod("baseUri", URI.class), 0); PAGE_SORT = MethodParameter.forMethodOrConstructor( - Methods.class.getDeclaredMethod("pagingAndSorting", Pageable.class), - 0 - ); - } catch(NoSuchMethodException e) { + Methods.class.getDeclaredMethod("pagingAndSorting", Pageable.class), 0); + } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } } - private final RepositoryRestConfiguration config = - new RepositoryRestConfiguration() - .setBaseUri(URI.create("http://localhost:8080")); - private final BaseUriMethodArgumentResolver baseUriResolver = - new BaseUriMethodArgumentResolver(config); - private final PageableHandlerMethodArgumentResolver pageSortResolver = - new PageableHandlerMethodArgumentResolver(); + private final RepositoryRestConfiguration config = new RepositoryRestConfiguration().setBaseUri(URI + .create("http://localhost:8080")); + private final BaseUriMethodArgumentResolver baseUriResolver = new BaseUriMethodArgumentResolver(config); + private final PageableHandlerMethodArgumentResolver pageSortResolver = new PageableHandlerMethodArgumentResolver(); private ModelAndViewContainer mavContainer; - @Mock WebDataBinderFactory webDataBinderFactory; + @Mock WebDataBinderFactory webDataBinderFactory; @Before public void setup() { mavContainer = new ModelAndViewContainer(); - + pageSortResolver.setOneIndexedParameters(true); pageSortResolver.setFallbackPageable(new PageRequest(1, 5)); } @Test public void baseUriMethodArgumentResolver() throws Exception { - assertThat("Finds @BaseURI-annotated java.net.URI parameter", - baseUriResolver.supportsParameter(BASE_URI), - is(true)); + assertThat("Finds @BaseURI-annotated java.net.URI parameter", baseUriResolver.supportsParameter(BASE_URI), is(true)); // Resolve the base URI - URI baseUri = (URI)baseUriResolver.resolveArgument( - BASE_URI, - mavContainer, - new ServletWebRequest(Requests.ROOT_REQUEST), - webDataBinderFactory - ); + URI baseUri = (URI) baseUriResolver.resolveArgument(BASE_URI, mavContainer, new ServletWebRequest( + Requests.ROOT_REQUEST), webDataBinderFactory); - assertThat("Base URI should be 'http://localhost:8080'", - baseUri.toString(), - is("http://localhost:8080")); + assertThat("Base URI should be 'http://localhost:8080'", baseUri.toString(), is("http://localhost:8080")); } @Test public void pagingAndSortingMethodArgumentResolver() throws Exception { - assertThat("Finds PagingAndSorting parameter", - pageSortResolver.supportsParameter(PAGE_SORT), - is(true)); + assertThat("Finds PagingAndSorting parameter", pageSortResolver.supportsParameter(PAGE_SORT), is(true)); // Resolve Page and Sort information - Pageable pageSort = pageSortResolver.resolveArgument( - PAGE_SORT, - mavContainer, - new ServletWebRequest(Requests.PAGE_REQUEST), - webDataBinderFactory - ); + Pageable pageSort = pageSortResolver.resolveArgument(PAGE_SORT, mavContainer, new ServletWebRequest( + Requests.PAGE_REQUEST), webDataBinderFactory); - assertThat("Finds page parameter value", - pageSort.getPageNumber(), - is(1)); - assertThat("Finds limit parameter value", - pageSort.getPageSize(), - is(10)); + assertThat("Finds page parameter value", pageSort.getPageNumber(), is(1)); + assertThat("Finds limit parameter value", pageSort.getPageSize(), is(10)); } static class Methods { - void baseUri(@BaseURI URI baseUri) { - } + void baseUri(@BaseURI URI baseUri) {} - void pagingAndSorting(Pageable pageSort) { - } + void pagingAndSorting(Pageable pageSort) {} } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/HttpEntityMatcher.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/HttpEntityMatcher.java index 89cb22799..1be15b70a 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/HttpEntityMatcher.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/HttpEntityMatcher.java @@ -11,40 +11,41 @@ import org.springframework.util.Assert; */ class HttpEntityMatcher extends BaseMatcher> { - private final HttpEntity expected; + private final HttpEntity expected; - public HttpEntityMatcher(HttpEntity expected) { - Assert.notNull(expected, "HttpEntity cannot be null"); - this.expected = expected; - } + public HttpEntityMatcher(HttpEntity expected) { + Assert.notNull(expected, "HttpEntity cannot be null"); + this.expected = expected; + } - public static HttpEntityMatcher httpEntity(HttpEntity httpEntity) { - return new HttpEntityMatcher(httpEntity); - } + public static HttpEntityMatcher httpEntity(HttpEntity httpEntity) { + return new HttpEntityMatcher(httpEntity); + } - @Override public boolean matches(Object item) { - if(!(item instanceof HttpEntity)) { - return false; - } + @Override + public boolean matches(Object item) { + if (!(item instanceof HttpEntity)) { + return false; + } - if(item instanceof ResponseEntity && expected instanceof ResponseEntity) { - ResponseEntity left = (ResponseEntity)expected; - ResponseEntity right = (ResponseEntity)item; + if (item instanceof ResponseEntity && expected instanceof ResponseEntity) { + ResponseEntity left = (ResponseEntity) expected; + ResponseEntity right = (ResponseEntity) item; - if(!left.getStatusCode().equals(right.getStatusCode())) { - return false; - } - } + if (!left.getStatusCode().equals(right.getStatusCode())) { + return false; + } + } - HttpEntity left = expected; - HttpEntity right = (HttpEntity)item; + HttpEntity left = expected; + HttpEntity right = (HttpEntity) item; - return left.getBody().equals(right.getBody()) - && left.getHeaders().equals(right.getHeaders()); - } + return left.getBody().equals(right.getBody()) && left.getHeaders().equals(right.getHeaders()); + } - @Override public void describeTo(Description description) { - description.appendText(expected.toString()); - } + @Override + public void describeTo(Description description) { + description.appendText(expected.toString()); + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestMvcTestConfig.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestMvcTestConfig.java index 7b108bba0..8fdc794fa 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestMvcTestConfig.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestMvcTestConfig.java @@ -11,10 +11,5 @@ import org.springframework.data.rest.webmvc.mongodb.MongoDbRepositoryConfig; * @author Jon Brisbin */ @Configuration -@Import({ - JpaRepositoryConfig.class, - MongoDbRepositoryConfig.class, - GemfireRepositoryConfig.class - }) -public class RepositoryRestMvcTestConfig extends RepositoryRestMvcConfiguration { -} +@Import({ JpaRepositoryConfig.class, MongoDbRepositoryConfig.class, GemfireRepositoryConfig.class }) +public class RepositoryRestMvcTestConfig extends RepositoryRestMvcConfiguration {} diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/Requests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/Requests.java index e2890c11c..3a90c6d71 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/Requests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/Requests.java @@ -7,15 +7,14 @@ import org.springframework.mock.web.MockHttpServletRequest; */ public abstract class Requests { - public static MockHttpServletRequest ROOT_REQUEST = new MockHttpServletRequest("GET", "http://localhost:8080/"); - public static MockHttpServletRequest PAGE_REQUEST = new MockHttpServletRequest("GET", "http://localhost:8080/"); + public static MockHttpServletRequest ROOT_REQUEST = new MockHttpServletRequest("GET", "http://localhost:8080/"); + public static MockHttpServletRequest PAGE_REQUEST = new MockHttpServletRequest("GET", "http://localhost:8080/"); - static { - PAGE_REQUEST.setParameter("page", "2"); - PAGE_REQUEST.setParameter("size", "10"); - } + static { + PAGE_REQUEST.setParameter("page", "2"); + PAGE_REQUEST.setParameter("size", "10"); + } - private Requests() { - } + private Requests() {} } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/ResourceProcessorHandlerMethodReturnValueHandlerUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/ResourceProcessorHandlerMethodReturnValueHandlerUnitTests.java index 34725784c..840154e76 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/ResourceProcessorHandlerMethodReturnValueHandlerUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/ResourceProcessorHandlerMethodReturnValueHandlerUnitTests.java @@ -50,278 +50,269 @@ import org.springframework.web.method.support.ModelAndViewContainer; /** * Unit tests for {@link org.springframework.data.rest.webmvc.ResourceProcessorHandlerMethodReturnValueHandler}. - * + * * @author Oliver Gierke * @author Jon Brisbin */ @RunWith(MockitoJUnitRunner.class) public class ResourceProcessorHandlerMethodReturnValueHandlerUnitTests { - static final Resource FOO = new Resource("foo"); - static final Resources> FOOS = new Resources>( - Collections.singletonList(FOO) - ); - static final StringResource FOO_RES = new StringResource("foo"); - static final HttpEntity> FOO_ENTITY = new HttpEntity>(FOO); - static final ResponseEntity> FOO_RESP_ENTITY = new ResponseEntity>( - FOO, - HttpStatus.OK - ); - static final HttpEntity FOO_RES_ENTITY = new HttpEntity(FOO_RES); - static final Resource BAR = new Resource("bar"); - static final Resources> BARS = new Resources>( - Collections.singletonList(BAR) - ); - static final StringResource BAR_RES = new StringResource("bar"); - static final HttpEntity> BAR_ENTITY = new HttpEntity>(BAR); - static final ResponseEntity> BAR_RESP_ENTITY = new ResponseEntity>( - BAR, - HttpStatus.OK - ); - static final HttpEntity BAR_RES_ENTITY = new HttpEntity(BAR_RES); - static final Resource LONG_10 = new Resource(10L); - static final Resource LONG_20 = new Resource(20L); - static final LongResource LONG_10_RES = new LongResource(10L); - static final LongResource LONG_20_RES = new LongResource(20L); - static final HttpEntity> LONG_10_ENTITY = new HttpEntity>(LONG_10); - static final HttpEntity LONG_10_RES_ENTITY = new HttpEntity(LONG_10_RES); - static final HttpEntity> LONG_20_ENTITY = new HttpEntity>(LONG_20); - static final HttpEntity LONG_20_RES_ENTITY = new HttpEntity(LONG_20_RES); - static final Map METHOD_PARAMS = new HashMap(); + static final Resource FOO = new Resource("foo"); + static final Resources> FOOS = new Resources>(Collections.singletonList(FOO)); + static final StringResource FOO_RES = new StringResource("foo"); + static final HttpEntity> FOO_ENTITY = new HttpEntity>(FOO); + static final ResponseEntity> FOO_RESP_ENTITY = new ResponseEntity>(FOO, + HttpStatus.OK); + static final HttpEntity FOO_RES_ENTITY = new HttpEntity(FOO_RES); + static final Resource BAR = new Resource("bar"); + static final Resources> BARS = new Resources>(Collections.singletonList(BAR)); + static final StringResource BAR_RES = new StringResource("bar"); + static final HttpEntity> BAR_ENTITY = new HttpEntity>(BAR); + static final ResponseEntity> BAR_RESP_ENTITY = new ResponseEntity>(BAR, + HttpStatus.OK); + static final HttpEntity BAR_RES_ENTITY = new HttpEntity(BAR_RES); + static final Resource LONG_10 = new Resource(10L); + static final Resource LONG_20 = new Resource(20L); + static final LongResource LONG_10_RES = new LongResource(10L); + static final LongResource LONG_20_RES = new LongResource(20L); + static final HttpEntity> LONG_10_ENTITY = new HttpEntity>(LONG_10); + static final HttpEntity LONG_10_RES_ENTITY = new HttpEntity(LONG_10_RES); + static final HttpEntity> LONG_20_ENTITY = new HttpEntity>(LONG_20); + static final HttpEntity LONG_20_RES_ENTITY = new HttpEntity(LONG_20_RES); + static final Map METHOD_PARAMS = new HashMap(); - static { - doWithMethods(Controller.class, new MethodCallback() { - @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - METHOD_PARAMS.put(method.getName(), new MethodParameter(method, -1)); - } - }); - } + static { + doWithMethods(Controller.class, new MethodCallback() { + @Override + public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + METHOD_PARAMS.put(method.getName(), new MethodParameter(method, -1)); + } + }); + } - @Mock HandlerMethodReturnValueHandler delegate; - List> resourceProcessors; + @Mock HandlerMethodReturnValueHandler delegate; + List> resourceProcessors; - @Before - public void setUp() { - resourceProcessors = new ArrayList>(); - } + @Before + public void setUp() { + resourceProcessors = new ArrayList>(); + } - @Test - public void supportsIfDelegateSupports() { - assertSupport(true); - } + @Test + public void supportsIfDelegateSupports() { + assertSupport(true); + } - @Test - public void doesNotSupportIfDelegateDoesNot() { - assertSupport(false); - } + @Test + public void doesNotSupportIfDelegateDoesNot() { + assertSupport(false); + } - @Test - public void postProcessesStringResource() throws Exception { - resourceProcessors.add(StringResourceProcessor.INSTANCE); - resourceProcessors.add(LongResourceProcessor.INSTANCE); + @Test + public void postProcessesStringResource() throws Exception { + resourceProcessors.add(StringResourceProcessor.INSTANCE); + resourceProcessors.add(LongResourceProcessor.INSTANCE); - invokeReturnValueHandler("stringResourceEntity", is(BAR), FOO); - } + invokeReturnValueHandler("stringResourceEntity", is(BAR), FOO); + } - @Test - public void postProcessesStringResourceInResponseEntity() throws Exception { - resourceProcessors.add(StringResourceProcessor.INSTANCE); - resourceProcessors.add(LongResourceProcessor.INSTANCE); + @Test + public void postProcessesStringResourceInResponseEntity() throws Exception { + resourceProcessors.add(StringResourceProcessor.INSTANCE); + resourceProcessors.add(LongResourceProcessor.INSTANCE); - invokeReturnValueHandler("stringResourceEntity", httpEntity(BAR_RESP_ENTITY), FOO_RESP_ENTITY); - } + invokeReturnValueHandler("stringResourceEntity", httpEntity(BAR_RESP_ENTITY), FOO_RESP_ENTITY); + } - @Test - public void postProcessesStringResourceInWildcardResponseEntity() throws Exception { - resourceProcessors.add(StringResourceProcessor.INSTANCE); - resourceProcessors.add(LongResourceProcessor.INSTANCE); + @Test + public void postProcessesStringResourceInWildcardResponseEntity() throws Exception { + resourceProcessors.add(StringResourceProcessor.INSTANCE); + resourceProcessors.add(LongResourceProcessor.INSTANCE); - invokeReturnValueHandler("resourceEntity", httpEntity(BAR_RESP_ENTITY), FOO_RESP_ENTITY); - } + invokeReturnValueHandler("resourceEntity", httpEntity(BAR_RESP_ENTITY), FOO_RESP_ENTITY); + } - @Test - public void postProcessesStringResources() throws Exception { - resourceProcessors.add(StringResourcesProcessor.INSTANCE); - resourceProcessors.add(LongResourceProcessor.INSTANCE); + @Test + public void postProcessesStringResources() throws Exception { + resourceProcessors.add(StringResourcesProcessor.INSTANCE); + resourceProcessors.add(LongResourceProcessor.INSTANCE); - invokeReturnValueHandler("resources", is(BARS), FOOS); - } + invokeReturnValueHandler("resources", is(BARS), FOOS); + } - @Test - public void postProcessesSpecializedStringResource() throws Exception { - resourceProcessors.add(SpecializedStringResourceProcessor.INSTANCE); - resourceProcessors.add(LongResourceProcessor.INSTANCE); + @Test + public void postProcessesSpecializedStringResource() throws Exception { + resourceProcessors.add(SpecializedStringResourceProcessor.INSTANCE); + resourceProcessors.add(LongResourceProcessor.INSTANCE); - invokeReturnValueHandler("stringResourceEntity", httpEntity(BAR_RES_ENTITY), FOO_RES_ENTITY); - } + invokeReturnValueHandler("stringResourceEntity", httpEntity(BAR_RES_ENTITY), FOO_RES_ENTITY); + } - @Test - public void postProcessesSpecializedStringUsingStringResourceProcessor() throws Exception { - resourceProcessors.add(StringResourceProcessor.INSTANCE); - resourceProcessors.add(LongResourceProcessor.INSTANCE); + @Test + public void postProcessesSpecializedStringUsingStringResourceProcessor() throws Exception { + resourceProcessors.add(StringResourceProcessor.INSTANCE); + resourceProcessors.add(LongResourceProcessor.INSTANCE); - invokeReturnValueHandler("specializedStringResourceEntity", httpEntity(BAR_ENTITY), FOO_RES_ENTITY); - } + invokeReturnValueHandler("specializedStringResourceEntity", httpEntity(BAR_ENTITY), FOO_RES_ENTITY); + } - @Test - public void postProcessesLongResource() throws Exception { - resourceProcessors.add(StringResourceProcessor.INSTANCE); - resourceProcessors.add(LongResourceProcessor.INSTANCE); + @Test + public void postProcessesLongResource() throws Exception { + resourceProcessors.add(StringResourceProcessor.INSTANCE); + resourceProcessors.add(LongResourceProcessor.INSTANCE); - invokeReturnValueHandler("longResource", is(LONG_20), LONG_10); - } + invokeReturnValueHandler("longResource", is(LONG_20), LONG_10); + } - @Test - public void postProcessesSpecializedLongResource() throws Exception { - resourceProcessors.add(StringResourceProcessor.INSTANCE); - resourceProcessors.add(SpecializedLongResourceProcessor.INSTANCE); + @Test + public void postProcessesSpecializedLongResource() throws Exception { + resourceProcessors.add(StringResourceProcessor.INSTANCE); + resourceProcessors.add(SpecializedLongResourceProcessor.INSTANCE); - invokeReturnValueHandler("specializedLongResourceEntity", httpEntity(LONG_20_RES_ENTITY), LONG_10_RES_ENTITY); - } + invokeReturnValueHandler("specializedLongResourceEntity", httpEntity(LONG_20_RES_ENTITY), LONG_10_RES_ENTITY); + } - @Test - public void doesNotPostProcesseLongResourceWithSpecializedLongResourceProcessor() throws Exception { - resourceProcessors.add(StringResourceProcessor.INSTANCE); - resourceProcessors.add(SpecializedLongResourceProcessor.INSTANCE); + @Test + public void doesNotPostProcesseLongResourceWithSpecializedLongResourceProcessor() throws Exception { + resourceProcessors.add(StringResourceProcessor.INSTANCE); + resourceProcessors.add(SpecializedLongResourceProcessor.INSTANCE); - invokeReturnValueHandler("numberResourceEntity", httpEntity(LONG_10_ENTITY), LONG_10_ENTITY); - } + invokeReturnValueHandler("numberResourceEntity", httpEntity(LONG_10_ENTITY), LONG_10_ENTITY); + } - @Test - public void postProcessesSpecializedLongResourceUsingLongResourceProcessor() throws Exception { - resourceProcessors.add(StringResourceProcessor.INSTANCE); - resourceProcessors.add(LongResourceProcessor.INSTANCE); + @Test + public void postProcessesSpecializedLongResourceUsingLongResourceProcessor() throws Exception { + resourceProcessors.add(StringResourceProcessor.INSTANCE); + resourceProcessors.add(LongResourceProcessor.INSTANCE); + + invokeReturnValueHandler("resourceEntity", is(LONG_20), LONG_10_RES); + } + + @Test + public void usesHeaderLinksResponseEntityIfConfigured() throws Exception { + + Resource resource = new Resource("foo", new Link("href", "rel")); + MethodParameter parameter = METHOD_PARAMS.get("resource"); + + ResourceProcessorHandlerMethodReturnValueHandler handler = new ResourceProcessorHandlerMethodReturnValueHandler( + delegate, resourceProcessors); + handler.setRootLinksAsHeaders(true); + handler.handleReturnValue(resource, parameter, null, null); - invokeReturnValueHandler("resourceEntity", is(LONG_20), LONG_10_RES); - } - - @Test - public void usesHeaderLinksResponseEntityIfConfigured() throws Exception { - - Resource resource = new Resource("foo", new Link("href", "rel")); - MethodParameter parameter = METHOD_PARAMS.get("resource"); - - ResourceProcessorHandlerMethodReturnValueHandler handler = new ResourceProcessorHandlerMethodReturnValueHandler(delegate, resourceProcessors); - handler.setRootLinksAsHeaders(true); - handler.handleReturnValue(resource, parameter, null, null); - verify(delegate, times(1)).handleReturnValue(Mockito.any(HeaderLinksResponseEntity.class), eq(parameter), Mockito.any(ModelAndViewContainer.class), Mockito.any(NativeWebRequest.class)); - } + } - // Helpers ---------------------------------------------------------// - private void invokeReturnValueHandler(String method, - final Matcher matcher, - Object returnValue) throws Exception { - final MethodParameter methodParam = METHOD_PARAMS.get(method); + // Helpers ---------------------------------------------------------// + private void invokeReturnValueHandler(String method, final Matcher matcher, Object returnValue) throws Exception { + final MethodParameter methodParam = METHOD_PARAMS.get(method); - if (methodParam == null) { - throw new IllegalArgumentException("Invalid method!"); - } + if (methodParam == null) { + throw new IllegalArgumentException("Invalid method!"); + } - HandlerMethodReturnValueHandler handler = new ResourceProcessorHandlerMethodReturnValueHandler( - delegate, - resourceProcessors - ); - handler.handleReturnValue(returnValue, methodParam, null, null); - } + HandlerMethodReturnValueHandler handler = new ResourceProcessorHandlerMethodReturnValueHandler(delegate, + resourceProcessors); + handler.handleReturnValue(returnValue, methodParam, null, null); + } - private void assertSupport(boolean value) { + private void assertSupport(boolean value) { - final MethodParameter parameter = Mockito.mock(MethodParameter.class); - when(delegate.supportsReturnType(Mockito.any(MethodParameter.class))).thenReturn(value); + final MethodParameter parameter = Mockito.mock(MethodParameter.class); + when(delegate.supportsReturnType(Mockito.any(MethodParameter.class))).thenReturn(value); - HandlerMethodReturnValueHandler handler = new ResourceProcessorHandlerMethodReturnValueHandler( - delegate, - resourceProcessors - ); + HandlerMethodReturnValueHandler handler = new ResourceProcessorHandlerMethodReturnValueHandler(delegate, + resourceProcessors); - assertThat(handler.supportsReturnType(parameter), is(value)); - } + assertThat(handler.supportsReturnType(parameter), is(value)); + } - enum StringResourceProcessor implements ResourceProcessor> { - INSTANCE; + enum StringResourceProcessor implements ResourceProcessor> { + INSTANCE; - @Override public Resource process(Resource resource) { - return BAR; - } - } + @Override + public Resource process(Resource resource) { + return BAR; + } + } - enum LongResourceProcessor implements ResourceProcessor> { - INSTANCE; + enum LongResourceProcessor implements ResourceProcessor> { + INSTANCE; - @Override public Resource process(Resource resource) { - return LONG_20; - } - } + @Override + public Resource process(Resource resource) { + return LONG_20; + } + } - enum StringResourcesProcessor implements ResourceProcessor>> { - INSTANCE; + enum StringResourcesProcessor implements ResourceProcessor>> { + INSTANCE; - @Override public Resources> process(Resources> resource) { - return BARS; - } - } + @Override + public Resources> process(Resources> resource) { + return BARS; + } + } - enum SpecializedStringResourceProcessor implements ResourceProcessor { - INSTANCE; + enum SpecializedStringResourceProcessor implements ResourceProcessor { + INSTANCE; - @Override - public StringResource process(StringResource resource) { - return BAR_RES; - } - } + @Override + public StringResource process(StringResource resource) { + return BAR_RES; + } + } - enum SpecializedLongResourceProcessor implements ResourceProcessor { - INSTANCE; + enum SpecializedLongResourceProcessor implements ResourceProcessor { + INSTANCE; - @Override - public LongResource process(LongResource resource) { - return LONG_20_RES; - } - } + @Override + public LongResource process(LongResource resource) { + return LONG_20_RES; + } + } - static interface Controller { + static interface Controller { - Resources> resources(); + Resources> resources(); - Resource resource(); + Resource resource(); - Resource longResource(); + Resource longResource(); - StringResource specializedResource(); + StringResource specializedResource(); - Object object(); + Object object(); - HttpEntity> resourceEntity(); + HttpEntity> resourceEntity(); - HttpEntity> resourcesEntity(); + HttpEntity> resourcesEntity(); - HttpEntity objectEntity(); + HttpEntity objectEntity(); - HttpEntity> stringResourceEntity(); + HttpEntity> stringResourceEntity(); - HttpEntity> numberResourceEntity(); + HttpEntity> numberResourceEntity(); - HttpEntity specializedStringResourceEntity(); + HttpEntity specializedStringResourceEntity(); - HttpEntity specializedLongResourceEntity(); + HttpEntity specializedLongResourceEntity(); - ResponseEntity> resourceResponseEntity(); + ResponseEntity> resourceResponseEntity(); - ResponseEntity> resourcesResponseEntity(); - } + ResponseEntity> resourcesResponseEntity(); + } - static class StringResource extends Resource { - public StringResource(String value) { - super(value); - } - } + static class StringResource extends Resource { + public StringResource(String value) { + super(value); + } + } - static class LongResource extends Resource { - public LongResource(Long value) { - super(value); - } - } + static class LongResource extends Resource { + public LongResource(Long value) { + super(value); + } + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvConfigurationIntegrationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvConfigurationIntegrationTests.java index adc3591d0..50606ec2e 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvConfigurationIntegrationTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvConfigurationIntegrationTests.java @@ -36,7 +36,7 @@ public class RepositoryRestMvConfigurationIntegrationTests { public static void setUp() { context = new AnnotationConfigApplicationContext(ExtendingConfiguration.class); } - + @AfterClass public static void tearDown() { if (context != null) { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/GemfireRepositoryConfig.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/GemfireRepositoryConfig.java index 8f5f9c08a..76395bd22 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/GemfireRepositoryConfig.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/GemfireRepositoryConfig.java @@ -21,7 +21,7 @@ import org.springframework.data.gemfire.repository.config.EnableGemfireRepositor /** * Spring JavaConfig configuration class to setup a Spring container and infrastructure components. - * + * * @author Oliver Gierke * @author David Turanski */ diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/AbstractPersistentEntity.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/AbstractPersistentEntity.java index 8eb8f6b6f..0bb0f21f0 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/AbstractPersistentEntity.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/AbstractPersistentEntity.java @@ -25,8 +25,7 @@ import org.springframework.data.annotation.Id; */ public class AbstractPersistentEntity { - @Id - private final Long id; + @Id private final Long id; /** * Returns the identifier of the entity. @@ -36,15 +35,14 @@ public class AbstractPersistentEntity { public Long getId() { return id; } - + protected AbstractPersistentEntity(Long id) { this.id = id; } - + protected AbstractPersistentEntity() { this.id = null; } - /* * (non-Javadoc) diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Address.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Address.java index 2a4306d95..ce09eeffe 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Address.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Address.java @@ -28,7 +28,7 @@ public class Address { /** * Creates a new {@link Address} from the given street, city and country. - * + * * @param street must not be {@literal null} or empty. * @param city must not be {@literal null} or empty. * @param country must not be {@literal null} or empty. diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Customer.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Customer.java index 36f07f8f9..a111b7a6a 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Customer.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Customer.java @@ -22,117 +22,110 @@ import java.util.Set; import org.springframework.data.gemfire.mapping.Region; import org.springframework.util.Assert; - /** * A customer. - * + * * @author Oliver Gierke * @author David Turanski */ @Region public class Customer extends AbstractPersistentEntity { - private EmailAddress emailAddress; - private String firstname, lastname; - private Set
addresses = new HashSet
(); + private EmailAddress emailAddress; + private String firstname, lastname; + private Set
addresses = new HashSet
(); - /** - * Creates a new {@link Customer} from the given parameters. - * - * @param id - * the unique id; - * @param emailAddress - * must not be {@literal null} or empty. - * @param firstname - * must not be {@literal null} or empty. - * @param lastname - * must not be {@literal null} or empty. - */ - public Customer(Long id, EmailAddress emailAddress, String firstname, String lastname) { - super(id); - Assert.hasText(firstname); - Assert.hasText(lastname); - Assert.notNull(emailAddress); + /** + * Creates a new {@link Customer} from the given parameters. + * + * @param id the unique id; + * @param emailAddress must not be {@literal null} or empty. + * @param firstname must not be {@literal null} or empty. + * @param lastname must not be {@literal null} or empty. + */ + public Customer(Long id, EmailAddress emailAddress, String firstname, String lastname) { + super(id); + Assert.hasText(firstname); + Assert.hasText(lastname); + Assert.notNull(emailAddress); - this.firstname = firstname; - this.lastname = lastname; - this.emailAddress = emailAddress; - } + this.firstname = firstname; + this.lastname = lastname; + this.emailAddress = emailAddress; + } - protected Customer() { - } + protected Customer() {} - /** - * Adds the given {@link Address} to the {@link Customer}. - * - * @param address - * must not be {@literal null}. - */ - public void add(Address address) { + /** + * Adds the given {@link Address} to the {@link Customer}. + * + * @param address must not be {@literal null}. + */ + public void add(Address address) { - Assert.notNull(address); - this.addresses.add(address); - } + Assert.notNull(address); + this.addresses.add(address); + } - /** - * Returns the firstname of the {@link Customer}. - * - * @return - */ - public String getFirstname() { - return firstname; - } + /** + * Returns the firstname of the {@link Customer}. + * + * @return + */ + public String getFirstname() { + return firstname; + } - /** - * Sets the firstname of the {@link Customer}. - * - * @param firstname - */ - public void setFirstname(String firstname) { - this.firstname = firstname; - } + /** + * Sets the firstname of the {@link Customer}. + * + * @param firstname + */ + public void setFirstname(String firstname) { + this.firstname = firstname; + } - /** - * Returns the lastname of the {@link Customer}. - * - * @return - */ - public String getLastname() { - return lastname; - } + /** + * Returns the lastname of the {@link Customer}. + * + * @return + */ + public String getLastname() { + return lastname; + } - /** - * Sets the lastname of the {@link Customer}. - * - * @param lastname - */ - public void setLastname(String lastname) { - this.lastname = lastname; - } + /** + * Sets the lastname of the {@link Customer}. + * + * @param lastname + */ + public void setLastname(String lastname) { + this.lastname = lastname; + } - /** - * Returns the {@link EmailAddress} of the {@link Customer}. - * - * @return - */ - public EmailAddress getEmailAddress() { - return emailAddress; - } + /** + * Returns the {@link EmailAddress} of the {@link Customer}. + * + * @return + */ + public EmailAddress getEmailAddress() { + return emailAddress; + } - /** - * Sets the emailAddress of the {@link Customer}. - * - * @param emailAddress - */ - public void setEmailAddress(EmailAddress emailAddress) { - this.emailAddress = emailAddress; - } + /** + * Sets the emailAddress of the {@link Customer}. + * + * @param emailAddress + */ + public void setEmailAddress(EmailAddress emailAddress) { + this.emailAddress = emailAddress; + } - /** - * Return the {@link Customer}'s addresses. - * - * @return - */ - public Set
getAddresses() { - return Collections.unmodifiableSet(addresses); - } + /** + * Return the {@link Customer}'s addresses. + * + * @return + */ + public Set
getAddresses() { + return Collections.unmodifiableSet(addresses); + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/CustomerRepository.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/CustomerRepository.java index 9e02d14ca..be0456306 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/CustomerRepository.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/CustomerRepository.java @@ -22,29 +22,27 @@ import org.springframework.data.repository.query.Param; /** * Repository interface to access {@link Customer}s. - * + * * @author Oliver Gierke * @author David Turanski */ public interface CustomerRepository extends CrudRepository { - /** - * Finds all {@link Customer}s with the given lastname. - * - * @param lastname - * - * @return - */ - List findByLastname(@Param("lastname") String lastname); + /** + * Finds all {@link Customer}s with the given lastname. + * + * @param lastname + * @return + */ + List findByLastname(@Param("lastname") String lastname); - /** - * Finds the Customer with the given {@link EmailAddress}. - * - * @param emailAddress - * - * @return - */ - Customer findByEmailAddress(@Param("email") EmailAddress emailAddress); + /** + * Finds the Customer with the given {@link EmailAddress}. + * + * @param emailAddress + * @return + */ + Customer findByEmailAddress(@Param("email") EmailAddress emailAddress); } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/EmailAddress.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/EmailAddress.java index 692fd4629..91bb4222a 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/EmailAddress.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/EmailAddress.java @@ -27,100 +27,97 @@ import org.springframework.util.StringUtils; /** * Value object to represent email addresses. - * + * * @author Oliver Gierke */ @JsonSerialize(using = ToStringSerializer.class) public final class EmailAddress { - private static final String EMAIL_REGEX = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - private static final Pattern PATTERN = Pattern.compile(EMAIL_REGEX); - private final String value; + private static final String EMAIL_REGEX = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; + private static final Pattern PATTERN = Pattern.compile(EMAIL_REGEX); + private final String value; - /** - * Creates a new {@link EmailAddress} from the given {@link String} representation. - * - * @param emailAddress - * must not be {@literal null} or empty. - */ - @JsonCreator - public EmailAddress(String emailAddress) { - Assert.isTrue(isValid(emailAddress), "Invalid email address!"); - this.value = emailAddress; - } + /** + * Creates a new {@link EmailAddress} from the given {@link String} representation. + * + * @param emailAddress must not be {@literal null} or empty. + */ + @JsonCreator + public EmailAddress(String emailAddress) { + Assert.isTrue(isValid(emailAddress), "Invalid email address!"); + this.value = emailAddress; + } - /** - * Returns whether the given {@link String} is a valid {@link EmailAddress} which means you can safely instantiate - * the - * class. - * - * @param candidate - * - * @return - */ - public static boolean isValid(String candidate) { - return candidate == null ? false : PATTERN.matcher(candidate).matches(); - } + /** + * Returns whether the given {@link String} is a valid {@link EmailAddress} which means you can safely instantiate the + * class. + * + * @param candidate + * @return + */ + public static boolean isValid(String candidate) { + return candidate == null ? false : PATTERN.matcher(candidate).matches(); + } - /* - * (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return value; - } + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return value; + } - /* - * (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { + /* + * (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { - if(this == obj) { - return true; - } + if (this == obj) { + return true; + } - if(!(obj instanceof EmailAddress)) { - return false; - } + if (!(obj instanceof EmailAddress)) { + return false; + } - EmailAddress that = (EmailAddress)obj; - return this.value.equals(that.value); - } + EmailAddress that = (EmailAddress) obj; + return this.value.equals(that.value); + } - /* - * (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return value.hashCode(); - } + /* + * (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return value.hashCode(); + } - @Component - static class EmailAddressToStringConverter implements Converter { + @Component + static class EmailAddressToStringConverter implements Converter { - /* - * (non-Javadoc) - * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object) - */ - @Override - public String convert(EmailAddress source) { - return source == null ? null : source.value; - } - } + /* + * (non-Javadoc) + * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object) + */ + @Override + public String convert(EmailAddress source) { + return source == null ? null : source.value; + } + } - @Component - static class StringToEmailAddressConverter implements Converter { + @Component + static class StringToEmailAddressConverter implements Converter { - /* - * (non-Javadoc) - * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object) - */ - public EmailAddress convert(String source) { - return StringUtils.hasText(source) ? new EmailAddress(source) : null; - } - } + /* + * (non-Javadoc) + * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object) + */ + public EmailAddress convert(String source) { + return StringUtils.hasText(source) ? new EmailAddress(source) : null; + } + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Product.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Product.java index 6c033c765..72f805f7c 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Product.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/Product.java @@ -24,110 +24,101 @@ import org.springframework.data.annotation.PersistenceConstructor; import org.springframework.data.gemfire.mapping.Region; import org.springframework.util.Assert; - /** * A product. - * + * * @author Oliver Gierke * @author David Turanski */ @Region public class Product extends AbstractPersistentEntity { - private String name, description; - private BigDecimal price; - private Map attributes = new HashMap(); + private String name, description; + private BigDecimal price; + private Map attributes = new HashMap(); - /** - * Creates a new {@link Product} with the given name. - * - * @param id - * a unique Id - * @param name - * must not be {@literal null} or empty. - * @param price - * must not be {@literal null} or less than or equal to zero. - */ - public Product(Long id, String name, BigDecimal price) { - this(id, name, price, null); - } + /** + * Creates a new {@link Product} with the given name. + * + * @param id a unique Id + * @param name must not be {@literal null} or empty. + * @param price must not be {@literal null} or less than or equal to zero. + */ + public Product(Long id, String name, BigDecimal price) { + this(id, name, price, null); + } - /** - * Creates a new {@link Product} from the given name and description. - * - * @param id - * a unique Id - * @param name - * must not be {@literal null} or empty. - * @param price - * must not be {@literal null} or less than or equal to zero. - * @param description - */ - @PersistenceConstructor - public Product(Long id, String name, BigDecimal price, String description) { - super(id); - Assert.hasText(name, "Name must not be null or empty!"); - Assert.isTrue(BigDecimal.ZERO.compareTo(price) < 0, "Price must be greater than zero!"); + /** + * Creates a new {@link Product} from the given name and description. + * + * @param id a unique Id + * @param name must not be {@literal null} or empty. + * @param price must not be {@literal null} or less than or equal to zero. + * @param description + */ + @PersistenceConstructor + public Product(Long id, String name, BigDecimal price, String description) { + super(id); + Assert.hasText(name, "Name must not be null or empty!"); + Assert.isTrue(BigDecimal.ZERO.compareTo(price) < 0, "Price must be greater than zero!"); - this.name = name; - this.price = price; - this.description = description; - } + this.name = name; + this.price = price; + this.description = description; + } - protected Product() { - } + protected Product() {} - /** - * Sets the attribute with the given name to the given value. - * - * @param name - * must not be {@literal null} or empty. - * @param value - */ - public void setAttribute(String name, String value) { + /** + * Sets the attribute with the given name to the given value. + * + * @param name must not be {@literal null} or empty. + * @param value + */ + public void setAttribute(String name, String value) { - Assert.hasText(name); + Assert.hasText(name); - if(value == null) { - this.attributes.remove(value); - } else { - this.attributes.put(name, value); - } - } + if (value == null) { + this.attributes.remove(value); + } else { + this.attributes.put(name, value); + } + } - /** - * Returns the {@link Product}'s name. - * - * @return - */ - public String getName() { - return name; - } + /** + * Returns the {@link Product}'s name. + * + * @return + */ + public String getName() { + return name; + } - /** - * Returns the {@link Product}'s description. - * - * @return - */ - public String getDescription() { - return description; - } + /** + * Returns the {@link Product}'s description. + * + * @return + */ + public String getDescription() { + return description; + } - /** - * Returns all the custom attributes of the {@link Product}. - * - * @return - */ - public Map getAttributes() { - return Collections.unmodifiableMap(attributes); - } + /** + * Returns all the custom attributes of the {@link Product}. + * + * @return + */ + public Map getAttributes() { + return Collections.unmodifiableMap(attributes); + } - /** - * Returns the price of the {@link Product}. - * - * @return - */ - public BigDecimal getPrice() { - return price; - } + /** + * Returns the price of the {@link Product}. + * + * @return + */ + public BigDecimal getPrice() { + return price; + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/ProductRepository.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/ProductRepository.java index 383bc667c..b1e19a721 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/ProductRepository.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/core/ProductRepository.java @@ -20,7 +20,6 @@ import java.util.List; import org.springframework.data.gemfire.repository.Query; import org.springframework.data.repository.CrudRepository; - /** * Repository interface to access {@link Product}s. * @@ -31,20 +30,22 @@ public interface ProductRepository extends CrudRepository { /** * Returns a list of {@link Product}s having a description which contains the given snippet. + * * @param the search string * @return */ - + List findByDescriptionContaining(String description); /** * Returns all {@link Product}s having the given attribute value. + * * @param attribute * @param value * @return */ @Query("SELECT * FROM /Product where attributes[$1] = $2") List findByAttributes(String key, String value); - + List findByName(String name); } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/order/LineItem.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/order/LineItem.java index 9d582fe8a..a78a66499 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/order/LineItem.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/order/LineItem.java @@ -25,72 +25,69 @@ import org.springframework.util.Assert; */ public class LineItem { - private BigDecimal price; - private int amount; - private Long productId; + private BigDecimal price; + private int amount; + private Long productId; - /** - * Creates a new {@link LineItem} for the given {@link Product}. - * - * @param product - * must not be {@literal null}. - */ - public LineItem(Product product) { - this(product, 1); - } + /** + * Creates a new {@link LineItem} for the given {@link Product}. + * + * @param product must not be {@literal null}. + */ + public LineItem(Product product) { + this(product, 1); + } - /** - * Creates a new {@link LineItem} for the given {@link Product} and amount. - * - * @param product - * must not be {@literal null}. - * @param amount - */ - public LineItem(Product product, int amount) { - Assert.notNull(product, "The given Product must not be null!"); - Assert.isTrue(amount > 0, "The amount of Products to be bought must be greater than 0!"); + /** + * Creates a new {@link LineItem} for the given {@link Product} and amount. + * + * @param product must not be {@literal null}. + * @param amount + */ + public LineItem(Product product, int amount) { + Assert.notNull(product, "The given Product must not be null!"); + Assert.isTrue(amount > 0, "The amount of Products to be bought must be greater than 0!"); - this.productId = product.getId(); - this.amount = amount; - this.price = product.getPrice(); - } + this.productId = product.getId(); + this.amount = amount; + this.price = product.getPrice(); + } - protected LineItem() { - } + protected LineItem() {} - /** - * Returns the id of the {@link Product} the {@link LineItem} refers to. - * - * @return - */ - public Long getProductId() { - return productId; - } + /** + * Returns the id of the {@link Product} the {@link LineItem} refers to. + * + * @return + */ + public Long getProductId() { + return productId; + } - /** - * Returns the amount of {@link Product}s to be ordered. - * - * @return - */ - public int getAmount() { - return amount; - } + /** + * Returns the amount of {@link Product}s to be ordered. + * + * @return + */ + public int getAmount() { + return amount; + } - /** - * Returns the price a single unit of the {@link LineItem}'s product. - * - * @return the price - */ - public BigDecimal getUnitPrice() { - return price; - } + /** + * Returns the price a single unit of the {@link LineItem}'s product. + * + * @return the price + */ + public BigDecimal getUnitPrice() { + return price; + } - /** - * Returns the total for the {@link LineItem}. - * - * @return - */ - public BigDecimal getTotal() { - return price.multiply(BigDecimal.valueOf(amount)); - } + /** + * Returns the total for the {@link LineItem}. + * + * @return + */ + public BigDecimal getTotal() { + return price.multiply(BigDecimal.valueOf(amount)); + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/order/Order.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/order/Order.java index e5000fd07..c8677b2ae 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/order/Order.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/gemfire/order/Order.java @@ -32,92 +32,88 @@ import org.springframework.util.Assert; @Region public class Order extends AbstractPersistentEntity { - private Long customerId; - private Address billingAddress; - private Address shippingAddress; - private Set lineItems = new HashSet(); + private Long customerId; + private Address billingAddress; + private Address shippingAddress; + private Set lineItems = new HashSet(); - /** - * Creates a new {@link Order} for the given {@link org.springframework.data.rest.webmvc.gemfire.core.Customer}. - * - * @param id - * order ID - * @param customerId - * must not be {@literal null}. - * @param shippingAddress - * must not be {@literal null}. - */ - public Order(Long id, Long customerId, Address shippingAddress) { - super(id); - Assert.notNull(customerId); - Assert.notNull(shippingAddress); + /** + * Creates a new {@link Order} for the given {@link org.springframework.data.rest.webmvc.gemfire.core.Customer}. + * + * @param id order ID + * @param customerId must not be {@literal null}. + * @param shippingAddress must not be {@literal null}. + */ + public Order(Long id, Long customerId, Address shippingAddress) { + super(id); + Assert.notNull(customerId); + Assert.notNull(shippingAddress); - this.customerId = customerId; - this.shippingAddress = shippingAddress; - } + this.customerId = customerId; + this.shippingAddress = shippingAddress; + } - protected Order() { - } + protected Order() {} - /** - * Adds the given {@link LineItem} to the {@link Order}. - * - * @param lineItem - */ - public void add(LineItem lineItem) { - this.lineItems.add(lineItem); - } + /** + * Adds the given {@link LineItem} to the {@link Order}. + * + * @param lineItem + */ + public void add(LineItem lineItem) { + this.lineItems.add(lineItem); + } - /** - * Returns the id of the {@link org.springframework.data.rest.webmvc.gemfire.core.Customer} who placed the {@link - * Order}. - * - * @return - */ - public Long getCustomerId() { - return customerId; - } + /** + * Returns the id of the {@link org.springframework.data.rest.webmvc.gemfire.core.Customer} who placed the + * {@link Order}. + * + * @return + */ + public Long getCustomerId() { + return customerId; + } - /** - * Returns the billing {@link Address} for this order. - * - * @return - */ - public Address getBillingAddress() { - return billingAddress != null ? billingAddress : shippingAddress; - } + /** + * Returns the billing {@link Address} for this order. + * + * @return + */ + public Address getBillingAddress() { + return billingAddress != null ? billingAddress : shippingAddress; + } - /** - * Returns the shipping {@link Address} for this order; - * - * @return - */ - public Address getShippingAddress() { - return shippingAddress; - } + /** + * Returns the shipping {@link Address} for this order; + * + * @return + */ + public Address getShippingAddress() { + return shippingAddress; + } - /** - * Returns all {@link LineItem}s currently belonging to the {@link Order}. - * - * @return - */ - public Set getLineItems() { - return Collections.unmodifiableSet(lineItems); - } + /** + * Returns all {@link LineItem}s currently belonging to the {@link Order}. + * + * @return + */ + public Set getLineItems() { + return Collections.unmodifiableSet(lineItems); + } - /** - * Returns the total of the {@link Order}. - * - * @return - */ - public BigDecimal getTotal() { + /** + * Returns the total of the {@link Order}. + * + * @return + */ + public BigDecimal getTotal() { - BigDecimal total = BigDecimal.ZERO; + BigDecimal total = BigDecimal.ZERO; - for(LineItem item : lineItems) { - total = total.add(item.getTotal()); - } + for (LineItem item : lineItems) { + total = total.add(item.getTotal()); + } - return total; - } + return total; + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaRepositoryConfig.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaRepositoryConfig.java index 6a0447263..f16eaf2b0 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaRepositoryConfig.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaRepositoryConfig.java @@ -40,26 +40,29 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement public class JpaRepositoryConfig { - @Bean public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - return builder.setType(EmbeddedDatabaseType.HSQL).build(); - } + @Bean + public DataSource dataSource() { + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); + return builder.setType(EmbeddedDatabaseType.HSQL).build(); + } - @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - vendorAdapter.setDatabase(Database.HSQL); - vendorAdapter.setGenerateDdl(true); + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + vendorAdapter.setDatabase(Database.HSQL); + vendorAdapter.setGenerateDdl(true); - LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); - factory.setJpaVendorAdapter(vendorAdapter); - factory.setPackagesToScan(getClass().getPackage().getName()); - factory.setDataSource(dataSource()); - factory.afterPropertiesSet(); - - return factory; - } + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(vendorAdapter); + factory.setPackagesToScan(getClass().getPackage().getName()); + factory.setDataSource(dataSource()); + factory.afterPropertiesSet(); - @Bean public PlatformTransactionManager transactionManager() { - return new JpaTransactionManager(); - } + return factory; + } + + @Bean + public PlatformTransactionManager transactionManager() { + return new JpaTransactionManager(); + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java index 134eb49fa..6e86445ef 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java @@ -32,7 +32,7 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration(classes = JpaRepositoryConfig.class) @Transactional public class JpaWebTests extends AbstractWebIntegrationTests { - + /* * (non-Javadoc) * @see org.springframework.data.rest.webmvc.AbstractWebIntegrationTests#expectedRootLinkRels() @@ -44,16 +44,16 @@ public class JpaWebTests extends AbstractWebIntegrationTests { @Test public void accessPersons() throws Exception { - + MockHttpServletResponse response = request("/people?page=0&size=1"); - + Link nextLink = assertHasLinkWithRel(Link.REL_NEXT, response); assertDoesNotHaveLinkWithRel(Link.REL_PREVIOUS, response); - + response = request(nextLink); assertHasLinkWithRel(Link.REL_PREVIOUS, response); nextLink = assertHasLinkWithRel(Link.REL_NEXT, response); - + response = request(nextLink); assertHasLinkWithRel(Link.REL_PREVIOUS, response); assertDoesNotHaveLinkWithRel(Link.REL_NEXT, response); diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/Person.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/Person.java index 352fdc9b9..a99768d0d 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/Person.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/Person.java @@ -17,90 +17,88 @@ import org.springframework.data.rest.repository.annotation.Description; /** * An entity that represents a person. - * + * * @author Jon Brisbin */ @Entity public class Person { - private Long id; - @Description("A person's first name") - private String firstName; - @Description("A person's last name") - private String lastName; - @Description("A person's siblings") - private List siblings = Collections.emptyList(); - private Person father; - @Description("Timestamp this person object was created") - private Date created; + private Long id; + @Description("A person's first name") private String firstName; + @Description("A person's last name") private String lastName; + @Description("A person's siblings") private List siblings = Collections.emptyList(); + private Person father; + @Description("Timestamp this person object was created") private Date created; - public Person() { - } + public Person() {} - public Person(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } + public Person(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } - @Id @GeneratedValue public Long getId() { - return id; - } + @Id + @GeneratedValue + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - @NotNull - public void setLastName(String lastName) { - this.lastName = lastName; - } + @NotNull + public void setLastName(String lastName) { + this.lastName = lastName; + } - public Person addSibling(Person p) { - if(siblings == Collections.EMPTY_LIST) { - siblings = new ArrayList(); - } - siblings.add(p); - return this; - } + public Person addSibling(Person p) { + if (siblings == Collections.EMPTY_LIST) { + siblings = new ArrayList(); + } + siblings.add(p); + return this; + } - @ManyToMany public List getSiblings() { - return siblings; - } + @ManyToMany + public List getSiblings() { + return siblings; + } - public void setSiblings(List siblings) { - this.siblings = siblings; - } + public void setSiblings(List siblings) { + this.siblings = siblings; + } - @ManyToOne public Person getFather() { - return father; - } + @ManyToOne + public Person getFather() { + return father; + } - public void setFather(Person father) { - this.father = father; - } + public void setFather(Person father) { + this.father = father; + } - public Date getCreated() { - return created; - } + public Date getCreated() { + return created; + } - public void setCreated(Date created) { - } + public void setCreated(Date created) {} - @PrePersist - private void prePersist() { - this.created = Calendar.getInstance().getTime(); - } + @PrePersist + private void prePersist() { + this.created = Calendar.getInstance().getTime(); + } -} \ No newline at end of file +} diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/PersonLoader.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/PersonLoader.java index 9a84ef3c3..941be0298 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/PersonLoader.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/PersonLoader.java @@ -12,20 +12,20 @@ import org.springframework.stereotype.Component; @Component public class PersonLoader implements InitializingBean { - @Autowired - PersonRepository people; + @Autowired PersonRepository people; - @Override public void afterPropertiesSet() throws Exception { - Person billyBob = people.save(new Person("Billy Bob", "Thornton")); + @Override + public void afterPropertiesSet() throws Exception { + Person billyBob = people.save(new Person("Billy Bob", "Thornton")); - Person john = new Person("John", "Doe"); - Person jane = new Person("Jane", "Doe"); - john.addSibling(jane); - john.setFather(billyBob); - jane.addSibling(john); - jane.setFather(billyBob); + Person john = new Person("John", "Doe"); + Person jane = new Person("Jane", "Doe"); + john.addSibling(jane); + john.setFather(billyBob); + jane.addSibling(john); + jane.setFather(billyBob); - people.save(Arrays.asList(john, jane)); - } + people.save(Arrays.asList(john, jane)); + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/PersonRepository.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/PersonRepository.java index 2f0fb2e9e..48f1f2997 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/PersonRepository.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/jpa/PersonRepository.java @@ -13,24 +13,21 @@ import org.springframework.data.rest.repository.annotation.RestResource; /** * A repository to manage {@link Person}s. - * + * * @author Jon Brisbin */ @RestResource(rel = "people", path = "people") public interface PersonRepository extends PagingAndSortingRepository { - @RestResource(rel = "firstname", path = "firstname") - public Page findByFirstName(@Param("firstName") String firstName, Pageable pageable); + @RestResource(rel = "firstname", path = "firstname") + public Page findByFirstName(@Param("firstName") String firstName, Pageable pageable); - public Person findFirstPersonByFirstName(@Param("firstName") String firstName); + public Person findFirstPersonByFirstName(@Param("firstName") String firstName); - public Page findByCreatedGreaterThan(@Param("date") Date date, Pageable pageable); + public Page findByCreatedGreaterThan(@Param("date") Date date, Pageable pageable); - @Query("select p from Person p where p.created > :date") - public Page findByCreatedUsingISO8601Date(@Param("date") - @ConvertWith( - ISO8601DateConverter.class) - Date date, - Pageable pageable); + @Query("select p from Person p where p.created > :date") + public Page findByCreatedUsingISO8601Date(@Param("date") @ConvertWith(ISO8601DateConverter.class) Date date, + Pageable pageable); } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java index 1009360ea..9680b2894 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java @@ -34,14 +34,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Transactional public class PersistentEntitySerializationTests { - private static final String PERSON_JSON_IN = "{\"firstName\": \"John\",\"lastName\": \"Doe\"}"; + private static final String PERSON_JSON_IN = "{\"firstName\": \"John\",\"lastName\": \"Doe\"}"; @Autowired ObjectMapper mapper; @Autowired Repositories repositories; @Autowired PersonRepository people; - + LinkDiscoverer linkDiscoverer; - + @Before public void setUp() { linkDiscoverer = new DefaultLinkDiscoverer(); @@ -49,9 +49,9 @@ public class PersistentEntitySerializationTests { @Test public void deserializesPersonEntity() throws IOException { - + Person p = mapper.readValue(PERSON_JSON_IN, Person.class); - + assertThat(p.getFirstName(), is("John")); assertThat(p.getLastName(), is("Doe")); assertThat(p.getSiblings(), is(Collections.EMPTY_LIST)); @@ -59,18 +59,18 @@ public class PersistentEntitySerializationTests { @Test public void serializesPersonEntity() throws IOException, InterruptedException { - + PersistentEntity persistentEntity = repositories.getPersistentEntity(Person.class); Person person = people.save(new Person("John", "Doe")); - + StringWriter writer = new StringWriter(); mapper.writeValue(writer, PersistentEntityResource.wrap(persistentEntity, person)); - + String s = writer.toString(); - + Link fatherLink = linkDiscoverer.findLinkWithRel("people.people.father", s); assertThat(fatherLink.getHref(), endsWith(new UriTemplate("/{id}/father").expand(person.getId()).toString())); - + Link siblingLink = linkDiscoverer.findLinkWithRel("people.people.siblings", s); assertThat(siblingLink.getHref(), endsWith(new UriTemplate("/{id}/siblings").expand(person.getId()).toString())); } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/RepositoryTestsConfig.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/RepositoryTestsConfig.java index 9844ce5bd..f57975bdf 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/RepositoryTestsConfig.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/RepositoryTestsConfig.java @@ -24,59 +24,60 @@ import com.fasterxml.jackson.databind.ObjectMapper; * @author Jon Brisbin */ @Configuration -@Import({JpaRepositoryConfig.class}) +@Import({ JpaRepositoryConfig.class }) @SuppressWarnings("deprecation") public class RepositoryTestsConfig { - @Autowired - private ApplicationContext appCtx; + @Autowired private ApplicationContext appCtx; - @Bean public Repositories repositories() { - return new Repositories(appCtx); - } + @Bean + public Repositories repositories() { + return new Repositories(appCtx); + } - @Bean public RepositoryRestConfiguration config() { - RepositoryRestConfiguration config = new RepositoryRestConfiguration(); + @Bean + public RepositoryRestConfiguration config() { + RepositoryRestConfiguration config = new RepositoryRestConfiguration(); - config.setResourceMappingForDomainType(Person.class) - .setRel("person"); + config.setResourceMappingForDomainType(Person.class).setRel("person"); -// config.setResourceMappingForRepository(ConfiguredPersonRepository.class) -// .setRel("people") -// .setPath("people") -// .setExported(false); + // config.setResourceMappingForRepository(ConfiguredPersonRepository.class) + // .setRel("people") + // .setPath("people") + // .setExported(false); - config.setResourceMappingForRepository(PersonRepository.class) - .setRel("people") - .setPath("people") - .addResourceMappingFor("findByFirstName") - .setRel("firstname") - .setPath("firstname"); - - config.setBaseUri(URI.create("http://localhost:8080")); + config.setResourceMappingForRepository(PersonRepository.class).setRel("people").setPath("people") + .addResourceMappingFor("findByFirstName").setRel("firstname").setPath("firstname"); - return config; - } + config.setBaseUri(URI.create("http://localhost:8080")); - @Bean public DefaultFormattingConversionService defaultConversionService() { - return new DefaultFormattingConversionService(); - } + return config; + } - @Bean public DomainClassConverter domainClassConverter() { - return new DomainClassConverter(defaultConversionService()); - } + @Bean + public DefaultFormattingConversionService defaultConversionService() { + return new DefaultFormattingConversionService(); + } - @Bean public UriDomainClassConverter uriDomainClassConverter() { - return new UriDomainClassConverter(); - } + @Bean + public DomainClassConverter domainClassConverter() { + return new DomainClassConverter(defaultConversionService()); + } - @Bean public Module persistentEntityModule() { - return new PersistentEntityJackson2Module(new ResourceMappings(config(), repositories())); - } + @Bean + public UriDomainClassConverter uriDomainClassConverter() { + return new UriDomainClassConverter(); + } - @Bean public ObjectMapper objectMapper() { - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(persistentEntityModule()); - return mapper; - } + @Bean + public Module persistentEntityModule() { + return new PersistentEntityJackson2Module(new ResourceMappings(config(), repositories())); + } + + @Bean + public ObjectMapper objectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(persistentEntityModule()); + return mapper; + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/MongoDbRepositoryConfig.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/MongoDbRepositoryConfig.java index 76818aa11..4f2da5313 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/MongoDbRepositoryConfig.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/MongoDbRepositoryConfig.java @@ -34,11 +34,13 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie @EnableMongoRepositories public class MongoDbRepositoryConfig { - @Bean public MongoDbFactory mongoDbFactory() throws UnknownHostException { - return new SimpleMongoDbFactory(new Mongo("localhost"), "spring-data-rest-example"); - } + @Bean + public MongoDbFactory mongoDbFactory() throws UnknownHostException { + return new SimpleMongoDbFactory(new Mongo("localhost"), "spring-data-rest-example"); + } - @Bean public MongoTemplate mongoTemplate() throws UnknownHostException { - return new MongoTemplate(mongoDbFactory()); - } + @Bean + public MongoTemplate mongoTemplate() throws UnknownHostException { + return new MongoTemplate(mongoDbFactory()); + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/MongoWebTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/MongoWebTests.java index dc8952e7a..080a9e55c 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/MongoWebTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/MongoWebTests.java @@ -29,33 +29,32 @@ import org.springframework.hateoas.Link; import org.springframework.test.context.ContextConfiguration; /** - * * @author Oliver Gierke */ @ContextConfiguration(classes = MongoDbRepositoryConfig.class) public class MongoWebTests extends AbstractWebIntegrationTests { @Autowired ProfileRepository repository; - + @Before public void populateProfiles() { - + Profile twitter = new Profile(); twitter.setPerson(1L); twitter.setType("Twitter"); - + Profile linkedIn = new Profile(); linkedIn.setPerson(1L); linkedIn.setType("LinkedIn"); - + repository.save(Arrays.asList(twitter, linkedIn)); } - + @After public void cleanUp() { repository.deleteAll(); } - + /* * (non-Javadoc) * @see org.springframework.data.rest.webmvc.AbstractWebIntegrationTests#expectedRootLinkRels() @@ -64,11 +63,11 @@ public class MongoWebTests extends AbstractWebIntegrationTests { protected Iterable expectedRootLinkRels() { return Arrays.asList("profile"); } - + @Test public void foo() throws Exception { - + Link profileLink = discoverUnique("profile"); - follow(profileLink).andExpect(jsonPath("$.content").value(hasSize(2))); + follow(profileLink).andExpect(jsonPath("$.content").value(hasSize(2))); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/Profile.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/Profile.java index dc5931e4c..595d9e4ee 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/Profile.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/Profile.java @@ -9,36 +9,35 @@ import org.springframework.data.mongodb.core.mapping.Document; @Document public class Profile { - @Id - private String id; - private Long person; - private String type; + @Id private String id; + private Long person; + private String type; - public String getId() { - return id; - } + public String getId() { + return id; + } - public Profile setId(String id) { - this.id = id; - return this; - } + public Profile setId(String id) { + this.id = id; + return this; + } - public Long getPerson() { - return person; - } + public Long getPerson() { + return person; + } - public Profile setPerson(Long person) { - this.person = person; - return this; - } + public Profile setPerson(Long person) { + this.person = person; + return this; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public Profile setType(String type) { - this.type = type; - return this; - } + public Profile setType(String type) { + this.type = type; + return this; + } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/ProfileRepository.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/ProfileRepository.java index 0d1fa7e31..bd39f3517 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/ProfileRepository.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mongodb/ProfileRepository.java @@ -5,5 +5,4 @@ import org.springframework.data.repository.PagingAndSortingRepository; /** * @author Jon Brisbin */ -public interface ProfileRepository extends PagingAndSortingRepository { -} +public interface ProfileRepository extends PagingAndSortingRepository {}