001/**
002 * Java Web Archive Toolkit - Software to read and validate ARC, WARC
003 * and GZip files. (http://jwat.org/)
004 * Copyright 2011-2012 Netarkivet.dk (http://netarkivet.dk/)
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.jwat.arc;
019
020import java.net.InetAddress;
021import java.util.Date;
022
023import org.jwat.common.ContentType;
024import org.jwat.common.Diagnosis;
025import org.jwat.common.DiagnosisType;
026import org.jwat.common.Diagnostics;
027import org.jwat.common.IPAddressParser;
028import org.jwat.common.Uri;
029import org.jwat.common.UriProfile;
030
031/**
032 * Separate class containing all the different types of field parser.
033 * Including validating parsers for strings, integers, longs,
034 * content-types, IP's, URI's and ARC dates.
035 *
036 * @author nicl
037 */
038public class ArcFieldParsers {
039
040    /** Diagnostics used to report diagnoses. Must be set prior to calling the various methods. */
041    public Diagnostics<Diagnosis> diagnostics;
042
043    /**
044     * Add an error diagnosis on the given entity stating that it is invalid
045     * and something else was expected. The optional information should provide
046     * more details and/or format information.
047     * @param entity entity examined
048     * @param information optional extra information
049     */
050    public void addInvalidExpectedError(String entity, String... information) {
051        diagnostics.addError(new Diagnosis(DiagnosisType.INVALID_EXPECTED, entity, information));
052    }
053
054    /**
055     * Add an error diagnosis on the given entity stating that it is required
056     * but is missing.
057     * @param entity entity examined
058     */
059    public void addRequiredMissingError(String entity) {
060        diagnostics.addError(new Diagnosis(DiagnosisType.REQUIRED_MISSING, entity));
061    }
062
063    /**
064     * Validates that the string is not null but only if nullable is false.
065     * @param str the value to validate
066     * @param field field name
067     * @param nullable allow empty or null value
068     * @return the original value
069     */
070    public String parseString(String str, String field, boolean nullable) {
071        if ((!nullable) && ((str == null) || (str.trim().length() == 0))) {
072            addRequiredMissingError("'" + field + "' value");
073        }
074        return str;
075    }
076
077    /**
078     * Returns an Integer object holding the value of the specified string.
079     * @param intStr the value to parse.
080     * @param field field name
081     * @param nullable allow empty or null value
082     * @return an integer object holding the value of the specified string or null, if unable to parse the value as an integer
083     */
084    public Integer parseInteger(String intStr, String field, boolean nullable) {
085         Integer iVal = null;
086         if (intStr != null && intStr.length() > 0) {
087            try {
088                iVal = Integer.valueOf(intStr);
089            } catch (Exception e) {
090                // Invalid integer value.
091                addInvalidExpectedError("'" + field + "' value", intStr, "Numeric format");
092            }
093         } else if (!nullable) {
094             // Missing mandatory value.
095             addRequiredMissingError("'" + field + "' value");
096         }
097         return iVal;
098    }
099
100    /**
101     * Returns a Long object holding the value of the specified string.
102     * @param longStr the value to parse.
103     * @param field field name
104     * @param nullable allow empty or null value
105     * @return a long object holding the value of the specified string or null, if unable to parse the value as a Long
106     */
107    public Long parseLong(String longStr, String field, boolean nullable) {
108        Long lVal = null;
109        if (longStr != null && longStr.length() > 0) {
110            try {
111                lVal = Long.valueOf(longStr);
112            } catch (Exception e) {
113                // Invalid long value.
114                addInvalidExpectedError("'" + field + "' value", longStr, "Numeric format");
115            }
116        } else if (!nullable) {
117             // Missing mandatory value.
118            addRequiredMissingError("'" + field + "' value");
119        }
120        return lVal;
121    }
122
123    /**
124     * Parse and validate a content type.
125     * @param contentTypeStr ARC record content type
126     * @param field field name
127     * @param nullable allow empty or null value
128     * @return content type or null, if unable to extract the content-type
129     */
130    public ContentType parseContentType(String contentTypeStr, String field, boolean nullable) {
131        ContentType contentType = null;
132        if (contentTypeStr != null && contentTypeStr.length() != 0) {
133            contentType = ContentType.parseContentType(contentTypeStr);
134            if (contentType == null) {
135                // Invalid content-type.
136                addInvalidExpectedError("'" + field + "' value", contentTypeStr, ArcConstants.CONTENT_TYPE_FORMAT);
137            }
138        } else if (!nullable) {
139            // Missing content-type.
140            addRequiredMissingError("'" + field + "' value");
141        }
142        return contentType;
143    }
144
145    /**
146     * Parse and validate an IP address.
147     * @param ipAddress the IP address to parse
148     * @param field field name
149     * @param nullable allow empty or null value
150     * @return the IP address or null, if unable to parse the value as an IP-address
151     */
152    public InetAddress parseIpAddress(String ipAddress, String field, boolean nullable) {
153        InetAddress inetAddr = null;
154        if (ipAddress != null && ipAddress.length() > 0) {
155            inetAddr = IPAddressParser.getAddress(ipAddress);
156            if (inetAddr == null) {
157                // Invalid date.
158                addInvalidExpectedError("'" + field + "' value", ipAddress, "IPv4 or IPv6 format");
159            }
160        } else if (!nullable) {
161            // Missing mandatory value.
162            addRequiredMissingError("'" + field + "' value");
163        }
164        return inetAddr;
165    }
166
167    /**
168     * Returns an URL object holding the value of the specified string.
169     * @param uriStr the URL to parse
170     * @param uriProfile profile used to validate URI
171     * @param field field name
172     * @param nullable allow empty or null value
173     * @return an URL object holding the value of the specified string or null, if unable to parse the value as an URL object
174     */
175    public Uri parseUri(String uriStr, UriProfile uriProfile, String field, boolean nullable) {
176        Uri uri = null;
177        if ((uriStr != null) && (uriStr.length() != 0)) {
178            try {
179                uri = new Uri(uriStr, uriProfile);
180            } catch (Exception e) {
181                // Invalid URI.
182                addInvalidExpectedError("'" + field + "' value", uriStr, e.getMessage());
183            }
184            if (uri != null) {
185                String scheme = uri.getScheme();
186                if (scheme == null) {
187                    uri = null;
188                    // Relative URI.
189                    addInvalidExpectedError("'" + field + "' value", uriStr, "Absolute URI");
190                }
191            }
192        } else if (!nullable) {
193            // Missing mandatory value.
194            addRequiredMissingError("'" + field + "' value");
195        }
196        return uri;
197    }
198
199    /**
200     * Parses ARC record date.
201     * @param dateStr the date to parse.
202     * @param field field name
203     * @param nullable allow empty or null value
204     * @return the formatted date or null, if unable to parse the value as an ARC record date
205     */
206    public Date parseDate(String dateStr, String field, boolean nullable) {
207        Date date = null;
208        if (dateStr != null && dateStr.length() > 0) {
209                date = ArcDateParser.getDate(dateStr);
210                if (date == null) {
211                    // Invalid date.
212                    addInvalidExpectedError("'" + field + "' value", dateStr, ArcConstants.ARC_DATE_FORMAT);
213                }
214        } else if (!nullable) {
215            // Missing mandatory value.
216            addRequiredMissingError("'" + field + "' value");
217        }
218        return date;
219    }
220
221}