Java tutorial
package net.eusashead.hateoas.response.impl; /* * #[license] * spring-responseentitybuilder * %% * Copyright (C) 2013 Eusa's Head * %% * 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. * %[license] */ import javax.servlet.http.HttpServletRequest; import net.eusashead.hateoas.header.ETagHeaderStrategy; import net.eusashead.hateoas.header.impl.HashingETagHeaderStrategy; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; public abstract class AbstractEntityResponseBuilder<T, V> extends AbstractResponseBuilder<T> { protected V entity; public AbstractEntityResponseBuilder(HttpServletRequest request) { super(request); } protected void setEntity(V entity) { this.entity = entity; assertEntity(); } protected void assertEntity() { if (entity == null) { throw new IllegalArgumentException("Entity T cannot be null."); } } protected void setEtagHeader() { assertEntity(); this.headers.setETag(new HashingETagHeaderStrategy().extract(entity).toString()); } protected void setEtagHeader(ETagHeaderStrategy etagStrategy) { assertEntity(); this.headers.setETag(etagStrategy.extract(entity).toString()); } protected ResponseEntity<V> buildResponseEntity(V body) { // ResponseEntity to return ResponseEntity<V> responseEntity; // Check ETag against request value if (headers.getETag() != null && compareEtagWithIfNoneMatch(headers.getETag())) { // Return 304 Not Modified responseEntity = new ResponseEntity<V>(headers, HttpStatus.NOT_MODIFIED); } else { // Is it a HEAD or a GET if (request.getMethod().equals("HEAD")) { // Return 204 and the headers responseEntity = new ResponseEntity<V>(headers, HttpStatus.NO_CONTENT); } else if (request.getMethod().equals("GET")) { // Return 200 and the entity responseEntity = new ResponseEntity<V>(body, headers, HttpStatus.OK); } else { throw new RuntimeException(String .format("esponseBuilder does not handle verb %s, only GET or HEAD.", request.getMethod())); } } // Return the ResponseEntity return responseEntity; } }