Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/**
* (c) Copyright 2020 IBM Corporation
* 1 New Orchard Road,
* Armonk, New York, 10504-1722
* United States
* +1 914 499 1900
* support: Nathaniel Mills [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.whitelistmasker.masker;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InvalidObjectException;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.management.modelmbean.InvalidTargetObjectTypeException;
import com.api.json.JSON;
import com.api.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* Common utility methods used by other classes
*
*/
public class MaskerUtils implements Serializable {
private static final long serialVersionUID = 7829338567692523456L;
static public final int iDayMilliseconds = 86400000;
static public final int iHourMilliseconds = 3600000;
static public final int iMinuteMilliseconds = 60000;
static final public Charset UTF8_CHARSET = Charset.forName("UTF-8");
static boolean s_debug = false; // true;
static Gson s_gson = new GsonBuilder().create();
/**
* Utility method to create a list of the content of an ArrayList by converting
* each object to its toString() representation and appending it within a list
* using the supplied delimiter. If a String is encountered in the ArrayList, it
* will be quoted (e.g., surrounded by double quote marks). The list itself is
* enclosed by an opening ('{') and closing ('}') brace.
*
* Note: there is no escaping of the characters in a String object, so if it
* contains a delimiter or a closing brace, you may get unexpected results.
*
* @param list
* the array list of objects to be converted to a list string.
* @return the list comprising an opening brace, then each object in the
* arraylist converted to a string, followed by the closing brace, with
* the caveat that string objects encountered in the arraylist are
* enclosed in a pair of double quotes.
* @see #listStringToArrayList
*/
static public String arrayListToListString(ArrayList> list) {
// WNM3: add support for Int[], Double[], Float[], Long[], String[]
// WNM3: escape the Strings?
if (list == null || list.size() == 0) {
return "{}"; // empty string
}
String strDelimiter = ",";
StringBuffer sb = new StringBuffer();
sb.append("{");
Object item = null;
for (int i = 0; i < list.size(); i++) {
if (i != 0) {
sb.append(strDelimiter);
}
item = list.get(i);
if (item instanceof Integer) {
sb.append(item.toString());
} else if (item instanceof Long) {
sb.append(item.toString());
} else if (item instanceof Double) {
sb.append(item.toString());
} else if (item instanceof Float) {
sb.append(item.toString());
} else if (item instanceof String) {
sb.append("\"");
sb.append(item.toString());
sb.append("\"");
} else {
// WNM3: not sure what to do here... hex of serialized?
sb.append("\"");
sb.append(item.toString());
sb.append("\"");
}
}
sb.append("}");
return sb.toString();
}
/**
* Set up filter if the supplied word contains an @ like in an email address, or
* starts or ends with a number, or contains http
*
* @param word
* value to be tested
* @return true if the word should be filtered
*/
static public boolean checkWordFilter(String word) {
if (word == null) {
return true;
}
word = word.trim();
if (word.length() == 0) {
return true;
}
// check for email pattern
if (word.contains("@")) {
return true;
}
// check for http pattern
if (word.toLowerCase().contains("http")) {
return true;
}
// check for non-words that begin with a number
char wordChar = word.charAt(0);
if (0x0030 <= wordChar && wordChar <= 0x0039) {
return true;
}
// check for non-words that end with a number
wordChar = word.charAt(word.length() - 1);
if (0x0030 <= wordChar && wordChar <= 0x0039) {
return true;
}
return false;
}
/**
* Cleans trailing characters from the supplied URL based on how URL's might be
* referenced within dialogs (e.g., removes trailing comma, double quote,
* question mark, or period, as well as newline, and carriage return.
*
* @param url
* the URL to be cleansed
* @return the cleansed URL
*/
static public String cleanURL(String url) {
// Truncate at newlines ("\r", "\n")
int index = url.indexOf("\r");
while (index >= 0) {
url = url.substring(0, index);
index = url.indexOf("\r");
}
index = url.indexOf("\n");
while (index >= 0) {
url = url.substring(0, index);
index = url.indexOf("\n");
}
index = url.indexOf("\u00A0");
if (index >= 0) {
url = url.substring(0, index);
}
// strip any trailing period, comma, double quote
while (url.endsWith(".") || url.endsWith(",") || url.endsWith("\"") || url.endsWith("!") || url.endsWith("'")
|| url.endsWith("?") || url.endsWith(":") || url.endsWith("]") || url.endsWith(")") || url.endsWith("`")
|| url.endsWith("\\") || url.endsWith("/") || url.endsWith("\r") || url.endsWith("\n") || url.endsWith("\t")
|| url.endsWith("\u00A0") || url.endsWith("\u2028") || url.endsWith("\u2029") || url.endsWith("\u2019")
|| url.endsWith("\u201A")) {
url = url.substring(0, url.length() - 1);
}
return url;
}
/**
* Strip off non-word characters from the beginning and end of the supplied
* word.
*
* @param word
* the word to be cleansed
* @return array of cleansed word parts: [0] prefix removed from word, [1]
* cleansed word, [2] suffix removed from word
*/
static public String[] cleanWord(String word) {
String[] result = new String[3];
result[0] = "";
result[1] = "";
result[2] = "";
if (word == null) {
return result;
}
word = trimSpaces(word);
if (word.length() == 0) {
result[1] = word;
return result;
}
// clean front
int index = 0;
int len = word.length();
char wordchar = word.charAt(index);
StringBuffer sb = new StringBuffer();
// numbers, letters, some quotes, but not @ (to block emails)
while (wordchar < 0x0030 || (wordchar > 0x0039 && wordchar < 0x0061 && wordchar != 0x0040)
|| (wordchar > 0x007a && wordchar <= 0x007f) || wordchar == '\u2003' || wordchar == '\u2013'
|| wordchar == '\u2018' || wordchar == '\u2019' || wordchar == '\u201C' || wordchar == '\u201D'
|| wordchar == '\u2022' || wordchar == '\u2026' || wordchar == '\u2028' || wordchar == '\u202A'
|| wordchar == '\u202C' || wordchar == '\u202F' || wordchar == '\u223C') {
sb.append(wordchar);
index++;
if (index == len) {
break;
}
wordchar = word.charAt(index);
}
result[0] = sb.toString();
if (index == len) {
return result;
}
word = word.substring(index);
len = word.length();
index = len - 1;
sb.setLength(0); // clear the accumulator
wordchar = word.charAt(index);
while (wordchar < 0x0030 || (wordchar > 0x0039 && wordchar < 0x0061 && wordchar != 0x0040)
|| (wordchar > 0x007a && wordchar <= 0x007f) || wordchar == '\u2003' || wordchar == '\u2013'
|| wordchar == '\u2018' || wordchar == '\u2019' || wordchar == '\u201C' || wordchar == '\u201D'
|| wordchar == '\u2022' || wordchar == '\u2026' || wordchar == '\u2028' || wordchar == '\u202A'
|| wordchar == '\u202C' || wordchar == '\u202F' || wordchar == '\u223C') {
sb.append(wordchar);
index--;
if (index == 0) {
break;
}
wordchar = word.charAt(index);
}
result[2] = sb.reverse().toString();
word = word.substring(0, index + 1);
result[1] = word;
return result;
}
/**
* Close a buffered reader opened using {@link #openTextFile(String)}
*
* @param br
*/
static public void closeTextFile(BufferedReader br) {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Close a buffered writer flushing its content first. Nothing happens if a null
* is passed.
*
* @param bw
* the buffered writer to be flushed and closed.
*/
static public void closeTextFile(BufferedWriter bw) {
if (bw != null) {
try {
bw.flush();
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Convert a number of milliseconds to a formatted String containing a sign,
* followed by the hours and minutes as in "-0500" or "+0100" which are used for
* TimeZones.
*
* @param iMillisecs
* the number of milliseconds from Greenwich Mean Time.
* @return a string of the form +/-hhmm as in "-0500" or "+0100"
*/
static public String convertMillisecondsToTimeZone(int iMillisecs) {
StringBuffer sb = new StringBuffer();
if (iMillisecs < 0) {
sb.append("-");
iMillisecs *= -1;
} else {
sb.append("+");
}
int iHours = iMillisecs / iHourMilliseconds;
if (iHours < 10) {
sb.append("0");
}
sb.append(iHours);
iMillisecs -= iHours * iHourMilliseconds;
int iMinutes = iMillisecs / iMinuteMilliseconds;
if (iMinutes < 10) {
sb.append("0");
}
sb.append(iMinutes);
return sb.toString();
}
/**
* Converts a timezone of the format +/-hhmm to milliseconds
*
* @param strTimeZone
* timezone offset from Greenwich Mean Time (GMT) for example
* "-0500" is Eastern Standard Time, "-0400" is Eastern
* Daylight Time, "+0000" is Greenwich Mean Time, and "+0100"
* is the offset for Europe/Paris.
*
* @return milliseconds from Greenwich Mean Time
*/
static public int convertTimeZoneToMilliseconds(String strTimeZone) {
int iMillisecs = 0;
if (strTimeZone == null || strTimeZone.length() != 5) {
return iMillisecs;
}
// convert timezone (+/-hhmm)
String strSign = strTimeZone.substring(0, 1);
String strHours = strTimeZone.substring(1, 3);
String strMinutes = strTimeZone.substring(3, 5);
try {
int iHours = new Integer(strHours).intValue();
int iMinutes = new Integer(strMinutes).intValue();
iMillisecs = iMinutes * iMinuteMilliseconds;
iMillisecs = iMillisecs + (iHours * iHourMilliseconds);
if (strSign.startsWith("-") == true) {
iMillisecs *= -1;
}
} catch (NumberFormatException nfe) {
iMillisecs = 0;
}
return iMillisecs;
}
/**
* Transform a fully qualified Class' name into just the name of the class
* without the leading package. For example,
* "com.whitelistmasker.masker.MaskerDate" would return just "MaskerDate"
*
* @param inClass
* @return name of the class without leading qualification
*/
static public String getNameFromClass(Class> inClass) {
return inClass.getName().lastIndexOf(".") == -1 ? inClass.getName()
: inClass.getName().substring(inClass.getName().lastIndexOf(".") + 1);
}
/**
* Determine if the String is empty (equals "").
*
* @param strInput
* the string to be evaluated.
* @return true if the strInput compares to {@link MaskerConstants#EMPTY_String}
* (""). Returns false if strInput is null or not empty.
*/
static public boolean isEmpty(String strInput) {
if (strInput == null) {
return false;
}
return strInput.compareTo(MaskerConstants.EMPTY_String) == 0;
}
static public boolean isUndefined(String test) {
if (test == null || test.length() == 0 || "?".equals(test)) {
return true;
}
return false;
}
/**
* Tests whether the supplied url is valid
*
* @param url
* the URL to be tested
* @return true if the URL references http or https protocol
*/
static public boolean isValidURL(String url) {
boolean result = false;
// must be http:// at minimum, could be https://
if (url.length() < 7) {
return result;
}
String secure = url.substring(4, 5);
if (secure.equalsIgnoreCase("s")) {
if (url.length() < 8) {
return result;
}
if (url.length() >= 12 && url.substring(5, 12).equals("://http")) {
return result;
}
result = url.substring(5, 8).equals("://");
} else {
if (secure.equals(":") == false) {
return result;
}
// now check for //
if (url.length() >= 11 && url.substring(4, 11).equals("://http")) {
return result;
}
result = url.substring(5, 7).equals("//");
}
return result;
}
/**
* Construct and return a sorted list of files in a directory identified by the
* dir that have extensions matching the ext
*
* @param dir
* the path to the directory containing files to be returned in the
* list
* @param ext
* the file extension (without the leading period) used to filter
* files in the dir
* @return sorted list of files in a directory identified by the dir that have
* extensions matching the ext
* @throws IOException
* if there is difficulty accessing the files in the
* supplied dir
*/
static public List listSourceFiles(Path dir, String ext) throws IOException {
List result = new ArrayList();
try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.{" + ext + "}")) {
for (Path entry : stream) {
result.add(entry);
}
} catch (DirectoryIteratorException ex) {
// I/O error encountered during the iteration, the cause is an
// IOException
throw ex.getCause();
}
result.sort(null);
return result;
}
/**
* Transform a list of fields contained in a String bounded with opening ('{')
* and closing ('}') braces, and delimited with one of the delimiters (comma,
* space, tab, pipe). Fields containing strings are expected to be enclosed in
* double quotes ('"').
*
* @param strList
* the list of fields enclosed in braces.
* @return an ArrayList of the fields parsed from the supplied list string.
* Note: if the passed strList is null or empty, an empty ArrayList is
* returned (e.g., its size() is 0).
* @see #arrayListToListString
*/
static public ArrayList