001/* 002 * This file is part of the JDrupes non-blocking HTTP Codec 003 * Copyright (C) 2017 Michael N. Lipp 004 * 005 * This program is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Lesser General Public License as published 007 * by the Free Software Foundation; either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 013 * License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public License along 016 * with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jdrupes.httpcodec.types; 020 021import java.text.ParseException; 022 023/** 024 * Implemented by classes that convert between a value and its 025 * string representation in the HTTP header field. 026 * 027 * @param <T> the type to be converted 028 */ 029public interface Converter<T> { 030 031 /** 032 * Returns the representation of this value in a header field. 033 * 034 * @param value the value to be converted 035 * @return the representation 036 */ 037 String asFieldValue(T value); 038 039 /** 040 * Returns the string representation of this header field as it 041 * appears in an HTTP message. Note that the returned string may 042 * span several lines (may contain CR/LF), if the converter is a 043 * {@link MultiValueConverter} with separate values, but never 044 * has a trailing CR/LF. 045 * 046 * @param fieldName the field name 047 * @param value the value 048 * @return the field as it occurs in a header 049 */ 050 default String asHeaderField(String fieldName, T value) { 051 return fieldName + ": " + asFieldValue(value); 052 } 053 054 /** 055 * Parses the given text and returns the parsed value. 056 * 057 * @param text the value from the header field 058 * @return the parsed value 059 * @throws ParseException if the value cannot be parsed 060 */ 061 T fromFieldValue(String text) throws ParseException; 062}