001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. 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 */ 018 019package org.apache.oozie; 020 021import com.google.common.base.Strings; 022import com.google.common.collect.LinkedListMultimap; 023import com.google.common.collect.ListMultimap; 024import org.apache.oozie.servlet.XServletException; 025 026import javax.servlet.ServletException; 027import javax.servlet.http.HttpServletResponse; 028import java.util.StringTokenizer; 029 030public class FilterParser { 031 032 private static final String PARAMETER_DELIMITER = ";"; 033 private static final String PARAMETER_EQUALS = "="; 034 035 /** 036 * Parse filter string to a map with key = filter name and values = filter values 037 * 038 * @param filterString the filter string 039 * @return filter key and values map 040 * @throws ServletException thrown if failed to parse filter string 041 */ 042 public static ListMultimap<String, String> parseFilter(String filterString) throws ServletException { 043 ListMultimap<String, String> filterFieldMap = LinkedListMultimap.create(); 044 if (filterString != null) { 045 StringTokenizer st = new StringTokenizer(filterString, PARAMETER_DELIMITER); 046 while (st.hasMoreTokens()) { 047 String token = st.nextToken(); 048 if (token.contains(PARAMETER_EQUALS)) { 049 String[] nameValuePair = token.split(PARAMETER_EQUALS); 050 if (nameValuePair.length != 2) { 051 filterFormatError(filterString); 052 } 053 String key = nameValuePair[0]; 054 String value = nameValuePair[1]; 055 if (Strings.isNullOrEmpty(key)) { 056 filterFormatError(filterString); 057 } 058 filterFieldMap.put(key, value); 059 } 060 else { 061 filterFormatError(filterString); 062 } 063 } 064 } 065 return filterFieldMap; 066 } 067 068 private static void filterFormatError(String filterString) throws ServletException { 069 throw new XServletException(HttpServletResponse.SC_BAD_REQUEST, ErrorCode.E0401, 070 String.format("elements must be semicolon-separated name=value pairs but was %s", filterString)); 071 072 } 073}