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 package org.apache.oozie.util; 019 020 import java.util.regex.Matcher; 021 import java.util.regex.Pattern; 022 023 /** 024 * Class for rule mapping 025 */ 026 public class MappingRule { 027 028 private static Pattern variableNamePattern = Pattern.compile("\\$\\{[0-9]\\}"); 029 private Pattern fromPattern; 030 private String fromString; 031 private String toString; 032 private boolean patternMatch; 033 034 /** 035 * Maps from source rule to destination rule 036 * @param fromRule - Rule for which input needs to be matched 037 * @param toRule - Rule for value to be returned 038 */ 039 public MappingRule(String fromRule, String toRule) { 040 if (fromRule.contains("$")) { 041 patternMatch = true; 042 fromRule = fromRule.replaceAll("\\.", "\\\\."); 043 Matcher match = variableNamePattern.matcher(fromRule); 044 fromRule = match.replaceAll("(.*)"); 045 fromPattern = Pattern.compile(fromRule); 046 } 047 else { 048 fromString = fromRule; 049 } 050 toString = toRule; 051 } 052 053 /** 054 * Gets the from rule 055 * @return 056 */ 057 public String getFromRule() { 058 return fromString; 059 } 060 061 /** 062 * Gets the to rule 063 * @return 064 */ 065 public String getToRule() { 066 return toString; 067 } 068 069 /** 070 * Applies rules based on the input 071 * @param input 072 * @return 073 */ 074 public String applyRule(String input) { 075 if (patternMatch) { 076 Matcher match = fromPattern.matcher(input); 077 if (match.matches()) { 078 String result = toString; 079 int count = match.groupCount(); 080 for (int i = 1; i <= count; i++) { 081 result = result.replace("${" + (i) + "}", match.group(i)); 082 } 083 return result; 084 } 085 } 086 else if (input.equals(fromString)) { 087 return toString; 088 } 089 return null; 090 } 091 }