com.seajas.search.utilities.query.QueryParametersUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.seajas.search.utilities.query.QueryParametersUtil.java

Source

/**
 * Copyright (C) 2013 Seajas, the Netherlands.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.seajas.search.utilities.query;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Utility used to parse and extract common parameters from their raw equivalents.
 * 
 * @author Jasper van Veghel <jasper@seajas.com>
 */
public class QueryParametersUtil {
    /**
     * The logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(QueryParametersUtil.class);

    /**
     * The parameter ID types.
     */
    public static enum QueryParameterType {
        TAXONOMY_IDS, LANGUAGE, FORMAT, CREATED, UNKNOWN
    };

    /**
     * Parse the given raw equivalent as a taxonomy ID list.
     * 
     * Note that we assume that the rawEquivalent has been validated as being in the correct format.
     * 
     * @param rawEquivalent
     * @return List<Integer>
     */
    public static List<Integer> parseTaxonomyIds(final String rawEquivalent) {
        List<Integer> result = new ArrayList<Integer>();

        String taxonomyIds = rawEquivalent.trim().replace("dcterms_coverage:", "");

        taxonomyIds = taxonomyIds.replace("(", "").replace(")", "");
        taxonomyIds = taxonomyIds.replace("'", "");
        taxonomyIds = taxonomyIds.replace(" ", ",");

        for (String taxonomyId : taxonomyIds.split(","))
            if (!StringUtils.isBlank(taxonomyId))
                try {
                    result.add(Integer.valueOf(taxonomyId));
                } catch (NumberFormatException e) {
                    logger.error("Could not parse taxonomy ID '" + taxonomyId + "' - skipping");
                }

        return result;
    }

    /**
     * Parse the given raw equivalent as a language identifier.
     * 
     * Note that we assume that the rawEquivalent has been validated as being in the correct format.
     * 
     * @param rawEquivalent
     * @return String
     */
    public static String parseLanguage(final String rawEquivalent) {
        String language = rawEquivalent.trim().replace("dcterms_language:", "");

        language = language.replace("(", "").replace(")", "");
        language = language.replace("'", "");

        return language;
    }

    /**
     * Parse the given raw equivalent as a MIME identifier (list).
     * 
     * Note that we assume that the rawEquivalent has been validated as being in the correct format.
     * 
     * @param rawEquivalent
     * @return String
     */
    public static String parseFormat(final String rawEquivalent) {
        String format = rawEquivalent.trim().replace("dcterms_format:", "");

        return format.replace("(", "").replace(")", "");
    }

    /**
     * Parse the given raw equivalent as the created line; this always results in two Date's, but either one of them can be null to indicate it was not specified.
     * 
     * Note that we assume that the rawEquivalent has been validated as being in the correct format.
     * 
     * @param rawEquivalent
     * @return String
     */
    public static Date[] parseCreated(final String rawEquivalent) {
        String createdString = rawEquivalent.trim().replace("dcterms_created:", "");

        createdString = createdString.replace("[", "").replace("]", "").trim();

        // Now parse the date created into its two components

        String[] createdParts = createdString.split(" TO ");

        if (createdParts.length == 2) {
            DateFormat solrDateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");

            Date startDate = null, endDate = null;

            try {
                if (!createdParts[0].trim().equals("NOW"))
                    startDate = solrDateFormatter.parse(createdParts[0].trim());
            } catch (java.text.ParseException e) {
                logger.error("Invalid start date '" + createdParts[0] + "' - returning as 'NOW'");
            }

            try {
                if (!createdParts[1].trim().equals("NOW"))
                    endDate = solrDateFormatter.parse(createdParts[1].trim());
            } catch (java.text.ParseException e) {
                logger.error("Invalid end date '" + createdParts[1] + "' - returning as 'NOW'");
            }

            return new Date[] { startDate, endDate };
        } else {
            logger.error("Invalid number of split created date arguments, taken from '" + createdString + "'");

            return new Date[] { null, null };
        }
    }

    /**
     * Retrieve the given parameter type, or null if it matches no known types.
     * 
     * @param rawEquivalent
     * @return QueryParameterType
     */
    public static QueryParameterType getParameterType(final String rawEquivalent) {
        if (Pattern.compile("^dcterms_coverage:").matcher(rawEquivalent).find())
            return QueryParameterType.TAXONOMY_IDS;
        else if (Pattern.compile("^dcterms_format:").matcher(rawEquivalent).find())
            return QueryParameterType.FORMAT;
        else if (Pattern.compile("^dcterms_created:").matcher(rawEquivalent).find())
            return QueryParameterType.CREATED;
        else if (Pattern.compile("^dcterms_language:").matcher(rawEquivalent).find())
            return QueryParameterType.LANGUAGE;
        else
            return QueryParameterType.UNKNOWN;
    }

    /**
     * Validate whether the given parameter matches the requested type.
     * 
     * @param rawEquivalent
     * @param type
     * @return boolean
     */
    public static boolean isParameterType(final String rawEquivalent, final QueryParameterType type) {
        return type.equals(getParameterType(rawEquivalent));
    }
}