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 org.apache.hadoop.conf.Configuration;
022import org.json.simple.JSONValue;
023
024import java.util.Map;
025import java.util.Properties;
026import java.util.Date;
027import java.net.URLEncoder;
028import java.io.UnsupportedEncodingException;
029
030/**
031 * Base EL constants and functions.
032 */
033public class ELConstantsFunctions {
034
035    /**
036     * KiloByte constant (1024). Defined for EL as 'KB'.
037     */
038    public static final long KB = 1024;
039
040    /**
041     * MegaByte constant (1024 KB). Defined for EL as 'MB'.
042     */
043    public static final long MB = KB * 1024;
044
045    /**
046     * GigaByte constant (1024 MB). Defined for EL as 'GB'.
047     */
048    public static final long GB = MB * 1024;
049
050    /**
051     * TeraByte constant (1024 GB). Defined for EL as 'TB'.
052     */
053    public static final long TB = GB * 1024;
054
055    /**
056     * PetaByte constant (1024 TB). Defined for EL as 'PB'.
057     */
058    public static final long PB = TB * 1024;
059
060    public static final int SUBMIT_MINUTES = 1;
061    public static final int SUBMIT_HOURS = 60;
062    public static final int SUBMIT_DAYS = 24 * 60;
063
064    /**
065     * Return the first not <code>null</code> value, or <code>null</code> if both are <code>null</code>. Defined for EL
066     * as 'Object firstNotNull(Object, Object)'.
067     *
068     * @param o1 first value.
069     * @param o2 second value.
070     * @return the first not <code>null</code> value, or or <code>null</code> if both are <code>null</code>
071     */
072    public static Object firstNotNull(Object o1, Object o2) {
073        return (o1 != null) ? o1 : o2;
074    }
075
076    /**
077     * Return the concatenation of 2 strings. <p> A string with <code>null</code> value is considered as an empty
078     * string.
079     *
080     * @param s1 first string.
081     * @param s2 second string.
082     * @return the concatenation of <code>s1</code> and <code>s2</code>.
083     */
084    public static String concat(String s1, String s2) {
085        StringBuilder sb = new StringBuilder();
086        if (s1 != null) {
087            sb.append(s1);
088        }
089        if (s2 != null) {
090            sb.append(s2);
091        }
092        return sb.toString();
093    }
094
095    /**
096     * Replace each occurrence of regular expression match in the first string
097     * with the <code>replacement</code> string. This EL function utilizes the
098     * java String class replaceAll method. For more details please see
099     *
100     * <code>http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)</code>
101     *
102     * @param src source string.
103     * @param regex the regular expression to which this string is to be
104     *        matched. null means no replacement.
105     * @param replacement - the string to be substituted for each match. If
106     *        null, it will considered as ""
107     * @return the replaced string.
108     */
109    public static String replaceAll(String src, String regex, String replacement) {
110        if (src != null && regex != null) {
111            if (replacement == null) {
112                replacement = "";
113            }
114            return src.replaceAll(regex, replacement);
115        }
116        return src;
117    }
118
119    /**
120     * Add the <code>append</code> string into each splitted sub-strings of the
121     * first string ('src'). The split is performed into <code>src</code> string
122     * using the <code>delimiter</code>. E.g.
123     * <code>appendAll("/a/b/,/c/b/,/c/d/", "ADD", ",")</code> will return
124     * <code>"/a/b/ADD,/c/b/ADD,/c/d/ADD"</code>
125     *
126     * @param src source string.
127     * @param append - the string to be appended for each match. If null, it
128     *        will considered as ""
129     * @param delimeter the string that is used to split the 'src' into
130     *        substring before the append. null means no append.
131     * @return the appended string.
132     */
133    public static String appendAll(String src, String append, String delimeter) {
134        if (src != null && delimeter != null) {
135            if (append == null) {
136                append = "";
137            }
138            String[] ret = src.split(delimeter);
139            StringBuilder result = new StringBuilder();
140            for (int i = 0; i < ret.length; i++) {
141                result.append(ret[i]).append(append);
142                if (i < (ret.length - 1)) { // Don't append to the last item
143                    result.append(delimeter);
144                }
145            }
146            // Java 8 skips a leading match if it's empty; to remain consistent with Java6,7, we check this case
147            if (src.startsWith(delimeter) && ret.length > 0 && !ret[0].equals("")) {
148                result.insert(0, append);
149            }
150            return result.toString();
151        }
152        return src;
153    }
154
155    /**
156     *
157     * @param input string to be trimmed
158     * @return the trimmed version of the given string or the empty string if the given string was <code>null</code>
159     */
160    public static String trim(String input) {
161        return org.apache.commons.lang.StringUtils.trimToEmpty(input);
162    }
163
164    /**
165     * Return the current datetime in ISO8601 using Oozie processing timezone, yyyy-MM-ddTHH:mmZ. i.e.:
166     * 1997-07-16T19:20Z
167     *
168     * @return the formatted time string.
169     */
170    public static String timestamp() {
171        return DateUtils.formatDateOozieTZ(new Date());
172    }
173
174    /**
175     * Translates a string into <code>application/x-www-form-urlencoded</code> format using UTF-8 encoding scheme. Bytes
176     * for unsafe characters are also obtained using UTF-8 scheme.
177     *
178     * @param input string to be encoded
179     * @return the encoded <code>String</code>
180     */
181    public static String urlEncode(String input) {
182        try {
183            return (input == null) ? "" : URLEncoder.encode(input, "UTF-8");
184        }
185        catch (UnsupportedEncodingException uee) {
186            throw new RuntimeException("It should never happen");
187        }
188    }
189
190    public static String toJsonStr(Map<String, String> map) {
191        String json = JSONValue.toJSONString(map);
192        return XmlUtils.escapeCharsForXML(json);
193    }
194
195    public static String toPropertiesStr(Map<String, String> map) {
196        Properties props = new Properties();
197        for (Map.Entry<String, String> entry: map.entrySet()) {
198            props.setProperty(entry.getKey(), entry.getValue());
199        }
200        return XmlUtils.escapeCharsForXML(PropertiesUtils.propertiesToString(props));
201    }
202
203    public static String toConfigurationStr(Map<String, String> map) {
204        Configuration conf = new Configuration(false);
205        for (Map.Entry<String, String> entry: map.entrySet()) {
206            conf.set(entry.getKey(), entry.getValue());
207        }
208        return XmlUtils.escapeCharsForXML(XmlUtils.prettyPrint(conf).toString());
209    }
210
211}