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.
/*
* #%L
* Wikitty :: api
* %%
* Copyright (C) 2009 - 2010 CodeLutin, Benjamin Poussin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
package org.nuiton.wikitty;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.Key;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import net.iharder.Base64;
import net.objecthunter.exp4j.ExpressionBuilder;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.converters.DateTimeConverter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.util.DateUtil;
import org.nuiton.wikitty.entities.BusinessEntity;
import org.nuiton.wikitty.entities.BusinessEntityImpl;
import org.nuiton.wikitty.entities.FieldType;
import org.nuiton.wikitty.entities.Wikitty;
import org.nuiton.wikitty.entities.WikittyExtension;
import org.nuiton.wikitty.entities.WikittyField;
import org.nuiton.wikitty.entities.WikittyImpl;
import org.nuiton.wikitty.entities.WikittyTypes;
import org.nuiton.wikitty.generator.WikittyTransformerUtil;
import org.nuiton.wikitty.services.WikittyServiceEnhanced;
/**
* Util static method for wikitty.
*
* @author poussin
* @version $Revision$ki
*
* Last update: $Date$ by : $Author$
*/
public class WikittyUtil implements WikittyConstants {
/** Pattern que doivent respecter les noms des extensions */
public static final String extensionNamePattern = "\\w+";
/** Pattern que doivent respecter les noms des champs des extensions */
public static final String extensionFieldNamePattern = "\\w+";
public static final String DEFAULT_MAJOR_VERSION = "0";
public static final String DEFAULT_MINOR_VERSION = "0";
public static final String DEFAULT_MAJOR_VERSION_PREFIX = DEFAULT_MAJOR_VERSION + ".";
public static final String DEFAULT_VERSION = DEFAULT_MAJOR_VERSION_PREFIX + DEFAULT_MINOR_VERSION;
public static final String DATE_NOW = "NOW";
public static final String DATE_TODAY = "TODAY";
public static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ'Z'";
// #1386 sletellier 20110309 : solr date is return like 2011-03-09T08:06:27.593Z
public static final String SOLR_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
/** to use log facility, just put in your code: log.info(\"...\"); */
static private Log log = LogFactory.getLog(WikittyUtil.class);
/** used to format date for solr */
protected static final TimeZone CANONICAL_TZ = TimeZone.getTimeZone("UTC");
protected static final Locale CANONICAL_LOCALE = Locale.US;
// FastDateFormat is thread-safe
static final protected FastDateFormat solrDateFormat = FastDateFormat.getInstance(
DATE_FORMAT, CANONICAL_TZ, CANONICAL_LOCALE);
public static final String[] DATE_FORMAT_ALLOWED = {
solrDateFormat.getPattern(),
DATE_FORMAT,
SOLR_DATE_FORMAT,
new SimpleDateFormat().toPattern(), // local dependent
"dd/MM/yy",
"dd/MM/yy hh:mm",
"dd/MM/yyyy",
"dd/MM/yyyy hh:mm",
"dd-MM-yy",
"dd-MM-yy hh:mm",
"dd-MM-yyyy",
"dd-MM-yyyy hh:mm",
"yyyyMMdd",
"yyyy-MM-dd",
"yyyy-MM-dd hh:mm",
"yyyy-MM-dd'T'hh:mm:ss'Z'",
"yyMMdd",
};
/** no break space, used to parse BigDecimal */
static final public String nbsp = new String(new int[]{160}, 0, 1);
// /** All date format parser used to convert string to date */
// static final protected DateFormat[] parserDateFormats = new DateFormat[] {
// solrDateFormat, DateFormat.getInstance(),
// // TODO poussin 20090813: add other date syntax
// };
static public Date parseDate(String dateAsString) throws ParseException {
return DateUtils.parseDate(dateAsString, DATE_FORMAT_ALLOWED);
}
static public String formatDate(Date date) throws ParseException {
if (date == null) {
return null;
}
return solrDateFormat.format(date);
}
// TODO poussin 20090902 use spring configuration to add mapping in this
// variable
/** contains mapping between interface and concret class that must be used */
static public Map, Class>> interfaceToClass = new HashMap, Class>>();
/**
* Pattern for tag value: tag="value" or tag=value. value can contains '"'
*/
static protected String tagValuesPatternString = "(\\w*)=(\".*?(?group 1: type (string)
*
group 2: name (string)
*
group 3: lower bound (number) can be null
*
group 4: upper bound (number) can be null, mutually exclusive with group 5
*
group 5: upper bound (n or *) can be null
*
group 6: unique can be null (legacy configuration, prefer use of {@code unique="true"}
*
group 7: not null can be null (legacy configuration, prefer use of {@code notNull="true"}
*
group 8: all tag/value (toto=titi tutu=tata;lala tata="truc bidulle")
*/
static protected Pattern fieldPattern = Pattern
.compile(
"\\s*(\\w+)\\s+(\\w+)(?:\\s*\\[(\\d+)-(?:(\\d+)|([\\*n]))\\])?(?:\\s+(unique))?(?:\\s+(not null))?((?:\\s+"
+ tagValuesPatternString + ")*)", Pattern.DOTALL);
/**
* parse FieldType definition and return field name. All field information
* are stored in fieldType object passed in argument
*
* @param def string field definition
* @param fieldType object used to put parsed information
* @return field name parsed in definition
*/
static public String parseField(String def, FieldType fieldType) {
Matcher match = fieldPattern.matcher(def);
if (match.matches()) {
fieldType.setType(WikittyTypes.parse(match.group(1)));
String name = match.group(2);
String lower = match.group(3);
if (lower != null) {
fieldType.setLowerBound(Integer.parseInt(lower));
}
String upper = match.group(4);
if (upper != null) {
fieldType.setUpperBound(Integer.parseInt(upper));
}
String noupper = match.group(5);
if (noupper != null) {
fieldType.setUpperBound(FieldType.NOLIMIT);
}
// parse group 8 before
String tagValues = match.group(8);
Map tagValuesMap = tagValuesToMap(tagValues);
// legacy field definition : unique
String uniqueString = match.group(6);
if (uniqueString != null) {
tagValuesMap.put(FieldType.TAG_UNIQUE, "true");
if (log.isWarnEnabled()) {
log.warn("Old field constraints definition detected \"unique\" ; prefer use of \"unique=true\"");
}
}
// legacy field definition : not null
String notNullString = match.group(7);
if (notNullString != null) {
tagValuesMap.put(FieldType.TAG_NOT_NULL, "true");
log.warn("Old field constraints definition detected \"non null\" ; prefer use of \"notNull=true\"");
}
fieldType.setTagValues(tagValuesMap);
return name;
} else {
throw new WikittyException(String.format(
"Bad FieldType definition '%s'", def));
}
}
/**
* Serialize tagValues to string
*
* @param tagValues tagValues as map
* @return string represent tagValues
*/
public static String tagValuesToString(Map tagValues) {
String result = WikittyTransformerUtil.tagValuesToString(tagValues);
return result;
}
/**
* Deserialize tagValues to map
*
* @param tagValues tagValues as string
* @return map represent tagValues
*/
public static Map tagValuesToMap(String tagValues) {
Map result = new HashMap();
if (tagValues != null) {
Matcher matchTagValues = tagValuesPattern.matcher(tagValues);
while (matchTagValues.find()) {
String tag = matchTagValues.group(1);
String value = matchTagValues.group(2);
if (value.startsWith("\"") && value.endsWith("\"")) {
// delete start and end "
value = value.substring(1, value.length() - 1);
// if value is between ", then inners " are quoted
value = StringEscapeUtils.unescapeJava(value);
}
result.put(tag, value);
}
}
return result;
}
/**
* Create map from string representation.
*
* ex: "String name", "Wikitty attachment[0-*]"
*
* @param definitions extension definition
* @return extensions map
*/
public static LinkedHashMap buildFieldMapExtension(
String... definitions) {
LinkedHashMap result = new LinkedHashMap();
for (String def : definitions) {
FieldType fieldType = new FieldType();
String name = WikittyUtil.parseField(def, fieldType);
if (log.isDebugEnabled()) {
log.debug("parse " + def + " => " + fieldType.toDefinition(name));
}
result.put(name, fieldType);
}
return result;
}
/**
* if version if null return 0 else version If version is not in format
* ., ".0" is added to the version
*
* @param version version
* @return the normalized version
*/
public static String normalizeVersion(String version) {
if (version == null || "".equals(version)) {
version = "0";
}
if (version.indexOf(".") == -1) {
version += ".0";
}
return version;
}
/**
* Return true if v1 and v2 are equals.
*
* 1.2.0 et 1.2 ne sont pas egaux
*
* @param v1 version
* @param v2 version
*
* @return {@code true} if v1 == v2
*/
public static boolean versionEquals(String v1, String v2) {
if (v1 == null || v2 == null) {
return false;
}
return normalizeVersion(v1).equals(normalizeVersion(v2));
}
/**
* Return true if v1 greater than v2.
*
* @param v1 version
* @param v2 version
* @return {@code true} if v1 > v2
*/
public static boolean versionGreaterThan(String v1, String v2) {
if (v1 != null && v2 == null) {
return true;
}
if (v1 == null) {
return false;
}
String[] v1s = normalizeVersion(v1).split("\\.");
String[] v2s = normalizeVersion(v2).split("\\.");
int minlen = Math.min(v1s.length, v2s.length);
for (int i = 0; i < minlen; i++) {
if (!v1s[i].equals(v2s[i])) {
return Integer.parseInt(v1s[i]) > Integer.parseInt(v2s[i]);
}
}
// si on est ici c que tout les nombres sont v1[i] = v2[i]
return v1s.length > v2s.length;
}
/**
* Increment minor version.
*
* @param v version as 3.1 where 1 is minor and 3 major
* @return incremented minor number (3.1 -> 3.2)
*/
static public String incrementMinorRevision(String v) {
String result;
if (v == null || "".equals(v)) {
result = "0.1";
} else {
v = v.trim();
String[] mm = v.split("\\.");
if (mm.length == 1) {
result = v + ".1";
} else {
int i = Integer.parseInt(mm[1]) + 1;
result = mm[0] + "." + i;
}
}
return result;
}
/**
* increment major version.
*
* @param v version as 3.2 where 2 is minor and 3 major
* @return incremented major number and reset minor number (3.2 -> 4.0)
*/
static public String incrementMajorRevision(String v) {
String result;
if (v == null || "".equals(v)) {
result = "1.0";
} else {
v = v.trim();
String[] mm = v.split("\\.");
int i = Integer.parseInt(mm[0]) + 1;
result = i + ".0";
}
return result;
}
/** Pattern de recherche des field dans les chaines de formatage
* @see {@link Formatter#formatSpecifier}
*/
static protected Pattern formatMatcher =
Pattern.compile("%([^0-9][^|$]*)(?:\\|(.*?))?(\\$(:?[-#+ 0,(\\<]*)?(:?\\d+)?(:?\\.\\d+)?[tT]?[a-zA-Z])");
/**
* Format wikitty for string representation.
* exemple:
*
"Hello %Person.firstName|unknown$s" if firstName field doesn't exist, unknow is used
*
"My company %Employee.company,Company.name|unknown$s" if employee has company field and this company has name field
*
* @param format format as {@link http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax}
* except that position is replace with fq field name.
* @param w wikitty to format
* @return String that represent the wikitty
*/
static public String format(String formatWikitty, Wikitty w) {
List> fields = new ArrayList>();
StringBuffer formatBuffer = new StringBuffer();
int i = 0;
// on collect tous les champs demande et leur valeur par defaut
// et en meme temps on cree la chaine formatBuffer qui substitue les
// champs par des numeros
Matcher matcher = formatMatcher.matcher(formatWikitty);
while(matcher.find()) {
String fieldAsked = matcher.group(1);
String defaultValue = matcher.group(2);
fields.add(new ImmutablePair(fieldAsked, defaultValue));
// i is incremented before replace, because String.format start at 1 not 0
matcher.appendReplacement(formatBuffer, "%"+(++i)+"$3");
}
matcher.appendTail(formatBuffer);
// la vrai chaine de formatage pour String.format
String format = formatBuffer.toString();
List