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.common;
019
020import java.util.HashMap;
021import java.util.Map;
022
023/**
024 * Field validation utility class.
025 *
026 * @author lbihanic, selghissassi, nicl
027 */
028public class FieldValidator {
029
030    /** Array of field names. */
031    protected String[] fieldNames;
032
033    /** <code>Map</code> of field name to field index mappings. */
034    protected Map<String, Integer> fieldIdxMap = new HashMap<String, Integer>();
035
036    /**
037     * Protected constructor to ensure correct instantiation.
038     */
039    protected FieldValidator() {
040    }
041
042    /**
043     * Prepares a validator for use on a given set of fields.
044     * @param fieldNames array of field names.
045     * @return validator used to look field by field name -&gt; index.
046     */
047    public static FieldValidator prepare(String[] fieldNames) {
048        FieldValidator fv = new FieldValidator();
049        fv.fieldNames = fieldNames;
050        for (int i = 0; i < fieldNames.length; ++i) {
051            fv.fieldIdxMap.put(fieldNames[i], i);
052        }
053        return fv;
054    }
055
056    /**
057     * Checks to if the index is out of bounds in the give array and also
058     * if the value if null or empty.
059     * @param array source value array
060     * @param idx desired index into array
061     * @return value index in array or null
062     */
063    public static String getArrayValue(String[] array, int idx) {
064        return ((array.length > idx) && (array[idx] != null)) ? array[idx] : null;
065    }
066
067}