View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.syncope.core.rest.cxf;
20  
21  import java.io.IOException;
22  import javax.ws.rs.container.ContainerRequestContext;
23  import javax.ws.rs.container.ContainerResponseContext;
24  import javax.ws.rs.container.ContainerResponseFilter;
25  import javax.ws.rs.core.EntityTag;
26  import javax.ws.rs.core.HttpHeaders;
27  import javax.ws.rs.ext.Provider;
28  import org.apache.commons.lang3.StringUtils;
29  import org.apache.syncope.common.lib.to.AnyTO;
30  import org.apache.syncope.common.lib.to.EntityTO;
31  import org.apache.syncope.common.lib.to.ProvisioningResult;
32  
33  /**
34   * Adds the {@code ETag} header to any response containing an instance of {@link AnyTO} as entity.
35   * The actual ETag value is computed on the basis of last change date (or creation date if not available).
36   */
37  @Provider
38  public class AddETagFilter implements ContainerResponseFilter {
39  
40      @Override
41      public void filter(final ContainerRequestContext reqCtx, final ContainerResponseContext resCtx) throws IOException {
42          if (resCtx.getEntityTag() == null) {
43              AnyTO annotated = null;
44              if (resCtx.getEntity() instanceof AnyTO) {
45                  annotated = (AnyTO) resCtx.getEntity();
46              } else if (resCtx.getEntity() instanceof ProvisioningResult) {
47                  EntityTO entity = ((ProvisioningResult<?>) resCtx.getEntity()).getEntity();
48                  if (entity instanceof AnyTO) {
49                      annotated = (AnyTO) entity;
50                  }
51              }
52              if (annotated != null) {
53                  String etagValue = annotated.getETagValue();
54                  if (StringUtils.isNotBlank(etagValue)) {
55                      resCtx.getHeaders().add(HttpHeaders.ETAG, new EntityTag(etagValue).toString());
56                  }
57              }
58          }
59      }
60  }