View Javadoc

1   /**
2    * Copyright © 2018 spring-data-dynamodb (https://github.com/derjust/spring-data-dynamodb)
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.socialsignin.spring.data.dynamodb.marshaller;
17  
18  import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshaller;
19  import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverter;
20  import org.springframework.util.StringUtils;
21  
22  import java.time.Instant;
23  import java.time.ZoneOffset;
24  import java.time.format.DateTimeFormatter;
25  
26  @SuppressWarnings("deprecation")
27  public class Instant2IsoDynamoDBMarshaller
28  		implements
29  			DynamoDBTypeConverter<String, Instant>,
30  			DynamoDBMarshaller<Instant> {
31  
32  	private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
33  
34  	private DateTimeFormatter getDateFormat() {
35  		return DateTimeFormatter.ofPattern(PATTERN).withZone(ZoneOffset.UTC);
36  	}
37  
38  	@Override
39  	public String convert(Instant object) {
40  		return marshall(object);
41  	}
42  
43  	@Override
44  	public String marshall(Instant getterReturnResult) {
45  		if (getterReturnResult == null) {
46  			return null;
47  		} else {
48  			return getDateFormat().format(getterReturnResult);
49  		}
50  	}
51  
52  	@Override
53  	public Instant unconvert(String object) {
54  		return unmarshall(Instant.class, object);
55  	}
56  
57  	@Override
58  	public Instant unmarshall(Class<Instant> clazz, String obj) {
59  		if (StringUtils.isEmpty(obj)) {
60  			return null;
61  		} else {
62  			return Instant.from(getDateFormat().parse(obj));
63  		}
64  	}
65  
66  }