com.loadtesting.showcase.springmvc.model.converter.JodaTimeConverter.java Source code

Java tutorial

Introduction

Here is the source code for com.loadtesting.showcase.springmvc.model.converter.JodaTimeConverter.java

Source

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.loadtesting.showcase.springmvc.model.converter;

import java.text.ParseException;
import java.util.concurrent.ConcurrentHashMap;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.loadtesting.showcase.springmvc.model.JodaTimeForm;

/**
 * @author Woranop Chaiyakulvat(nineworanop@gmail.com)
 */
public class JodaTimeConverter {
    private final String pattern;
    private final ConcurrentHashMap<DateTimeZone, DateTimeFormatter> map;

    public JodaTimeConverter(String pattern) {
        this.map = new ConcurrentHashMap<DateTimeZone, DateTimeFormatter>(DateTimeZone.getAvailableIDs().size());
        this.pattern = pattern;
    }

    public JodaTimeForm convert(JodaTimeForm form) throws ParseException {
        DateTimeFormatter format1 = getFormat(form.getFromTimeZone());
        DateTime date = format1.parseDateTime(form.getInputDate());
        DateTimeFormatter format2 = getFormat(form.getToTimeZone());
        String outputDate = format2.print(date);
        JodaTimeForm resultForm = new JodaTimeForm();
        resultForm.setInputDate(form.getInputDate());
        resultForm.setFromTimeZone(form.getFromTimeZone());
        resultForm.setToTimeZone(form.getToTimeZone());
        resultForm.setOutputDate(outputDate);
        return resultForm;
    }

    public DateTimeFormatter getFormat(DateTimeZone timeZone) {
        DateTimeFormatter result = map.get(timeZone);
        if (result == null) {
            DateTimeFormatter newValue = DateTimeFormat.forPattern(pattern).withZone(timeZone);
            result = map.putIfAbsent(timeZone, newValue);
            if (result == null) {
                result = newValue;
            }
        }
        return result;
    }
}