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