Migrate ALL java files from /src to /src/main/java - OFBIZ-7790
This is the first of two steps in the above mentioned JIRA. This first step changes the java source directory for every component from /src to /src/main/java. The next step will be adding unit tests to every component in /src/test/java Thank you to Deepak Dixit for tips on how to use the SVN commands to make the appropriate file moving. git-svn-id: https://svn.apache.org/repos/asf/ofbiz/trunk@1752838 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
+18
@@ -0,0 +1,18 @@
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you 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.
|
||||
|
||||
org.ofbiz.common.scripting.ScriptHelperFactoryImpl
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you 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.
|
||||
|
||||
org.ofbiz.common.authentication.example.TestFailAuthenticator
|
||||
org.ofbiz.common.authentication.example.TestPassAuthenticator
|
||||
@@ -0,0 +1,178 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.HttpClient;
|
||||
import org.ofbiz.base.util.HttpClientException;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
/**
|
||||
* OFBIZ CDyne Services: for info see http://www.cdyne.com/developers/overview.aspx
|
||||
*/
|
||||
public class CdyneServices {
|
||||
|
||||
public final static String module = CdyneServices.class.getName();
|
||||
public static final String resource = "CommonUiLabels";
|
||||
public final static String licenseKey = UtilProperties.getPropertyValue("cdyne", "LicenseKey", "0");
|
||||
|
||||
/**
|
||||
* CDyne ReturnCityState Service
|
||||
*@param dctx The DispatchContext that this service is operating in
|
||||
*@param context Map containing the input parameters
|
||||
*@return Map with the result of the service, the output parameters
|
||||
*/
|
||||
public static Map<String, Object> cdyneReturnCityState(DispatchContext dctx, Map<String, ?> context) {
|
||||
String zipcode = (String) context.get("zipcode");
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
String serviceUrl = "http://ws.cdyne.com/psaddress/addresslookup.asmx/ReturnCityState?zipcode=" + zipcode + "&LicenseKey=" + licenseKey;
|
||||
try {
|
||||
String httpResponse = HttpClient.getUrlContent(serviceUrl);
|
||||
|
||||
Document addressDocument = UtilXml.readXmlDocument(httpResponse);
|
||||
Element addressRootElement = addressDocument.getDocumentElement();
|
||||
|
||||
Map<String, Object> response = ServiceUtil.returnSuccess();
|
||||
populateCdyneAddress(addressRootElement, response);
|
||||
|
||||
if ("true".equals(response.get("ServiceError"))) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonCDyneServiceError", UtilMisc.toMap("zipcode", zipcode), locale));
|
||||
}
|
||||
if ("true".equals(response.get("AddressError"))) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonCDyneAddressError", UtilMisc.toMap("zipcode", zipcode), locale));
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (HttpClientException e) {
|
||||
Debug.logError(e, "Error calling CDyne service at URL [" + serviceUrl + "]: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonCDyneCallingError", UtilMisc.toMap("serviceUrl", serviceUrl, "errorString", e.toString()), locale));
|
||||
} catch (SAXException e) {
|
||||
Debug.logError(e, "Error parsing XML result from CDyne service at URL [" + serviceUrl + "]: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonCDyneParsingError", UtilMisc.toMap("serviceUrl", serviceUrl, "errorString", e.toString()), locale));
|
||||
} catch (ParserConfigurationException e) {
|
||||
Debug.logError(e, "Error parsing XML result from CDyne service at URL [" + serviceUrl + "]: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonCDyneParsingError", UtilMisc.toMap("serviceUrl", serviceUrl, "errorString", e.toString()), locale));
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, "Error parsing XML result from CDyne service at URL [" + serviceUrl + "]: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonCDyneParsingError", UtilMisc.toMap("serviceUrl", serviceUrl, "errorString", e.toString()), locale));
|
||||
}
|
||||
}
|
||||
|
||||
public static void populateCdyneAddress(Element addressRootElement, Map<String, Object> targetContext) {
|
||||
targetContext.put("ServiceError", UtilXml.childElementValue(addressRootElement, "ServiceError"));
|
||||
targetContext.put("AddressError", UtilXml.childElementValue(addressRootElement, "AddressError"));
|
||||
targetContext.put("AddressFoundBeMoreSpecific", UtilXml.childElementValue(addressRootElement, "AddressFoundBeMoreSpecific"));
|
||||
targetContext.put("NeededCorrection", UtilXml.childElementValue(addressRootElement, "NeededCorrection"));
|
||||
|
||||
targetContext.put("DeliveryAddress", UtilXml.childElementValue(addressRootElement, "DeliveryAddress"));
|
||||
targetContext.put("City", UtilXml.childElementValue(addressRootElement, "City"));
|
||||
targetContext.put("StateAbbrev", UtilXml.childElementValue(addressRootElement, "StateAbbrev"));
|
||||
targetContext.put("ZipCode", UtilXml.childElementValue(addressRootElement, "ZipCode"));
|
||||
targetContext.put("County", UtilXml.childElementValue(addressRootElement, "County"));
|
||||
targetContext.put("CountyNum", UtilXml.childElementValue(addressRootElement, "CountyNum"));
|
||||
targetContext.put("PreferredCityName", UtilXml.childElementValue(addressRootElement, "PreferredCityName"));
|
||||
|
||||
targetContext.put("DeliveryPoint", UtilXml.childElementValue(addressRootElement, "DeliveryPoint"));
|
||||
targetContext.put("CheckDigit", UtilXml.childElementValue(addressRootElement, "CheckDigit"));
|
||||
|
||||
targetContext.put("CSKey", UtilXml.childElementValue(addressRootElement, "CSKey"));
|
||||
targetContext.put("FIPS", UtilXml.childElementValue(addressRootElement, "FIPS"));
|
||||
|
||||
targetContext.put("FromLongitude", UtilXml.childElementValue(addressRootElement, "FromLongitude"));
|
||||
targetContext.put("FromLatitude", UtilXml.childElementValue(addressRootElement, "FromLatitude"));
|
||||
targetContext.put("ToLongitude", UtilXml.childElementValue(addressRootElement, "ToLongitude"));
|
||||
targetContext.put("ToLatitude", UtilXml.childElementValue(addressRootElement, "ToLatitude"));
|
||||
targetContext.put("AvgLongitude", UtilXml.childElementValue(addressRootElement, "AvgLongitude"));
|
||||
targetContext.put("AvgLatitude", UtilXml.childElementValue(addressRootElement, "AvgLatitude"));
|
||||
|
||||
targetContext.put("CMSA", UtilXml.childElementValue(addressRootElement, "CMSA"));
|
||||
targetContext.put("PMSA", UtilXml.childElementValue(addressRootElement, "PMSA"));
|
||||
targetContext.put("MSA", UtilXml.childElementValue(addressRootElement, "MSA"));
|
||||
targetContext.put("MA", UtilXml.childElementValue(addressRootElement, "MA"));
|
||||
|
||||
targetContext.put("TimeZone", UtilXml.childElementValue(addressRootElement, "TimeZone"));
|
||||
targetContext.put("hasDaylightSavings", UtilXml.childElementValue(addressRootElement, "hasDaylightSavings"));
|
||||
targetContext.put("AreaCode", UtilXml.childElementValue(addressRootElement, "AreaCode"));
|
||||
targetContext.put("LLCertainty", UtilXml.childElementValue(addressRootElement, "LLCertainty"));
|
||||
|
||||
targetContext.put("CensusBlockNum", UtilXml.childElementValue(addressRootElement, "CensusBlockNum"));
|
||||
targetContext.put("CensusTractNum", UtilXml.childElementValue(addressRootElement, "CensusTractNum"));
|
||||
|
||||
/*
|
||||
Example URL: http://ws.cdyne.com/psaddress/addresslookup.asmx/ReturnCityState?zipcode=93940&LicenseKey=0
|
||||
NOTE: 0 is a test LicenseKey
|
||||
|
||||
Example Response:
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://ws.cdyne.com/">
|
||||
<ServiceError>false</ServiceError>
|
||||
<AddressError>false</AddressError>
|
||||
<AddressFoundBeMoreSpecific>false</AddressFoundBeMoreSpecific>
|
||||
<NeededCorrection>true</NeededCorrection>
|
||||
|
||||
<DeliveryAddress>**UNKNOWN**</DeliveryAddress>
|
||||
<City>DEL REY OAKS</City>
|
||||
<StateAbbrev>CA</StateAbbrev>
|
||||
<ZipCode>93940</ZipCode>
|
||||
<County>MONTEREY</County>
|
||||
<CountyNum>0</CountyNum>
|
||||
<PreferredCityName>MONTEREY</PreferredCityName>
|
||||
|
||||
<DeliveryPoint>99</DeliveryPoint>
|
||||
<CheckDigit>0</CheckDigit>
|
||||
|
||||
<CSKey>Z20854</CSKey>
|
||||
<FIPS>06053</FIPS>
|
||||
|
||||
<FromLongitude>-121.919965</FromLongitude>
|
||||
<FromLatitude>36.362864</FromLatitude>
|
||||
<ToLongitude>-121.647022</ToLongitude>
|
||||
<ToLatitude>36.652645</ToLatitude>
|
||||
<AvgLongitude>-121.7834935</AvgLongitude>
|
||||
<AvgLatitude>36.5077545</AvgLatitude>
|
||||
|
||||
<CMSA>7120</CMSA>
|
||||
<PMSA />
|
||||
<MSA>7120</MSA>
|
||||
<MA>712</MA>
|
||||
|
||||
<TimeZone>PST</TimeZone>
|
||||
<hasDaylightSavings>true</hasDaylightSavings>
|
||||
<AreaCode>831</AreaCode>
|
||||
<LLCertainty>90</LLCertainty>
|
||||
|
||||
<CensusBlockNum>9003</CensusBlockNum>
|
||||
<CensusTractNum>0134.00</CensusTractNum>
|
||||
</Address>
|
||||
*/
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.FontMetrics;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.io.Writer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
|
||||
import org.apache.commons.lang.RandomStringUtils;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.ofbiz.base.lang.JSON;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.UtilHttp;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.base.util.cache.UtilCache;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.ofbiz.entity.util.EntityUtilProperties;
|
||||
import org.ofbiz.security.Security;
|
||||
|
||||
/**
|
||||
* Common Services
|
||||
*/
|
||||
public class CommonEvents {
|
||||
|
||||
public static final String module = CommonEvents.class.getName();
|
||||
|
||||
private static final String[] ignoreAttrs = new String[] { // Attributes removed for security reason; _ERROR_MESSAGE_ is kept
|
||||
"javax.servlet.request.key_size",
|
||||
"_CONTEXT_ROOT_",
|
||||
"_FORWARDED_FROM_SERVLET_",
|
||||
"javax.servlet.request.ssl_session",
|
||||
"javax.servlet.request.ssl_session_id",
|
||||
"multiPartMap",
|
||||
"javax.servlet.request.cipher_suite",
|
||||
"targetRequestUri",
|
||||
"_SERVER_ROOT_URL_",
|
||||
"_CONTROL_PATH_",
|
||||
"thisRequestUri"
|
||||
};
|
||||
|
||||
private static final UtilCache<String, Map<String, String>> appletSessions = UtilCache.createUtilCache("AppletSessions", 0, 600000, true);
|
||||
|
||||
public static String checkAppletRequest(HttpServletRequest request, HttpServletResponse response) {
|
||||
Delegator delegator = (Delegator) request.getAttribute("delegator");
|
||||
String sessionId = request.getParameter("sessionId");
|
||||
String visitId = request.getParameter("visitId");
|
||||
sessionId = sessionId.trim();
|
||||
visitId = visitId.trim();
|
||||
|
||||
String responseString = "";
|
||||
|
||||
GenericValue visit = null;
|
||||
try {
|
||||
visit = EntityQuery.use(delegator).from("Visit").where("visitId", visitId).queryOne();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Cannot Visit Object", module);
|
||||
}
|
||||
|
||||
if (visit != null && visit.getString("sessionId").equals(sessionId) && appletSessions.containsKey(sessionId)) {
|
||||
Map<String, String> sessionMap = appletSessions.get(sessionId);
|
||||
if (sessionMap != null && sessionMap.containsKey("followPage"))
|
||||
responseString = sessionMap.remove("followPage");
|
||||
}
|
||||
|
||||
try {
|
||||
PrintWriter out = response.getWriter();
|
||||
response.setContentType("text/plain");
|
||||
out.println(responseString);
|
||||
out.close();
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, "Problems writing servlet output!", module);
|
||||
}
|
||||
|
||||
return "success";
|
||||
}
|
||||
|
||||
public static String receiveAppletRequest(HttpServletRequest request, HttpServletResponse response) {
|
||||
Delegator delegator = (Delegator) request.getAttribute("delegator");
|
||||
String sessionId = request.getParameter("sessionId");
|
||||
String visitId = request.getParameter("visitId");
|
||||
sessionId = sessionId.trim();
|
||||
visitId = visitId.trim();
|
||||
|
||||
String responseString = "ERROR";
|
||||
|
||||
GenericValue visit = null;
|
||||
try {
|
||||
visit = EntityQuery.use(delegator).from("Visit").where("visitId", visitId).queryOne();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Cannot Visit Object", module);
|
||||
}
|
||||
|
||||
if (visit.getString("sessionId").equals(sessionId)) {
|
||||
String currentPage = request.getParameter("currentPage");
|
||||
Map<String, String> sessionMap = appletSessions.get(sessionId);
|
||||
if (sessionMap != null) {
|
||||
String followers = sessionMap.get("followers");
|
||||
List<String> folList = StringUtil.split(followers, ",");
|
||||
for (String follower: folList) {
|
||||
Map<String, String> folSesMap = UtilMisc.toMap("followPage", currentPage);
|
||||
appletSessions.put(follower, folSesMap);
|
||||
}
|
||||
}
|
||||
responseString = "OK";
|
||||
}
|
||||
|
||||
try {
|
||||
PrintWriter out = response.getWriter();
|
||||
response.setContentType("text/plain");
|
||||
out.println(responseString);
|
||||
out.close();
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, "Problems writing servlet output!", module);
|
||||
}
|
||||
|
||||
return "success";
|
||||
}
|
||||
|
||||
public static String setAppletFollower(HttpServletRequest request, HttpServletResponse response) {
|
||||
Security security = (Security) request.getAttribute("security");
|
||||
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
|
||||
String visitId = request.getParameter("visitId");
|
||||
if (visitId != null) request.setAttribute("visitId", visitId);
|
||||
if (security.hasPermission("SEND_CONTROL_APPLET", userLogin)) {
|
||||
String followerSessionId = request.getParameter("followerSid");
|
||||
String followSessionId = request.getParameter("followSid");
|
||||
Map<String, String> follow = appletSessions.get(followSessionId);
|
||||
if (follow == null) follow = new LinkedHashMap<String, String>();
|
||||
String followerListStr = follow.get("followers");
|
||||
if (followerListStr == null) {
|
||||
followerListStr = followerSessionId;
|
||||
} else {
|
||||
followerListStr = followerListStr + "," + followerSessionId;
|
||||
}
|
||||
appletSessions.put(followSessionId, follow);
|
||||
appletSessions.put(followerSessionId, null);
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
|
||||
public static String setFollowerPage(HttpServletRequest request, HttpServletResponse response) {
|
||||
Security security = (Security) request.getAttribute("security");
|
||||
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
|
||||
String visitId = request.getParameter("visitId");
|
||||
if (visitId != null) request.setAttribute("visitId", visitId);
|
||||
if (security.hasPermission("SEND_CONTROL_APPLET", userLogin)) {
|
||||
String followerSessionId = request.getParameter("followerSid");
|
||||
String pageUrl = request.getParameter("pageUrl");
|
||||
Map<String, String> follow = appletSessions.get(followerSessionId);
|
||||
if (follow == null) follow = new LinkedHashMap<String, String>();
|
||||
follow.put("followPage", pageUrl);
|
||||
appletSessions.put(followerSessionId, follow);
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
|
||||
/** Simple event to set the users per-session locale setting. The user's locale
|
||||
* setting should be passed as a "newLocale" request parameter. */
|
||||
public static String setSessionLocale(HttpServletRequest request, HttpServletResponse response) {
|
||||
String localeString = request.getParameter("newLocale");
|
||||
if (UtilValidate.isNotEmpty(localeString)) {
|
||||
UtilHttp.setLocale(request, localeString);
|
||||
|
||||
// update the UserLogin object
|
||||
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
|
||||
if (userLogin == null) {
|
||||
userLogin = (GenericValue) request.getSession().getAttribute("autoUserLogin");
|
||||
}
|
||||
|
||||
if (userLogin != null) {
|
||||
GenericValue ulUpdate = GenericValue.create(userLogin);
|
||||
ulUpdate.set("lastLocale", localeString);
|
||||
try {
|
||||
ulUpdate.store();
|
||||
userLogin.refreshFromCache();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
|
||||
/** Simple event to set the user's per-session time zone setting. */
|
||||
public static String setSessionTimeZone(HttpServletRequest request, HttpServletResponse response) {
|
||||
String tzString = request.getParameter("tzId");
|
||||
if (UtilValidate.isNotEmpty(tzString)) {
|
||||
UtilHttp.setTimeZone(request, tzString);
|
||||
|
||||
// update the UserLogin object
|
||||
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
|
||||
if (userLogin == null) {
|
||||
userLogin = (GenericValue) request.getSession().getAttribute("autoUserLogin");
|
||||
}
|
||||
|
||||
if (userLogin != null) {
|
||||
GenericValue ulUpdate = GenericValue.create(userLogin);
|
||||
ulUpdate.set("lastTimeZone", tzString);
|
||||
try {
|
||||
ulUpdate.store();
|
||||
userLogin.refreshFromCache();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
|
||||
/** Simple event to set the users per-session currency uom value */
|
||||
public static String setSessionCurrencyUom(HttpServletRequest request, HttpServletResponse response) {
|
||||
String currencyUom = request.getParameter("currencyUom");
|
||||
if (UtilValidate.isNotEmpty(currencyUom)) {
|
||||
// update the session
|
||||
UtilHttp.setCurrencyUom(request.getSession(), currencyUom);
|
||||
|
||||
// update the UserLogin object
|
||||
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
|
||||
if (userLogin == null) {
|
||||
userLogin = (GenericValue) request.getSession().getAttribute("autoUserLogin");
|
||||
}
|
||||
|
||||
if (userLogin != null) {
|
||||
GenericValue ulUpdate = GenericValue.create(userLogin);
|
||||
ulUpdate.set("lastCurrencyUom", currencyUom);
|
||||
try {
|
||||
ulUpdate.store();
|
||||
userLogin.refreshFromCache();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
|
||||
public static String jsonResponseFromRequestAttributes(HttpServletRequest request, HttpServletResponse response) {
|
||||
// pull out the service response from the request attribute
|
||||
|
||||
Map<String, Object> attrMap = UtilHttp.getJSONAttributeMap(request);
|
||||
|
||||
for (String ignoreAttr : ignoreAttrs) {
|
||||
if (attrMap.containsKey(ignoreAttr)) {
|
||||
attrMap.remove(ignoreAttr);
|
||||
}
|
||||
}
|
||||
try {
|
||||
JSON json = JSON.from(attrMap);
|
||||
writeJSONtoResponse(json, request.getMethod(), response);
|
||||
} catch (Exception e) {
|
||||
return "error";
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
|
||||
private static void writeJSONtoResponse(JSON json, String httpMethod, HttpServletResponse response) throws UnsupportedEncodingException {
|
||||
String jsonStr = json.toString();
|
||||
if (jsonStr == null) {
|
||||
Debug.logError("JSON Object was empty; fatal error!", module);
|
||||
return;
|
||||
}
|
||||
|
||||
// This was added for security reason (OFBIZ-5409), you might need to remove the "//" prefix when handling the JSON response
|
||||
// Though normally you simply have to access the data you want, so should not be annoyed by the "//" prefix
|
||||
if ("GET".equalsIgnoreCase(httpMethod)) {
|
||||
Debug.logWarning("for security reason (OFBIZ-5409) the the '//' prefix was added handling the JSON response. "
|
||||
+ "Normally you simply have to access the data you want, so should not be annoyed by the '//' prefix."
|
||||
+ "You might need to remove it if you use Ajax GET responses (not recommended)."
|
||||
+ "In case, the util.js scrpt is there to help you", module);
|
||||
jsonStr = "//" + jsonStr;
|
||||
}
|
||||
|
||||
// set the JSON content type
|
||||
response.setContentType("application/json");
|
||||
// jsonStr.length is not reliable for unicode characters
|
||||
response.setContentLength(jsonStr.getBytes("UTF8").length);
|
||||
|
||||
// return the JSON String
|
||||
Writer out;
|
||||
try {
|
||||
out = response.getWriter();
|
||||
out.write(jsonStr);
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getJSONuiLabelArray(HttpServletRequest request, HttpServletResponse response)
|
||||
throws UnsupportedEncodingException, IOException {
|
||||
// Format - {resource1 : [key1, key2 ...], resource2 : [key1, key2, ...], ...}
|
||||
String jsonString = request.getParameter("requiredLabels");
|
||||
Map<String, List<String>> uiLabelObject = null;
|
||||
if (UtilValidate.isNotEmpty(jsonString)) {
|
||||
JSON json = JSON.from(jsonString);
|
||||
uiLabelObject = UtilGenerics.<Map<String, List<String>>> cast(json.toObject(Map.class));
|
||||
}
|
||||
if (UtilValidate.isEmpty(uiLabelObject)) {
|
||||
Debug.logError("No resource and labels found in JSON string: " + jsonString, module);
|
||||
return "error";
|
||||
}
|
||||
Locale locale = UtilHttp.getLocale(request);
|
||||
Map<String, List<String>> uiLabelMap = new HashMap<String, List<String>>();
|
||||
Set<Map.Entry<String, List<String>>> entrySet = uiLabelObject.entrySet();
|
||||
for (Map.Entry<String, List<String>> entry : entrySet) {
|
||||
String resource = entry.getKey();
|
||||
List<String> resourceKeys = entry.getValue();
|
||||
if (resourceKeys != null) {
|
||||
List<String> labels = new ArrayList<String>(resourceKeys.size());
|
||||
for (String resourceKey : resourceKeys) {
|
||||
String label = UtilProperties.getMessage(resource, resourceKey, locale);
|
||||
labels.add(label);
|
||||
}
|
||||
uiLabelMap.put(resource, labels);
|
||||
}
|
||||
}
|
||||
writeJSONtoResponse(JSON.from(uiLabelMap), request.getMethod(), response);
|
||||
return "success";
|
||||
}
|
||||
|
||||
public static String getJSONuiLabel(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException {
|
||||
// Format - {resource : key}
|
||||
String jsonString = request.getParameter("requiredLabel");
|
||||
Map<String, String> uiLabelObject = null;
|
||||
if (UtilValidate.isNotEmpty(jsonString)) {
|
||||
JSON json = JSON.from(jsonString);
|
||||
uiLabelObject = UtilGenerics.<Map<String, String>>cast(json.toObject(Map.class));
|
||||
}
|
||||
if (UtilValidate.isEmpty(uiLabelObject)) {
|
||||
Debug.logError("No resource and labels found in JSON string: " + jsonString, module);
|
||||
return "error";
|
||||
} else if (uiLabelObject.size() > 1) {
|
||||
Debug.logError("More than one resource found, please use the method: getJSONuiLabelArray", module);
|
||||
return "error";
|
||||
}
|
||||
Locale locale = UtilHttp.getLocale(request);
|
||||
Map<String, String> uiLabelMap = new HashMap<String, String>();
|
||||
Set<Map.Entry<String, String>> entrySet = uiLabelObject.entrySet();
|
||||
for (Map.Entry<String, String> entry : entrySet) {
|
||||
String resource = entry.getKey();
|
||||
String resourceKey = entry.getValue();
|
||||
if (resourceKey != null) {
|
||||
String label = UtilProperties.getMessage(resource, resourceKey, locale);
|
||||
uiLabelMap.put(resource, label);
|
||||
}
|
||||
}
|
||||
writeJSONtoResponse(JSON.from(uiLabelMap), request.getMethod(), response);
|
||||
return "success";
|
||||
}
|
||||
|
||||
public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
|
||||
try {
|
||||
Delegator delegator = (Delegator) request.getAttribute("delegator");
|
||||
final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"), "default");
|
||||
final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha", "captcha." + captchaSizeConfigName, delegator);
|
||||
final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|");
|
||||
final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored
|
||||
|
||||
final int fontSize = Integer.parseInt(captchaSizeConfigs[0]);
|
||||
final int height = Integer.parseInt(captchaSizeConfigs[1]);
|
||||
final int width = Integer.parseInt(captchaSizeConfigs[2]);
|
||||
final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha", "captcha.code_length", 6);
|
||||
final char[] availableChars = EntityUtilProperties.getPropertyValue("captcha", "captcha.characters", delegator).toCharArray();
|
||||
|
||||
//It is possible to pass the font size, image width and height with the request as well
|
||||
Color backgroundColor = Color.gray;
|
||||
Color borderColor = Color.DARK_GRAY;
|
||||
Color textColor = Color.ORANGE;
|
||||
Color circleColor = new Color(160, 160, 160);
|
||||
Font textFont = new Font("Arial", Font.PLAIN, fontSize);
|
||||
int circlesToDraw = 6;
|
||||
float horizMargin = 20.0f;
|
||||
double rotationRange = 0.7; // in radians
|
||||
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
|
||||
Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
|
||||
|
||||
g.setColor(backgroundColor);
|
||||
g.fillRect(0, 0, width, height);
|
||||
|
||||
//Generating some circles for background noise
|
||||
g.setColor(circleColor);
|
||||
for (int i = 0; i < circlesToDraw; i++) {
|
||||
int circleRadius = (int) (Math.random() * height / 2.0);
|
||||
int circleX = (int) (Math.random() * width - circleRadius);
|
||||
int circleY = (int) (Math.random() * height - circleRadius);
|
||||
g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
|
||||
}
|
||||
g.setColor(textColor);
|
||||
g.setFont(textFont);
|
||||
|
||||
FontMetrics fontMetrics = g.getFontMetrics();
|
||||
int maxAdvance = fontMetrics.getMaxAdvance();
|
||||
int fontHeight = fontMetrics.getHeight();
|
||||
|
||||
String captchaCode = RandomStringUtils.random(6, availableChars);
|
||||
|
||||
float spaceForLetters = -horizMargin * 2 + width;
|
||||
float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);
|
||||
|
||||
for (int i = 0; i < captchaCode.length(); i++) {
|
||||
|
||||
// this is a separate canvas used for the character so that
|
||||
// we can rotate it independently
|
||||
int charWidth = fontMetrics.charWidth(captchaCode.charAt(i));
|
||||
int charDim = Math.max(maxAdvance, fontHeight);
|
||||
int halfCharDim = (charDim / 2);
|
||||
|
||||
BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D charGraphics = charImage.createGraphics();
|
||||
charGraphics.translate(halfCharDim, halfCharDim);
|
||||
double angle = (Math.random() - 0.5) * rotationRange;
|
||||
charGraphics.transform(AffineTransform.getRotateInstance(angle));
|
||||
charGraphics.translate(-halfCharDim, -halfCharDim);
|
||||
charGraphics.setColor(textColor);
|
||||
charGraphics.setFont(textFont);
|
||||
|
||||
int charX = (int) (0.5 * charDim - 0.5 * charWidth);
|
||||
charGraphics.drawString("" + captchaCode.charAt(i), charX,
|
||||
((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()));
|
||||
|
||||
float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
|
||||
int y = ((height - charDim) / 2);
|
||||
|
||||
g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);
|
||||
|
||||
charGraphics.dispose();
|
||||
}
|
||||
// Drawing the image border
|
||||
g.setColor(borderColor);
|
||||
g.drawRect(0, 0, width - 1, height - 1);
|
||||
g.dispose();
|
||||
response.setContentType("image/jpeg");
|
||||
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
|
||||
HttpSession session = request.getSession();
|
||||
Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_"));
|
||||
if (captchaCodeMap == null) {
|
||||
captchaCodeMap = new HashMap<String, String>();
|
||||
session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap);
|
||||
}
|
||||
captchaCodeMap.put(captchaCodeId, captchaCode);
|
||||
} catch (Exception ioe) {
|
||||
Debug.logError(ioe.getMessage(), module);
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
import static org.ofbiz.base.util.UtilGenerics.checkList;
|
||||
import static org.ofbiz.base.util.UtilGenerics.checkMap;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.io.Writer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import javax.mail.internet.MimeMessage;
|
||||
|
||||
import org.ofbiz.base.metrics.Metrics;
|
||||
import org.ofbiz.base.metrics.MetricsFactory;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilCodec;
|
||||
import org.ofbiz.base.util.UtilDateTime;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.transaction.TransactionUtil;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.GenericServiceException;
|
||||
import org.ofbiz.service.LocalDispatcher;
|
||||
import org.ofbiz.service.ModelService;
|
||||
import org.ofbiz.service.ServiceSynchronization;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
import org.ofbiz.service.mail.MimeMessageWrapper;
|
||||
|
||||
/**
|
||||
* Common Services
|
||||
*/
|
||||
public class CommonServices {
|
||||
|
||||
public final static String module = CommonServices.class.getName();
|
||||
public static final String resource = "CommonUiLabels";
|
||||
|
||||
/**
|
||||
* Generic Test Service
|
||||
*@param dctx The DispatchContext that this service is operating in
|
||||
*@param context Map containing the input parameters
|
||||
*@return Map with the result of the service, the output parameters
|
||||
*/
|
||||
public static Map<String, Object> testService(DispatchContext dctx, Map<String, ?> context) {
|
||||
Map<String, Object> response = ServiceUtil.returnSuccess();
|
||||
|
||||
if (context.size() > 0) {
|
||||
for (Map.Entry<String, ?> entry: context.entrySet()) {
|
||||
Object cKey = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
|
||||
System.out.println("---- SVC-CONTEXT: " + cKey + " => " + value);
|
||||
}
|
||||
}
|
||||
if (!context.containsKey("message")) {
|
||||
response.put("resp", "no message found");
|
||||
} else {
|
||||
System.out.println("-----SERVICE TEST----- : " + (String) context.get("message"));
|
||||
response.put("resp", "service done");
|
||||
}
|
||||
|
||||
System.out.println("----- SVC: " + dctx.getName() + " -----");
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic Test SOAP Service
|
||||
*@param dctx The DispatchContext that this service is operating in
|
||||
*@param context Map containing the input parameters
|
||||
*@return Map with the result of the service, the output parameters
|
||||
*/
|
||||
public static Map<String, Object> testSOAPService(DispatchContext dctx, Map<String, ?> context) {
|
||||
Delegator delegator = dctx.getDelegator();
|
||||
Map<String, Object> response = ServiceUtil.returnSuccess();
|
||||
|
||||
List<GenericValue> testingNodes = new LinkedList<GenericValue>();
|
||||
for (int i = 0; i < 3; i ++) {
|
||||
GenericValue testingNode = delegator.makeValue("TestingNode");
|
||||
testingNode.put("testingNodeId", "TESTING_NODE" + i);
|
||||
testingNode.put("description", "Testing Node " + i);
|
||||
testingNode.put("createdStamp", UtilDateTime.nowTimestamp());
|
||||
testingNodes.add(testingNode);
|
||||
}
|
||||
response.put("testingNodes", testingNodes);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static Map<String, Object> blockingTestService(DispatchContext dctx, Map<String, ?> context) {
|
||||
Long duration = (Long) context.get("duration");
|
||||
if (duration == null) {
|
||||
duration = 30000l;
|
||||
}
|
||||
System.out.println("-----SERVICE BLOCKING----- : " + duration/1000d +" seconds");
|
||||
try {
|
||||
Thread.sleep(duration);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
return CommonServices.testService(dctx, context);
|
||||
}
|
||||
|
||||
public static Map<String, Object> testRollbackListener(DispatchContext dctx, Map<String, ?> context) {
|
||||
try {
|
||||
ServiceSynchronization.registerRollbackService(dctx, "testScv", null, context, false, false);
|
||||
} catch (GenericServiceException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonTestRollingBack", locale));
|
||||
}
|
||||
|
||||
public static Map<String, Object> testCommitListener(DispatchContext dctx, Map<String, ?> context) {
|
||||
try {
|
||||
ServiceSynchronization.registerCommitService(dctx, "testScv", null, context, false, false);
|
||||
} catch (GenericServiceException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Note Record
|
||||
*@param ctx The DispatchContext that this service is operating in
|
||||
*@param context Map containing the input parameters
|
||||
*@return Map with the result of the service, the output parameters
|
||||
*/
|
||||
public static Map<String, Object> createNote(DispatchContext ctx, Map<String, ?> context) {
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
GenericValue userLogin = (GenericValue) context.get("userLogin");
|
||||
Timestamp noteDate = (Timestamp) context.get("noteDate");
|
||||
String partyId = (String) context.get("partyId");
|
||||
String noteName = (String) context.get("noteName");
|
||||
String note = (String) context.get("note");
|
||||
String noteId = delegator.getNextSeqId("NoteData");
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
if (noteDate == null) {
|
||||
noteDate = UtilDateTime.nowTimestamp();
|
||||
}
|
||||
|
||||
|
||||
// check for a party id
|
||||
if (partyId == null) {
|
||||
if (userLogin != null && userLogin.get("partyId") != null)
|
||||
partyId = userLogin.getString("partyId");
|
||||
}
|
||||
|
||||
Map<String, Object> fields = UtilMisc.toMap("noteId", noteId, "noteName", noteName, "noteInfo", note,
|
||||
"noteParty", partyId, "noteDateTime", noteDate);
|
||||
|
||||
try {
|
||||
GenericValue newValue = delegator.makeValue("NoteData", fields);
|
||||
|
||||
delegator.create(newValue);
|
||||
} catch (GenericEntityException e) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNoteCannotBeUpdated", UtilMisc.toMap("errorString", e.getMessage()), locale));
|
||||
}
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
|
||||
result.put("noteId", noteId);
|
||||
result.put("partyId", partyId);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service for setting debugging levels.
|
||||
*@param dctc The DispatchContext that this service is operating in
|
||||
*@param context Map containing the input parameters
|
||||
*@return Map with the result of the service, the output parameters
|
||||
*/
|
||||
public static Map<String, Object> adjustDebugLevels(DispatchContext dctc, Map<String, ?> context) {
|
||||
Debug.set(Debug.FATAL, "Y".equalsIgnoreCase((String) context.get("fatal")));
|
||||
Debug.set(Debug.ERROR, "Y".equalsIgnoreCase((String) context.get("error")));
|
||||
Debug.set(Debug.WARNING, "Y".equalsIgnoreCase((String) context.get("warning")));
|
||||
Debug.set(Debug.IMPORTANT, "Y".equalsIgnoreCase((String) context.get("important")));
|
||||
Debug.set(Debug.INFO, "Y".equalsIgnoreCase((String) context.get("info")));
|
||||
Debug.set(Debug.TIMING, "Y".equalsIgnoreCase((String) context.get("timing")));
|
||||
Debug.set(Debug.VERBOSE, "Y".equalsIgnoreCase((String) context.get("verbose")));
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
public static Map<String, Object> forceGc(DispatchContext dctx, Map<String, ?> context) {
|
||||
System.gc();
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
/**
|
||||
* Echo service; returns exactly what was sent.
|
||||
* This service does not have required parameters and does not validate
|
||||
*/
|
||||
public static Map<String, Object> echoService(DispatchContext dctx, Map<String, ?> context) {
|
||||
Map<String, Object> result = new LinkedHashMap<String, Object>();
|
||||
result.putAll(context);
|
||||
result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return Error Service; Used for testing error handling
|
||||
*/
|
||||
public static Map<String, Object> returnErrorService(DispatchContext dctx, Map<String, ?> context) {
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonServiceReturnError", locale));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return TRUE Service; ECA Condition Service
|
||||
*/
|
||||
public static Map<String, Object> conditionTrueService(DispatchContext dctx, Map<String, ?> context) {
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
result.put("conditionReply", Boolean.TRUE);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return FALSE Service; ECA Condition Service
|
||||
*/
|
||||
public static Map<String, Object> conditionFalseService(DispatchContext dctx, Map<String, ?> context) {
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
result.put("conditionReply", Boolean.FALSE);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Cause a Referential Integrity Error */
|
||||
public static Map<String, Object> entityFailTest(DispatchContext dctx, Map<String, ?> context) {
|
||||
Delegator delegator = dctx.getDelegator();
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
|
||||
// attempt to create a DataSource entity w/ an invalid dataSourceTypeId
|
||||
GenericValue newEntity = delegator.makeValue("DataSource");
|
||||
newEntity.set("dataSourceId", "ENTITY_FAIL_TEST");
|
||||
newEntity.set("dataSourceTypeId", "ENTITY_FAIL_TEST");
|
||||
newEntity.set("description", "Entity Fail Test - Delete me if I am here");
|
||||
try {
|
||||
delegator.create(newEntity);
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEntityTestFailure", locale));
|
||||
}
|
||||
|
||||
/*
|
||||
try {
|
||||
newEntity.remove();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
*/
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
/** Test entity sorting */
|
||||
public static Map<String, Object> entitySortTest(DispatchContext dctx, Map<String, ?> context) {
|
||||
Delegator delegator = dctx.getDelegator();
|
||||
Set<ModelEntity> set = new TreeSet<ModelEntity>();
|
||||
|
||||
set.add(delegator.getModelEntity("Person"));
|
||||
set.add(delegator.getModelEntity("PartyRole"));
|
||||
set.add(delegator.getModelEntity("Party"));
|
||||
set.add(delegator.getModelEntity("ContactMech"));
|
||||
set.add(delegator.getModelEntity("PartyContactMech"));
|
||||
set.add(delegator.getModelEntity("OrderHeader"));
|
||||
set.add(delegator.getModelEntity("OrderItem"));
|
||||
set.add(delegator.getModelEntity("OrderContactMech"));
|
||||
set.add(delegator.getModelEntity("OrderRole"));
|
||||
set.add(delegator.getModelEntity("Product"));
|
||||
set.add(delegator.getModelEntity("RoleType"));
|
||||
|
||||
for (ModelEntity modelEntity: set) {
|
||||
Debug.logInfo(modelEntity.getEntityName(), module);
|
||||
}
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
public static Map<String, Object> makeALotOfVisits(DispatchContext dctx, Map<String, ?> context) {
|
||||
Delegator delegator = dctx.getDelegator();
|
||||
int count = ((Integer) context.get("count")).intValue();
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
GenericValue v = delegator.makeValue("Visit");
|
||||
String seqId = delegator.getNextSeqId("Visit");
|
||||
|
||||
v.set("visitId", seqId);
|
||||
v.set("userCreated", "N");
|
||||
v.set("sessionId", "NA-" + seqId);
|
||||
v.set("serverIpAddress", "127.0.0.1");
|
||||
v.set("serverHostName", "localhost");
|
||||
v.set("webappName", "webtools");
|
||||
v.set("initialLocale", "en_US");
|
||||
v.set("initialRequest", "https://localhost:8443/webtools/control/main");
|
||||
v.set("initialReferrer", "https://localhost:8443/webtools/control/main");
|
||||
v.set("initialUserAgent", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1");
|
||||
v.set("clientIpAddress", "127.0.0.1");
|
||||
v.set("clientHostName", "localhost");
|
||||
v.set("fromDate", UtilDateTime.nowTimestamp());
|
||||
|
||||
try {
|
||||
delegator.create(v);
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
public static Map<String, Object> displayXaDebugInfo(DispatchContext dctx, Map<String, ?> context) {
|
||||
if (TransactionUtil.debugResources()) {
|
||||
if (UtilValidate.isNotEmpty(TransactionUtil.debugResMap)) {
|
||||
TransactionUtil.logRunningTx();
|
||||
} else {
|
||||
Debug.logInfo("No running transaction to display.", module);
|
||||
}
|
||||
} else {
|
||||
Debug.logInfo("Debug resources is disabled.", module);
|
||||
}
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
public static Map<String, Object> byteBufferTest(DispatchContext dctx, Map<String, ?> context) {
|
||||
ByteBuffer buffer1 = (ByteBuffer) context.get("byteBuffer1");
|
||||
ByteBuffer buffer2 = (ByteBuffer) context.get("byteBuffer2");
|
||||
String fileName1 = (String) context.get("saveAsFileName1");
|
||||
String fileName2 = (String) context.get("saveAsFileName2");
|
||||
String ofbizHome = System.getProperty("ofbiz.home");
|
||||
String outputPath1 = ofbizHome + (fileName1.startsWith("/") ? fileName1 : "/" + fileName1);
|
||||
String outputPath2 = ofbizHome + (fileName2.startsWith("/") ? fileName2 : "/" + fileName2);
|
||||
RandomAccessFile file1 = null, file2 = null;
|
||||
|
||||
try {
|
||||
file1 = new RandomAccessFile(outputPath1, "rw");
|
||||
file2 = new RandomAccessFile(outputPath2, "rw");
|
||||
file1.write(buffer1.array());
|
||||
file2.write(buffer2.array());
|
||||
} catch (FileNotFoundException e) {
|
||||
Debug.logError(e, module);
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
} finally {
|
||||
try {
|
||||
file1.close();
|
||||
file2.close();
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
public static Map<String, Object> uploadTest(DispatchContext dctx, Map<String, ?> context) {
|
||||
LocalDispatcher dispatcher = dctx.getDispatcher();
|
||||
GenericValue userLogin = (GenericValue) context.get("userLogin");
|
||||
|
||||
byte[] array = (byte[]) context.get("uploadFile");
|
||||
String fileName = (String) context.get("_uploadFile_fileName");
|
||||
String contentType = (String) context.get("_uploadFile_contentType");
|
||||
|
||||
Map<String, Object> createCtx = new LinkedHashMap<String, Object>();
|
||||
createCtx.put("binData", array);
|
||||
createCtx.put("dataResourceTypeId", "OFBIZ_FILE");
|
||||
createCtx.put("dataResourceName", fileName);
|
||||
createCtx.put("dataCategoryId", "PERSONAL");
|
||||
createCtx.put("statusId", "CTNT_PUBLISHED");
|
||||
createCtx.put("mimeTypeId", contentType);
|
||||
createCtx.put("userLogin", userLogin);
|
||||
|
||||
Map<String, Object> createResp = null;
|
||||
try {
|
||||
createResp = dispatcher.runSync("createFile", createCtx);
|
||||
} catch (GenericServiceException e) {
|
||||
Debug.logError(e, module);
|
||||
return ServiceUtil.returnError(e.getMessage());
|
||||
}
|
||||
if (ServiceUtil.isError(createResp)) {
|
||||
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createResp));
|
||||
}
|
||||
|
||||
GenericValue dataResource = (GenericValue) createResp.get("dataResource");
|
||||
if (dataResource != null) {
|
||||
Map<String, Object> contentCtx = new LinkedHashMap<String, Object>();
|
||||
contentCtx.put("dataResourceId", dataResource.getString("dataResourceId"));
|
||||
contentCtx.put("localeString", ((Locale) context.get("locale")).toString());
|
||||
contentCtx.put("contentTypeId", "DOCUMENT");
|
||||
contentCtx.put("mimeTypeId", contentType);
|
||||
contentCtx.put("contentName", fileName);
|
||||
contentCtx.put("statusId", "CTNT_PUBLISHED");
|
||||
contentCtx.put("userLogin", userLogin);
|
||||
|
||||
Map<String, Object> contentResp = null;
|
||||
try {
|
||||
contentResp = dispatcher.runSync("createContent", contentCtx);
|
||||
} catch (GenericServiceException e) {
|
||||
Debug.logError(e, module);
|
||||
return ServiceUtil.returnError(e.getMessage());
|
||||
}
|
||||
if (ServiceUtil.isError(contentResp)) {
|
||||
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(contentResp));
|
||||
}
|
||||
}
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
public static Map<String, Object> simpleMapListTest(DispatchContext dctx, Map<String, ?> context) {
|
||||
List<String> listOfStrings = checkList(context.get("listOfStrings"), String.class);
|
||||
Map<String, String> mapOfStrings = checkMap(context.get("mapOfStrings"), String.class, String.class);
|
||||
|
||||
for (String str: listOfStrings) {
|
||||
String v = mapOfStrings.get(str);
|
||||
Debug.logInfo("SimpleMapListTest: " + str + " -> " + v, module);
|
||||
}
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
public static Map<String, Object> mcaTest(DispatchContext dctx, Map<String, ?> context) {
|
||||
MimeMessageWrapper wrapper = (MimeMessageWrapper) context.get("messageWrapper");
|
||||
MimeMessage message = wrapper.getMessage();
|
||||
try {
|
||||
if (message.getAllRecipients() != null) {
|
||||
Debug.logInfo("To: " + UtilMisc.toListArray(message.getAllRecipients()), module);
|
||||
}
|
||||
if (message.getFrom() != null) {
|
||||
Debug.logInfo("From: " + UtilMisc.toListArray(message.getFrom()), module);
|
||||
}
|
||||
Debug.logInfo("Subject: " + message.getSubject(), module);
|
||||
if (message.getSentDate() != null) {
|
||||
Debug.logInfo("Sent: " + message.getSentDate().toString(), module);
|
||||
}
|
||||
if (message.getReceivedDate() != null) {
|
||||
Debug.logInfo("Received: " + message.getReceivedDate().toString(), module);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
public static Map<String, Object> streamTest(DispatchContext dctx, Map<String, ?> context) {
|
||||
InputStream in = (InputStream) context.get("inputStream");
|
||||
OutputStream out = (OutputStream) context.get("outputStream");
|
||||
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
|
||||
Writer writer = new OutputStreamWriter(out);
|
||||
String line;
|
||||
|
||||
try {
|
||||
while ((line = reader.readLine()) != null) {
|
||||
Debug.logInfo("Read line: " + line, module);
|
||||
writer.write(line);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
return ServiceUtil.returnError(e.getMessage());
|
||||
} finally {
|
||||
try {
|
||||
writer.close();
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
result.put("contentType", "text/plain");
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Map<String, Object> ping(DispatchContext dctx, Map<String, ?> context) {
|
||||
Delegator delegator = dctx.getDelegator();
|
||||
String message = (String) context.get("message");
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
if (message == null) {
|
||||
message = "PONG";
|
||||
}
|
||||
|
||||
long count = -1;
|
||||
try {
|
||||
count = EntityQuery.use(delegator).from("SequenceValueItem").queryCount();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonPingDatasourceCannotConnect", locale));
|
||||
}
|
||||
|
||||
if (count > 0) {
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
result.put("message", message);
|
||||
return result;
|
||||
} else {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonPingDatasourceInvalidCount", locale));
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<String, Object> getAllMetrics(DispatchContext dctx, Map<String, ?> context) {
|
||||
List<Map<String, Object>> metricsMapList = new LinkedList<Map<String, Object>>();
|
||||
Collection<Metrics> metricsList = MetricsFactory.getMetrics();
|
||||
for (Metrics metrics : metricsList) {
|
||||
Map<String, Object> metricsMap = new LinkedHashMap<String, Object>();
|
||||
metricsMap.put("name", metrics.getName());
|
||||
metricsMap.put("serviceRate", metrics.getServiceRate());
|
||||
metricsMap.put("threshold", metrics.getThreshold());
|
||||
metricsMap.put("totalEvents", metrics.getTotalEvents());
|
||||
metricsMapList.add(metricsMap);
|
||||
}
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
result.put("metricsList", metricsMapList);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Map<String, Object> resetMetric(DispatchContext dctx, Map<String, ?> context) {
|
||||
String originalName = (String) context.get("name");
|
||||
String name = UtilCodec.getDecoder("url").decode(originalName);
|
||||
if (name == null) {
|
||||
return ServiceUtil.returnError("Exception thrown while decoding metric name \"" + originalName + "\"");
|
||||
}
|
||||
Metrics metric = MetricsFactory.getMetric(name);
|
||||
if (metric != null) {
|
||||
metric.reset();
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
return ServiceUtil.returnError("Metric \"" + name + "\" not found.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.condition.EntityExpr;
|
||||
import org.ofbiz.entity.condition.EntityOperator;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.ofbiz.entity.util.EntityTypeUtil;
|
||||
import org.ofbiz.entity.util.EntityUtilProperties;
|
||||
|
||||
/**
|
||||
* Common Workers
|
||||
*/
|
||||
public final class CommonWorkers {
|
||||
|
||||
public final static String module = CommonWorkers.class.getName();
|
||||
|
||||
private CommonWorkers() {}
|
||||
|
||||
public static List<GenericValue> getCountryList(Delegator delegator) {
|
||||
List<GenericValue> geoList = new LinkedList<GenericValue>();
|
||||
String defaultCountry = EntityUtilProperties.getPropertyValue("general", "country.geo.id.default", delegator);
|
||||
GenericValue defaultGeo = null;
|
||||
if (UtilValidate.isNotEmpty(defaultCountry)) {
|
||||
try {
|
||||
defaultGeo = EntityQuery.use(delegator).from("Geo").where("geoId", defaultCountry).cache().queryOne();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Cannot lookup Geo", module);
|
||||
}
|
||||
}
|
||||
|
||||
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("geoTypeId", EntityOperator.EQUALS, "COUNTRY"));
|
||||
List<String> countriesAvailable = StringUtil.split(EntityUtilProperties.getPropertyValue("general", "countries.geo.id.available", delegator), ",");
|
||||
if (UtilValidate.isNotEmpty(countriesAvailable)) {
|
||||
// only available countries (we don't verify the list of geoId in countries.geo.id.available)
|
||||
exprs.add(EntityCondition.makeCondition("geoId", EntityOperator.IN, countriesAvailable));
|
||||
}
|
||||
|
||||
List<GenericValue> countriesList = new LinkedList<GenericValue>();
|
||||
try {
|
||||
countriesList = EntityQuery.use(delegator).from("Geo").where(exprs).orderBy("geoName").cache(true).queryList();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Cannot lookup Geo", module);
|
||||
}
|
||||
if (defaultGeo != null) {
|
||||
geoList.add(defaultGeo);
|
||||
boolean removeDefaultGeo = UtilValidate.isEmpty(countriesList);
|
||||
if (!removeDefaultGeo) {
|
||||
for (GenericValue country : countriesList) {
|
||||
if (country.get("geoId").equals(defaultGeo.get("geoId"))) {
|
||||
removeDefaultGeo = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (removeDefaultGeo) {
|
||||
geoList.remove(0); // Remove default country to avoid double rows in drop-down, from 1st place to keep alphabetical order
|
||||
}
|
||||
geoList.addAll(countriesList);
|
||||
} else {
|
||||
geoList = countriesList;
|
||||
}
|
||||
return geoList;
|
||||
}
|
||||
|
||||
public static List<GenericValue> getStateList(Delegator delegator) {
|
||||
List<GenericValue> geoList = new LinkedList<GenericValue>();
|
||||
EntityCondition condition = EntityCondition.makeCondition(EntityOperator.OR, EntityCondition.makeCondition("geoTypeId", "STATE"), EntityCondition.makeCondition("geoTypeId", "PROVINCE"), EntityCondition.makeCondition("geoTypeId", "TERRITORY"),
|
||||
EntityCondition.makeCondition("geoTypeId", "MUNICIPALITY"));
|
||||
try {
|
||||
geoList = EntityQuery.use(delegator).from("Geo").where(condition).orderBy("geoName").cache(true).queryList();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Cannot lookup State Geos: " + e.toString(), module);
|
||||
}
|
||||
return geoList;
|
||||
}
|
||||
|
||||
public static List<GenericValue> getAssociatedStateList(Delegator delegator, String country) {
|
||||
return getAssociatedStateList(delegator, country, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of regional geo associations.
|
||||
*/
|
||||
public static List<GenericValue> getAssociatedStateList(Delegator delegator, String country, String listOrderBy) {
|
||||
if (UtilValidate.isEmpty(country)) {
|
||||
// Load the system default country
|
||||
country = EntityUtilProperties.getPropertyValue("general", "country.geo.id.default", delegator);
|
||||
}
|
||||
|
||||
if (UtilValidate.isEmpty(listOrderBy)) {
|
||||
listOrderBy = "geoId";
|
||||
}
|
||||
List<String> sortList = UtilMisc.toList(listOrderBy);
|
||||
|
||||
List<GenericValue> geoList = new LinkedList<GenericValue>();
|
||||
try {
|
||||
// Check if the country is a country group and get recursively the
|
||||
// states
|
||||
List<GenericValue> regionList = EntityQuery.use(delegator)
|
||||
.from("GeoAssocAndGeoToWithState")
|
||||
.where("geoIdFrom", country, "geoAssocTypeId", "GROUP_MEMBER", "geoTypeId", "GROUP")
|
||||
.orderBy(sortList)
|
||||
.cache(true)
|
||||
.queryList();
|
||||
if (regionList.size() == 1) {
|
||||
for (GenericValue region : regionList) {
|
||||
List<GenericValue> tmpState = EntityQuery.use(delegator)
|
||||
.from("GeoAssocAndGeoTo")
|
||||
.where("geoId", region.getString("geoIdFrom"))
|
||||
.orderBy(sortList)
|
||||
.cache(true)
|
||||
.queryList();
|
||||
for (GenericValue state : tmpState) {
|
||||
geoList.addAll(getAssociatedStateList(delegator, state.getString("geoIdFrom"), listOrderBy));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// get all related states
|
||||
EntityCondition stateProvinceFindCond = EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition("geoIdFrom", country),
|
||||
EntityCondition.makeCondition("geoAssocTypeId", "REGIONS"),
|
||||
EntityCondition.makeCondition(EntityOperator.OR, EntityCondition.makeCondition("geoTypeId", "STATE"), EntityCondition.makeCondition("geoTypeId", "PROVINCE"), EntityCondition.makeCondition("geoTypeId", "MUNICIPALITY"),
|
||||
EntityCondition.makeCondition("geoTypeId", "TERRITORY"), EntityCondition.makeCondition("geoTypeId", "COUNTY")));
|
||||
geoList.addAll(EntityQuery.use(delegator)
|
||||
.from("GeoAssocAndGeoToWithState")
|
||||
.where(stateProvinceFindCond)
|
||||
.orderBy(sortList)
|
||||
.cache(true)
|
||||
.queryList()
|
||||
);
|
||||
} catch (GenericEntityException e){
|
||||
Debug.logError(e, "Cannot lookup Geo", module);
|
||||
}
|
||||
|
||||
return geoList;
|
||||
}
|
||||
|
||||
/**
|
||||
* A generic method to be used on Type enities, e.g. ProductType. Recurse to the root level in the type hierarchy
|
||||
* and checks if the specified type childType has parentType as its parent somewhere in the hierarchy.
|
||||
*
|
||||
* @param delegator The Delegator object.
|
||||
* @param entityName Name of the Type entity on which check is performed.
|
||||
* @param primaryKey Primary Key field of the Type entity.
|
||||
* @param childType Type value for which the check is performed.
|
||||
* @param parentTypeField Field in Type entity which stores the parent type.
|
||||
* @param parentType Value of the parent type against which check is performed.
|
||||
* @return boolean value based on the check results.
|
||||
*
|
||||
* @deprecated Moved to {@link org.ofbiz.entity.util.EntityTypeUtil#hasParentType(Delegator, String, String, String, String, String) EntityTypeUtil}
|
||||
*/
|
||||
@Deprecated
|
||||
public static boolean hasParentType(Delegator delegator, String entityName, String primaryKey, String childType, String parentTypeField, String parentType) {
|
||||
return EntityTypeUtil.hasParentType(delegator, entityName, primaryKey, childType, parentTypeField, parentType);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
/**
|
||||
* Data Model Constants
|
||||
*/
|
||||
public final class DataModelConstants {
|
||||
|
||||
/** Constant for denote that the Sequence ID does not apply (i.e. corresponds to all) */
|
||||
public static final String SEQ_ID_NA = "_NA_";
|
||||
}
|
||||
@@ -0,0 +1,775 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
import static org.ofbiz.base.util.UtilGenerics.checkList;
|
||||
import static org.ofbiz.base.util.UtilGenerics.checkMap;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.ObjectType;
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
import org.ofbiz.base.util.UtilDateTime;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.UtilHttp;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.condition.EntityComparisonOperator;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.condition.EntityConditionList;
|
||||
import org.ofbiz.entity.condition.EntityFunction;
|
||||
import org.ofbiz.entity.condition.EntityOperator;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
import org.ofbiz.entity.util.EntityListIterator;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.ofbiz.entity.util.EntityUtil;
|
||||
import org.ofbiz.entity.util.EntityUtilProperties;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.GenericServiceException;
|
||||
import org.ofbiz.service.LocalDispatcher;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
|
||||
/**
|
||||
* FindServices Class
|
||||
*/
|
||||
public class FindServices {
|
||||
|
||||
public static final String module = FindServices.class.getName();
|
||||
public static final String resource = "CommonUiLabels";
|
||||
public static Map<String, EntityComparisonOperator<?, ?>> entityOperators;
|
||||
|
||||
static {
|
||||
entityOperators = new LinkedHashMap<String, EntityComparisonOperator<?, ?>>();
|
||||
entityOperators.put("between", EntityOperator.BETWEEN);
|
||||
entityOperators.put("equals", EntityOperator.EQUALS);
|
||||
entityOperators.put("greaterThan", EntityOperator.GREATER_THAN);
|
||||
entityOperators.put("greaterThanEqualTo", EntityOperator.GREATER_THAN_EQUAL_TO);
|
||||
entityOperators.put("in", EntityOperator.IN);
|
||||
entityOperators.put("not-in", EntityOperator.NOT_IN);
|
||||
entityOperators.put("lessThan", EntityOperator.LESS_THAN);
|
||||
entityOperators.put("lessThanEqualTo", EntityOperator.LESS_THAN_EQUAL_TO);
|
||||
entityOperators.put("like", EntityOperator.LIKE);
|
||||
entityOperators.put("notLike", EntityOperator.NOT_LIKE);
|
||||
entityOperators.put("not", EntityOperator.NOT);
|
||||
entityOperators.put("notEqual", EntityOperator.NOT_EQUAL);
|
||||
}
|
||||
|
||||
public FindServices() {}
|
||||
|
||||
/**
|
||||
* prepareField, analyse inputFields to created normalizedFields a map with field name and operator.
|
||||
*
|
||||
* This is use to the generic method that expects entity data affixed with special suffixes
|
||||
* to indicate their purpose in formulating an SQL query statement.
|
||||
* @param inputFields Input parameters run thru UtilHttp.getParameterMap
|
||||
* @return a map with field name and operator
|
||||
*/
|
||||
public static Map<String, Map<String, Map<String, Object>>> prepareField(Map<String, ?> inputFields, Map<String, Object> queryStringMap, Map<String, List<Object[]>> origValueMap) {
|
||||
// Strip the "_suffix" off of the parameter name and
|
||||
// build a three-level map of values keyed by fieldRoot name,
|
||||
// fld0 or fld1, and, then, "op" or "value"
|
||||
// ie. id
|
||||
// - fld0
|
||||
// - op:like
|
||||
// - value:abc
|
||||
// - fld1 (if there is a range)
|
||||
// - op:lessThan
|
||||
// - value:55 (note: these two "flds" wouldn't really go together)
|
||||
// Also note that op/fld can be in any order. (eg. id_fld1_equals or id_equals_fld1)
|
||||
// Note that "normalizedFields" will contain values other than those
|
||||
// Contained in the associated entity.
|
||||
// Those extra fields will be ignored in the second half of this method.
|
||||
Map<String, Map<String, Map<String, Object>>> normalizedFields = new LinkedHashMap<String, Map<String, Map<String, Object>>>();
|
||||
//StringBuffer queryStringBuf = new StringBuffer();
|
||||
for (String fieldNameRaw: inputFields.keySet()) { // The name as it appeas in the HTML form
|
||||
String fieldNameRoot = null; // The entity field name. Everything to the left of the first "_" if
|
||||
// it exists, or the whole word, if not.
|
||||
String fieldPair = null; // "fld0" or "fld1" - begin/end of range or just fld0 if no range.
|
||||
Object fieldValue = null; // If it is a "value" field, it will be the value to be used in the query.
|
||||
// If it is an "op" field, it will be "equals", "greaterThan", etc.
|
||||
int iPos = -1;
|
||||
int iPos2 = -1;
|
||||
Map<String, Map<String, Object>> subMap = null;
|
||||
Map<String, Object> subMap2 = null;
|
||||
String fieldMode = null;
|
||||
|
||||
fieldValue = inputFields.get(fieldNameRaw);
|
||||
if (ObjectType.isEmpty(fieldValue)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
//queryStringBuffer.append(fieldNameRaw + "=" + fieldValue);
|
||||
queryStringMap.put(fieldNameRaw, fieldValue);
|
||||
iPos = fieldNameRaw.indexOf("_"); // Look for suffix
|
||||
|
||||
// This is a hack to skip fields from "multi" forms
|
||||
// These would have the form "fieldName_o_1"
|
||||
if (iPos >= 0) {
|
||||
String suffix = fieldNameRaw.substring(iPos + 1);
|
||||
iPos2 = suffix.indexOf("_");
|
||||
if (iPos2 == 1) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// If no suffix, assume no range (default to fld0) and operations of equals
|
||||
// If no field op is present, it will assume "equals".
|
||||
if (iPos < 0) {
|
||||
fieldNameRoot = fieldNameRaw;
|
||||
fieldPair = "fld0";
|
||||
fieldMode = "value";
|
||||
} else { // Must have at least "fld0/1" or "equals, greaterThan, etc."
|
||||
// Some bogus fields will slip in, like "ENTITY_NAME", but they will be ignored
|
||||
|
||||
fieldNameRoot = fieldNameRaw.substring(0, iPos);
|
||||
String suffix = fieldNameRaw.substring(iPos + 1);
|
||||
iPos2 = suffix.indexOf("_");
|
||||
if (iPos2 < 0) {
|
||||
if (suffix.startsWith("fld")) {
|
||||
// If only one token and it starts with "fld"
|
||||
// assume it is a value field, not an op
|
||||
fieldPair = suffix;
|
||||
fieldMode = "value";
|
||||
} else {
|
||||
// if it does not start with fld, assume it is an op or the 'ignore case' (ic) field
|
||||
fieldPair = "fld0";
|
||||
fieldMode = suffix;
|
||||
}
|
||||
} else {
|
||||
String tkn0 = suffix.substring(0, iPos2);
|
||||
String tkn1 = suffix.substring(iPos2 + 1);
|
||||
// If suffix has two parts, let them be in any order
|
||||
// One will be "fld0/1" and the other will be the op (eg. equals, greaterThan_
|
||||
if (tkn0.startsWith("fld")) {
|
||||
fieldPair = tkn0;
|
||||
fieldMode = tkn1;
|
||||
} else {
|
||||
fieldPair = tkn1;
|
||||
fieldMode = tkn0;
|
||||
}
|
||||
}
|
||||
}
|
||||
subMap = normalizedFields.get(fieldNameRoot);
|
||||
if (subMap == null) {
|
||||
subMap = new LinkedHashMap<String, Map<String, Object>>();
|
||||
normalizedFields.put(fieldNameRoot, subMap);
|
||||
}
|
||||
subMap2 = subMap.get(fieldPair);
|
||||
if (subMap2 == null) {
|
||||
subMap2 = new LinkedHashMap<String, Object>();
|
||||
subMap.put(fieldPair, subMap2);
|
||||
}
|
||||
subMap2.put(fieldMode, fieldValue);
|
||||
|
||||
List<Object[]> origList = origValueMap.get(fieldNameRoot);
|
||||
if (origList == null) {
|
||||
origList = new LinkedList<Object[]>();
|
||||
origValueMap.put(fieldNameRoot, origList);
|
||||
}
|
||||
Object [] origValues = {fieldNameRaw, fieldValue};
|
||||
origList.add(origValues);
|
||||
}
|
||||
return normalizedFields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses input parameters and returns an <code>EntityCondition</code> list.
|
||||
*
|
||||
* @param parameters
|
||||
* @param fieldList
|
||||
* @param queryStringMap
|
||||
* @param delegator
|
||||
* @param context
|
||||
* @return returns an EntityCondition list
|
||||
*/
|
||||
public static List<EntityCondition> createConditionList(Map<String, ? extends Object> parameters, List<ModelField> fieldList, Map<String, Object> queryStringMap, Delegator delegator, Map<String, ?> context) {
|
||||
Set<String> processed = new LinkedHashSet<String>();
|
||||
Set<String> keys = new LinkedHashSet<String>();
|
||||
Map<String, ModelField> fieldMap = new LinkedHashMap<String, ModelField>();
|
||||
for (ModelField modelField : fieldList) {
|
||||
fieldMap.put(modelField.getName(), modelField);
|
||||
}
|
||||
List<EntityCondition> result = new LinkedList<EntityCondition>();
|
||||
for (Map.Entry<String, ? extends Object> entry : parameters.entrySet()) {
|
||||
String parameterName = entry.getKey();
|
||||
if (processed.contains(parameterName)) {
|
||||
continue;
|
||||
}
|
||||
keys.clear();
|
||||
String fieldName = parameterName;
|
||||
Object fieldValue = null;
|
||||
String operation = null;
|
||||
boolean ignoreCase = false;
|
||||
if (parameterName.endsWith("_ic") || parameterName.endsWith("_op")) {
|
||||
fieldName = parameterName.substring(0, parameterName.length() - 3);
|
||||
} else if (parameterName.endsWith("_value")) {
|
||||
fieldName = parameterName.substring(0, parameterName.length() - 6);
|
||||
}
|
||||
String key = fieldName.concat("_ic");
|
||||
if (parameters.containsKey(key)) {
|
||||
keys.add(key);
|
||||
ignoreCase = "Y".equals(parameters.get(key));
|
||||
}
|
||||
key = fieldName.concat("_op");
|
||||
if (parameters.containsKey(key)) {
|
||||
keys.add(key);
|
||||
operation = (String) parameters.get(key);
|
||||
}
|
||||
key = fieldName.concat("_value");
|
||||
if (parameters.containsKey(key)) {
|
||||
keys.add(key);
|
||||
fieldValue = parameters.get(key);
|
||||
}
|
||||
if (fieldName.endsWith("_fld0") || fieldName.endsWith("_fld1")) {
|
||||
if (parameters.containsKey(fieldName)) {
|
||||
keys.add(fieldName);
|
||||
}
|
||||
fieldName = fieldName.substring(0, fieldName.length() - 5);
|
||||
}
|
||||
if (parameters.containsKey(fieldName)) {
|
||||
keys.add(fieldName);
|
||||
}
|
||||
processed.addAll(keys);
|
||||
ModelField modelField = fieldMap.get(fieldName);
|
||||
if (modelField == null) {
|
||||
continue;
|
||||
}
|
||||
if (fieldValue == null) {
|
||||
fieldValue = parameters.get(fieldName);
|
||||
}
|
||||
if (ObjectType.isEmpty(fieldValue) && !"empty".equals(operation)) {
|
||||
continue;
|
||||
}
|
||||
result.add(createSingleCondition(modelField, operation, fieldValue, ignoreCase, delegator, context));
|
||||
for (String mapKey : keys) {
|
||||
queryStringMap.put(mapKey, parameters.get(mapKey));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a single <code>EntityCondition</code> based on a set of parameters.
|
||||
*
|
||||
* @param modelField
|
||||
* @param operation
|
||||
* @param fieldValue
|
||||
* @param ignoreCase
|
||||
* @param delegator
|
||||
* @param context
|
||||
* @return return an EntityCondition
|
||||
*/
|
||||
public static EntityCondition createSingleCondition(ModelField modelField, String operation, Object fieldValue, boolean ignoreCase, Delegator delegator, Map<String, ?> context) {
|
||||
EntityCondition cond = null;
|
||||
String fieldName = modelField.getName();
|
||||
EntityComparisonOperator<?, ?> fieldOp = null;
|
||||
if (operation != null) {
|
||||
if (operation.equals("contains")) {
|
||||
fieldOp = EntityOperator.LIKE;
|
||||
fieldValue = "%" + fieldValue + "%";
|
||||
} else if ("not-contains".equals(operation) || "notContains".equals(operation)) {
|
||||
fieldOp = EntityOperator.NOT_LIKE;
|
||||
fieldValue = "%" + fieldValue + "%";
|
||||
} else if (operation.equals("empty")) {
|
||||
return EntityCondition.makeCondition(fieldName, EntityOperator.EQUALS, null);
|
||||
} else if (operation.equals("like")) {
|
||||
fieldOp = EntityOperator.LIKE;
|
||||
fieldValue = fieldValue + "%";
|
||||
} else if ("not-like".equals(operation) || "notLike".equals(operation)) {
|
||||
fieldOp = EntityOperator.NOT_LIKE;
|
||||
fieldValue = fieldValue + "%";
|
||||
} else if ("opLessThan".equals(operation)) {
|
||||
fieldOp = EntityOperator.LESS_THAN;
|
||||
} else if ("upToDay".equals(operation)) {
|
||||
fieldOp = EntityOperator.LESS_THAN;
|
||||
} else if ("upThruDay".equals(operation)) {
|
||||
fieldOp = EntityOperator.LESS_THAN_EQUAL_TO;
|
||||
} else if (operation.equals("greaterThanFromDayStart")) {
|
||||
String timeStampString = (String) fieldValue;
|
||||
Object startValue = modelField.getModelEntity().convertFieldValue(modelField, dayStart(timeStampString, 0), delegator, context);
|
||||
return EntityCondition.makeCondition(fieldName, EntityOperator.GREATER_THAN_EQUAL_TO, startValue);
|
||||
} else if (operation.equals("sameDay")) {
|
||||
String timeStampString = (String) fieldValue;
|
||||
Object startValue = modelField.getModelEntity().convertFieldValue(modelField, dayStart(timeStampString, 0), delegator, context);
|
||||
EntityCondition startCond = EntityCondition.makeCondition(fieldName, EntityOperator.GREATER_THAN_EQUAL_TO, startValue);
|
||||
Object endValue = modelField.getModelEntity().convertFieldValue(modelField, dayStart(timeStampString, 1), delegator, context);
|
||||
EntityCondition endCond = EntityCondition.makeCondition(fieldName, EntityOperator.LESS_THAN, endValue);
|
||||
return EntityCondition.makeCondition(startCond, endCond);
|
||||
} else {
|
||||
fieldOp = entityOperators.get(operation);
|
||||
}
|
||||
} else {
|
||||
if (UtilValidate.isNotEmpty(UtilGenerics.toList(fieldValue))) {
|
||||
fieldOp = EntityOperator.IN;
|
||||
} else {
|
||||
fieldOp = EntityOperator.EQUALS;
|
||||
}
|
||||
}
|
||||
Object fieldObject = fieldValue;
|
||||
if ((fieldOp != EntityOperator.IN && fieldOp != EntityOperator.NOT_IN ) || !(fieldValue instanceof Collection<?>)) {
|
||||
fieldObject = modelField.getModelEntity().convertFieldValue(modelField, fieldValue, delegator, context);
|
||||
}
|
||||
if (ignoreCase && fieldObject instanceof String) {
|
||||
cond = EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(fieldName), fieldOp, EntityFunction.UPPER(((String)fieldValue).toUpperCase()));
|
||||
} else {
|
||||
if (fieldObject.equals(GenericEntity.NULL_FIELD.toString())) {
|
||||
fieldObject = null;
|
||||
}
|
||||
cond = EntityCondition.makeCondition(fieldName, fieldOp, fieldObject);
|
||||
}
|
||||
if (EntityOperator.NOT_EQUAL.equals(fieldOp) && fieldObject != null) {
|
||||
cond = EntityCondition.makeCondition(UtilMisc.toList(cond, EntityCondition.makeCondition(fieldName, null)), EntityOperator.OR);
|
||||
}
|
||||
return cond;
|
||||
}
|
||||
|
||||
/**
|
||||
* createCondition, comparing the normalizedFields with the list of keys, .
|
||||
*
|
||||
* This is use to the generic method that expects entity data affixed with special suffixes
|
||||
* to indicate their purpose in formulating an SQL query statement.
|
||||
* @param modelEntity the model entity object
|
||||
* @param normalizedFields list of field the user have populated
|
||||
* @return a arrayList usable to create an entityCondition
|
||||
*/
|
||||
public static List<EntityCondition> createCondition(ModelEntity modelEntity, Map<String, Map<String, Map<String, Object>>> normalizedFields, Map<String, Object> queryStringMap, Map<String, List<Object[]>> origValueMap, Delegator delegator, Map<String, ?> context) {
|
||||
Map<String, Map<String, Object>> subMap = null;
|
||||
Map<String, Object> subMap2 = null;
|
||||
Object fieldValue = null; // If it is a "value" field, it will be the value to be used in the query.
|
||||
// If it is an "op" field, it will be "equals", "greaterThan", etc.
|
||||
EntityCondition cond = null;
|
||||
List<EntityCondition> tmpList = new LinkedList<EntityCondition>();
|
||||
String opString = null;
|
||||
boolean ignoreCase = false;
|
||||
List<ModelField> fields = modelEntity.getFieldsUnmodifiable();
|
||||
for (ModelField modelField: fields) {
|
||||
String fieldName = modelField.getName();
|
||||
subMap = normalizedFields.get(fieldName);
|
||||
if (subMap == null) {
|
||||
continue;
|
||||
}
|
||||
subMap2 = subMap.get("fld0");
|
||||
fieldValue = subMap2.get("value");
|
||||
opString = (String) subMap2.get("op");
|
||||
// null fieldValue is OK if operator is "empty"
|
||||
if (fieldValue == null && !"empty".equals(opString)) {
|
||||
continue;
|
||||
}
|
||||
ignoreCase = "Y".equals(subMap2.get("ic"));
|
||||
cond = createSingleCondition(modelField, opString, fieldValue, ignoreCase, delegator, context);
|
||||
tmpList.add(cond);
|
||||
subMap2 = subMap.get("fld1");
|
||||
if (subMap2 == null) {
|
||||
continue;
|
||||
}
|
||||
fieldValue = subMap2.get("value");
|
||||
opString = (String) subMap2.get("op");
|
||||
if (fieldValue == null && !"empty".equals(opString)) {
|
||||
continue;
|
||||
}
|
||||
ignoreCase = "Y".equals(subMap2.get("ic"));
|
||||
cond = createSingleCondition(modelField, opString, fieldValue, ignoreCase, delegator, context);
|
||||
tmpList.add(cond);
|
||||
// add to queryStringMap
|
||||
List<Object[]> origList = origValueMap.get(fieldName);
|
||||
if (UtilValidate.isNotEmpty(origList)) {
|
||||
for (Object[] arr: origList) {
|
||||
queryStringMap.put((String) arr[0], arr[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return tmpList;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* same as performFind but now returning a list instead of an iterator
|
||||
* Extra parameters viewIndex: startPage of the partial list (0 = first page)
|
||||
* viewSize: the length of the page (number of records)
|
||||
* Extra output parameter: listSize: size of the totallist
|
||||
* list : the list itself.
|
||||
*
|
||||
* @param dctx
|
||||
* @param context
|
||||
* @return Map
|
||||
*/
|
||||
public static Map<String, Object> performFindList(DispatchContext dctx, Map<String, Object> context) {
|
||||
Integer viewSize = (Integer) context.get("viewSize");
|
||||
if (viewSize == null) viewSize = Integer.valueOf(20); // default
|
||||
context.put("viewSize", viewSize);
|
||||
Integer viewIndex = (Integer) context.get("viewIndex");
|
||||
if (viewIndex == null) viewIndex = Integer.valueOf(0); // default
|
||||
context.put("viewIndex", viewIndex);
|
||||
|
||||
Map<String, Object> result = performFind(dctx,context);
|
||||
|
||||
int start = viewIndex.intValue() * viewSize.intValue();
|
||||
List<GenericValue> list = null;
|
||||
Integer listSize = 0;
|
||||
try {
|
||||
EntityListIterator it = (EntityListIterator) result.get("listIt");
|
||||
list = it.getPartialList(start+1, viewSize); // list starts at '1'
|
||||
listSize = it.getResultsSizeAfterPartialList();
|
||||
it.close();
|
||||
} catch (Exception e) {
|
||||
Debug.logInfo("Problem getting partial list" + e,module);
|
||||
}
|
||||
|
||||
result.put("listSize", listSize);
|
||||
result.put("list",list);
|
||||
result.remove("listIt");
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* performFind
|
||||
*
|
||||
* This is a generic method that expects entity data affixed with special suffixes
|
||||
* to indicate their purpose in formulating an SQL query statement.
|
||||
*/
|
||||
public static Map<String, Object> performFind(DispatchContext dctx, Map<String, ?> context) {
|
||||
String entityName = (String) context.get("entityName");
|
||||
String orderBy = (String) context.get("orderBy");
|
||||
Map<String, ?> inputFields = checkMap(context.get("inputFields"), String.class, Object.class); // Input
|
||||
String noConditionFind = (String) context.get("noConditionFind");
|
||||
String distinct = (String) context.get("distinct");
|
||||
List<String> fieldList = UtilGenerics.<String>checkList(context.get("fieldList"));
|
||||
GenericValue userLogin = (GenericValue) context.get("userLogin");
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
Delegator delegator = dctx.getDelegator();
|
||||
if (UtilValidate.isEmpty(noConditionFind)) {
|
||||
// try finding in inputFields Map
|
||||
noConditionFind = (String) inputFields.get("noConditionFind");
|
||||
}
|
||||
if (UtilValidate.isEmpty(noConditionFind)) {
|
||||
// Use configured default
|
||||
noConditionFind = EntityUtilProperties.getPropertyValue("widget", "widget.defaultNoConditionFind", delegator);
|
||||
}
|
||||
String filterByDate = (String) context.get("filterByDate");
|
||||
if (UtilValidate.isEmpty(filterByDate)) {
|
||||
// try finding in inputFields Map
|
||||
filterByDate = (String) inputFields.get("filterByDate");
|
||||
}
|
||||
Timestamp filterByDateValue = (Timestamp) context.get("filterByDateValue");
|
||||
String fromDateName = (String) context.get("fromDateName");
|
||||
if (UtilValidate.isEmpty(fromDateName)) {
|
||||
// try finding in inputFields Map
|
||||
fromDateName = (String) inputFields.get("fromDateName");
|
||||
}
|
||||
String thruDateName = (String) context.get("thruDateName");
|
||||
if (UtilValidate.isEmpty(thruDateName)) {
|
||||
// try finding in inputFields Map
|
||||
thruDateName = (String) inputFields.get("thruDateName");
|
||||
}
|
||||
|
||||
Integer viewSize = (Integer) context.get("viewSize");
|
||||
Integer viewIndex = (Integer) context.get("viewIndex");
|
||||
Integer maxRows = null;
|
||||
if (viewSize != null && viewIndex != null) {
|
||||
maxRows = viewSize * (viewIndex + 1);
|
||||
}
|
||||
|
||||
LocalDispatcher dispatcher = dctx.getDispatcher();
|
||||
|
||||
Map<String, Object> prepareResult = null;
|
||||
try {
|
||||
prepareResult = dispatcher.runSync("prepareFind", UtilMisc.toMap("entityName", entityName, "orderBy", orderBy,
|
||||
"inputFields", inputFields, "filterByDate", filterByDate, "noConditionFind", noConditionFind,
|
||||
"filterByDateValue", filterByDateValue, "userLogin", userLogin, "fromDateName", fromDateName, "thruDateName", thruDateName,
|
||||
"locale", context.get("locale"), "timeZone", context.get("timeZone")));
|
||||
} catch (GenericServiceException gse) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFindErrorPreparingConditions", UtilMisc.toMap("errorString", gse.getMessage()), locale));
|
||||
}
|
||||
EntityConditionList<EntityCondition> exprList = UtilGenerics.cast(prepareResult.get("entityConditionList"));
|
||||
List<String> orderByList = checkList(prepareResult.get("orderByList"), String.class);
|
||||
|
||||
Map<String, Object> executeResult = null;
|
||||
try {
|
||||
executeResult = dispatcher.runSync("executeFind", UtilMisc.toMap("entityName", entityName, "orderByList", orderByList,
|
||||
"fieldList", fieldList, "entityConditionList", exprList,
|
||||
"noConditionFind", noConditionFind, "distinct", distinct,
|
||||
"locale", context.get("locale"), "timeZone", context.get("timeZone"),
|
||||
"maxRows", maxRows));
|
||||
} catch (GenericServiceException gse) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFindErrorRetrieveIterator", UtilMisc.toMap("errorString", gse.getMessage()), locale));
|
||||
}
|
||||
|
||||
if (executeResult.get("listIt") == null) {
|
||||
if (Debug.verboseOn()) Debug.logVerbose("No list iterator found for query string + [" + prepareResult.get("queryString") + "]", module);
|
||||
}
|
||||
|
||||
Map<String, Object> results = ServiceUtil.returnSuccess();
|
||||
results.put("listIt", executeResult.get("listIt"));
|
||||
results.put("listSize", executeResult.get("listSize"));
|
||||
results.put("queryString", prepareResult.get("queryString"));
|
||||
results.put("queryStringMap", prepareResult.get("queryStringMap"));
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* prepareFind
|
||||
*
|
||||
* This is a generic method that expects entity data affixed with special suffixes
|
||||
* to indicate their purpose in formulating an SQL query statement.
|
||||
*/
|
||||
public static Map<String, Object> prepareFind(DispatchContext dctx, Map<String, ?> context) {
|
||||
String entityName = (String) context.get("entityName");
|
||||
Delegator delegator = dctx.getDelegator();
|
||||
String orderBy = (String) context.get("orderBy");
|
||||
Map<String, ?> inputFields = checkMap(context.get("inputFields"), String.class, Object.class); // Input
|
||||
String noConditionFind = (String) context.get("noConditionFind");
|
||||
if (UtilValidate.isEmpty(noConditionFind)) {
|
||||
// try finding in inputFields Map
|
||||
noConditionFind = (String) inputFields.get("noConditionFind");
|
||||
}
|
||||
if (UtilValidate.isEmpty(noConditionFind)) {
|
||||
// Use configured default
|
||||
noConditionFind = EntityUtilProperties.getPropertyValue("widget", "widget.defaultNoConditionFind", delegator);
|
||||
}
|
||||
String filterByDate = (String) context.get("filterByDate");
|
||||
if (UtilValidate.isEmpty(filterByDate)) {
|
||||
// try finding in inputFields Map
|
||||
filterByDate = (String) inputFields.get("filterByDate");
|
||||
}
|
||||
Timestamp filterByDateValue = (Timestamp) context.get("filterByDateValue");
|
||||
String fromDateName = (String) context.get("fromDateName");
|
||||
String thruDateName = (String) context.get("thruDateName");
|
||||
|
||||
Map<String, Object> queryStringMap = new LinkedHashMap<String, Object>();
|
||||
ModelEntity modelEntity = delegator.getModelEntity(entityName);
|
||||
List<EntityCondition> tmpList = createConditionList(inputFields, modelEntity.getFieldsUnmodifiable(), queryStringMap, delegator, context);
|
||||
|
||||
/* the filter by date condition should only be added when there are other conditions or when
|
||||
* the user has specified a noConditionFind. Otherwise, specifying filterByDate will become
|
||||
* its own condition.
|
||||
*/
|
||||
if (tmpList.size() > 0 || "Y".equals(noConditionFind)) {
|
||||
if ("Y".equals(filterByDate)) {
|
||||
queryStringMap.put("filterByDate", filterByDate);
|
||||
if (UtilValidate.isEmpty(fromDateName)) fromDateName = "fromDate";
|
||||
else queryStringMap.put("fromDateName", fromDateName);
|
||||
if (UtilValidate.isEmpty(thruDateName)) thruDateName = "thruDate";
|
||||
else queryStringMap.put("thruDateName", thruDateName);
|
||||
if (UtilValidate.isEmpty(filterByDateValue)) {
|
||||
EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr(fromDateName, thruDateName);
|
||||
tmpList.add(filterByDateCondition);
|
||||
} else {
|
||||
queryStringMap.put("filterByDateValue", filterByDateValue);
|
||||
EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr(filterByDateValue, fromDateName, thruDateName);
|
||||
tmpList.add(filterByDateCondition);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EntityConditionList<EntityCondition> exprList = null;
|
||||
if (tmpList.size() > 0) {
|
||||
exprList = EntityCondition.makeCondition(tmpList);
|
||||
}
|
||||
|
||||
List<String> orderByList = null;
|
||||
if (UtilValidate.isNotEmpty(orderBy)) {
|
||||
orderByList = StringUtil.split(orderBy,"|");
|
||||
}
|
||||
|
||||
Map<String, Object> results = ServiceUtil.returnSuccess();
|
||||
queryStringMap.put("noConditionFind", noConditionFind);
|
||||
String queryString = UtilHttp.urlEncodeArgs(queryStringMap);
|
||||
results.put("queryString", queryString);
|
||||
results.put("queryStringMap", queryStringMap);
|
||||
results.put("orderByList", orderByList);
|
||||
results.put("entityConditionList", exprList);
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* executeFind
|
||||
*
|
||||
* This is a generic method that returns an EntityListIterator.
|
||||
*/
|
||||
public static Map<String, Object> executeFind(DispatchContext dctx, Map<String, ?> context) {
|
||||
String entityName = (String) context.get("entityName");
|
||||
EntityConditionList<EntityCondition> entityConditionList = UtilGenerics.cast(context.get("entityConditionList"));
|
||||
List<String> orderByList = checkList(context.get("orderByList"), String.class);
|
||||
boolean noConditionFind = "Y".equals(context.get("noConditionFind"));
|
||||
boolean distinct = "Y".equals(context.get("distinct"));
|
||||
List<String> fieldList = UtilGenerics.checkList(context.get("fieldList"));
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
Set<String> fieldSet = null;
|
||||
if (fieldList != null) {
|
||||
fieldSet = UtilMisc.makeSetWritable(fieldList);
|
||||
}
|
||||
Integer maxRows = (Integer) context.get("maxRows");
|
||||
maxRows = maxRows != null ? maxRows : -1;
|
||||
Delegator delegator = dctx.getDelegator();
|
||||
// Retrieve entities - an iterator over all the values
|
||||
EntityListIterator listIt = null;
|
||||
int listSize = 0;
|
||||
try {
|
||||
if (noConditionFind || (entityConditionList != null && entityConditionList.getConditionListSize() > 0)) {
|
||||
listIt = EntityQuery.use(delegator)
|
||||
.select(fieldSet)
|
||||
.from(entityName)
|
||||
.where(entityConditionList)
|
||||
.orderBy(orderByList)
|
||||
.cursorScrollInsensitive()
|
||||
.maxRows(maxRows)
|
||||
.distinct(distinct)
|
||||
.queryIterator();
|
||||
listSize = listIt.getResultsSizeAfterPartialList();
|
||||
}
|
||||
} catch (GenericEntityException e) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFindErrorRunning", UtilMisc.toMap("entityName", entityName, "errorString", e.getMessage()), locale));
|
||||
}
|
||||
|
||||
Map<String, Object> results = ServiceUtil.returnSuccess();
|
||||
results.put("listIt", listIt);
|
||||
results.put("listSize", listSize);
|
||||
return results;
|
||||
}
|
||||
|
||||
private static String dayStart(String timeStampString, int daysLater) {
|
||||
String retValue = null;
|
||||
Timestamp ts = null;
|
||||
Timestamp startTs = null;
|
||||
try {
|
||||
ts = Timestamp.valueOf(timeStampString);
|
||||
} catch (IllegalArgumentException e) {
|
||||
timeStampString += " 00:00:00.000";
|
||||
try {
|
||||
ts = Timestamp.valueOf(timeStampString);
|
||||
} catch (IllegalArgumentException e2) {
|
||||
return retValue;
|
||||
}
|
||||
}
|
||||
startTs = UtilDateTime.getDayStart(ts, daysLater);
|
||||
retValue = startTs.toString();
|
||||
return retValue;
|
||||
}
|
||||
|
||||
public static Map<String, Object> buildReducedQueryString(Map<String, ?> inputFields, String entityName, Delegator delegator) {
|
||||
// Strip the "_suffix" off of the parameter name and
|
||||
// build a three-level map of values keyed by fieldRoot name,
|
||||
// fld0 or fld1, and, then, "op" or "value"
|
||||
// ie. id
|
||||
// - fld0
|
||||
// - op:like
|
||||
// - value:abc
|
||||
// - fld1 (if there is a range)
|
||||
// - op:lessThan
|
||||
// - value:55 (note: these two "flds" wouldn't really go together)
|
||||
// Also note that op/fld can be in any order. (eg. id_fld1_equals or id_equals_fld1)
|
||||
// Note that "normalizedFields" will contain values other than those
|
||||
// Contained in the associated entity.
|
||||
// Those extra fields will be ignored in the second half of this method.
|
||||
ModelEntity modelEntity = delegator.getModelEntity(entityName);
|
||||
Map<String, Object> normalizedFields = new LinkedHashMap<String, Object>();
|
||||
//StringBuffer queryStringBuf = new StringBuffer();
|
||||
for (String fieldNameRaw: inputFields.keySet()) { // The name as it appeas in the HTML form
|
||||
String fieldNameRoot = null; // The entity field name. Everything to the left of the first "_" if
|
||||
// it exists, or the whole word, if not.
|
||||
Object fieldValue = null; // If it is a "value" field, it will be the value to be used in the query.
|
||||
// If it is an "op" field, it will be "equals", "greaterThan", etc.
|
||||
int iPos = -1;
|
||||
int iPos2 = -1;
|
||||
|
||||
fieldValue = inputFields.get(fieldNameRaw);
|
||||
if (ObjectType.isEmpty(fieldValue)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
//queryStringBuffer.append(fieldNameRaw + "=" + fieldValue);
|
||||
iPos = fieldNameRaw.indexOf("_"); // Look for suffix
|
||||
|
||||
// This is a hack to skip fields from "multi" forms
|
||||
// These would have the form "fieldName_o_1"
|
||||
if (iPos >= 0) {
|
||||
String suffix = fieldNameRaw.substring(iPos + 1);
|
||||
iPos2 = suffix.indexOf("_");
|
||||
if (iPos2 == 1) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// If no suffix, assume no range (default to fld0) and operations of equals
|
||||
// If no field op is present, it will assume "equals".
|
||||
if (iPos < 0) {
|
||||
fieldNameRoot = fieldNameRaw;
|
||||
} else { // Must have at least "fld0/1" or "equals, greaterThan, etc."
|
||||
// Some bogus fields will slip in, like "ENTITY_NAME", but they will be ignored
|
||||
|
||||
fieldNameRoot = fieldNameRaw.substring(0, iPos);
|
||||
}
|
||||
if (modelEntity.isField(fieldNameRoot)) {
|
||||
normalizedFields.put(fieldNameRaw, fieldValue);
|
||||
}
|
||||
}
|
||||
return normalizedFields;
|
||||
}
|
||||
/**
|
||||
* Returns the first generic item of the service 'performFind'
|
||||
* Same parameters as performFind service but returns a single GenericValue
|
||||
*
|
||||
* @param dctx
|
||||
* @param context
|
||||
* @return returns the first item
|
||||
*/
|
||||
public static Map<String, Object> performFindItem(DispatchContext dctx, Map<String, Object> context) {
|
||||
context.put("viewSize", 1);
|
||||
context.put("viewIndex", 0);
|
||||
Map<String, Object> result = org.ofbiz.common.FindServices.performFind(dctx,context);
|
||||
|
||||
List<GenericValue> list = null;
|
||||
GenericValue item= null;
|
||||
try {
|
||||
EntityListIterator it = (EntityListIterator) result.get("listIt");
|
||||
list = it.getPartialList(1, 1); // list starts at '1'
|
||||
if (UtilValidate.isNotEmpty(list)) {
|
||||
item = list.get(0);
|
||||
}
|
||||
it.close();
|
||||
} catch (Exception e) {
|
||||
Debug.logInfo("Problem getting list Item" + e,module);
|
||||
}
|
||||
|
||||
if (!UtilValidate.isEmpty(item)) {
|
||||
result.put("item",item);
|
||||
}
|
||||
result.remove("listIt");
|
||||
|
||||
if (result.containsKey("listSize")) {
|
||||
result.remove("listSize");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
import static org.ofbiz.base.util.UtilGenerics.checkList;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.net.ftp.FTP;
|
||||
import org.apache.commons.net.ftp.FTPClient;
|
||||
import org.apache.commons.net.ftp.FTPReply;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
|
||||
/**
|
||||
* FTP Services.
|
||||
*
|
||||
*/
|
||||
public class FtpServices {
|
||||
|
||||
public final static String module = FtpServices.class.getName();
|
||||
public static final String resource = "CommonUiLabels";
|
||||
|
||||
public static Map<String, Object> putFile(DispatchContext dctx, Map<String, ?> context) {
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
Debug.logInfo("[putFile] starting...", module);
|
||||
InputStream localFile = null;
|
||||
try {
|
||||
localFile = new FileInputStream((String) context.get("localFilename"));
|
||||
} catch (IOException ioe) {
|
||||
Debug.logError(ioe, "[putFile] Problem opening local file", module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
|
||||
}
|
||||
List<String> errorList = new LinkedList<String>();
|
||||
FTPClient ftp = new FTPClient();
|
||||
try {
|
||||
Integer defaultTimeout = (Integer) context.get("defaultTimeout");
|
||||
if (UtilValidate.isNotEmpty(defaultTimeout)) {
|
||||
Debug.logInfo("[putFile] set default timeout to: " + defaultTimeout.intValue() + " milliseconds", module);
|
||||
ftp.setDefaultTimeout(defaultTimeout.intValue());
|
||||
}
|
||||
Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module);
|
||||
ftp.connect((String) context.get("hostname"));
|
||||
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
|
||||
Debug.logInfo("[putFile] Server refused connection", module);
|
||||
errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale));
|
||||
} else {
|
||||
String username = (String) context.get("username");
|
||||
String password = (String) context.get("password");
|
||||
Debug.logInfo("[putFile] logging in: username=" + username + ", password=" + password, module);
|
||||
if (!ftp.login(username, password)) {
|
||||
Debug.logInfo("[putFile] login failed", module);
|
||||
errorList.add(UtilProperties.getMessage(resource, "CommonFtpLoginFailure", UtilMisc.toMap("username", username, "password", password), locale));
|
||||
} else {
|
||||
Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
|
||||
boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
|
||||
if (binary) {
|
||||
ftp.setFileType(FTP.BINARY_FILE_TYPE);
|
||||
}
|
||||
Boolean passiveMode = (Boolean) context.get("passiveMode");
|
||||
boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue();
|
||||
if (passive) {
|
||||
ftp.enterLocalPassiveMode();
|
||||
}
|
||||
Debug.logInfo("[putFile] storing local file remotely as: " + context.get("remoteFilename"), module);
|
||||
if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) {
|
||||
Debug.logInfo("[putFile] store was unsuccessful", module);
|
||||
errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully", UtilMisc.toMap("replyString", ftp.getReplyString()), locale));
|
||||
} else {
|
||||
Debug.logInfo("[putFile] store was successful", module);
|
||||
List<String> siteCommands = checkList(context.get("siteCommands"), String.class);
|
||||
if (siteCommands != null) {
|
||||
for (String command : siteCommands) {
|
||||
Debug.logInfo("[putFile] sending SITE command: " + command, module);
|
||||
if (!ftp.sendSiteCommand(command)) {
|
||||
errorList.add(UtilProperties.getMessage(resource, "CommonFtpSiteCommandFailed", UtilMisc.toMap("command", command, "replyString", ftp.getReplyString()), locale));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ftp.logout();
|
||||
}
|
||||
} catch (IOException ioe) {
|
||||
Debug.logWarning(ioe, "[putFile] caught exception: " + ioe.getMessage(), module);
|
||||
errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer", UtilMisc.toMap("errorString", ioe.getMessage()), locale));
|
||||
} finally {
|
||||
try {
|
||||
if (ftp.isConnected()) {
|
||||
ftp.disconnect();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Debug.logWarning(e, "[putFile] Problem with FTP disconnect: ", module);
|
||||
}
|
||||
try {
|
||||
localFile.close();
|
||||
} catch (Exception e) {
|
||||
Debug.logWarning(e, "[putFile] Problem closing local file: ", module);
|
||||
}
|
||||
}
|
||||
if (errorList.size() > 0) {
|
||||
Debug.logError("[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module);
|
||||
return ServiceUtil.returnError(errorList);
|
||||
}
|
||||
Debug.logInfo("[putFile] finished successfully", module);
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
public static Map<String, Object> getFile(DispatchContext dctx, Map<String, ?> context) {
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
String localFilename = (String) context.get("localFilename");
|
||||
OutputStream localFile = null;
|
||||
try {
|
||||
localFile = new FileOutputStream(localFilename);
|
||||
} catch (IOException ioe) {
|
||||
Debug.logError(ioe, "[getFile] Problem opening local file", module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
|
||||
}
|
||||
List<String> errorList = new LinkedList<String>();
|
||||
FTPClient ftp = new FTPClient();
|
||||
try {
|
||||
Integer defaultTimeout = (Integer) context.get("defaultTimeout");
|
||||
if (UtilValidate.isNotEmpty(defaultTimeout)) {
|
||||
Debug.logInfo("[getFile] Set default timeout to: " + defaultTimeout.intValue() + " milliseconds", module);
|
||||
ftp.setDefaultTimeout(defaultTimeout.intValue());
|
||||
}
|
||||
ftp.connect((String) context.get("hostname"));
|
||||
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
|
||||
errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale));
|
||||
} else {
|
||||
String username = (String) context.get("username");
|
||||
String password = (String) context.get("password");
|
||||
if (!ftp.login(username, password)) {
|
||||
errorList.add(UtilProperties.getMessage(resource, "CommonFtpLoginFailure", UtilMisc.toMap("username", username, "password", password), locale));
|
||||
} else {
|
||||
Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
|
||||
boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
|
||||
if (binary) {
|
||||
ftp.setFileType(FTP.BINARY_FILE_TYPE);
|
||||
}
|
||||
Boolean passiveMode = (Boolean) context.get("passiveMode");
|
||||
boolean passive = (passiveMode == null) ? false : passiveMode.booleanValue();
|
||||
if (passive) {
|
||||
ftp.enterLocalPassiveMode();
|
||||
}
|
||||
if (!ftp.retrieveFile((String) context.get("remoteFilename"), localFile)) {
|
||||
errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully", UtilMisc.toMap("replyString", ftp.getReplyString()), locale));
|
||||
}
|
||||
}
|
||||
ftp.logout();
|
||||
}
|
||||
} catch (IOException ioe) {
|
||||
Debug.logWarning(ioe, "[getFile] caught exception: " + ioe.getMessage(), module);
|
||||
errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer", UtilMisc.toMap("errorString", ioe.getMessage()), locale));
|
||||
} finally {
|
||||
try {
|
||||
if (ftp.isConnected()) {
|
||||
ftp.disconnect();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Debug.logWarning(e, "[getFile] Problem with FTP disconnect: ", module);
|
||||
}
|
||||
try {
|
||||
localFile.close();
|
||||
} catch (Exception e) {
|
||||
Debug.logWarning(e, "[getFile] Problem closing local file: ", module);
|
||||
}
|
||||
}
|
||||
if (errorList.size() > 0) {
|
||||
Debug.logError("[getFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module);
|
||||
return ServiceUtil.returnError(errorList);
|
||||
}
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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.
|
||||
*/
|
||||
|
||||
// - BSF JavaScript test script
|
||||
|
||||
x = bsf.lookupBean("message");
|
||||
m = bsf.lookupBean("response");
|
||||
m.put("result", x);
|
||||
|
||||
bsf.registerBean("response", m);
|
||||
java.lang.System.out.println("BSF - JS: " + x);
|
||||
@@ -0,0 +1,206 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.FileUtil;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.template.FreeMarkerWorker;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
|
||||
// Use the createJsLanguageFileMapping service to create or update the JsLanguageFilesMapping.java. You will still need to compile thereafter
|
||||
|
||||
public class JsLanguageFileMappingCreator {
|
||||
|
||||
private static final String module = JsLanguageFileMappingCreator.class.getName();
|
||||
|
||||
public static Map<String, Object> createJsLanguageFileMapping(DispatchContext ctx, Map<String, ?> context) {
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
String encoding = (String) context.get("encoding"); // default value: UTF-8
|
||||
|
||||
List<Locale> localeList = UtilMisc.availableLocales();
|
||||
Map<String, Object> jQueryLocaleFile = new LinkedHashMap<String, Object>();
|
||||
Map<String, String> dateJsLocaleFile = new LinkedHashMap<String, String>();
|
||||
Map<String, String> validationLocaleFile = new LinkedHashMap<String, String>();
|
||||
Map<String, String> dateTimePickerLocaleFile = new LinkedHashMap<String, String>();
|
||||
|
||||
// setup some variables to locate the js files
|
||||
String componentRoot = "component://images/webapp";
|
||||
String jqueryUiLocaleRelPath = "/images/jquery/ui/i18n/";
|
||||
String dateJsLocaleRelPath = "/images/jquery/plugins/datejs/";
|
||||
String validateRelPath = "/images/jquery/plugins/validate/localization/";
|
||||
String dateTimePickerJsLocaleRelPath = "/images/jquery/plugins/datetimepicker/localization/";
|
||||
String jsFilePostFix = ".js";
|
||||
String dateJsLocalePrefix = "date-";
|
||||
String validateLocalePrefix = "messages_";
|
||||
//String validateMethLocalePrefix = "methods__";
|
||||
String jqueryUiLocalePrefix = "jquery.ui.datepicker-";
|
||||
String dateTimePickerPrefix = "jquery-ui-timepicker-";
|
||||
String defaultLocaleDateJs = "en-US";
|
||||
String defaultLocaleJquery = "en"; // Beware to keep the OFBiz specific jquery.ui.datepicker-en.js file when upgrading...
|
||||
|
||||
for (Locale locale : localeList) {
|
||||
String displayCountry = locale.toString();
|
||||
String modifiedDisplayCountry = null;
|
||||
String modifiedDisplayCountryForValidation = null;
|
||||
if (displayCountry.contains("_")) {
|
||||
modifiedDisplayCountry = displayCountry.replace("_", "-");
|
||||
modifiedDisplayCountryForValidation = displayCountry; // messages*.js use "_" not "-" as others
|
||||
} else {
|
||||
modifiedDisplayCountry = displayCountry;
|
||||
}
|
||||
|
||||
String strippedLocale = locale.getLanguage();
|
||||
|
||||
File file = null;
|
||||
String fileUrl = null;
|
||||
|
||||
/*
|
||||
* Try to open the date-js language file
|
||||
*/
|
||||
String fileName = componentRoot + dateJsLocaleRelPath + dateJsLocalePrefix + modifiedDisplayCountry + jsFilePostFix;
|
||||
file = FileUtil.getFile(fileName);
|
||||
|
||||
if (file.exists()) {
|
||||
fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + modifiedDisplayCountry + jsFilePostFix;
|
||||
} else {
|
||||
// Try to guess a language
|
||||
String tmpLocale = strippedLocale + "-" + strippedLocale.toUpperCase();
|
||||
fileName = componentRoot + dateJsLocaleRelPath + dateJsLocalePrefix + tmpLocale + jsFilePostFix;
|
||||
file = FileUtil.getFile(fileName);
|
||||
if (file.exists()) {
|
||||
fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + tmpLocale + jsFilePostFix;
|
||||
} else {
|
||||
// use language en-US as fallback
|
||||
fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + defaultLocaleDateJs + jsFilePostFix;
|
||||
}
|
||||
}
|
||||
dateJsLocaleFile.put(displayCountry, fileUrl);
|
||||
|
||||
/*
|
||||
* Try to open the jquery validation language file
|
||||
*/
|
||||
if (modifiedDisplayCountryForValidation != null) { // Try 1st lang_country
|
||||
fileName = componentRoot + validateRelPath + validateLocalePrefix + modifiedDisplayCountryForValidation + jsFilePostFix;
|
||||
file = FileUtil.getFile(fileName);
|
||||
if (file.exists()) {
|
||||
fileUrl = validateRelPath + validateLocalePrefix + modifiedDisplayCountryForValidation + jsFilePostFix;
|
||||
} else { // lang only
|
||||
fileName = componentRoot + validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix;
|
||||
file = FileUtil.getFile(fileName);
|
||||
if (file.exists()) {
|
||||
fileUrl = validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix;
|
||||
} else {
|
||||
// use default language en as fallback
|
||||
fileUrl = validateRelPath + validateLocalePrefix + defaultLocaleJquery + jsFilePostFix;
|
||||
}
|
||||
}
|
||||
} else { // Then try lang only
|
||||
fileName = componentRoot + validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix;
|
||||
file = FileUtil.getFile(fileName);
|
||||
if (file.exists()) {
|
||||
fileUrl = validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix;
|
||||
} else {
|
||||
// use default language en as fallback
|
||||
fileUrl = validateRelPath + validateLocalePrefix + defaultLocaleJquery + jsFilePostFix;
|
||||
}
|
||||
}
|
||||
validationLocaleFile.put(displayCountry, fileUrl);
|
||||
|
||||
/*
|
||||
* Try to open the jquery timepicker language file
|
||||
*/
|
||||
fileName = componentRoot + jqueryUiLocaleRelPath + jqueryUiLocalePrefix + strippedLocale + jsFilePostFix;
|
||||
file = FileUtil.getFile(fileName);
|
||||
|
||||
if (file.exists()) {
|
||||
fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + strippedLocale + jsFilePostFix;
|
||||
} else {
|
||||
// Try to guess a language
|
||||
fileName = componentRoot + jqueryUiLocaleRelPath + jqueryUiLocalePrefix + modifiedDisplayCountry + jsFilePostFix;
|
||||
file = FileUtil.getFile(fileName);
|
||||
if (file.exists()) {
|
||||
fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + modifiedDisplayCountry + jsFilePostFix;
|
||||
} else {
|
||||
// use default language en as fallback
|
||||
fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + defaultLocaleJquery + jsFilePostFix;
|
||||
}
|
||||
}
|
||||
jQueryLocaleFile.put(displayCountry, fileUrl);
|
||||
|
||||
/*
|
||||
* Try to open the datetimepicker language file
|
||||
*/
|
||||
fileName = componentRoot + dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + strippedLocale + jsFilePostFix;
|
||||
file = FileUtil.getFile(fileName);
|
||||
|
||||
if (file.exists()) {
|
||||
fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + strippedLocale + jsFilePostFix;
|
||||
} else {
|
||||
// Try to guess a language
|
||||
fileName = componentRoot + dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + modifiedDisplayCountry + jsFilePostFix;
|
||||
file = FileUtil.getFile(fileName);
|
||||
if (file.exists()) {
|
||||
fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + modifiedDisplayCountry + jsFilePostFix;
|
||||
} else {
|
||||
// use default language en as fallback
|
||||
fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + defaultLocaleJquery + jsFilePostFix;
|
||||
}
|
||||
}
|
||||
dateTimePickerLocaleFile.put(displayCountry, fileUrl);
|
||||
}
|
||||
|
||||
// check the template file
|
||||
String template = "framework/common/template/JsLanguageFilesMapping.ftl";
|
||||
String output = "framework/common/src/org/ofbiz/common/JsLanguageFilesMapping.java";
|
||||
Map<String, Object> mapWrapper = new HashMap<String, Object>();
|
||||
mapWrapper.put("datejs", dateJsLocaleFile);
|
||||
mapWrapper.put("jquery", jQueryLocaleFile);
|
||||
mapWrapper.put("validation", validationLocaleFile);
|
||||
mapWrapper.put("dateTime", dateTimePickerLocaleFile);
|
||||
|
||||
// some magic to create a new java file: render it as FTL
|
||||
Writer writer = new StringWriter();
|
||||
try {
|
||||
FreeMarkerWorker.renderTemplateAtLocation(template, mapWrapper, writer);
|
||||
// write it as a Java file
|
||||
File file = new File(output);
|
||||
FileUtils.writeStringToFile(file, writer.toString(), encoding);
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.logError(e, module);
|
||||
return ServiceUtil.returnError("The Outputfile could not be created: " + e.getMessage());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,730 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public final class JsLanguageFilesMapping {
|
||||
|
||||
// DO NOT EDIT THIS FILE! THIS IS AUTO GENERATED AND WILL GET WRITTEN OVER PERIODICALLY WHEN THE DATA CHANGE
|
||||
// Rather use the createJsLanguageFileMapping service to create or update it. You will still need to compile thereafter
|
||||
|
||||
public static class datejs {
|
||||
|
||||
private static Map<String, String> localeFiles = new HashMap<String, String>();
|
||||
private static String defaultDateJs = "/images/jquery/plugins/datejs/date-en-US.js";
|
||||
|
||||
static {
|
||||
localeFiles.put("sq", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sq_AL", "/images/jquery/plugins/datejs/date-sq-AL.js");
|
||||
localeFiles.put("ar", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("ar_DZ", "/images/jquery/plugins/datejs/date-ar-DZ.js");
|
||||
localeFiles.put("ar_BH", "/images/jquery/plugins/datejs/date-ar-BH.js");
|
||||
localeFiles.put("ar_EG", "/images/jquery/plugins/datejs/date-ar-EG.js");
|
||||
localeFiles.put("ar_IQ", "/images/jquery/plugins/datejs/date-ar-IQ.js");
|
||||
localeFiles.put("ar_JO", "/images/jquery/plugins/datejs/date-ar-JO.js");
|
||||
localeFiles.put("ar_KW", "/images/jquery/plugins/datejs/date-ar-KW.js");
|
||||
localeFiles.put("ar_LB", "/images/jquery/plugins/datejs/date-ar-LB.js");
|
||||
localeFiles.put("ar_LY", "/images/jquery/plugins/datejs/date-ar-LY.js");
|
||||
localeFiles.put("ar_MA", "/images/jquery/plugins/datejs/date-ar-MA.js");
|
||||
localeFiles.put("ar_OM", "/images/jquery/plugins/datejs/date-ar-OM.js");
|
||||
localeFiles.put("ar_QA", "/images/jquery/plugins/datejs/date-ar-QA.js");
|
||||
localeFiles.put("ar_SA", "/images/jquery/plugins/datejs/date-ar-SA.js");
|
||||
localeFiles.put("ar_SD", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("ar_SY", "/images/jquery/plugins/datejs/date-ar-SY.js");
|
||||
localeFiles.put("ar_TN", "/images/jquery/plugins/datejs/date-ar-TN.js");
|
||||
localeFiles.put("ar_AE", "/images/jquery/plugins/datejs/date-ar-AE.js");
|
||||
localeFiles.put("ar_YE", "/images/jquery/plugins/datejs/date-ar-YE.js");
|
||||
localeFiles.put("be", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("be_BY", "/images/jquery/plugins/datejs/date-be-BY.js");
|
||||
localeFiles.put("bg", "/images/jquery/plugins/datejs/date-bg-BG.js");
|
||||
localeFiles.put("bg_BG", "/images/jquery/plugins/datejs/date-bg-BG.js");
|
||||
localeFiles.put("ca", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("ca_ES", "/images/jquery/plugins/datejs/date-ca-ES.js");
|
||||
localeFiles.put("zh", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("zh_CN", "/images/jquery/plugins/datejs/date-zh-CN.js");
|
||||
localeFiles.put("zh_HK", "/images/jquery/plugins/datejs/date-zh-HK.js");
|
||||
localeFiles.put("zh_SG", "/images/jquery/plugins/datejs/date-zh-SG.js");
|
||||
localeFiles.put("zh_TW", "/images/jquery/plugins/datejs/date-zh-TW.js");
|
||||
localeFiles.put("hr", "/images/jquery/plugins/datejs/date-hr-HR.js");
|
||||
localeFiles.put("hr_HR", "/images/jquery/plugins/datejs/date-hr-HR.js");
|
||||
localeFiles.put("cs", "/images/jquery/plugins/datejs/date-cs-CZ.js");
|
||||
localeFiles.put("cs_CZ", "/images/jquery/plugins/datejs/date-cs-CZ.js");
|
||||
localeFiles.put("da", "/images/jquery/plugins/datejs/date-da-DA.js");
|
||||
localeFiles.put("da_DK", "/images/jquery/plugins/datejs/date-da-DK.js");
|
||||
localeFiles.put("nl", "/images/jquery/plugins/datejs/date-nl-NL.js");
|
||||
localeFiles.put("nl_BE", "/images/jquery/plugins/datejs/date-nl-BE.js");
|
||||
localeFiles.put("nl_NL", "/images/jquery/plugins/datejs/date-nl-NL.js");
|
||||
localeFiles.put("en", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("en_AU", "/images/jquery/plugins/datejs/date-en-AU.js");
|
||||
localeFiles.put("en_CA", "/images/jquery/plugins/datejs/date-en-CA.js");
|
||||
localeFiles.put("en_IN", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("en_IE", "/images/jquery/plugins/datejs/date-en-IE.js");
|
||||
localeFiles.put("en_MT", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("en_NZ", "/images/jquery/plugins/datejs/date-en-NZ.js");
|
||||
localeFiles.put("en_PH", "/images/jquery/plugins/datejs/date-en-PH.js");
|
||||
localeFiles.put("en_SG", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("en_ZA", "/images/jquery/plugins/datejs/date-en-ZA.js");
|
||||
localeFiles.put("en_GB", "/images/jquery/plugins/datejs/date-en-GB.js");
|
||||
localeFiles.put("en_US", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("et", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("et_EE", "/images/jquery/plugins/datejs/date-et-EE.js");
|
||||
localeFiles.put("fi", "/images/jquery/plugins/datejs/date-fi-FI.js");
|
||||
localeFiles.put("fi_FI", "/images/jquery/plugins/datejs/date-fi-FI.js");
|
||||
localeFiles.put("fr", "/images/jquery/plugins/datejs/date-fr-FR.js");
|
||||
localeFiles.put("fr_BE", "/images/jquery/plugins/datejs/date-fr-BE.js");
|
||||
localeFiles.put("fr_CA", "/images/jquery/plugins/datejs/date-fr-CA.js");
|
||||
localeFiles.put("fr_FR", "/images/jquery/plugins/datejs/date-fr-FR.js");
|
||||
localeFiles.put("fr_LU", "/images/jquery/plugins/datejs/date-fr-LU.js");
|
||||
localeFiles.put("fr_CH", "/images/jquery/plugins/datejs/date-fr-CH.js");
|
||||
localeFiles.put("de", "/images/jquery/plugins/datejs/date-de-DE.js");
|
||||
localeFiles.put("de_AT", "/images/jquery/plugins/datejs/date-de-AT.js");
|
||||
localeFiles.put("de_DE", "/images/jquery/plugins/datejs/date-de-DE.js");
|
||||
localeFiles.put("de_GR", "/images/jquery/plugins/datejs/date-de-DE.js");
|
||||
localeFiles.put("de_LU", "/images/jquery/plugins/datejs/date-de-LU.js");
|
||||
localeFiles.put("de_CH", "/images/jquery/plugins/datejs/date-de-CH.js");
|
||||
localeFiles.put("el", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("el_CY", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("el_GR", "/images/jquery/plugins/datejs/date-el-GR.js");
|
||||
localeFiles.put("iw", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("iw_IL", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("hi", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("hi_IN", "/images/jquery/plugins/datejs/date-hi-IN.js");
|
||||
localeFiles.put("hu", "/images/jquery/plugins/datejs/date-hu-HU.js");
|
||||
localeFiles.put("hu_HU", "/images/jquery/plugins/datejs/date-hu-HU.js");
|
||||
localeFiles.put("is", "/images/jquery/plugins/datejs/date-is-IS.js");
|
||||
localeFiles.put("is_IS", "/images/jquery/plugins/datejs/date-is-IS.js");
|
||||
localeFiles.put("in", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("in_ID", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("ga", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("ga_IE", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("it", "/images/jquery/plugins/datejs/date-it-IT.js");
|
||||
localeFiles.put("it_IT", "/images/jquery/plugins/datejs/date-it-IT.js");
|
||||
localeFiles.put("it_CH", "/images/jquery/plugins/datejs/date-it-CH.js");
|
||||
localeFiles.put("ja", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("ja_JP", "/images/jquery/plugins/datejs/date-ja-JP.js");
|
||||
localeFiles.put("ja_JP_JP_#u-ca-japanese", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("ko", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("ko_KR", "/images/jquery/plugins/datejs/date-ko-KR.js");
|
||||
localeFiles.put("lv", "/images/jquery/plugins/datejs/date-lv-LV.js");
|
||||
localeFiles.put("lv_LV", "/images/jquery/plugins/datejs/date-lv-LV.js");
|
||||
localeFiles.put("lt", "/images/jquery/plugins/datejs/date-lt-LT.js");
|
||||
localeFiles.put("lt_LT", "/images/jquery/plugins/datejs/date-lt-LT.js");
|
||||
localeFiles.put("mk", "/images/jquery/plugins/datejs/date-mk-MK.js");
|
||||
localeFiles.put("mk_MK", "/images/jquery/plugins/datejs/date-mk-MK.js");
|
||||
localeFiles.put("ms", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("ms_MY", "/images/jquery/plugins/datejs/date-ms-MY.js");
|
||||
localeFiles.put("mt", "/images/jquery/plugins/datejs/date-mt-MT.js");
|
||||
localeFiles.put("mt_MT", "/images/jquery/plugins/datejs/date-mt-MT.js");
|
||||
localeFiles.put("no", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("no_NO", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("no_NO_NY", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("pl", "/images/jquery/plugins/datejs/date-pl-PL.js");
|
||||
localeFiles.put("pl_PL", "/images/jquery/plugins/datejs/date-pl-PL.js");
|
||||
localeFiles.put("pt", "/images/jquery/plugins/datejs/date-pt-PT.js");
|
||||
localeFiles.put("pt_BR", "/images/jquery/plugins/datejs/date-pt-BR.js");
|
||||
localeFiles.put("pt_PT", "/images/jquery/plugins/datejs/date-pt-PT.js");
|
||||
localeFiles.put("ro", "/images/jquery/plugins/datejs/date-ro-RO.js");
|
||||
localeFiles.put("ro_RO", "/images/jquery/plugins/datejs/date-ro-RO.js");
|
||||
localeFiles.put("ru", "/images/jquery/plugins/datejs/date-ru-RU.js");
|
||||
localeFiles.put("ru_RU", "/images/jquery/plugins/datejs/date-ru-RU.js");
|
||||
localeFiles.put("sr", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sr_BA", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sr__#Latn", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sr_BA_#Latn", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sr_ME_#Latn", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sr_RS_#Latn", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sr_ME", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sr_CS", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sr_RS", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sk", "/images/jquery/plugins/datejs/date-sk-SK.js");
|
||||
localeFiles.put("sk_SK", "/images/jquery/plugins/datejs/date-sk-SK.js");
|
||||
localeFiles.put("sl", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sl_SI", "/images/jquery/plugins/datejs/date-sl-SI.js");
|
||||
localeFiles.put("es", "/images/jquery/plugins/datejs/date-es-ES.js");
|
||||
localeFiles.put("es_AR", "/images/jquery/plugins/datejs/date-es-AR.js");
|
||||
localeFiles.put("es_BO", "/images/jquery/plugins/datejs/date-es-BO.js");
|
||||
localeFiles.put("es_CL", "/images/jquery/plugins/datejs/date-es-CL.js");
|
||||
localeFiles.put("es_CO", "/images/jquery/plugins/datejs/date-es-CO.js");
|
||||
localeFiles.put("es_CR", "/images/jquery/plugins/datejs/date-es-CR.js");
|
||||
localeFiles.put("es_CU", "/images/jquery/plugins/datejs/date-es-ES.js");
|
||||
localeFiles.put("es_DO", "/images/jquery/plugins/datejs/date-es-DO.js");
|
||||
localeFiles.put("es_EC", "/images/jquery/plugins/datejs/date-es-EC.js");
|
||||
localeFiles.put("es_SV", "/images/jquery/plugins/datejs/date-es-SV.js");
|
||||
localeFiles.put("es_GT", "/images/jquery/plugins/datejs/date-es-GT.js");
|
||||
localeFiles.put("es_HN", "/images/jquery/plugins/datejs/date-es-HN.js");
|
||||
localeFiles.put("es_MX", "/images/jquery/plugins/datejs/date-es-MX.js");
|
||||
localeFiles.put("es_NI", "/images/jquery/plugins/datejs/date-es-NI.js");
|
||||
localeFiles.put("es_PA", "/images/jquery/plugins/datejs/date-es-PA.js");
|
||||
localeFiles.put("es_PY", "/images/jquery/plugins/datejs/date-es-PY.js");
|
||||
localeFiles.put("es_PE", "/images/jquery/plugins/datejs/date-es-PE.js");
|
||||
localeFiles.put("es_PR", "/images/jquery/plugins/datejs/date-es-PR.js");
|
||||
localeFiles.put("es_ES", "/images/jquery/plugins/datejs/date-es-ES.js");
|
||||
localeFiles.put("es_US", "/images/jquery/plugins/datejs/date-es-ES.js");
|
||||
localeFiles.put("es_UY", "/images/jquery/plugins/datejs/date-es-UY.js");
|
||||
localeFiles.put("es_VE", "/images/jquery/plugins/datejs/date-es-VE.js");
|
||||
localeFiles.put("sv", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("sv_SE", "/images/jquery/plugins/datejs/date-sv-SE.js");
|
||||
localeFiles.put("th", "/images/jquery/plugins/datejs/date-th-TH.js");
|
||||
localeFiles.put("th_TH", "/images/jquery/plugins/datejs/date-th-TH.js");
|
||||
localeFiles.put("th_TH_TH_#u-nu-thai", "/images/jquery/plugins/datejs/date-th-TH.js");
|
||||
localeFiles.put("tr", "/images/jquery/plugins/datejs/date-tr-TR.js");
|
||||
localeFiles.put("tr_TR", "/images/jquery/plugins/datejs/date-tr-TR.js");
|
||||
localeFiles.put("uk", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("uk_UA", "/images/jquery/plugins/datejs/date-uk-UA.js");
|
||||
localeFiles.put("vi", "/images/jquery/plugins/datejs/date-en-US.js");
|
||||
localeFiles.put("vi_VN", "/images/jquery/plugins/datejs/date-vi-VN.js");
|
||||
}
|
||||
|
||||
public static String getFilePath(String locale) {
|
||||
if (datejs.localeFiles.containsKey(locale)) {
|
||||
return datejs.localeFiles.get(locale);
|
||||
}
|
||||
return datejs.defaultDateJs;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class jquery {
|
||||
private static Map<String, String> localeFiles = new HashMap<String, String>();
|
||||
private static String defaultDateJs = "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js";
|
||||
|
||||
static {
|
||||
localeFiles.put("sq", "/images/jquery/ui/i18n/jquery.ui.datepicker-sq.js");
|
||||
localeFiles.put("sq_AL", "/images/jquery/ui/i18n/jquery.ui.datepicker-sq.js");
|
||||
localeFiles.put("ar", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_DZ", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_BH", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_EG", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_IQ", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_JO", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_KW", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_LB", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_LY", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_MA", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_OM", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_QA", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_SA", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_SD", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_SY", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_TN", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_AE", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("ar_YE", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js");
|
||||
localeFiles.put("be", "/images/jquery/ui/i18n/jquery.ui.datepicker-be.js");
|
||||
localeFiles.put("be_BY", "/images/jquery/ui/i18n/jquery.ui.datepicker-be.js");
|
||||
localeFiles.put("bg", "/images/jquery/ui/i18n/jquery.ui.datepicker-bg.js");
|
||||
localeFiles.put("bg_BG", "/images/jquery/ui/i18n/jquery.ui.datepicker-bg.js");
|
||||
localeFiles.put("ca", "/images/jquery/ui/i18n/jquery.ui.datepicker-ca.js");
|
||||
localeFiles.put("ca_ES", "/images/jquery/ui/i18n/jquery.ui.datepicker-ca.js");
|
||||
localeFiles.put("zh", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("zh_CN", "/images/jquery/ui/i18n/jquery.ui.datepicker-zh-CN.js");
|
||||
localeFiles.put("zh_HK", "/images/jquery/ui/i18n/jquery.ui.datepicker-zh-HK.js");
|
||||
localeFiles.put("zh_SG", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("zh_TW", "/images/jquery/ui/i18n/jquery.ui.datepicker-zh-TW.js");
|
||||
localeFiles.put("hr", "/images/jquery/ui/i18n/jquery.ui.datepicker-hr.js");
|
||||
localeFiles.put("hr_HR", "/images/jquery/ui/i18n/jquery.ui.datepicker-hr.js");
|
||||
localeFiles.put("cs", "/images/jquery/ui/i18n/jquery.ui.datepicker-cs.js");
|
||||
localeFiles.put("cs_CZ", "/images/jquery/ui/i18n/jquery.ui.datepicker-cs.js");
|
||||
localeFiles.put("da", "/images/jquery/ui/i18n/jquery.ui.datepicker-da.js");
|
||||
localeFiles.put("da_DK", "/images/jquery/ui/i18n/jquery.ui.datepicker-da.js");
|
||||
localeFiles.put("nl", "/images/jquery/ui/i18n/jquery.ui.datepicker-nl.js");
|
||||
localeFiles.put("nl_BE", "/images/jquery/ui/i18n/jquery.ui.datepicker-nl.js");
|
||||
localeFiles.put("nl_NL", "/images/jquery/ui/i18n/jquery.ui.datepicker-nl.js");
|
||||
localeFiles.put("en", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_AU", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_CA", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_IN", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_IE", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_MT", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_NZ", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_PH", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_SG", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_ZA", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_GB", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("en_US", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("et", "/images/jquery/ui/i18n/jquery.ui.datepicker-et.js");
|
||||
localeFiles.put("et_EE", "/images/jquery/ui/i18n/jquery.ui.datepicker-et.js");
|
||||
localeFiles.put("fi", "/images/jquery/ui/i18n/jquery.ui.datepicker-fi.js");
|
||||
localeFiles.put("fi_FI", "/images/jquery/ui/i18n/jquery.ui.datepicker-fi.js");
|
||||
localeFiles.put("fr", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js");
|
||||
localeFiles.put("fr_BE", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js");
|
||||
localeFiles.put("fr_CA", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js");
|
||||
localeFiles.put("fr_FR", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js");
|
||||
localeFiles.put("fr_LU", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js");
|
||||
localeFiles.put("fr_CH", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js");
|
||||
localeFiles.put("de", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js");
|
||||
localeFiles.put("de_AT", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js");
|
||||
localeFiles.put("de_DE", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js");
|
||||
localeFiles.put("de_GR", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js");
|
||||
localeFiles.put("de_LU", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js");
|
||||
localeFiles.put("de_CH", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js");
|
||||
localeFiles.put("el", "/images/jquery/ui/i18n/jquery.ui.datepicker-el.js");
|
||||
localeFiles.put("el_CY", "/images/jquery/ui/i18n/jquery.ui.datepicker-el.js");
|
||||
localeFiles.put("el_GR", "/images/jquery/ui/i18n/jquery.ui.datepicker-el.js");
|
||||
localeFiles.put("iw", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("iw_IL", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("hi", "/images/jquery/ui/i18n/jquery.ui.datepicker-hi.js");
|
||||
localeFiles.put("hi_IN", "/images/jquery/ui/i18n/jquery.ui.datepicker-hi.js");
|
||||
localeFiles.put("hu", "/images/jquery/ui/i18n/jquery.ui.datepicker-hu.js");
|
||||
localeFiles.put("hu_HU", "/images/jquery/ui/i18n/jquery.ui.datepicker-hu.js");
|
||||
localeFiles.put("is", "/images/jquery/ui/i18n/jquery.ui.datepicker-is.js");
|
||||
localeFiles.put("is_IS", "/images/jquery/ui/i18n/jquery.ui.datepicker-is.js");
|
||||
localeFiles.put("in", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("in_ID", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("ga", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("ga_IE", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("it", "/images/jquery/ui/i18n/jquery.ui.datepicker-it.js");
|
||||
localeFiles.put("it_IT", "/images/jquery/ui/i18n/jquery.ui.datepicker-it.js");
|
||||
localeFiles.put("it_CH", "/images/jquery/ui/i18n/jquery.ui.datepicker-it.js");
|
||||
localeFiles.put("ja", "/images/jquery/ui/i18n/jquery.ui.datepicker-ja.js");
|
||||
localeFiles.put("ja_JP", "/images/jquery/ui/i18n/jquery.ui.datepicker-ja.js");
|
||||
localeFiles.put("ja_JP_JP_#u-ca-japanese", "/images/jquery/ui/i18n/jquery.ui.datepicker-ja.js");
|
||||
localeFiles.put("ko", "/images/jquery/ui/i18n/jquery.ui.datepicker-ko.js");
|
||||
localeFiles.put("ko_KR", "/images/jquery/ui/i18n/jquery.ui.datepicker-ko.js");
|
||||
localeFiles.put("lv", "/images/jquery/ui/i18n/jquery.ui.datepicker-lv.js");
|
||||
localeFiles.put("lv_LV", "/images/jquery/ui/i18n/jquery.ui.datepicker-lv.js");
|
||||
localeFiles.put("lt", "/images/jquery/ui/i18n/jquery.ui.datepicker-lt.js");
|
||||
localeFiles.put("lt_LT", "/images/jquery/ui/i18n/jquery.ui.datepicker-lt.js");
|
||||
localeFiles.put("mk", "/images/jquery/ui/i18n/jquery.ui.datepicker-mk.js");
|
||||
localeFiles.put("mk_MK", "/images/jquery/ui/i18n/jquery.ui.datepicker-mk.js");
|
||||
localeFiles.put("ms", "/images/jquery/ui/i18n/jquery.ui.datepicker-ms.js");
|
||||
localeFiles.put("ms_MY", "/images/jquery/ui/i18n/jquery.ui.datepicker-ms.js");
|
||||
localeFiles.put("mt", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("mt_MT", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js");
|
||||
localeFiles.put("no", "/images/jquery/ui/i18n/jquery.ui.datepicker-no.js");
|
||||
localeFiles.put("no_NO", "/images/jquery/ui/i18n/jquery.ui.datepicker-no.js");
|
||||
localeFiles.put("no_NO_NY", "/images/jquery/ui/i18n/jquery.ui.datepicker-no.js");
|
||||
localeFiles.put("pl", "/images/jquery/ui/i18n/jquery.ui.datepicker-pl.js");
|
||||
localeFiles.put("pl_PL", "/images/jquery/ui/i18n/jquery.ui.datepicker-pl.js");
|
||||
localeFiles.put("pt", "/images/jquery/ui/i18n/jquery.ui.datepicker-pt.js");
|
||||
localeFiles.put("pt_BR", "/images/jquery/ui/i18n/jquery.ui.datepicker-pt.js");
|
||||
localeFiles.put("pt_PT", "/images/jquery/ui/i18n/jquery.ui.datepicker-pt.js");
|
||||
localeFiles.put("ro", "/images/jquery/ui/i18n/jquery.ui.datepicker-ro.js");
|
||||
localeFiles.put("ro_RO", "/images/jquery/ui/i18n/jquery.ui.datepicker-ro.js");
|
||||
localeFiles.put("ru", "/images/jquery/ui/i18n/jquery.ui.datepicker-ru.js");
|
||||
localeFiles.put("ru_RU", "/images/jquery/ui/i18n/jquery.ui.datepicker-ru.js");
|
||||
localeFiles.put("sr", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js");
|
||||
localeFiles.put("sr_BA", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js");
|
||||
localeFiles.put("sr__#Latn", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js");
|
||||
localeFiles.put("sr_BA_#Latn", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js");
|
||||
localeFiles.put("sr_ME_#Latn", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js");
|
||||
localeFiles.put("sr_RS_#Latn", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js");
|
||||
localeFiles.put("sr_ME", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js");
|
||||
localeFiles.put("sr_CS", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js");
|
||||
localeFiles.put("sr_RS", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js");
|
||||
localeFiles.put("sk", "/images/jquery/ui/i18n/jquery.ui.datepicker-sk.js");
|
||||
localeFiles.put("sk_SK", "/images/jquery/ui/i18n/jquery.ui.datepicker-sk.js");
|
||||
localeFiles.put("sl", "/images/jquery/ui/i18n/jquery.ui.datepicker-sl.js");
|
||||
localeFiles.put("sl_SI", "/images/jquery/ui/i18n/jquery.ui.datepicker-sl.js");
|
||||
localeFiles.put("es", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_AR", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_BO", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_CL", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_CO", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_CR", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_CU", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_DO", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_EC", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_SV", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_GT", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_HN", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_MX", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_NI", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_PA", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_PY", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_PE", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_PR", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_ES", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_US", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_UY", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("es_VE", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js");
|
||||
localeFiles.put("sv", "/images/jquery/ui/i18n/jquery.ui.datepicker-sv.js");
|
||||
localeFiles.put("sv_SE", "/images/jquery/ui/i18n/jquery.ui.datepicker-sv.js");
|
||||
localeFiles.put("th", "/images/jquery/ui/i18n/jquery.ui.datepicker-th.js");
|
||||
localeFiles.put("th_TH", "/images/jquery/ui/i18n/jquery.ui.datepicker-th.js");
|
||||
localeFiles.put("th_TH_TH_#u-nu-thai", "/images/jquery/ui/i18n/jquery.ui.datepicker-th.js");
|
||||
localeFiles.put("tr", "/images/jquery/ui/i18n/jquery.ui.datepicker-tr.js");
|
||||
localeFiles.put("tr_TR", "/images/jquery/ui/i18n/jquery.ui.datepicker-tr.js");
|
||||
localeFiles.put("uk", "/images/jquery/ui/i18n/jquery.ui.datepicker-uk.js");
|
||||
localeFiles.put("uk_UA", "/images/jquery/ui/i18n/jquery.ui.datepicker-uk.js");
|
||||
localeFiles.put("vi", "/images/jquery/ui/i18n/jquery.ui.datepicker-vi.js");
|
||||
localeFiles.put("vi_VN", "/images/jquery/ui/i18n/jquery.ui.datepicker-vi.js");
|
||||
}
|
||||
|
||||
public static String getFilePath(String locale) {
|
||||
if (datejs.localeFiles.containsKey(locale)) {
|
||||
return jquery.localeFiles.get(locale);
|
||||
}
|
||||
return jquery.defaultDateJs;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class validation {
|
||||
private static Map<String, String> localeFiles = new HashMap<String, String>();
|
||||
private static String defaultValidation = "/images/webapp/images/jquery/plugins/validate/localization/messages_en.js";
|
||||
|
||||
static {
|
||||
localeFiles.put("sq", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("sq_AL", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("ar", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_DZ", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_BH", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_EG", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_IQ", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_JO", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_KW", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_LB", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_LY", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_MA", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_OM", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_QA", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_SA", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_SD", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_SY", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_TN", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_AE", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("ar_YE", "/images/jquery/plugins/validate/localization/messages_ar.js");
|
||||
localeFiles.put("be", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("be_BY", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("bg", "/images/jquery/plugins/validate/localization/messages_bg.js");
|
||||
localeFiles.put("bg_BG", "/images/jquery/plugins/validate/localization/messages_bg.js");
|
||||
localeFiles.put("ca", "/images/jquery/plugins/validate/localization/messages_ca.js");
|
||||
localeFiles.put("ca_ES", "/images/jquery/plugins/validate/localization/messages_ca.js");
|
||||
localeFiles.put("zh", "/images/jquery/plugins/validate/localization/messages_zh.js");
|
||||
localeFiles.put("zh_CN", "/images/jquery/plugins/validate/localization/messages_zh.js");
|
||||
localeFiles.put("zh_HK", "/images/jquery/plugins/validate/localization/messages_zh.js");
|
||||
localeFiles.put("zh_SG", "/images/jquery/plugins/validate/localization/messages_zh.js");
|
||||
localeFiles.put("zh_TW", "/images/jquery/plugins/validate/localization/messages_zh_TW.js");
|
||||
localeFiles.put("hr", "/images/jquery/plugins/validate/localization/messages_hr.js");
|
||||
localeFiles.put("hr_HR", "/images/jquery/plugins/validate/localization/messages_hr.js");
|
||||
localeFiles.put("cs", "/images/jquery/plugins/validate/localization/messages_cs.js");
|
||||
localeFiles.put("cs_CZ", "/images/jquery/plugins/validate/localization/messages_cs.js");
|
||||
localeFiles.put("da", "/images/jquery/plugins/validate/localization/messages_da.js");
|
||||
localeFiles.put("da_DK", "/images/jquery/plugins/validate/localization/messages_da.js");
|
||||
localeFiles.put("nl", "/images/jquery/plugins/validate/localization/messages_nl.js");
|
||||
localeFiles.put("nl_BE", "/images/jquery/plugins/validate/localization/messages_nl.js");
|
||||
localeFiles.put("nl_NL", "/images/jquery/plugins/validate/localization/messages_nl.js");
|
||||
localeFiles.put("en", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_AU", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_CA", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_IN", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_IE", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_MT", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_NZ", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_PH", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_SG", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_ZA", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_GB", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("en_US", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("et", "/images/jquery/plugins/validate/localization/messages_et.js");
|
||||
localeFiles.put("et_EE", "/images/jquery/plugins/validate/localization/messages_et.js");
|
||||
localeFiles.put("fi", "/images/jquery/plugins/validate/localization/messages_fi.js");
|
||||
localeFiles.put("fi_FI", "/images/jquery/plugins/validate/localization/messages_fi.js");
|
||||
localeFiles.put("fr", "/images/jquery/plugins/validate/localization/messages_fr.js");
|
||||
localeFiles.put("fr_BE", "/images/jquery/plugins/validate/localization/messages_fr.js");
|
||||
localeFiles.put("fr_CA", "/images/jquery/plugins/validate/localization/messages_fr.js");
|
||||
localeFiles.put("fr_FR", "/images/jquery/plugins/validate/localization/messages_fr.js");
|
||||
localeFiles.put("fr_LU", "/images/jquery/plugins/validate/localization/messages_fr.js");
|
||||
localeFiles.put("fr_CH", "/images/jquery/plugins/validate/localization/messages_fr.js");
|
||||
localeFiles.put("de", "/images/jquery/plugins/validate/localization/messages_de.js");
|
||||
localeFiles.put("de_AT", "/images/jquery/plugins/validate/localization/messages_de.js");
|
||||
localeFiles.put("de_DE", "/images/jquery/plugins/validate/localization/messages_de.js");
|
||||
localeFiles.put("de_GR", "/images/jquery/plugins/validate/localization/messages_de.js");
|
||||
localeFiles.put("de_LU", "/images/jquery/plugins/validate/localization/messages_de.js");
|
||||
localeFiles.put("de_CH", "/images/jquery/plugins/validate/localization/messages_de.js");
|
||||
localeFiles.put("el", "/images/jquery/plugins/validate/localization/messages_el.js");
|
||||
localeFiles.put("el_CY", "/images/jquery/plugins/validate/localization/messages_el.js");
|
||||
localeFiles.put("el_GR", "/images/jquery/plugins/validate/localization/messages_el.js");
|
||||
localeFiles.put("iw", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("iw_IL", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("hi", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("hi_IN", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("hu", "/images/jquery/plugins/validate/localization/messages_hu.js");
|
||||
localeFiles.put("hu_HU", "/images/jquery/plugins/validate/localization/messages_hu.js");
|
||||
localeFiles.put("is", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("is_IS", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("in", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("in_ID", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("ga", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("ga_IE", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("it", "/images/jquery/plugins/validate/localization/messages_it.js");
|
||||
localeFiles.put("it_IT", "/images/jquery/plugins/validate/localization/messages_it.js");
|
||||
localeFiles.put("it_CH", "/images/jquery/plugins/validate/localization/messages_it.js");
|
||||
localeFiles.put("ja", "/images/jquery/plugins/validate/localization/messages_ja.js");
|
||||
localeFiles.put("ja_JP", "/images/jquery/plugins/validate/localization/messages_ja.js");
|
||||
localeFiles.put("ja_JP_JP_#u-ca-japanese", "/images/jquery/plugins/validate/localization/messages_ja.js");
|
||||
localeFiles.put("ko", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("ko_KR", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("lv", "/images/jquery/plugins/validate/localization/messages_lv.js");
|
||||
localeFiles.put("lv_LV", "/images/jquery/plugins/validate/localization/messages_lv.js");
|
||||
localeFiles.put("lt", "/images/jquery/plugins/validate/localization/messages_lt.js");
|
||||
localeFiles.put("lt_LT", "/images/jquery/plugins/validate/localization/messages_lt.js");
|
||||
localeFiles.put("mk", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("mk_MK", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("ms", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("ms_MY", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("mt", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("mt_MT", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("no", "/images/jquery/plugins/validate/localization/messages_no.js");
|
||||
localeFiles.put("no_NO", "/images/jquery/plugins/validate/localization/messages_no.js");
|
||||
localeFiles.put("no_NO_NY", "/images/jquery/plugins/validate/localization/messages_no.js");
|
||||
localeFiles.put("pl", "/images/jquery/plugins/validate/localization/messages_pl.js");
|
||||
localeFiles.put("pl_PL", "/images/jquery/plugins/validate/localization/messages_pl.js");
|
||||
localeFiles.put("pt", "/images/jquery/plugins/validate/localization/messages_en.js");
|
||||
localeFiles.put("pt_BR", "/images/jquery/plugins/validate/localization/messages_pt_BR.js");
|
||||
localeFiles.put("pt_PT", "/images/jquery/plugins/validate/localization/messages_pt_PT.js");
|
||||
localeFiles.put("ro", "/images/jquery/plugins/validate/localization/messages_ro.js");
|
||||
localeFiles.put("ro_RO", "/images/jquery/plugins/validate/localization/messages_ro.js");
|
||||
localeFiles.put("ru", "/images/jquery/plugins/validate/localization/messages_ru.js");
|
||||
localeFiles.put("ru_RU", "/images/jquery/plugins/validate/localization/messages_ru.js");
|
||||
localeFiles.put("sr", "/images/jquery/plugins/validate/localization/messages_sr.js");
|
||||
localeFiles.put("sr_BA", "/images/jquery/plugins/validate/localization/messages_sr.js");
|
||||
localeFiles.put("sr__#Latn", "/images/jquery/plugins/validate/localization/messages_sr.js");
|
||||
localeFiles.put("sr_BA_#Latn", "/images/jquery/plugins/validate/localization/messages_sr.js");
|
||||
localeFiles.put("sr_ME_#Latn", "/images/jquery/plugins/validate/localization/messages_sr.js");
|
||||
localeFiles.put("sr_RS_#Latn", "/images/jquery/plugins/validate/localization/messages_sr.js");
|
||||
localeFiles.put("sr_ME", "/images/jquery/plugins/validate/localization/messages_sr.js");
|
||||
localeFiles.put("sr_CS", "/images/jquery/plugins/validate/localization/messages_sr.js");
|
||||
localeFiles.put("sr_RS", "/images/jquery/plugins/validate/localization/messages_sr.js");
|
||||
localeFiles.put("sk", "/images/jquery/plugins/validate/localization/messages_sk.js");
|
||||
localeFiles.put("sk_SK", "/images/jquery/plugins/validate/localization/messages_sk.js");
|
||||
localeFiles.put("sl", "/images/jquery/plugins/validate/localization/messages_sl.js");
|
||||
localeFiles.put("sl_SI", "/images/jquery/plugins/validate/localization/messages_sl.js");
|
||||
localeFiles.put("es", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_AR", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_BO", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_CL", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_CO", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_CR", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_CU", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_DO", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_EC", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_SV", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_GT", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_HN", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_MX", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_NI", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_PA", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_PY", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_PE", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_PR", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_ES", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_US", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_UY", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("es_VE", "/images/jquery/plugins/validate/localization/messages_es.js");
|
||||
localeFiles.put("sv", "/images/jquery/plugins/validate/localization/messages_sv.js");
|
||||
localeFiles.put("sv_SE", "/images/jquery/plugins/validate/localization/messages_sv.js");
|
||||
localeFiles.put("th", "/images/jquery/plugins/validate/localization/messages_th.js");
|
||||
localeFiles.put("th_TH", "/images/jquery/plugins/validate/localization/messages_th.js");
|
||||
localeFiles.put("th_TH_TH_#u-nu-thai", "/images/jquery/plugins/validate/localization/messages_th.js");
|
||||
localeFiles.put("tr", "/images/jquery/plugins/validate/localization/messages_tr.js");
|
||||
localeFiles.put("tr_TR", "/images/jquery/plugins/validate/localization/messages_tr.js");
|
||||
localeFiles.put("uk", "/images/jquery/plugins/validate/localization/messages_uk.js");
|
||||
localeFiles.put("uk_UA", "/images/jquery/plugins/validate/localization/messages_uk.js");
|
||||
localeFiles.put("vi", "/images/jquery/plugins/validate/localization/messages_vi.js");
|
||||
localeFiles.put("vi_VN", "/images/jquery/plugins/validate/localization/messages_vi.js");
|
||||
}
|
||||
|
||||
public static String getFilePath(String locale) {
|
||||
if (validation.localeFiles.containsKey(locale)) {
|
||||
return validation.localeFiles.get(locale);
|
||||
}
|
||||
return validation.defaultValidation;
|
||||
}
|
||||
}
|
||||
|
||||
public static class dateTime {
|
||||
private static Map<String, String> localeFiles = new HashMap<String, String>();
|
||||
private static String defaultDateTime = "/images/webapp/images/jquery/ui/i18n/jquery.ui.datepicker-en.js";
|
||||
|
||||
static {
|
||||
localeFiles.put("sq", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("sq_AL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_DZ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_BH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_EG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_IQ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_JO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_KW", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_LB", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_LY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_MA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_OM", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_QA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_SA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_SD", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_SY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_TN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_AE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ar_YE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("be", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("be_BY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("bg", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-bg.js");
|
||||
localeFiles.put("bg_BG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-bg.js");
|
||||
localeFiles.put("ca", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ca.js");
|
||||
localeFiles.put("ca_ES", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ca.js");
|
||||
localeFiles.put("zh", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("zh_CN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-zh-CN.js");
|
||||
localeFiles.put("zh_HK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-zh-HK.js");
|
||||
localeFiles.put("zh_SG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("zh_TW", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-zh-TW.js");
|
||||
localeFiles.put("hr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hr.js");
|
||||
localeFiles.put("hr_HR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hr.js");
|
||||
localeFiles.put("cs", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-cs.js");
|
||||
localeFiles.put("cs_CZ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-cs.js");
|
||||
localeFiles.put("da", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-da.js");
|
||||
localeFiles.put("da_DK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-da.js");
|
||||
localeFiles.put("nl", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-nl.js");
|
||||
localeFiles.put("nl_BE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-nl.js");
|
||||
localeFiles.put("nl_NL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-nl.js");
|
||||
localeFiles.put("en", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_AU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_CA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_IN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_IE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_MT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_NZ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_PH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_SG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_ZA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_GB", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("en_US", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("et", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-et.js");
|
||||
localeFiles.put("et_EE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-et.js");
|
||||
localeFiles.put("fi", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fi.js");
|
||||
localeFiles.put("fi_FI", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fi.js");
|
||||
localeFiles.put("fr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js");
|
||||
localeFiles.put("fr_BE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js");
|
||||
localeFiles.put("fr_CA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js");
|
||||
localeFiles.put("fr_FR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js");
|
||||
localeFiles.put("fr_LU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js");
|
||||
localeFiles.put("fr_CH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js");
|
||||
localeFiles.put("de", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js");
|
||||
localeFiles.put("de_AT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js");
|
||||
localeFiles.put("de_DE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js");
|
||||
localeFiles.put("de_GR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js");
|
||||
localeFiles.put("de_LU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js");
|
||||
localeFiles.put("de_CH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js");
|
||||
localeFiles.put("el", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-el.js");
|
||||
localeFiles.put("el_CY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-el.js");
|
||||
localeFiles.put("el_GR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-el.js");
|
||||
localeFiles.put("iw", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("iw_IL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("hi", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("hi_IN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("hu", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hu.js");
|
||||
localeFiles.put("hu_HU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hu.js");
|
||||
localeFiles.put("is", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("is_IS", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("in", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("in_ID", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ga", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ga_IE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("it", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-it.js");
|
||||
localeFiles.put("it_IT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-it.js");
|
||||
localeFiles.put("it_CH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-it.js");
|
||||
localeFiles.put("ja", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ja.js");
|
||||
localeFiles.put("ja_JP", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ja.js");
|
||||
localeFiles.put("ja_JP_JP_#u-ca-japanese", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ja.js");
|
||||
localeFiles.put("ko", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ko.js");
|
||||
localeFiles.put("ko_KR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ko.js");
|
||||
localeFiles.put("lv", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("lv_LV", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("lt", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-lt.js");
|
||||
localeFiles.put("lt_LT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-lt.js");
|
||||
localeFiles.put("mk", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("mk_MK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ms", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("ms_MY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("mt", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("mt_MT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("no", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-no.js");
|
||||
localeFiles.put("no_NO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-no.js");
|
||||
localeFiles.put("no_NO_NY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-no.js");
|
||||
localeFiles.put("pl", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pl.js");
|
||||
localeFiles.put("pl_PL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pl.js");
|
||||
localeFiles.put("pt", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pt.js");
|
||||
localeFiles.put("pt_BR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pt.js");
|
||||
localeFiles.put("pt_PT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pt.js");
|
||||
localeFiles.put("ro", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ro.js");
|
||||
localeFiles.put("ro_RO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ro.js");
|
||||
localeFiles.put("ru", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ru.js");
|
||||
localeFiles.put("ru_RU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ru.js");
|
||||
localeFiles.put("sr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("sr_BA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("sr__#Latn", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("sr_BA_#Latn", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("sr_ME_#Latn", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("sr_RS_#Latn", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("sr_ME", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("sr_CS", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("sr_RS", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sr-RS.js");
|
||||
localeFiles.put("sk", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sk.js");
|
||||
localeFiles.put("sk_SK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sk.js");
|
||||
localeFiles.put("sl", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("sl_SI", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js");
|
||||
localeFiles.put("es", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_AR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_BO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_CL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_CO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_CR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_CU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_DO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_EC", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_SV", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_GT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_HN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_MX", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_NI", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_PA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_PY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_PE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_PR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_ES", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_US", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_UY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("es_VE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js");
|
||||
localeFiles.put("sv", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sv.js");
|
||||
localeFiles.put("sv_SE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sv.js");
|
||||
localeFiles.put("th", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-th.js");
|
||||
localeFiles.put("th_TH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-th.js");
|
||||
localeFiles.put("th_TH_TH_#u-nu-thai", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-th.js");
|
||||
localeFiles.put("tr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-tr.js");
|
||||
localeFiles.put("tr_TR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-tr.js");
|
||||
localeFiles.put("uk", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-uk.js");
|
||||
localeFiles.put("uk_UA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-uk.js");
|
||||
localeFiles.put("vi", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-vi.js");
|
||||
localeFiles.put("vi_VN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-vi.js");
|
||||
}
|
||||
|
||||
public static String getFilePath(String locale) {
|
||||
if (dateTime.localeFiles.containsKey(locale)) {
|
||||
return dateTime.localeFiles.get(locale);
|
||||
}
|
||||
return dateTime.defaultDateTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
|
||||
/**
|
||||
* A few utility methods related to Keyword Search.
|
||||
*/
|
||||
public final class KeywordSearchUtil {
|
||||
|
||||
public static final String module = KeywordSearchUtil.class.getName();
|
||||
|
||||
private static Set<String> thesaurusRelsToInclude = new HashSet<String>();
|
||||
private static Set<String> thesaurusRelsForReplace = new HashSet<String>();
|
||||
|
||||
static {
|
||||
thesaurusRelsToInclude.add("KWTR_UF");
|
||||
thesaurusRelsToInclude.add("KWTR_USE");
|
||||
thesaurusRelsToInclude.add("KWTR_CS");
|
||||
thesaurusRelsToInclude.add("KWTR_NT");
|
||||
thesaurusRelsToInclude.add("KWTR_BT");
|
||||
thesaurusRelsToInclude.add("KWTR_RT");
|
||||
|
||||
thesaurusRelsForReplace.add("KWTR_USE");
|
||||
thesaurusRelsForReplace.add("KWTR_CS");
|
||||
}
|
||||
|
||||
private KeywordSearchUtil () {}
|
||||
|
||||
public static String getSeparators() {
|
||||
// String separators = ";: ,.!?\t\"\'\r\n\\/()[]{}*%<>-+_";
|
||||
String seps = UtilProperties.getPropertyValue("keywordsearch", "index.keyword.separators", ";: ,.!?\t\"\'\r\n\\/()[]{}*%<>-+_");
|
||||
return seps;
|
||||
}
|
||||
|
||||
public static String getStopWordBagOr() {
|
||||
return UtilProperties.getPropertyValue("keywordsearch", "stop.word.bag.or");
|
||||
}
|
||||
public static String getStopWordBagAnd() {
|
||||
return UtilProperties.getPropertyValue("keywordsearch", "stop.word.bag.and");
|
||||
}
|
||||
|
||||
public static boolean getRemoveStems() {
|
||||
String removeStemsStr = UtilProperties.getPropertyValue("keywordsearch", "remove.stems");
|
||||
return "true".equals(removeStemsStr);
|
||||
}
|
||||
public static Set<String> getStemSet() {
|
||||
String stemBag = UtilProperties.getPropertyValue("keywordsearch", "stem.bag");
|
||||
Set<String> stemSet = new TreeSet<String>();
|
||||
if (UtilValidate.isNotEmpty(stemBag)) {
|
||||
String curToken;
|
||||
StringTokenizer tokenizer = new StringTokenizer(stemBag, ": ");
|
||||
while (tokenizer.hasMoreTokens()) {
|
||||
curToken = tokenizer.nextToken();
|
||||
stemSet.add(curToken);
|
||||
}
|
||||
}
|
||||
return stemSet;
|
||||
}
|
||||
|
||||
public static void processForKeywords(String str, Map<String, Long> keywords, boolean forSearch, boolean anyPrefix, boolean anySuffix, boolean isAnd) {
|
||||
String separators = getSeparators();
|
||||
String stopWordBagOr = getStopWordBagOr();
|
||||
String stopWordBagAnd = getStopWordBagAnd();
|
||||
|
||||
boolean removeStems = getRemoveStems();
|
||||
Set<String> stemSet = getStemSet();
|
||||
|
||||
processForKeywords(str, keywords, separators, stopWordBagAnd, stopWordBagOr, removeStems, stemSet, forSearch, anyPrefix, anySuffix, isAnd);
|
||||
}
|
||||
|
||||
public static void processKeywordsForIndex(String str, Map<String, Long> keywords, String separators, String stopWordBagAnd, String stopWordBagOr, boolean removeStems, Set<String> stemSet) {
|
||||
processForKeywords(str, keywords, separators, stopWordBagAnd, stopWordBagOr, removeStems, stemSet, false, false, false, false);
|
||||
}
|
||||
|
||||
public static void processForKeywords(String str, Map<String, Long> keywords, String separators, String stopWordBagAnd, String stopWordBagOr, boolean removeStems, Set<String> stemSet, boolean forSearch, boolean anyPrefix, boolean anySuffix, boolean isAnd) {
|
||||
Set<String> keywordSet = makeKeywordSet(str, separators, forSearch);
|
||||
fixupKeywordSet(keywordSet, keywords, stopWordBagAnd, stopWordBagOr, removeStems, stemSet, forSearch, anyPrefix, anySuffix, isAnd);
|
||||
}
|
||||
|
||||
public static void fixupKeywordSet(Set<String> keywordSet, Map<String, Long> keywords, String stopWordBagAnd, String stopWordBagOr, boolean removeStems, Set<String> stemSet, boolean forSearch, boolean anyPrefix, boolean anySuffix, boolean isAnd) {
|
||||
if (keywordSet == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (String token: keywordSet) {
|
||||
|
||||
// when cleaning up the tokens the ordering is inportant: check stop words, remove stems, then get rid of 1 character tokens (1 digit okay)
|
||||
|
||||
// check stop words
|
||||
String colonToken = ":" + token + ":";
|
||||
if (forSearch) {
|
||||
if ((isAnd && stopWordBagAnd.indexOf(colonToken) >= 0) || (!isAnd && stopWordBagOr.indexOf(colonToken) >= 0)) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
if (stopWordBagOr.indexOf(colonToken) >= 0 && stopWordBagAnd.indexOf(colonToken) >= 0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// remove stems
|
||||
if (removeStems) {
|
||||
for (String stem: stemSet) {
|
||||
if (token.endsWith(stem)) {
|
||||
token = token.substring(0, token.length() - stem.length());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// get rid of all length 0 tokens now
|
||||
if (token.length() == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// get rid of all length 1 character only tokens, pretty much useless
|
||||
if (token.length() == 1 && Character.isLetter(token.charAt(0))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (forSearch) {
|
||||
StringBuilder strSb = new StringBuilder();
|
||||
if (anyPrefix) strSb.append('%');
|
||||
strSb.append(token);
|
||||
if (anySuffix) strSb.append('%');
|
||||
// replace all %% with %
|
||||
int dblPercIdx = -1;
|
||||
while ((dblPercIdx = strSb.indexOf("%%")) >= 0) {
|
||||
//Debug.logInfo("before strSb: " + strSb, module);
|
||||
strSb.replace(dblPercIdx, dblPercIdx+2, "%");
|
||||
//Debug.logInfo("after strSb: " + strSb, module);
|
||||
}
|
||||
token = strSb.toString();
|
||||
}
|
||||
|
||||
// group by word, add up weight
|
||||
Long curWeight = keywords.get(token);
|
||||
if (curWeight == null) {
|
||||
keywords.put(token, Long.valueOf(1));
|
||||
} else {
|
||||
keywords.put(token, Long.valueOf(curWeight.longValue() + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Set<String> makeKeywordSet(String str, String separators, boolean forSearch) {
|
||||
if (separators == null) separators = getSeparators();
|
||||
|
||||
Set<String> keywords = new TreeSet<String>();
|
||||
if (str.length() > 0) {
|
||||
// strip off weird characters
|
||||
str = str.replaceAll("\\\302\\\240|\\\240", " ");
|
||||
|
||||
if (forSearch) {
|
||||
// remove %_*? from separators if is for a search
|
||||
StringBuilder sb = new StringBuilder(separators);
|
||||
if (sb.indexOf("%") >= 0) sb.deleteCharAt(sb.indexOf("%"));
|
||||
if (sb.indexOf("_") >= 0) sb.deleteCharAt(sb.indexOf("_"));
|
||||
if (sb.indexOf("*") >= 0) sb.deleteCharAt(sb.indexOf("*"));
|
||||
if (sb.indexOf("?") >= 0) sb.deleteCharAt(sb.indexOf("?"));
|
||||
separators = sb.toString();
|
||||
}
|
||||
|
||||
StringTokenizer tokener = new StringTokenizer(str, separators, false);
|
||||
while (tokener.hasMoreTokens()) {
|
||||
// make sure it is lower case before doing anything else
|
||||
String token = tokener.nextToken().toLowerCase();
|
||||
|
||||
if (forSearch) {
|
||||
// these characters will only be present if it is for a search, ie not for indexing
|
||||
token = token.replace('*', '%');
|
||||
token = token.replace('?', '_');
|
||||
}
|
||||
|
||||
keywords.add(token);
|
||||
}
|
||||
}
|
||||
return keywords;
|
||||
}
|
||||
|
||||
public static Set<String> fixKeywordsForSearch(Set<String> keywordSet, boolean anyPrefix, boolean anySuffix, boolean removeStems, boolean isAnd) {
|
||||
Map<String, Long> keywords = new LinkedHashMap<String, Long>();
|
||||
fixupKeywordSet(keywordSet, keywords, getStopWordBagAnd(), getStopWordBagOr(), removeStems, getStemSet(), true, anyPrefix, anySuffix, isAnd);
|
||||
return keywords.keySet();
|
||||
}
|
||||
|
||||
public static boolean expandKeywordForSearch(String enteredKeyword, Set<String> addToSet, Delegator delegator) {
|
||||
boolean replaceEnteredKeyword = false;
|
||||
|
||||
try {
|
||||
List<GenericValue> thesaurusList = EntityQuery.use(delegator).from("KeywordThesaurus").where("enteredKeyword", enteredKeyword).cache(true).queryList();
|
||||
for (GenericValue keywordThesaurus: thesaurusList) {
|
||||
String relationshipEnumId = (String) keywordThesaurus.get("relationshipEnumId");
|
||||
if (thesaurusRelsToInclude.contains(relationshipEnumId)) {
|
||||
addToSet.addAll(makeKeywordSet(keywordThesaurus.getString("alternateKeyword"), null, true));
|
||||
if (thesaurusRelsForReplace.contains(relationshipEnumId)) {
|
||||
replaceEnteredKeyword = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Error expanding entered keyword", module);
|
||||
}
|
||||
|
||||
Debug.logInfo("Expanded keyword [" + enteredKeyword + "], got set: " + addToSet, module);
|
||||
return replaceEnteredKeyword;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.DelegatorFactory;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.ofbiz.entity.util.EntityUtil;
|
||||
import org.ofbiz.webapp.control.ContextFilter;
|
||||
import org.ofbiz.webapp.website.WebSiteWorker;
|
||||
|
||||
public final class UrlServletHelper extends ContextFilter {
|
||||
|
||||
public final static String module = UrlServletHelper.class.getName();
|
||||
|
||||
private UrlServletHelper() {}
|
||||
|
||||
public static void setRequestAttributes(ServletRequest request, Delegator delegator, ServletContext servletContext) {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
// check if multi tenant is enabled
|
||||
boolean useMultitenant = EntityUtil.isMultiTenantEnabled();
|
||||
if (useMultitenant) {
|
||||
// get tenant delegator by domain name
|
||||
String serverName = request.getServerName();
|
||||
try {
|
||||
// if tenant was specified, replace delegator with the new per-tenant delegator and set tenantId to session attribute
|
||||
delegator = getDelegator(servletContext);
|
||||
|
||||
//Use base delegator for fetching data from entity of entityGroup org.ofbiz.tenant
|
||||
Delegator baseDelegator = DelegatorFactory.getDelegator(delegator.getDelegatorBaseName());
|
||||
GenericValue tenantDomainName = EntityQuery.use(baseDelegator).from("TenantDomainName").where("domainName", serverName).queryOne();
|
||||
|
||||
if (UtilValidate.isNotEmpty(tenantDomainName)) {
|
||||
String tenantId = tenantDomainName.getString("tenantId");
|
||||
// make that tenant active, setup a new delegator and a new dispatcher
|
||||
String tenantDelegatorName = delegator.getDelegatorBaseName() + "#" + tenantId;
|
||||
httpRequest.getSession().setAttribute("delegatorName", tenantDelegatorName);
|
||||
|
||||
// after this line the delegator is replaced with the new per-tenant delegator
|
||||
delegator = DelegatorFactory.getDelegator(tenantDelegatorName);
|
||||
servletContext.setAttribute("delegator", delegator);
|
||||
}
|
||||
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e, "Unable to get Tenant", module);
|
||||
}
|
||||
}
|
||||
|
||||
// set the web context in the request for future use
|
||||
request.setAttribute("servletContext", httpRequest.getSession().getServletContext());
|
||||
request.setAttribute("delegator", delegator);
|
||||
|
||||
// set the webSiteId in the session
|
||||
if (UtilValidate.isEmpty(httpRequest.getSession().getAttribute("webSiteId"))){
|
||||
httpRequest.getSession().setAttribute("webSiteId", httpRequest.getSession().getServletContext().getAttribute("webSiteId"));
|
||||
}
|
||||
}
|
||||
|
||||
public static void setViewQueryParameters(ServletRequest request, StringBuilder urlBuilder) {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
if (UtilValidate.isEmpty(httpRequest.getServletPath())) {
|
||||
return;
|
||||
}
|
||||
String pathInfo = httpRequest.getServletPath();
|
||||
String viewIndex = null;
|
||||
String viewSize = null;
|
||||
String viewSort = null;
|
||||
String searchString = null;
|
||||
|
||||
int queryStringIndex = pathInfo.indexOf("?");
|
||||
if (queryStringIndex >= 0) {
|
||||
List<String> queryStringTokens = StringUtil.split(pathInfo.substring(queryStringIndex + 1), "&");
|
||||
for (String queryStringToken : queryStringTokens) {
|
||||
int equalIndex = queryStringToken.indexOf("=");
|
||||
String name = queryStringToken.substring(0, equalIndex - 1);
|
||||
String value = queryStringToken.substring(equalIndex + 1, queryStringToken.length() - 1);
|
||||
|
||||
if ("viewIndex".equals(name)) {
|
||||
viewIndex = value;
|
||||
} else if ("viewSize".equals(name)) {
|
||||
viewSize = value;
|
||||
} else if ("viewSort".equals(name)) {
|
||||
viewSort = value;
|
||||
} else if ("searchString".equals(name)) {
|
||||
searchString = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (UtilValidate.isNotEmpty(httpRequest.getParameter("viewIndex"))) {
|
||||
viewIndex = httpRequest.getParameter("viewIndex");
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(httpRequest.getParameter("viewSize"))) {
|
||||
viewSize = httpRequest.getParameter("viewSize");
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(httpRequest.getParameter("viewSort"))) {
|
||||
viewSort = httpRequest.getParameter("viewSort");
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(httpRequest.getParameter("searchString"))) {
|
||||
searchString = httpRequest.getParameter("searchString");
|
||||
}
|
||||
|
||||
//Set query string parameters to url
|
||||
if(UtilValidate.isNotEmpty(viewIndex)){
|
||||
urlBuilder.append("/~VIEW_INDEX=" + viewIndex);
|
||||
request.setAttribute("VIEW_INDEX", viewIndex);
|
||||
}
|
||||
if(UtilValidate.isNotEmpty(viewSize)){
|
||||
urlBuilder.append("/~VIEW_SIZE=" + viewSize);
|
||||
request.setAttribute("VIEW_SIZE", viewSize);
|
||||
}
|
||||
if(UtilValidate.isNotEmpty(viewSort)){
|
||||
urlBuilder.append("/~VIEW_SORT=" + viewSort);
|
||||
request.setAttribute("VIEW_SORT", viewSort);
|
||||
}
|
||||
if(UtilValidate.isNotEmpty(searchString)){
|
||||
urlBuilder.append("/~SEARCH_STRING=" + searchString);
|
||||
request.setAttribute("SEARCH_STRING", searchString);
|
||||
}
|
||||
}
|
||||
public static void checkPathAlias(ServletRequest request, ServletResponse response, Delegator delegator, String pathInfo) {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
HttpServletResponse httpResponse = (HttpServletResponse) response;
|
||||
String webSiteId = WebSiteWorker.getWebSiteId(request);
|
||||
// check path alias
|
||||
GenericValue pathAlias = null;
|
||||
try {
|
||||
pathAlias = EntityQuery.use(delegator)
|
||||
.from("WebSitePathAlias")
|
||||
.where("webSiteId", webSiteId, "pathAlias", pathInfo)
|
||||
.cache()
|
||||
.queryOne();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
if (pathAlias != null) {
|
||||
String alias = pathAlias.getString("aliasTo");
|
||||
String contentId = pathAlias.getString("contentId");
|
||||
if (contentId == null && UtilValidate.isNotEmpty(alias)) {
|
||||
if (!alias.startsWith("/")) {
|
||||
alias = "/" + alias;
|
||||
}
|
||||
|
||||
RequestDispatcher rd = request.getRequestDispatcher(alias);
|
||||
try {
|
||||
rd.forward(request, response);
|
||||
return;
|
||||
} catch (ServletException e) {
|
||||
Debug.logWarning(e, module);
|
||||
} catch (IOException e) {
|
||||
Debug.logWarning(e, module);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// send 404 error if a URI is alias TO
|
||||
try {
|
||||
List<GenericValue> aliasTos = EntityQuery.use(delegator)
|
||||
.from("WebSitePathAlias")
|
||||
.where("webSiteId", webSiteId, "aliasTo", httpRequest.getRequestURI())
|
||||
.queryList();
|
||||
if (UtilValidate.isNotEmpty(aliasTos)) {
|
||||
httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found");
|
||||
return;
|
||||
}
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static String invalidCharacter(String str) {
|
||||
str = str.replace("&", "-");
|
||||
str = str.replace("\"", "-");
|
||||
str = str.replace("×", "-");
|
||||
str = str.replace("÷", "-");
|
||||
str = str.replace(" ", "-");
|
||||
str = str.replace("!", "-");
|
||||
str = str.replace("#", "-");
|
||||
str = str.replace("$", "-");
|
||||
str = str.replace("%", "-");
|
||||
str = str.replace("'", "-");
|
||||
str = str.replace("(", "-");
|
||||
str = str.replace(")", "-");
|
||||
str = str.replace("*", "-");
|
||||
str = str.replace("+", "-");
|
||||
str = str.replace(",", "-");
|
||||
str = str.replace(".", "-");
|
||||
str = str.replace("/", "-");
|
||||
str = str.replace(":", "-");
|
||||
str = str.replace(";", "-");
|
||||
str = str.replace("<", "-");
|
||||
str = str.replace("=", "-");
|
||||
str = str.replace(">", "-");
|
||||
str = str.replace("?", "-");
|
||||
str = str.replace("@", "-");
|
||||
str = str.replace("[", "-");
|
||||
str = str.replace("\\", "-");
|
||||
str = str.replace("]", "-");
|
||||
str = str.replace("^", "-");
|
||||
str = str.replace("_", "-");
|
||||
str = str.replace("`", "-");
|
||||
str = str.replace("{", "-");
|
||||
str = str.replace("|", "-");
|
||||
str = str.replace("}", "-");
|
||||
str = str.replace("~", "-");
|
||||
str = str.replace("¢", "-");
|
||||
str = str.replace("£", "-");
|
||||
str = str.replace("¤", "-");
|
||||
str = str.replace("§", "-");
|
||||
str = str.replace("¨", "-");
|
||||
str = str.replace("¬", "-");
|
||||
str = str.replace("ˉ", "-");
|
||||
str = str.replace("°", "-");
|
||||
str = str.replace("±", "-");
|
||||
str = str.replace("μ", "-");
|
||||
str = str.replace("•", "-");
|
||||
str = str.replace("!", "-");
|
||||
str = str.replace("¥", "-");
|
||||
str = str.replace("……", "-");
|
||||
str = str.replace("(", "-");
|
||||
str = str.replace(")", "-");
|
||||
str = str.replace("——", "-");
|
||||
str = str.replace("【", "-");
|
||||
str = str.replace("】", "-");
|
||||
str = str.replace("{", "-");
|
||||
str = str.replace("}", "-");
|
||||
str = str.replace(":", "-");
|
||||
str = str.replace(";", "-");
|
||||
str = str.replace("“", "-");
|
||||
str = str.replace("、", "-");
|
||||
str = str.replace("《", "-");
|
||||
str = str.replace("》", "-");
|
||||
str = str.replace(",", "-");
|
||||
str = str.replace("。", "-");
|
||||
str = str.replace("‘", "-");
|
||||
str = str.replace("?", "-");
|
||||
str = str.replace("–", "");
|
||||
while(str.startsWith("-")){
|
||||
str = str.substring(1);
|
||||
}
|
||||
while(str.endsWith("-")){
|
||||
str = str.substring(0,str.length() - 1);
|
||||
}
|
||||
while(str.indexOf("--") != -1){
|
||||
str = str.replace("--","-");
|
||||
}
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.authentication;
|
||||
|
||||
import java.security.AccessController;
|
||||
import java.security.PrivilegedAction;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Iterator;
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.common.authentication.api.Authenticator;
|
||||
import org.ofbiz.common.authentication.api.AuthenticatorException;
|
||||
import org.ofbiz.service.LocalDispatcher;
|
||||
|
||||
/**
|
||||
* AuthHelper
|
||||
*/
|
||||
public final class AuthHelper {
|
||||
|
||||
private static final String module = AuthHelper.class.getName();
|
||||
private static List<Authenticator> authenticators = new ArrayList<Authenticator>();
|
||||
private static boolean authenticatorsLoaded = false;
|
||||
|
||||
private AuthHelper() {}
|
||||
|
||||
public static boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException {
|
||||
if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()");
|
||||
for (Authenticator auth : authenticators) {
|
||||
boolean pass = auth.authenticate(username, password, isServiceAuth);
|
||||
if (pass) {
|
||||
return true;
|
||||
} else if (auth.isSingleAuthenticator()) {
|
||||
throw new AuthenticatorException();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void logout(String username) throws AuthenticatorException {
|
||||
if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()");
|
||||
for (Authenticator auth : authenticators) {
|
||||
auth.logout(username);
|
||||
}
|
||||
}
|
||||
|
||||
public static void syncUser(String username) throws AuthenticatorException {
|
||||
if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()");
|
||||
for (Authenticator auth : authenticators) {
|
||||
if (auth.isUserSynchronized()) {
|
||||
auth.syncUser(username);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void updatePassword(String username, String password, String newPassword) throws AuthenticatorException {
|
||||
if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()");
|
||||
for (Authenticator auth : authenticators) {
|
||||
auth.updatePassword(username, password, newPassword);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean authenticatorsLoaded() {
|
||||
return authenticatorsLoaded;
|
||||
}
|
||||
|
||||
public static void loadAuthenticators(LocalDispatcher dispatcher) {
|
||||
if (!authenticatorsLoaded) {
|
||||
loadAuthenticators_internal(dispatcher);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized static void loadAuthenticators_internal(LocalDispatcher dispatcher) {
|
||||
if (!authenticatorsLoaded) {
|
||||
Iterator<Authenticator> it = ServiceLoader.load(Authenticator.class, getContextClassLoader()).iterator();
|
||||
while (it.hasNext()) {
|
||||
try {
|
||||
Authenticator auth = it.next();
|
||||
if (auth.isEnabled()) {
|
||||
auth.initialize(dispatcher);
|
||||
authenticators.add(auth);
|
||||
}
|
||||
} catch (ClassCastException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
|
||||
Collections.sort(authenticators, new AuthenticationComparator());
|
||||
authenticatorsLoaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* Do not move this into a shared global util class; doing so
|
||||
* would mean the method would have to be public, and then it
|
||||
* could be called by any other non-secure source.
|
||||
*/
|
||||
private static ClassLoader getContextClassLoader() {
|
||||
return AccessController.doPrivileged(
|
||||
new PrivilegedAction<ClassLoader>() {
|
||||
public ClassLoader run() {
|
||||
ClassLoader cl = null;
|
||||
try {
|
||||
cl = Thread.currentThread().getContextClassLoader();
|
||||
} catch (SecurityException e) {
|
||||
Debug.logError(e, e.getMessage(), module);
|
||||
}
|
||||
return cl;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.authentication;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
import org.ofbiz.common.authentication.api.Authenticator;
|
||||
|
||||
/**
|
||||
* AuthenticationComparator
|
||||
*
|
||||
* Used to sort Authenticators by weight
|
||||
*/
|
||||
public class AuthenticationComparator implements Comparator<Authenticator> {
|
||||
|
||||
/**
|
||||
* Compares its two arguments for order. Returns a negative integer,
|
||||
* zero, or a positive integer as the first argument is less than, equal
|
||||
* to, or greater than the second.<p>
|
||||
* <p/>
|
||||
* The implementor must ensure that <tt>sgn(compare(x, y)) ==
|
||||
* -sgn(compare(y, x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This
|
||||
* implies that <tt>compare(x, y)</tt> must throw an exception if and only
|
||||
* if <tt>compare(y, x)</tt> throws an exception.)<p>
|
||||
* <p/>
|
||||
* The implementor must also ensure that the relation is transitive:
|
||||
* <tt>((compare(x, y)>0) && (compare(y, z)>0))</tt> implies
|
||||
* <tt>compare(x, z)>0</tt>.<p>
|
||||
* <p/>
|
||||
* Finally, the implementer must ensure that <tt>compare(x, y)==0</tt>
|
||||
* implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all
|
||||
* <tt>z</tt>.<p>
|
||||
* <p/>
|
||||
* It is generally the case, but <i>not</i> strictly required that
|
||||
* <tt>(compare(x, y)==0) == (x.equals(y))</tt>. Generally speaking,
|
||||
* any comparator that violates this condition should clearly indicate
|
||||
* this fact. The recommended language is "Note: this comparator
|
||||
* imposes orderings that are inconsistent with equals."
|
||||
*
|
||||
* @param a1 the first object to be compared.
|
||||
* @param a2 the second object to be compared.
|
||||
* @return a negative integer, zero, or a positive integer as the
|
||||
* first argument is less than, equal to, or greater than the
|
||||
* second.
|
||||
* @throws ClassCastException if the arguments' types prevent them from
|
||||
* being compared by this Comparator.
|
||||
*/
|
||||
public int compare(Authenticator a1, Authenticator a2) {
|
||||
if (a1.getWeight() < a2.getWeight()) {
|
||||
return -1;
|
||||
} else if (a1.getWeight() > a2.getWeight()) {
|
||||
return 1;
|
||||
} else if (!a1.getClass().equals(a2.getClass())) {
|
||||
return -1;
|
||||
} else {
|
||||
return a1.getClass().getName().compareTo(a2.getClass().getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.authentication.api;
|
||||
|
||||
import org.ofbiz.service.LocalDispatcher;
|
||||
|
||||
/**
|
||||
* Authenticator
|
||||
*
|
||||
* Classes which implement this interface (directly) will be auto-discovered and loaded as Authenticators
|
||||
* as long as isEnabled() returns true. All implementations MUST be in the org.ofbiz top level package in
|
||||
* order to be discovered.
|
||||
*/
|
||||
public interface Authenticator {
|
||||
|
||||
/**
|
||||
* Method called when authenticator is first initialized (the delegator
|
||||
* object can be obtained from the LocalDispatcher)
|
||||
* @param dispatcher The LocalDispatcher to use for this Authenticator
|
||||
*/
|
||||
public void initialize(LocalDispatcher dispatcher);
|
||||
|
||||
/**
|
||||
* Method to authenticate a user
|
||||
* @param username User's username
|
||||
* @param password User's password
|
||||
* @param isServiceAuth true if authentication is for a service call
|
||||
* @return true if the user is authenticated
|
||||
* @throws AuthenticatorException when a fatal error occurs during authentication
|
||||
*/
|
||||
public boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException;
|
||||
|
||||
/**
|
||||
* Logs a user out
|
||||
* @param username User's username
|
||||
* @throws AuthenticatorException when logout fails
|
||||
*/
|
||||
public void logout(String username) throws AuthenticatorException;
|
||||
|
||||
/**
|
||||
* Reads user information and syncs it to OFBiz (i.e. UserLogin, Person, etc)
|
||||
* Note: when creating a UserLogin object, be sure to set 'externalAuthId'
|
||||
* @param username User's username
|
||||
* @throws AuthenticatorException user synchronization fails
|
||||
*/
|
||||
public void syncUser(String username) throws AuthenticatorException;
|
||||
|
||||
/**
|
||||
* Updates a user's password
|
||||
* @param username User's username
|
||||
* @param password User's current password
|
||||
* @param newPassword User's new password
|
||||
* @throws AuthenticatorException when update password fails
|
||||
*/
|
||||
public void updatePassword(String username, String password, String newPassword) throws AuthenticatorException;
|
||||
|
||||
/**
|
||||
* Weight of this authenticator (lower weights are run first)
|
||||
* @return the weight of this Authenticator
|
||||
*/
|
||||
public float getWeight();
|
||||
|
||||
/**
|
||||
* Is the user synchronized back to OFBiz
|
||||
* @return true if the user record is copied to the OFB database
|
||||
*/
|
||||
public boolean isUserSynchronized();
|
||||
|
||||
/**
|
||||
* Is this expected to be the only authenticator, if so errors will be thrown when users cannot be found
|
||||
* @return true if this is expected to be the only Authenticator
|
||||
*/
|
||||
public boolean isSingleAuthenticator();
|
||||
|
||||
/**
|
||||
* Flag to test if this Authenticator is enabled
|
||||
* @return true if the Authenticator is enabled
|
||||
*/
|
||||
public boolean isEnabled();
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.authentication.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.ofbiz.base.util.GeneralException;
|
||||
|
||||
/**
|
||||
* AuthenticatorException
|
||||
*/
|
||||
public class AuthenticatorException extends GeneralException {
|
||||
|
||||
private static final long serialVersionUID = 2836939874682240962L;
|
||||
|
||||
/**
|
||||
* Creates new <code>GeneralException</code> without detail message.
|
||||
*/
|
||||
public AuthenticatorException() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an <code>GeneralException</code> with the specified detail message.
|
||||
*
|
||||
* @param msg the detail message.
|
||||
*/
|
||||
public AuthenticatorException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an <code>GeneralException</code> with the specified detail message and nested Exception.
|
||||
*
|
||||
* @param msg the detail message.
|
||||
* @param nested the nested exception.
|
||||
*/
|
||||
public AuthenticatorException(String msg, Throwable nested) {
|
||||
super(msg, nested);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an <code>GeneralException</code> with the specified detail message and nested Exception.
|
||||
*
|
||||
* @param nested the nested exception.
|
||||
*/
|
||||
public AuthenticatorException(Throwable nested) {
|
||||
super(nested);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an <code>GeneralException</code> with the specified detail message, list and nested Exception.
|
||||
*
|
||||
* @param msg the detail message.
|
||||
* @param messages error message list.
|
||||
*/
|
||||
public AuthenticatorException(String msg, List<String> messages) {
|
||||
super(msg, messages);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an <code>GeneralException</code> with the specified detail message, list and nested Exception.
|
||||
*
|
||||
* @param msg the detail message.
|
||||
* @param messages error message list.
|
||||
* @param nested the nested exception
|
||||
*/
|
||||
public AuthenticatorException(String msg, List<String> messages, Throwable nested) {
|
||||
super(msg, messages, nested);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an <code>GeneralException</code> with the specified detail message list and nested Exception.
|
||||
*
|
||||
* @param messages error message list.
|
||||
* @param nested the nested exception.
|
||||
*/
|
||||
public AuthenticatorException(List<String> messages, Throwable nested) {
|
||||
super(messages, nested);
|
||||
}
|
||||
|
||||
public AuthenticatorException(List<String> messages) {
|
||||
super(messages);
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.authentication.example;
|
||||
|
||||
import org.ofbiz.common.authentication.api.Authenticator;
|
||||
import org.ofbiz.common.authentication.api.AuthenticatorException;
|
||||
import org.ofbiz.service.LocalDispatcher;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
|
||||
/**
|
||||
* LocalAuthenticator
|
||||
*/
|
||||
public class TestFailAuthenticator implements Authenticator {
|
||||
|
||||
private static final String module = TestFailAuthenticator.class.getName();
|
||||
protected Delegator delegator;
|
||||
protected LocalDispatcher dispatcher;
|
||||
protected float weight = 1;
|
||||
|
||||
/**
|
||||
* Method called when authenticator is first initialized (the delegator
|
||||
* object can be obtained from the LocalDispatcher)
|
||||
*
|
||||
* @param dispatcher The LocalDispatcher to use for this Authenticator
|
||||
*/
|
||||
public void initialize(LocalDispatcher dispatcher) {
|
||||
this.dispatcher = dispatcher;
|
||||
this.delegator = dispatcher.getDelegator();
|
||||
Debug.logInfo(this.getClass().getName() + " Authenticator initialized", module);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method to authenticate a user
|
||||
*
|
||||
* @param username User's username
|
||||
* @param password User's password
|
||||
* @param isServiceAuth true if authentication is for a service call
|
||||
* @return true if the user is authenticated
|
||||
* @throws org.ofbiz.common.authentication.api.AuthenticatorException
|
||||
* when a fatal error occurs during authentication
|
||||
*/
|
||||
public boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException {
|
||||
Debug.logInfo(this.getClass().getName() + " Authenticator authenticate() -- returning false", module);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a user out
|
||||
*
|
||||
* @param username User's username
|
||||
* @throws org.ofbiz.common.authentication.api.AuthenticatorException
|
||||
* when logout fails
|
||||
*/
|
||||
public void logout(String username) throws AuthenticatorException {
|
||||
Debug.logInfo(this.getClass().getName() + " Authenticator logout()", module);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads user information and syncs it to OFBiz (i.e. UserLogin, Person, etc)
|
||||
*
|
||||
* @param username User's username
|
||||
* @throws org.ofbiz.common.authentication.api.AuthenticatorException
|
||||
* user synchronization fails
|
||||
*/
|
||||
public void syncUser(String username) throws AuthenticatorException {
|
||||
Debug.logInfo(this.getClass().getName() + " Authenticator syncUser()", module);
|
||||
// no user info to sync
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a user's password
|
||||
*
|
||||
* @param username User's username
|
||||
* @param password User's current password
|
||||
* @param newPassword User's new password
|
||||
* @throws org.ofbiz.common.authentication.api.AuthenticatorException
|
||||
* when update password fails
|
||||
*/
|
||||
public void updatePassword(String username, String password, String newPassword) throws AuthenticatorException {
|
||||
Debug.logInfo(this.getClass().getName() + " Authenticator updatePassword()", module);
|
||||
}
|
||||
|
||||
/**
|
||||
* Weight of this authenticator (lower weights are run first)
|
||||
*
|
||||
* @return the weight of this Authenticator
|
||||
*/
|
||||
public float getWeight() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the user synchronized back to OFBiz
|
||||
*
|
||||
* @return true if the user record is copied to the OFB database
|
||||
*/
|
||||
public boolean isUserSynchronized() {
|
||||
Debug.logInfo(this.getClass().getName() + " Authenticator isUserSynchronized()", module);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this expected to be the only authenticator, if so errors will be thrown when users cannot be found
|
||||
*
|
||||
* @return true if this is expected to be the only Authenticator
|
||||
*/
|
||||
public boolean isSingleAuthenticator() {
|
||||
Debug.logInfo(this.getClass().getName() + " Authenticator isSingleAuthenticator()", module);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flag to test if this Authenticator is enabled
|
||||
*
|
||||
* @return true if the Authenticator is enabled
|
||||
*/
|
||||
public boolean isEnabled() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.authentication.example;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.common.authentication.api.AuthenticatorException;
|
||||
|
||||
/**
|
||||
* TestPassAuthenticator
|
||||
*/
|
||||
public class TestPassAuthenticator extends TestFailAuthenticator {
|
||||
|
||||
private static final String module = TestPassAuthenticator.class.getName();
|
||||
|
||||
/**
|
||||
* Method to authenticate a user
|
||||
*
|
||||
* @param username User's username
|
||||
* @param password User's password
|
||||
* @param isServiceAuth true if authentication is for a service call
|
||||
* @return true if the user is authenticated
|
||||
* @throws org.ofbiz.common.authentication.api.AuthenticatorException
|
||||
* when a fatal error occurs during authentication
|
||||
*/
|
||||
@Override
|
||||
public boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException {
|
||||
Debug.logInfo(this.getClass().getName() + " Authenticator authenticate() -- returning false", module);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flag to test if this Authenticator is enabled
|
||||
*
|
||||
* @return true if the Authenticator is enabled
|
||||
*/
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,742 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.email;
|
||||
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.security.Security;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.activation.DataHandler;
|
||||
import javax.activation.DataSource;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.SendFailedException;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.Transport;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeBodyPart;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import javax.mail.internet.MimeMultipart;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.transform.stream.StreamSource;
|
||||
|
||||
import org.apache.fop.apps.Fop;
|
||||
import org.apache.fop.apps.MimeConstants;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.GeneralException;
|
||||
import org.ofbiz.base.util.HttpClient;
|
||||
import org.ofbiz.base.util.HttpClientException;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.base.util.collections.MapStack;
|
||||
import org.ofbiz.base.util.string.FlexibleStringExpander;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.util.EntityUtilProperties;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.GenericServiceException;
|
||||
import org.ofbiz.service.LocalDispatcher;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
import org.ofbiz.service.mail.MimeMessageWrapper;
|
||||
import org.ofbiz.webapp.view.ApacheFopWorker;
|
||||
import org.ofbiz.widget.renderer.macro.MacroScreenRenderer;
|
||||
import org.ofbiz.widget.renderer.ScreenRenderer;
|
||||
import org.ofbiz.widget.renderer.ScreenStringRenderer;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import com.sun.mail.smtp.SMTPAddressFailedException;
|
||||
|
||||
import freemarker.template.TemplateException;
|
||||
|
||||
/**
|
||||
* Email Services
|
||||
*/
|
||||
public class EmailServices {
|
||||
|
||||
public final static String module = EmailServices.class.getName();
|
||||
|
||||
public static final String resource = "CommonUiLabels";
|
||||
|
||||
/**
|
||||
* Basic JavaMail Service
|
||||
*@param ctx The DispatchContext that this service is operating in
|
||||
*@param context Map containing the input parameters
|
||||
*@return Map with the result of the service, the output parameters
|
||||
*/
|
||||
public static Map<String, Object> sendMail(DispatchContext ctx, Map<String, ? extends Object> context) {
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
String communicationEventId = (String) context.get("communicationEventId");
|
||||
String orderId = (String) context.get("orderId");
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
if (communicationEventId != null) {
|
||||
Debug.logInfo("SendMail Running, for communicationEventId : " + communicationEventId, module);
|
||||
}
|
||||
Map<String, Object> results = ServiceUtil.returnSuccess();
|
||||
String subject = (String) context.get("subject");
|
||||
subject = FlexibleStringExpander.expandString(subject, context);
|
||||
|
||||
String partyId = (String) context.get("partyId");
|
||||
String body = (String) context.get("body");
|
||||
List<Map<String, Object>> bodyParts = UtilGenerics.checkList(context.get("bodyParts"));
|
||||
GenericValue userLogin = (GenericValue) context.get("userLogin");
|
||||
|
||||
results.put("communicationEventId", communicationEventId);
|
||||
results.put("partyId", partyId);
|
||||
results.put("subject", subject);
|
||||
|
||||
if (UtilValidate.isNotEmpty(orderId)) {
|
||||
results.put("orderId", orderId);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(body)) {
|
||||
body = FlexibleStringExpander.expandString(body, context);
|
||||
results.put("body", body);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(bodyParts)) {
|
||||
results.put("bodyParts", bodyParts);
|
||||
}
|
||||
results.put("userLogin", userLogin);
|
||||
|
||||
String sendTo = (String) context.get("sendTo");
|
||||
String sendCc = (String) context.get("sendCc");
|
||||
String sendBcc = (String) context.get("sendBcc");
|
||||
|
||||
// check to see if we should redirect all mail for testing
|
||||
String redirectAddress = EntityUtilProperties.getPropertyValue("general", "mail.notifications.redirectTo", delegator);
|
||||
if (UtilValidate.isNotEmpty(redirectAddress)) {
|
||||
String originalRecipients = " [To: " + sendTo + ", Cc: " + sendCc + ", Bcc: " + sendBcc + "]";
|
||||
subject += originalRecipients;
|
||||
sendTo = redirectAddress;
|
||||
sendCc = null;
|
||||
sendBcc = null;
|
||||
if (subject.length() > 255) {
|
||||
subject = subject.substring(0, 255);
|
||||
}
|
||||
}
|
||||
|
||||
String sendFrom = (String) context.get("sendFrom");
|
||||
String sendType = (String) context.get("sendType");
|
||||
String port = (String) context.get("port");
|
||||
String socketFactoryClass = (String) context.get("socketFactoryClass");
|
||||
String socketFactoryPort = (String) context.get("socketFactoryPort");
|
||||
String socketFactoryFallback = (String) context.get("socketFactoryFallback");
|
||||
String sendVia = (String) context.get("sendVia");
|
||||
String authUser = (String) context.get("authUser");
|
||||
String authPass = (String) context.get("authPass");
|
||||
String messageId = (String) context.get("messageId");
|
||||
String contentType = (String) context.get("contentType");
|
||||
Boolean sendPartial = (Boolean) context.get("sendPartial");
|
||||
Boolean isStartTLSEnabled = (Boolean) context.get("startTLSEnabled");
|
||||
|
||||
boolean useSmtpAuth = false;
|
||||
|
||||
// define some default
|
||||
if (sendType == null || sendType.equals("mail.smtp.host")) {
|
||||
sendType = "mail.smtp.host";
|
||||
if (UtilValidate.isEmpty(sendVia)) {
|
||||
sendVia = EntityUtilProperties.getPropertyValue("general", "mail.smtp.relay.host", "localhost", delegator);
|
||||
}
|
||||
if (UtilValidate.isEmpty(authUser)) {
|
||||
authUser = EntityUtilProperties.getPropertyValue("general", "mail.smtp.auth.user", delegator);
|
||||
}
|
||||
if (UtilValidate.isEmpty(authPass)) {
|
||||
authPass = EntityUtilProperties.getPropertyValue("general", "mail.smtp.auth.password", delegator);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(authUser)) {
|
||||
useSmtpAuth = true;
|
||||
}
|
||||
if (UtilValidate.isEmpty(port)) {
|
||||
port = EntityUtilProperties.getPropertyValue("general", "mail.smtp.port", delegator);
|
||||
}
|
||||
if (UtilValidate.isEmpty(socketFactoryPort)) {
|
||||
socketFactoryPort = EntityUtilProperties.getPropertyValue("general", "mail.smtp.socketFactory.port", delegator);
|
||||
}
|
||||
if (UtilValidate.isEmpty(socketFactoryClass)) {
|
||||
socketFactoryClass = EntityUtilProperties.getPropertyValue("general", "mail.smtp.socketFactory.class", delegator);
|
||||
}
|
||||
if (UtilValidate.isEmpty(socketFactoryFallback)) {
|
||||
socketFactoryFallback = EntityUtilProperties.getPropertyValue("general", "mail.smtp.socketFactory.fallback", "false", delegator);
|
||||
}
|
||||
if (sendPartial == null) {
|
||||
sendPartial = EntityUtilProperties.propertyValueEqualsIgnoreCase("general", "mail.smtp.sendpartial", "true", delegator) ? true : false;
|
||||
}
|
||||
if (isStartTLSEnabled == null) {
|
||||
isStartTLSEnabled = EntityUtilProperties.propertyValueEqualsIgnoreCase("general", "mail.smtp.starttls.enable", "true", delegator);
|
||||
}
|
||||
} else if (sendVia == null) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendMissingParameterSendVia", locale));
|
||||
}
|
||||
|
||||
if (contentType == null) {
|
||||
contentType = "text/html";
|
||||
}
|
||||
|
||||
if (UtilValidate.isNotEmpty(bodyParts)) {
|
||||
contentType = "multipart/mixed";
|
||||
}
|
||||
results.put("contentType", contentType);
|
||||
|
||||
Session session;
|
||||
MimeMessage mail;
|
||||
try {
|
||||
Properties props = System.getProperties();
|
||||
props.put(sendType, sendVia);
|
||||
if (UtilValidate.isNotEmpty(port)) {
|
||||
props.put("mail.smtp.port", port);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(socketFactoryPort)) {
|
||||
props.put("mail.smtp.socketFactory.port", socketFactoryPort);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(socketFactoryClass)) {
|
||||
props.put("mail.smtp.socketFactory.class", socketFactoryClass);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(socketFactoryFallback)) {
|
||||
props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);
|
||||
}
|
||||
if (useSmtpAuth) {
|
||||
props.put("mail.smtp.auth", "true");
|
||||
}
|
||||
if (sendPartial != null) {
|
||||
props.put("mail.smtp.sendpartial", sendPartial ? "true" : "false");
|
||||
}
|
||||
if (isStartTLSEnabled) {
|
||||
props.put("mail.smtp.starttls.enable", "true");
|
||||
}
|
||||
|
||||
session = Session.getInstance(props);
|
||||
boolean debug = EntityUtilProperties.propertyValueEqualsIgnoreCase("general", "mail.debug.on", "Y", delegator);
|
||||
session.setDebug(debug);
|
||||
|
||||
mail = new MimeMessage(session);
|
||||
if (messageId != null) {
|
||||
mail.setHeader("In-Reply-To", messageId);
|
||||
mail.setHeader("References", messageId);
|
||||
}
|
||||
mail.setFrom(new InternetAddress(sendFrom));
|
||||
mail.setSubject(subject, "UTF-8");
|
||||
mail.setHeader("X-Mailer", "Apache OFBiz, The Open For Business Project");
|
||||
mail.setSentDate(new Date());
|
||||
mail.addRecipients(Message.RecipientType.TO, sendTo);
|
||||
|
||||
if (UtilValidate.isNotEmpty(sendCc)) {
|
||||
mail.addRecipients(Message.RecipientType.CC, sendCc);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(sendBcc)) {
|
||||
mail.addRecipients(Message.RecipientType.BCC, sendBcc);
|
||||
}
|
||||
|
||||
if (UtilValidate.isNotEmpty(bodyParts)) {
|
||||
// check for multipart message (with attachments)
|
||||
// BodyParts contain a list of Maps items containing content(String) and type(String) of the attachement
|
||||
MimeMultipart mp = new MimeMultipart();
|
||||
Debug.logInfo(bodyParts.size() + " multiparts found",module);
|
||||
for (Map<String, Object> bodyPart: bodyParts) {
|
||||
Object bodyPartContent = bodyPart.get("content");
|
||||
MimeBodyPart mbp = new MimeBodyPart();
|
||||
|
||||
if (bodyPartContent instanceof String) {
|
||||
Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + bodyPart.get("content").toString().length() , module);
|
||||
mbp.setText((String) bodyPartContent, "UTF-8", ((String) bodyPart.get("type")).substring(5));
|
||||
} else if (bodyPartContent instanceof byte[]) {
|
||||
ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) bodyPartContent, (String) bodyPart.get("type"));
|
||||
Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + ((byte[]) bodyPartContent).length , module);
|
||||
mbp.setDataHandler(new DataHandler(bads));
|
||||
} else if (bodyPartContent instanceof DataHandler) {
|
||||
mbp.setDataHandler((DataHandler) bodyPartContent);
|
||||
} else {
|
||||
mbp.setDataHandler(new DataHandler(bodyPartContent, (String) bodyPart.get("type")));
|
||||
}
|
||||
|
||||
String fileName = (String) bodyPart.get("filename");
|
||||
if (fileName != null) {
|
||||
mbp.setFileName(fileName);
|
||||
}
|
||||
mp.addBodyPart(mbp);
|
||||
}
|
||||
mail.setContent(mp);
|
||||
mail.saveChanges();
|
||||
} else {
|
||||
// create the singelpart message
|
||||
if (contentType.startsWith("text")) {
|
||||
mail.setText(body, "UTF-8", contentType.substring(5));
|
||||
} else {
|
||||
mail.setContent(body, contentType);
|
||||
}
|
||||
mail.saveChanges();
|
||||
}
|
||||
} catch (MessagingException e) {
|
||||
Debug.logError(e, "MessagingException when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module);
|
||||
Debug.logError("Email message that could not be created to [" + sendTo + "] had context: " + context, module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendMessagingException", UtilMisc.toMap("sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale));
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, "IOExcepton when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module);
|
||||
Debug.logError("Email message that could not be created to [" + sendTo + "] had context: " + context, module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendIOException", UtilMisc.toMap("sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale));
|
||||
}
|
||||
|
||||
// check to see if sending mail is enabled
|
||||
String mailEnabled = EntityUtilProperties.getPropertyValue("general", "mail.notifications.enabled", "N", delegator);
|
||||
if (!"Y".equalsIgnoreCase(mailEnabled)) {
|
||||
// no error; just return as if we already processed
|
||||
Debug.logImportant("Mail notifications disabled in general.properties; mail with subject [" + subject + "] not sent to addressee [" + sendTo + "]", module);
|
||||
Debug.logVerbose("What would have been sent, the addressee: " + sendTo + " subject: " + subject + " context: " + context, module);
|
||||
results.put("messageWrapper", new MimeMessageWrapper(session, mail));
|
||||
return results;
|
||||
}
|
||||
|
||||
Transport trans = null;
|
||||
try {
|
||||
trans = session.getTransport("smtp");
|
||||
if (!useSmtpAuth) {
|
||||
trans.connect();
|
||||
} else {
|
||||
trans.connect(sendVia, authUser, authPass);
|
||||
}
|
||||
trans.sendMessage(mail, mail.getAllRecipients());
|
||||
results.put("messageWrapper", new MimeMessageWrapper(session, mail));
|
||||
results.put("messageId", mail.getMessageID());
|
||||
trans.close();
|
||||
} catch (SendFailedException e) {
|
||||
// message code prefix may be used by calling services to determine the cause of the failure
|
||||
Debug.logError(e, "[ADDRERR] Address error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module);
|
||||
List<SMTPAddressFailedException> failedAddresses = new LinkedList<SMTPAddressFailedException>();
|
||||
Exception nestedException = null;
|
||||
while ((nestedException = e.getNextException()) != null && nestedException instanceof MessagingException) {
|
||||
if (nestedException instanceof SMTPAddressFailedException) {
|
||||
SMTPAddressFailedException safe = (SMTPAddressFailedException) nestedException;
|
||||
Debug.logError("Failed to send message to [" + safe.getAddress() + "], return code [" + safe.getReturnCode() + "], return message [" + safe.getMessage() + "]", module);
|
||||
failedAddresses.add(safe);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Boolean sendFailureNotification = (Boolean) context.get("sendFailureNotification");
|
||||
if (sendFailureNotification == null || sendFailureNotification) {
|
||||
sendFailureNotification(ctx, context, mail, failedAddresses);
|
||||
results.put("messageWrapper", new MimeMessageWrapper(session, mail));
|
||||
try {
|
||||
results.put("messageId", mail.getMessageID());
|
||||
trans.close();
|
||||
} catch (MessagingException e1) {
|
||||
Debug.logError(e1, module);
|
||||
}
|
||||
} else {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendAddressError", UtilMisc.toMap("sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale));
|
||||
}
|
||||
} catch (MessagingException e) {
|
||||
// message code prefix may be used by calling services to determine the cause of the failure
|
||||
Debug.logError(e, "[CON] Connection error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module);
|
||||
Debug.logError("Email message that could not be sent to [" + sendTo + "] had context: " + context, module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendConnectionError", UtilMisc.toMap("sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* JavaMail Service that gets body content from a URL
|
||||
*@param ctx The DispatchContext that this service is operating in
|
||||
*@param rcontext Map containing the input parameters
|
||||
*@return Map with the result of the service, the output parameters
|
||||
*/
|
||||
public static Map<String, Object> sendMailFromUrl(DispatchContext ctx, Map<String, ? extends Object> rcontext) {
|
||||
// pretty simple, get the content and then call the sendMail method below
|
||||
Map<String, Object> sendMailContext = UtilMisc.makeMapWritable(rcontext);
|
||||
String bodyUrl = (String) sendMailContext.remove("bodyUrl");
|
||||
Map<String, Object> bodyUrlParameters = UtilGenerics.checkMap(sendMailContext.remove("bodyUrlParameters"));
|
||||
Locale locale = (Locale) rcontext.get("locale");
|
||||
LocalDispatcher dispatcher = ctx.getDispatcher();
|
||||
|
||||
URL url = null;
|
||||
|
||||
try {
|
||||
url = new URL(bodyUrl);
|
||||
} catch (MalformedURLException e) {
|
||||
Debug.logWarning(e, module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendMalformedUrl", UtilMisc.toMap("bodyUrl", bodyUrl, "errorString", e.toString()), locale));
|
||||
}
|
||||
|
||||
HttpClient httpClient = new HttpClient(url, bodyUrlParameters);
|
||||
String body = null;
|
||||
|
||||
try {
|
||||
body = httpClient.post();
|
||||
} catch (HttpClientException e) {
|
||||
Debug.logWarning(e, module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendGettingError", UtilMisc.toMap("errorString", e.toString()), locale));
|
||||
}
|
||||
|
||||
sendMailContext.put("body", body);
|
||||
Map<String, Object> sendMailResult;
|
||||
try {
|
||||
sendMailResult = dispatcher.runSync("sendMail", sendMailContext);
|
||||
} catch (GenericServiceException e) {
|
||||
Debug.logError(e, module);
|
||||
return ServiceUtil.returnError(e.getMessage());
|
||||
}
|
||||
|
||||
// just return the same result; it contains all necessary information
|
||||
return sendMailResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* JavaMail Service that gets body content from a Screen Widget
|
||||
* defined in the product store record and if available as attachment also.
|
||||
*@param dctx The DispatchContext that this service is operating in
|
||||
*@param rServiceContext Map containing the input parameters
|
||||
*@return Map with the result of the service, the output parameters
|
||||
*/
|
||||
public static Map<String, Object> sendMailFromScreen(DispatchContext dctx, Map<String, ? extends Object> rServiceContext) {
|
||||
Map<String, Object> serviceContext = UtilMisc.makeMapWritable(rServiceContext);
|
||||
LocalDispatcher dispatcher = dctx.getDispatcher();
|
||||
String webSiteId = (String) serviceContext.remove("webSiteId");
|
||||
String bodyText = (String) serviceContext.remove("bodyText");
|
||||
String bodyScreenUri = (String) serviceContext.remove("bodyScreenUri");
|
||||
String xslfoAttachScreenLocationParam = (String) serviceContext.remove("xslfoAttachScreenLocation");
|
||||
String attachmentNameParam = (String) serviceContext.remove("attachmentName");
|
||||
List<String> xslfoAttachScreenLocationListParam = UtilGenerics.checkList(serviceContext.remove("xslfoAttachScreenLocationList"));
|
||||
List<String> attachmentNameListParam = UtilGenerics.checkList(serviceContext.remove("attachmentNameList"));
|
||||
|
||||
List<String> xslfoAttachScreenLocationList = new LinkedList<String>();
|
||||
List<String> attachmentNameList = new LinkedList<String>();
|
||||
if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationParam)) xslfoAttachScreenLocationList.add(xslfoAttachScreenLocationParam);
|
||||
if (UtilValidate.isNotEmpty(attachmentNameParam)) attachmentNameList.add(attachmentNameParam);
|
||||
if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationListParam)) xslfoAttachScreenLocationList.addAll(xslfoAttachScreenLocationListParam);
|
||||
if (UtilValidate.isNotEmpty(attachmentNameListParam)) attachmentNameList.addAll(attachmentNameListParam);
|
||||
|
||||
Locale locale = (Locale) serviceContext.get("locale");
|
||||
Map<String, Object> bodyParameters = UtilGenerics.checkMap(serviceContext.remove("bodyParameters"));
|
||||
if (bodyParameters == null) {
|
||||
bodyParameters = MapStack.create();
|
||||
}
|
||||
if (!bodyParameters.containsKey("locale")) {
|
||||
bodyParameters.put("locale", locale);
|
||||
} else {
|
||||
locale = (Locale) bodyParameters.get("locale");
|
||||
}
|
||||
String partyId = (String) serviceContext.get("partyId");
|
||||
if (partyId == null) {
|
||||
partyId = (String) bodyParameters.get("partyId");
|
||||
}
|
||||
String orderId = (String) bodyParameters.get("orderId");
|
||||
String custRequestId = (String) bodyParameters.get("custRequestId");
|
||||
|
||||
bodyParameters.put("communicationEventId", serviceContext.get("communicationEventId"));
|
||||
NotificationServices.setBaseUrl(dctx.getDelegator(), webSiteId, bodyParameters);
|
||||
String contentType = (String) serviceContext.remove("contentType");
|
||||
|
||||
StringWriter bodyWriter = new StringWriter();
|
||||
|
||||
MapStack<String> screenContext = MapStack.create();
|
||||
screenContext.put("locale", locale);
|
||||
|
||||
ScreenStringRenderer screenStringRenderer = null;
|
||||
try {
|
||||
screenStringRenderer = new MacroScreenRenderer(EntityUtilProperties.getPropertyValue("widget", "screen.name", dctx.getDelegator()),
|
||||
EntityUtilProperties.getPropertyValue("widget", "screen.screenrenderer", dctx.getDelegator()));
|
||||
} catch (TemplateException e) {
|
||||
Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale));
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale));
|
||||
}
|
||||
ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, screenStringRenderer);
|
||||
screens.populateContextForService(dctx, bodyParameters);
|
||||
screenContext.putAll(bodyParameters);
|
||||
|
||||
if (bodyScreenUri != null) {
|
||||
try {
|
||||
screens.render(bodyScreenUri);
|
||||
} catch (GeneralException e) {
|
||||
Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale));
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale));
|
||||
} catch (SAXException e) {
|
||||
Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale));
|
||||
} catch (ParserConfigurationException e) {
|
||||
Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale));
|
||||
}
|
||||
}
|
||||
|
||||
boolean isMultiPart = false;
|
||||
|
||||
// check if attachment screen location passed in
|
||||
if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationList)) {
|
||||
List<Map<String, ? extends Object>> bodyParts = new LinkedList<Map<String, ? extends Object>>();
|
||||
if (bodyText != null) {
|
||||
bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
|
||||
bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyText, "type", "text/html"));
|
||||
} else {
|
||||
bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyWriter.toString(), "type", "text/html"));
|
||||
}
|
||||
|
||||
for (int i = 0; i < xslfoAttachScreenLocationList.size(); i++) {
|
||||
String xslfoAttachScreenLocation = xslfoAttachScreenLocationList.get(i);
|
||||
String attachmentName = "Details.pdf";
|
||||
if (UtilValidate.isNotEmpty(attachmentNameList) && attachmentNameList.size() >= i) {
|
||||
attachmentName = attachmentNameList.get(i);
|
||||
}
|
||||
isMultiPart = true;
|
||||
// start processing fo pdf attachment
|
||||
try {
|
||||
Writer writer = new StringWriter();
|
||||
MapStack<String> screenContextAtt = MapStack.create();
|
||||
// substitute the freemarker variables...
|
||||
ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(EntityUtilProperties.getPropertyValue("widget", "screenfop.name", dctx.getDelegator()),
|
||||
EntityUtilProperties.getPropertyValue("widget", "screenfop.screenrenderer", dctx.getDelegator()));
|
||||
ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContext, foScreenStringRenderer);
|
||||
screensAtt.populateContextForService(dctx, bodyParameters);
|
||||
screenContextAtt.putAll(bodyParameters);
|
||||
screensAtt.render(xslfoAttachScreenLocation);
|
||||
|
||||
/*
|
||||
try { // save generated fo file for debugging
|
||||
String buf = writer.toString();
|
||||
java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("/tmp/file1.xml"));
|
||||
fw.write(buf.toString());
|
||||
fw.close();
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, "Couldn't save xsl-fo xml debug file: " + e.toString(), module);
|
||||
}
|
||||
*/
|
||||
|
||||
// create the input stream for the generation
|
||||
StreamSource src = new StreamSource(new StringReader(writer.toString()));
|
||||
|
||||
// create the output stream for the generation
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
|
||||
Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
|
||||
ApacheFopWorker.transform(src, null, fop);
|
||||
|
||||
// and generate the PDF
|
||||
baos.flush();
|
||||
baos.close();
|
||||
|
||||
// store in the list of maps for sendmail....
|
||||
bodyParts.add(UtilMisc.<String, Object> toMap("content", baos.toByteArray(), "type", "application/pdf", "filename",
|
||||
attachmentName));
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, "Error rendering PDF attachment for email: " + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenPdfError",
|
||||
UtilMisc.toMap("errorString", e.toString()), locale));
|
||||
}
|
||||
|
||||
serviceContext.put("bodyParts", bodyParts);
|
||||
}
|
||||
} else {
|
||||
isMultiPart = false;
|
||||
// store body and type for single part message in the context.
|
||||
if (bodyText != null) {
|
||||
bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
|
||||
serviceContext.put("body", bodyText);
|
||||
} else {
|
||||
serviceContext.put("body", bodyWriter.toString());
|
||||
}
|
||||
|
||||
// Only override the default contentType in case of plaintext, since other contentTypes may be multipart
|
||||
// and would require specific handling.
|
||||
if (contentType != null && contentType.equalsIgnoreCase("text/plain")) {
|
||||
serviceContext.put("contentType", "text/plain");
|
||||
} else {
|
||||
serviceContext.put("contentType", "text/html");
|
||||
}
|
||||
}
|
||||
|
||||
// also expand the subject at this point, just in case it has the FlexibleStringExpander syntax in it...
|
||||
String subject = (String) serviceContext.remove("subject");
|
||||
subject = FlexibleStringExpander.expandString(subject, screenContext, locale);
|
||||
Debug.logInfo("Expanded email subject to: " + subject, module);
|
||||
serviceContext.put("subject", subject);
|
||||
serviceContext.put("partyId", partyId);
|
||||
if (UtilValidate.isNotEmpty(orderId)) {
|
||||
serviceContext.put("orderId", orderId);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(custRequestId)) {
|
||||
serviceContext.put("custRequestId", custRequestId);
|
||||
}
|
||||
|
||||
if (Debug.verboseOn()) Debug.logVerbose("sendMailFromScreen sendMail context: " + serviceContext, module);
|
||||
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
Map<String, Object> sendMailResult;
|
||||
Boolean hideInLog = (Boolean) serviceContext.get("hideInLog");
|
||||
hideInLog = hideInLog == null ? false : hideInLog;
|
||||
try {
|
||||
if (!hideInLog) {
|
||||
if (isMultiPart) {
|
||||
sendMailResult = dispatcher.runSync("sendMailMultiPart", serviceContext);
|
||||
} else {
|
||||
sendMailResult = dispatcher.runSync("sendMail", serviceContext);
|
||||
}
|
||||
} else {
|
||||
if (isMultiPart) {
|
||||
sendMailResult = dispatcher.runSync("sendMailMultiPartHiddenInLog", serviceContext);
|
||||
} else {
|
||||
sendMailResult = dispatcher.runSync("sendMailHiddenInLog", serviceContext);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, "Error send email:" + e.toString(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendError", UtilMisc.toMap("errorString", e.toString()), locale));
|
||||
}
|
||||
if (ServiceUtil.isError(sendMailResult)) {
|
||||
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(sendMailResult));
|
||||
}
|
||||
|
||||
result.put("messageWrapper", sendMailResult.get("messageWrapper"));
|
||||
result.put("body", bodyWriter.toString());
|
||||
result.put("subject", subject);
|
||||
result.put("communicationEventId", sendMailResult.get("communicationEventId"));
|
||||
if (UtilValidate.isNotEmpty(orderId)) {
|
||||
result.put("orderId", orderId);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(custRequestId)) {
|
||||
result.put("custRequestId", custRequestId);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* JavaMail Service same than sendMailFromScreen but with hidden result in log.
|
||||
* To prevent having not encoded passwords shown in log
|
||||
*@param dctx The DispatchContext that this service is operating in
|
||||
*@param rServiceContext Map containing the input parameters
|
||||
*@return Map with the result of the service, the output parameters
|
||||
*/
|
||||
public static Map<String, Object> sendMailHiddenInLogFromScreen(DispatchContext dctx, Map<String, ? extends Object> rServiceContext) {
|
||||
Map<String, Object> serviceContext = UtilMisc.makeMapWritable(rServiceContext);
|
||||
serviceContext.put("hideInLog", true);
|
||||
return sendMailFromScreen(dctx, serviceContext);
|
||||
}
|
||||
|
||||
public static void sendFailureNotification(DispatchContext dctx, Map<String, ? extends Object> context, MimeMessage message, List<SMTPAddressFailedException> failures) {
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
Map<String, Object> newContext = new LinkedHashMap<String, Object>();
|
||||
newContext.put("userLogin", context.get("userLogin"));
|
||||
newContext.put("sendFailureNotification", false);
|
||||
newContext.put("sendFrom", context.get("sendFrom"));
|
||||
newContext.put("sendTo", context.get("sendFrom"));
|
||||
newContext.put("subject", UtilProperties.getMessage(resource, "CommonEmailSendUndeliveredMail", locale));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(UtilProperties.getMessage(resource, "CommonEmailDeliveryFailed", locale));
|
||||
sb.append("/n/n");
|
||||
for (SMTPAddressFailedException failure : failures) {
|
||||
sb.append(failure.getAddress());
|
||||
sb.append(": ");
|
||||
sb.append(failure.getMessage());
|
||||
sb.append("/n/n");
|
||||
}
|
||||
sb.append(UtilProperties.getMessage(resource, "CommonEmailDeliveryOriginalMessage", locale));
|
||||
sb.append("/n/n");
|
||||
List<Map<String, Object>> bodyParts = new LinkedList<Map<String, Object>>();
|
||||
bodyParts.add(UtilMisc.<String, Object>toMap("content", sb.toString(), "type", "text/plain"));
|
||||
Map<String, Object> bodyPart = new LinkedHashMap<String, Object>();
|
||||
bodyPart.put("content", sb.toString());
|
||||
bodyPart.put("type", "text/plain");
|
||||
try {
|
||||
bodyParts.add(UtilMisc.<String, Object>toMap("content", message.getDataHandler()));
|
||||
} catch (MessagingException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
newContext.put("bodyParts", bodyParts);
|
||||
try {
|
||||
dctx.getDispatcher().runSync("sendMailMultiPart", newContext);
|
||||
} catch (GenericServiceException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
|
||||
/** class to create a file in memory required for sending as an attachment */
|
||||
public static class StringDataSource implements DataSource {
|
||||
private String contentType;
|
||||
private ByteArrayOutputStream contentArray;
|
||||
|
||||
public StringDataSource(String content, String contentType) throws IOException {
|
||||
this.contentType = contentType;
|
||||
contentArray = new ByteArrayOutputStream();
|
||||
contentArray.write(content.getBytes("iso-8859-1"));
|
||||
contentArray.flush();
|
||||
contentArray.close();
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return contentType == null ? "application/octet-stream" : contentType;
|
||||
}
|
||||
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(contentArray.toByteArray());
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "stringDatasource";
|
||||
}
|
||||
|
||||
public OutputStream getOutputStream() throws IOException {
|
||||
throw new IOException("Cannot write to this read-only resource");
|
||||
}
|
||||
}
|
||||
|
||||
/** class to create a file in memory required for sending as an attachment */
|
||||
public static class ByteArrayDataSource implements DataSource {
|
||||
private String contentType;
|
||||
private byte[] contentArray;
|
||||
|
||||
public ByteArrayDataSource(byte[] content, String contentType) throws IOException {
|
||||
this.contentType = contentType;
|
||||
this.contentArray = content;
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return contentType == null ? "application/octet-stream" : contentType;
|
||||
}
|
||||
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(contentArray);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "ByteArrayDataSource";
|
||||
}
|
||||
|
||||
public OutputStream getOutputStream() throws IOException {
|
||||
throw new IOException("Cannot write to this read-only resource");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.email;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.net.URL;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.component.ComponentConfig.WebappInfo;
|
||||
import org.ofbiz.base.location.FlexibleLocation;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.template.FreeMarkerWorker;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.GenericServiceException;
|
||||
import org.ofbiz.service.LocalDispatcher;
|
||||
import org.ofbiz.service.ModelService;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
import org.ofbiz.webapp.OfbizUrlBuilder;
|
||||
import org.ofbiz.webapp.WebAppUtil;
|
||||
|
||||
import freemarker.template.TemplateException;
|
||||
|
||||
/**
|
||||
* Provides generic services related to preparing and
|
||||
* delivering notifications via email.
|
||||
* <p>
|
||||
* To use the NotificationService, a message specific service should be
|
||||
* defined for a particular <a href="http://freemarker.sourceforge.net/docs/dgui_quickstart_template.html">
|
||||
* Freemarker Template</a> mapping the required fields of the
|
||||
* template to the required attributes of the service.
|
||||
* <p>
|
||||
* This service definition should extend the <code>sendNotificationInterface<code>
|
||||
* or the <code>prepareNotificationInterface</code> service interface
|
||||
* and simply invoke the associated method defined in this class.
|
||||
* <p>
|
||||
* <blockquote>
|
||||
* <pre>
|
||||
* <service name="sendPoPickupNotification" engine="java"
|
||||
* location="org.ofbiz.content.email.NotificationServices" invoke="sendNotification">
|
||||
* <description>Sends notification based on a message template</description>
|
||||
* <implements service="sendNotificationInterface"/>
|
||||
* <attribute name="orderId" type="String" mode="IN" optional="false"/>
|
||||
* </service>
|
||||
* </pre>
|
||||
* </blockquote>
|
||||
* <p>
|
||||
* An optional parameter available to all message templates is <code>baseUrl</code>
|
||||
* which can either be specified when the service is invoked or let the
|
||||
* <code>NotificationService</code> attempt to resolve it as best it can,
|
||||
* see {@link #setBaseUrl(Delegator, String, Map) setBaseUrl(Map)} for details on how this is achieved.
|
||||
* <p>
|
||||
* The following example shows what a simple notification message template,
|
||||
* associated with the above service, might contain:
|
||||
* <blockquote>
|
||||
* <pre>
|
||||
* Please use the following link to schedule a delivery date:
|
||||
* <p>
|
||||
* ${baseUrl}/ordermgr/control/schedulepo?orderId=${orderId}"
|
||||
* </pre>
|
||||
* </blockquote>
|
||||
* <p>
|
||||
* The template file must be found on the classpath at runtime and
|
||||
* match the "templateName" field passed to the service when it
|
||||
* is invoked.
|
||||
* <p>
|
||||
* For complex messages with a large number of dynamic fields, it may be wise
|
||||
* to implement a custom service that takes one or two parameters that can
|
||||
* be used to resolve the rest of the required fields and then pass them to
|
||||
* the {@link #prepareNotification(DispatchContext, Map) prepareNotification(DispatchContext, Map)}
|
||||
* or {@link #sendNotification(DispatchContext, Map) sendNotification(DispatchContext, Map)}
|
||||
* methods directly to generate or generate and send the notification respectively.
|
||||
*
|
||||
*/
|
||||
public class NotificationServices {
|
||||
|
||||
public static final String module = NotificationServices.class.getName();
|
||||
public static final String resource = "CommonUiLabels";
|
||||
|
||||
/**
|
||||
* This will use the {@link #prepareNotification(DispatchContext, Map) prepareNotification(DispatchContext, Map)}
|
||||
* method to generate the body of the notification message to send
|
||||
* and then deliver it via the "sendMail" service.
|
||||
* <p>
|
||||
* If the "body" parameter is already specified, the message body generation
|
||||
* phase will be skipped and the notification will be sent with the
|
||||
* specified body instead. This can be used to combine both service
|
||||
* calls in a decoupled manner if other steps are required between
|
||||
* generating the message body and sending the notification.
|
||||
*
|
||||
* @param ctx The dispatching context of the service
|
||||
* @param context The map containing all the fields associated with
|
||||
* the sevice
|
||||
* @return A Map with the service response messages in it
|
||||
*/
|
||||
public static Map<String, Object> sendNotification(DispatchContext ctx, Map<String, ? extends Object> context) {
|
||||
LocalDispatcher dispatcher = ctx.getDispatcher();
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
Map<String, Object> result = null;
|
||||
|
||||
try {
|
||||
// see whether the optional 'body' attribute was specified or needs to be processed
|
||||
// nulls are handled the same as not specified
|
||||
String body = (String) context.get("body");
|
||||
|
||||
if (body == null) {
|
||||
// prepare the body of the notification email
|
||||
Map<String, Object> bodyResult = prepareNotification(ctx, context);
|
||||
|
||||
// ensure the body was generated successfully
|
||||
if (bodyResult.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)) {
|
||||
body = (String) bodyResult.get("body");
|
||||
} else {
|
||||
// otherwise just report the error
|
||||
Debug.logError("prepareNotification failed: " + bodyResult.get(ModelService.ERROR_MESSAGE), module);
|
||||
body = null;
|
||||
}
|
||||
}
|
||||
|
||||
// make sure we have a valid body before sending
|
||||
if (body != null) {
|
||||
// retain only the required attributes for the sendMail service
|
||||
Map<String, Object> emailContext = new LinkedHashMap<String, Object>();
|
||||
emailContext.put("sendTo", context.get("sendTo"));
|
||||
emailContext.put("body", body);
|
||||
emailContext.put("sendCc", context.get("sendCc"));
|
||||
emailContext.put("sendBcc", context.get("sendBcc"));
|
||||
emailContext.put("sendFrom", context.get("sendFrom"));
|
||||
emailContext.put("subject", context.get("subject"));
|
||||
emailContext.put("sendVia", context.get("sendVia"));
|
||||
emailContext.put("sendType", context.get("sendType"));
|
||||
emailContext.put("contentType", context.get("contentType"));
|
||||
|
||||
// pass on to the sendMail service
|
||||
result = dispatcher.runSync("sendMail", emailContext);
|
||||
} else {
|
||||
Debug.logError("Invalid email body; null is not allowed", module);
|
||||
result = ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailInvalidBody", locale));
|
||||
}
|
||||
} catch (GenericServiceException serviceException) {
|
||||
Debug.logError(serviceException, "Error sending email", module);
|
||||
result = ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailDeliveryError", locale));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* This will process the associated notification template definition
|
||||
* with all the fields contained in the given context and generate
|
||||
* the message body of the notification.
|
||||
* <p>
|
||||
* The result returned will contain the appropriate response
|
||||
* messages indicating success or failure and the OUT parameter,
|
||||
* "body" containing the generated message.
|
||||
*
|
||||
* @param ctx The dispatching context of the service
|
||||
* @param context The map containing all the fields associated with
|
||||
* the sevice
|
||||
* @return A new Map indicating success or error containing the
|
||||
* body generated from the template and the input parameters.
|
||||
*/
|
||||
public static Map<String, Object> prepareNotification(DispatchContext ctx, Map<String, ? extends Object> context) {
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
String templateName = (String) context.get("templateName");
|
||||
Map<String, Object> templateData = UtilGenerics.checkMap(context.get("templateData"));
|
||||
String webSiteId = (String) context.get("webSiteId");
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
Map<String, Object> result = null;
|
||||
if (templateData == null) {
|
||||
templateData = new LinkedHashMap<String, Object>();
|
||||
}
|
||||
|
||||
try {
|
||||
// ensure the baseURl is defined
|
||||
setBaseUrl(delegator, webSiteId, templateData);
|
||||
|
||||
// initialize the template reader and processor
|
||||
URL templateUrl = FlexibleLocation.resolveLocation(templateName);
|
||||
|
||||
if (templateUrl == null) {
|
||||
Debug.logError("Problem getting the template URL: " + templateName + " not found", module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailProblemFindingTemplate", locale));
|
||||
}
|
||||
|
||||
// process the template with the given data and write
|
||||
// the email body to the String buffer
|
||||
Writer writer = new StringWriter();
|
||||
FreeMarkerWorker.renderTemplate(templateUrl.toExternalForm(), templateData, writer);
|
||||
|
||||
// extract the newly created body for the notification email
|
||||
String notificationBody = writer.toString();
|
||||
|
||||
// generate the successful response
|
||||
result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "CommonNotifyEmailMessageBodyGeneratedSuccessfully", locale));
|
||||
result.put("body", notificationBody);
|
||||
} catch (IOException ie) {
|
||||
Debug.logError(ie, "Problems reading template", module);
|
||||
result = ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailProblemReadingTemplate", locale));
|
||||
} catch (TemplateException te) {
|
||||
Debug.logError(te, "Problems processing template", module);
|
||||
result = ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailProblemProcessingTemplate", locale));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* The expectation is that a lot of notification messages will include
|
||||
* a link back to one or more pages in the system, which will require knowledge
|
||||
* of the base URL to extrapolate. This method will ensure that the
|
||||
* <code>baseUrl</code> field is set in the given context.
|
||||
* <p>
|
||||
* If it has been specified a default <code>baseUrl</code> will be
|
||||
* set using a best effort approach. If it is specified in the
|
||||
* url.properties configuration files of the system, that will be
|
||||
* used, otherwise it will attempt resolve the fully qualified
|
||||
* local host name.
|
||||
* <p>
|
||||
* <i>Note:</i> I thought it might be useful to have some dynamic way
|
||||
* of extending the default properties provided by the NotificationService,
|
||||
* such as the <code>baseUrl</code>, perhaps using the standard
|
||||
* <code>ResourceBundle</code> java approach so that both classes
|
||||
* and static files may be invoked.
|
||||
*
|
||||
* @param context The context to check and, if necessary, set the
|
||||
* <code>baseUrl</code>.
|
||||
*/
|
||||
public static void setBaseUrl(Delegator delegator, String webSiteId, Map<String, Object> context) {
|
||||
// If the baseUrl was not specified we can do a best effort instead
|
||||
if (!context.containsKey("baseUrl")) {
|
||||
try {
|
||||
WebappInfo webAppInfo = null;
|
||||
if (webSiteId != null) {
|
||||
webAppInfo = WebAppUtil.getWebappInfoFromWebsiteId(webSiteId);
|
||||
}
|
||||
OfbizUrlBuilder builder = OfbizUrlBuilder.from(webAppInfo, delegator);
|
||||
StringBuilder newURL = new StringBuilder();
|
||||
builder.buildHostPart(newURL, "", false);
|
||||
context.put("baseUrl", newURL.toString());
|
||||
newURL = new StringBuilder();
|
||||
builder.buildHostPart(newURL, "", true);
|
||||
context.put("baseSecureUrl", newURL.toString());
|
||||
} catch (Exception e) {
|
||||
Debug.logWarning(e, "Exception thrown while adding baseUrl to context: ", module);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.geo;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.ofbiz.entity.util.EntityUtil;
|
||||
|
||||
/**
|
||||
* Worker methods for Geos
|
||||
*/
|
||||
public final class GeoWorker {
|
||||
|
||||
public static final String module = GeoWorker.class.getName();
|
||||
|
||||
private GeoWorker() {}
|
||||
|
||||
public static List<GenericValue> expandGeoGroup(String geoId, Delegator delegator) {
|
||||
GenericValue geo = null;
|
||||
try {
|
||||
geo = EntityQuery.use(delegator).from("Geo").where("geoId", geoId).cache().queryOne();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Unable to look up Geo from geoId : " + geoId, module);
|
||||
}
|
||||
return expandGeoGroup(geo);
|
||||
}
|
||||
|
||||
public static List<GenericValue> expandGeoGroup(GenericValue geo) {
|
||||
if (geo == null) {
|
||||
return new LinkedList<GenericValue>();
|
||||
}
|
||||
if (!"GROUP".equals(geo.getString("geoTypeId"))) {
|
||||
return UtilMisc.toList(geo);
|
||||
}
|
||||
|
||||
//Debug.logInfo("Expanding geo : " + geo, module);
|
||||
|
||||
List<GenericValue> geoList = new LinkedList<GenericValue>();
|
||||
List<GenericValue> thisGeoAssoc = null;
|
||||
try {
|
||||
thisGeoAssoc = geo.getRelated("AssocGeoAssoc", UtilMisc.toMap("geoAssocTypeId", "GROUP_MEMBER"), null, false);
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Unable to get associated Geo GROUP_MEMBER relationship(s)", module);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(thisGeoAssoc)) {
|
||||
for (GenericValue nextGeoAssoc: thisGeoAssoc) {
|
||||
GenericValue nextGeo = null;
|
||||
try {
|
||||
nextGeo = nextGeoAssoc.getRelatedOne("MainGeo", false);
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Unable to get related Geo", module);
|
||||
}
|
||||
geoList.addAll(expandGeoGroup(nextGeo));
|
||||
}
|
||||
} else {
|
||||
//Debug.logInfo("No associated geos with this group", module);
|
||||
}
|
||||
|
||||
//Debug.logInfo("Expanded to : " + geoList, module);
|
||||
|
||||
return geoList;
|
||||
}
|
||||
|
||||
public static Map<String, String> expandGeoRegionDeep(Map<String, String> geoIdByTypeMapOrig, Delegator delegator) throws GenericEntityException {
|
||||
if (UtilValidate.isEmpty(geoIdByTypeMapOrig)) {
|
||||
return geoIdByTypeMapOrig;
|
||||
}
|
||||
Map<String, String> geoIdByTypeMapTemp = new LinkedHashMap<String, String>();
|
||||
for (Map.Entry<String, String> geoIdByTypeEntry: geoIdByTypeMapOrig.entrySet()) {
|
||||
List<GenericValue> geoAssocList = EntityQuery.use(delegator)
|
||||
.from("GeoAssoc")
|
||||
.where("geoIdTo", geoIdByTypeEntry.getValue(), "geoAssocTypeId", "REGIONS")
|
||||
.cache(true)
|
||||
.queryList();
|
||||
for (GenericValue geoAssoc: geoAssocList) {
|
||||
GenericValue newGeo = EntityQuery.use(delegator).from("Geo").where("geoId", geoAssoc.get("geoId")).cache().queryOne();
|
||||
geoIdByTypeMapTemp.put(newGeo.getString("geoTypeId"), newGeo.getString("geoId"));
|
||||
}
|
||||
}
|
||||
geoIdByTypeMapTemp = expandGeoRegionDeep(geoIdByTypeMapTemp, delegator);
|
||||
Map<String, String> geoIdByTypeMapNew = new LinkedHashMap<String, String>();
|
||||
// add the temp Map first, then the original over top of it, ie give the original priority over the sub/expanded values
|
||||
geoIdByTypeMapNew.putAll(geoIdByTypeMapTemp);
|
||||
geoIdByTypeMapNew.putAll(geoIdByTypeMapOrig);
|
||||
return geoIdByTypeMapNew;
|
||||
}
|
||||
|
||||
public static boolean containsGeo(List<GenericValue> geoList, String geoId, Delegator delegator) {
|
||||
GenericValue geo = null;
|
||||
try {
|
||||
geo = EntityQuery.use(delegator).from("Geo").where("geoId", geoId).cache().queryOne();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Unable to look up Geo from geoId : " + geoId, module);
|
||||
}
|
||||
return containsGeo(geoList, geo);
|
||||
}
|
||||
|
||||
public static boolean containsGeo(List<GenericValue> geoList, GenericValue geo) {
|
||||
if (geoList == null || geo == null) {
|
||||
return false;
|
||||
}
|
||||
//Debug.logInfo("Contains Geo : " + geoList.contains(geo));
|
||||
return geoList.contains(geo);
|
||||
}
|
||||
|
||||
public static GenericValue findLatestGeoPoint(Delegator delegator, String entityName, String mainId, String mainValueId, String secondId, String secondValueId) {
|
||||
List<GenericValue> gptList = null;
|
||||
if (UtilValidate.isNotEmpty(secondId) && UtilValidate.isNotEmpty(secondValueId)) {
|
||||
try {
|
||||
gptList = EntityQuery.use(delegator)
|
||||
.from(entityName)
|
||||
.where(mainId, mainValueId, secondId, secondValueId)
|
||||
.orderBy("-fromDate")
|
||||
.queryList();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Error while finding latest GeoPoint for " + mainId + " with Id [" + mainValueId + "] and " + secondId + " Id [" + secondValueId + "] " + e.toString(), module);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
gptList = EntityQuery.use(delegator).from(entityName).where(mainId, mainValueId).orderBy("-fromDate").queryList();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Error while finding latest GeoPoint for " + mainId + " with Id [" + mainValueId + "] " + e.toString(), module);
|
||||
}
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(gptList)) {
|
||||
gptList = EntityUtil.filterByDate(gptList);
|
||||
return EntityUtil.getFirst(gptList);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.image;
|
||||
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.Image;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.swing.ImageIcon;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.xml.sax.SAXException;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* ImageTransform Class
|
||||
* <p>
|
||||
* Services to apply transformation to images
|
||||
*/
|
||||
public class ImageTransform {
|
||||
|
||||
public static final String module = ImageTransform.class.getName();
|
||||
public static final String resource = "CommonErrorUiLabels";
|
||||
|
||||
public ImageTransform() {
|
||||
}
|
||||
|
||||
/**
|
||||
* getBufferedImage
|
||||
* <p>
|
||||
* Set a buffered image
|
||||
*
|
||||
* @param fileLocation Full file Path or URL
|
||||
* @return URL images for all different size types
|
||||
* @throws IOException Error prevents the document from being fully parsed
|
||||
* @throws JDOMException Errors occur in parsing
|
||||
*/
|
||||
public static Map<String, Object> getBufferedImage(String fileLocation, Locale locale)
|
||||
throws IllegalArgumentException, IOException {
|
||||
|
||||
/* VARIABLES */
|
||||
BufferedImage bufImg;
|
||||
Map<String, Object> result = new LinkedHashMap<String, Object>();
|
||||
|
||||
/* BUFFERED IMAGE */
|
||||
try {
|
||||
bufImg = ImageIO.read(new File(fileLocation));
|
||||
} catch (IllegalArgumentException e) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.input_is_null", locale) + " : " + fileLocation + " ; " + e.toString();
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", errMsg);
|
||||
return result;
|
||||
} catch (IOException e) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.error_occurs_during_reading", locale) + " : " + fileLocation + " ; " + e.toString();
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", errMsg);
|
||||
return result;
|
||||
}
|
||||
|
||||
result.put("responseMessage", "success");
|
||||
result.put("bufferedImage", bufImg);
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* scaleImage
|
||||
* <p>
|
||||
* scale original image related to the ImageProperties.xml dimensions
|
||||
*
|
||||
* @param bufImg Buffered image to scale
|
||||
* @param imgHeight Original image height
|
||||
* @param imgWidth Original image width
|
||||
* @param dimensionMap Image dimensions by size type
|
||||
* @param sizeType Size type to scale
|
||||
* @return New scaled buffered image
|
||||
*/
|
||||
public static Map<String, Object> scaleImage(BufferedImage bufImg, double imgHeight, double imgWidth, Map<String, Map<String, String>> dimensionMap, String sizeType, Locale locale) {
|
||||
|
||||
/* VARIABLES */
|
||||
BufferedImage bufNewImg;
|
||||
double defaultHeight, defaultWidth, scaleFactor;
|
||||
Map<String, Object> result = new LinkedHashMap<String, Object>();
|
||||
|
||||
/* DIMENSIONS from ImageProperties */
|
||||
// A missed dimension is authorized
|
||||
if (dimensionMap.get(sizeType).containsKey("height")) {
|
||||
defaultHeight = Double.parseDouble(dimensionMap.get(sizeType).get("height").toString());
|
||||
} else {
|
||||
defaultHeight = -1;
|
||||
}
|
||||
if (dimensionMap.get(sizeType).containsKey("width")) {
|
||||
defaultWidth = Double.parseDouble(dimensionMap.get(sizeType).get("width").toString());
|
||||
} else {
|
||||
defaultWidth = -1;
|
||||
}
|
||||
if (defaultHeight == 0.0 || defaultWidth == 0.0) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.one_default_dimension_is_null", locale) + " : defaultHeight = " + defaultHeight + " ; defaultWidth = " + defaultWidth;
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", errMsg);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* SCALE FACTOR */
|
||||
// find the right Scale Factor related to the Image Dimensions
|
||||
if (defaultHeight == -1) {
|
||||
scaleFactor = defaultWidth / imgWidth;
|
||||
if (scaleFactor == 0.0) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.width_scale_factor_is_null", locale) + " (defaultWidth = " + defaultWidth + "; imgWidth = " + imgWidth;
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", errMsg);
|
||||
return result;
|
||||
}
|
||||
} else if (defaultWidth == -1) {
|
||||
scaleFactor = defaultHeight / imgHeight;
|
||||
if (scaleFactor == 0.0) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.height_scale_factor_is_null", locale) + " (defaultHeight = " + defaultHeight + "; imgHeight = " + imgHeight;
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", errMsg);
|
||||
return result;
|
||||
}
|
||||
} else if (imgHeight > imgWidth) {
|
||||
scaleFactor = defaultHeight / imgHeight;
|
||||
if (scaleFactor == 0.0) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.height_scale_factor_is_null", locale) + " (defaultHeight = " + defaultHeight + "; imgHeight = " + imgHeight;
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", errMsg);
|
||||
return result;
|
||||
}
|
||||
// get scaleFactor from the smallest width
|
||||
if (defaultWidth < (imgWidth * scaleFactor)) {
|
||||
scaleFactor = defaultWidth / imgWidth;
|
||||
}
|
||||
} else {
|
||||
scaleFactor = defaultWidth / imgWidth;
|
||||
if (scaleFactor == 0.0) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.width_scale_factor_is_null", locale) + " (defaultWidth = " + defaultWidth + "; imgWidth = " + imgWidth;
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", errMsg);
|
||||
return result;
|
||||
}
|
||||
// get scaleFactor from the smallest height
|
||||
if (defaultHeight < (imgHeight * scaleFactor)) {
|
||||
scaleFactor = defaultHeight / imgHeight;
|
||||
}
|
||||
}
|
||||
|
||||
if (scaleFactor == 0.0) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.final_scale_factor_is_null", locale) + " = " + scaleFactor;
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", errMsg);
|
||||
return result;
|
||||
}
|
||||
int bufImgType;
|
||||
if (BufferedImage.TYPE_CUSTOM == bufImg.getType()) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.unknown_buffered_image_type", locale);
|
||||
Debug.logWarning(errMsg, module);
|
||||
// apply a type for image majority
|
||||
bufImgType = BufferedImage.TYPE_INT_ARGB_PRE;
|
||||
} else {
|
||||
bufImgType = bufImg.getType();
|
||||
}
|
||||
|
||||
// scale original image with new size
|
||||
Image newImg = bufImg.getScaledInstance((int) (imgWidth * scaleFactor), (int) (imgHeight * scaleFactor), Image.SCALE_SMOOTH);
|
||||
|
||||
bufNewImg = ImageTransform.toBufferedImage(newImg, bufImgType);
|
||||
|
||||
result.put("responseMessage", "success");
|
||||
result.put("bufferedImage", bufNewImg);
|
||||
result.put("scaleFactor", scaleFactor);
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* getXMLValue
|
||||
* <p>
|
||||
* From a XML element, get a values map
|
||||
*
|
||||
* @param fileFullPath File path to parse
|
||||
* @return Map contains asked attribute values by attribute name
|
||||
*/
|
||||
public static Map<String, Object> getXMLValue(String fileFullPath, Locale locale)
|
||||
throws IllegalStateException, IOException {
|
||||
|
||||
/* VARIABLES */
|
||||
Document document;
|
||||
Element rootElt;
|
||||
Map<String, Map<String, String>> valueMap = new LinkedHashMap<String, Map<String, String>>();
|
||||
Map<String, Object> result = new LinkedHashMap<String, Object>();
|
||||
|
||||
/* PARSING */
|
||||
try {
|
||||
document = UtilXml.readXmlDocument(new FileInputStream(fileFullPath), fileFullPath);
|
||||
} catch (ParserConfigurationException e) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.errors_occurred_during_parsing", locale) + " ImageProperties.xml " + e.toString();
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", "error");
|
||||
return result;
|
||||
} catch (SAXException e) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.errors_occurred_during_parsing", locale) + " ImageProperties.xml " + e.toString();
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", "error");
|
||||
return result;
|
||||
} catch (IOException e) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.error_prevents_the document_from_being_fully_parsed", locale) + e.toString();
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", "error");
|
||||
return result;
|
||||
}
|
||||
// set Root Element
|
||||
try {
|
||||
rootElt = document.getDocumentElement();
|
||||
} catch (IllegalStateException e) {
|
||||
String errMsg = UtilProperties.getMessage(resource, "ImageTransform.root_element_has_not_been_set", locale) + e.toString();
|
||||
Debug.logError(errMsg, module);
|
||||
result.put("errorMessage", "error");
|
||||
return result;
|
||||
}
|
||||
|
||||
/* get NAME and VALUE */
|
||||
List<? extends Element> children = UtilXml.childElementList(rootElt); // FIXME : despite upgrading to jdom 1.1, it seems that getChildren is pre 1.5 java code (ie getChildren does not retun List<Element> but only List)
|
||||
for (Element currentElt : children) {
|
||||
Map<String, String> eltMap = new LinkedHashMap<String, String>();
|
||||
List<? extends Element> children2 = UtilXml.childElementList(currentElt);
|
||||
if (children2.size() > 0) {
|
||||
Map<String, String> childMap = new LinkedHashMap<String, String>();
|
||||
// loop over Children 1st level
|
||||
for (Element currentChild : children2) {
|
||||
childMap.put(currentChild.getAttribute("name"), currentChild.getAttribute("value"));
|
||||
}
|
||||
valueMap.put(currentElt.getAttribute("name"), childMap);
|
||||
} else {
|
||||
eltMap.put(currentElt.getAttribute("name"), currentElt.getAttribute("value"));
|
||||
valueMap.put(currentElt.getNodeName(), eltMap);
|
||||
}
|
||||
}
|
||||
|
||||
result.put("responseMessage", "success");
|
||||
result.put("xml", valueMap);
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* toBufferedImage
|
||||
* <p>
|
||||
* Transform from an Image instance to a BufferedImage instance
|
||||
*
|
||||
* @param image Source image
|
||||
* @return BufferedImage
|
||||
*/
|
||||
public static BufferedImage toBufferedImage(Image image) {
|
||||
return ImageTransform.toBufferedImage(image, BufferedImage.TYPE_INT_ARGB_PRE);
|
||||
}
|
||||
|
||||
public static BufferedImage toBufferedImage(Image image, int bufImgType) {
|
||||
/** Check if the image isn't already a BufferedImage instance */
|
||||
if( image instanceof BufferedImage ) {
|
||||
return( (BufferedImage)image );
|
||||
} else {
|
||||
/** Full image loading */
|
||||
image = new ImageIcon(image).getImage();
|
||||
|
||||
/** new BufferedImage creation */
|
||||
BufferedImage bufferedImage = new BufferedImage(
|
||||
image.getWidth(null),
|
||||
image.getHeight(null),
|
||||
bufImgType);
|
||||
|
||||
Graphics2D g = bufferedImage.createGraphics();
|
||||
g.drawImage(image,0,0,null);
|
||||
g.dispose();
|
||||
|
||||
return( bufferedImage );
|
||||
}
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.login;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.NamingException;
|
||||
import javax.naming.directory.DirContext;
|
||||
import javax.naming.directory.InitialDirContext;
|
||||
import javax.transaction.Transaction;
|
||||
|
||||
import org.ofbiz.base.crypto.HashCrypt;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.transaction.GenericTransactionException;
|
||||
import org.ofbiz.entity.transaction.TransactionUtil;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.ofbiz.entity.util.EntityUtilProperties;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
|
||||
/** LDAP Authentication Services.
|
||||
*/
|
||||
public class LdapAuthenticationServices {
|
||||
|
||||
public static final String module = LdapAuthenticationServices.class.getName();
|
||||
|
||||
public static boolean userLogin(DispatchContext ctx, Map<String, ?> context) {
|
||||
Debug.logVerbose("Starting LDAP authentication", module);
|
||||
Properties env = UtilProperties.getProperties("jndiLdap");
|
||||
String username = (String) context.get("login.username");
|
||||
if (username == null) {
|
||||
username = (String) context.get("username");
|
||||
}
|
||||
String password = (String) context.get("login.password");
|
||||
if (password == null) {
|
||||
password = (String) context.get("password");
|
||||
}
|
||||
String dn = null;
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
boolean isServiceAuth = context.get("isServiceAuth") != null && ((Boolean) context.get("isServiceAuth")).booleanValue();
|
||||
GenericValue userLogin = null;
|
||||
try {
|
||||
userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", username).cache(isServiceAuth).queryOne();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e, "", module);
|
||||
}
|
||||
if (userLogin != null) {
|
||||
dn = userLogin.getString("userLdapDn");
|
||||
}
|
||||
if (UtilValidate.isEmpty(dn)) {
|
||||
String dnTemplate = (String) env.get("ldap.dn.template");
|
||||
if (dnTemplate != null) {
|
||||
dn = dnTemplate.replace("%u", username);
|
||||
}
|
||||
Debug.logVerbose("Using DN template: " + dn, module);
|
||||
} else {
|
||||
Debug.logVerbose("Using UserLogin.userLdapDn: " + dn, module);
|
||||
}
|
||||
env.put(Context.SECURITY_PRINCIPAL, dn);
|
||||
env.put(Context.SECURITY_CREDENTIALS, password);
|
||||
try {
|
||||
// Create initial context
|
||||
DirContext ldapCtx = new InitialDirContext(env);
|
||||
ldapCtx.close();
|
||||
} catch (NamingException e) {
|
||||
Debug.logVerbose("LDAP authentication failed: " + e.getMessage(), module);
|
||||
return false;
|
||||
}
|
||||
Debug.logVerbose("LDAP authentication succeeded", module);
|
||||
if (!"true".equals(env.get("ldap.synchronize.passwords"))) {
|
||||
return true;
|
||||
}
|
||||
// Synchronize user's OFBiz password with user's LDAP password
|
||||
if (userLogin != null) {
|
||||
boolean useEncryption = "true".equals(EntityUtilProperties.getPropertyValue("security", "password.encrypt", delegator));
|
||||
String currentPassword = userLogin.getString("currentPassword");
|
||||
boolean samePassword;
|
||||
if (useEncryption) {
|
||||
samePassword = HashCrypt.comparePassword(currentPassword, LoginServices.getHashType(), password);
|
||||
} else {
|
||||
samePassword = currentPassword.equals(password);
|
||||
}
|
||||
if (!samePassword) {
|
||||
Debug.logVerbose("Starting password synchronization", module);
|
||||
userLogin.set("currentPassword", useEncryption ? HashCrypt.cryptUTF8(LoginServices.getHashType(), null, password) : password, false);
|
||||
Transaction parentTx = null;
|
||||
boolean beganTransaction = false;
|
||||
try {
|
||||
try {
|
||||
parentTx = TransactionUtil.suspend();
|
||||
} catch (GenericTransactionException e) {
|
||||
Debug.logError(e, "Could not suspend transaction: " + e.getMessage(), module);
|
||||
}
|
||||
try {
|
||||
beganTransaction = TransactionUtil.begin();
|
||||
userLogin.store();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Error saving UserLogin", module);
|
||||
try {
|
||||
TransactionUtil.rollback(beganTransaction, "Error saving UserLogin", e);
|
||||
} catch (GenericTransactionException e2) {
|
||||
Debug.logError(e2, "Could not rollback nested transaction: " + e2.getMessage(), module);
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
TransactionUtil.commit(beganTransaction);
|
||||
Debug.logVerbose("Password synchronized", module);
|
||||
} catch (GenericTransactionException e) {
|
||||
Debug.logError(e, "Could not commit nested transaction: " + e.getMessage(), module);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (parentTx != null) {
|
||||
try {
|
||||
TransactionUtil.resume(parentTx);
|
||||
Debug.logVerbose("Resumed the parent transaction.", module);
|
||||
} catch (GenericTransactionException e) {
|
||||
Debug.logError(e, "Could not resume parent nested transaction: " + e.getMessage(), module);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,57 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.period;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
|
||||
import org.ofbiz.base.util.UtilDateTime;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.condition.EntityConditionList;
|
||||
import org.ofbiz.entity.condition.EntityExpr;
|
||||
import org.ofbiz.entity.condition.EntityOperator;
|
||||
|
||||
public final class PeriodWorker {
|
||||
|
||||
public static String module = PeriodWorker.class.getName();
|
||||
|
||||
private PeriodWorker() {}
|
||||
|
||||
/**
|
||||
* Method to get a condition that checks that the given fieldName is in a given timePeriod.
|
||||
*/
|
||||
public static EntityCondition getFilterByPeriodExpr(String fieldName, GenericValue timePeriod) {
|
||||
Timestamp fromDate;
|
||||
Timestamp thruDate;
|
||||
if (timePeriod.get("fromDate") instanceof Timestamp) {
|
||||
fromDate = timePeriod.getTimestamp("fromDate");
|
||||
thruDate = timePeriod.getTimestamp("thruDate");
|
||||
} else {
|
||||
fromDate = UtilDateTime.toTimestamp(timePeriod.getDate("fromDate"));
|
||||
thruDate = UtilDateTime.toTimestamp(timePeriod.getDate("thruDate"));
|
||||
}
|
||||
|
||||
EntityConditionList<EntityExpr> betweenCondition = EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(fieldName, EntityOperator.GREATER_THAN, fromDate),
|
||||
EntityCondition.makeCondition(fieldName, EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
|
||||
return EntityCondition.makeCondition(EntityCondition.makeCondition(fieldName, EntityOperator.NOT_EQUAL, null), betweenCondition);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.preferences;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.GeneralException;
|
||||
import org.ofbiz.base.util.ObjectType;
|
||||
import static org.ofbiz.base.util.UtilGenerics.checkMap;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
|
||||
/**
|
||||
* User preference services.<p>User preferences are stored as key-value pairs.
|
||||
* <p>User preferences can be grouped - so that multiple preference pairs can be
|
||||
* handled at once. Preference groups also allow a single userPrefTypeId to be
|
||||
* used more than once - with each occurence having a unique userPrefGroupTypeId.</p>
|
||||
* <p>User preference values are stored as Strings, so the easiest and most
|
||||
* efficient way to handle user preference values is to keep them as strings.
|
||||
* This class handles any data conversion needed.</p>
|
||||
*/
|
||||
public class PreferenceServices {
|
||||
public static final String module = PreferenceServices.class.getName();
|
||||
|
||||
public static final String resource = "PrefErrorUiLabels";
|
||||
|
||||
/**
|
||||
* Retrieves a single user preference from persistent storage. Call with
|
||||
* userPrefTypeId and optional userPrefLoginId. If userPrefLoginId isn't
|
||||
* specified, then the currently logged-in user's userLoginId will be
|
||||
* used. The retrieved preference is contained in the <b>userPrefMap</b> element.
|
||||
* @param ctx The DispatchContext that this service is operating in.
|
||||
* @param context Map containing the input arguments.
|
||||
* @return Map with the result of the service, the output parameters.
|
||||
*/
|
||||
public static Map<String, Object> getUserPreference(DispatchContext ctx, Map<String, ?> context) {
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
if (!PreferenceWorker.isValidGetId(ctx, context)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.permissionError", locale));
|
||||
}
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
|
||||
String userPrefTypeId = (String) context.get("userPrefTypeId");
|
||||
if (UtilValidate.isEmpty(userPrefTypeId)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.invalidArgument", locale));
|
||||
}
|
||||
String userLoginId = PreferenceWorker.getUserLoginId(context, true);
|
||||
Map<String, String> fieldMap = UtilMisc.toMap("userLoginId", userLoginId, "userPrefTypeId", userPrefTypeId);
|
||||
String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
|
||||
if (UtilValidate.isNotEmpty(userPrefGroupTypeId)) {
|
||||
fieldMap.put("userPrefGroupTypeId", userPrefGroupTypeId);
|
||||
}
|
||||
|
||||
Map<String, Object> userPrefMap = null;
|
||||
try {
|
||||
GenericValue preference = EntityQuery.use(delegator).from("UserPreference").where(fieldMap).cache(true).queryFirst();
|
||||
if (preference != null) {
|
||||
userPrefMap = PreferenceWorker.createUserPrefMap(preference);
|
||||
}
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.readFailure", new Object[] { e.getMessage() }, locale));
|
||||
} catch (GeneralException e) {
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.readFailure", new Object[] { e.getMessage() }, locale));
|
||||
}
|
||||
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
result.put("userPrefMap", userPrefMap);
|
||||
if (userPrefMap != null) {
|
||||
// Put the value in the result Map too, makes access easier for calling methods.
|
||||
Object userPrefValue = userPrefMap.get(userPrefTypeId);
|
||||
if (userPrefValue != null) {
|
||||
result.put("userPrefValue", userPrefValue);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a group of user preferences from persistent storage. Call with
|
||||
* userPrefGroupTypeId and optional userPrefLoginId. If userPrefLoginId isn't
|
||||
* specified, then the currently logged-in user's userLoginId will be
|
||||
* used. The retrieved preferences group is contained in the <b>userPrefMap</b> element.
|
||||
* @param ctx The DispatchContext that this service is operating in.
|
||||
* @param context Map containing the input arguments.
|
||||
* @return Map with the result of the service, the output parameters.
|
||||
*/
|
||||
public static Map<String, Object> getUserPreferenceGroup(DispatchContext ctx, Map<String, ?> context) {
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
if (!PreferenceWorker.isValidGetId(ctx, context)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.permissionError", locale));
|
||||
}
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
|
||||
String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
|
||||
if (UtilValidate.isEmpty(userPrefGroupTypeId)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.invalidArgument", locale));
|
||||
}
|
||||
String userLoginId = PreferenceWorker.getUserLoginId(context, false);
|
||||
|
||||
Map<String, Object> userPrefMap = null;
|
||||
try {
|
||||
Map<String, String> fieldMap = UtilMisc.toMap("userLoginId", "_NA_", "userPrefGroupTypeId", userPrefGroupTypeId);
|
||||
userPrefMap = PreferenceWorker.createUserPrefMap(EntityQuery.use(delegator).from("UserPreference").where(fieldMap).cache(true).queryList());
|
||||
if (userLoginId != null) {
|
||||
fieldMap.put("userLoginId", userLoginId);
|
||||
userPrefMap.putAll(PreferenceWorker.createUserPrefMap(EntityQuery.use(delegator).from("UserPreference").where(fieldMap).cache(true).queryList()));
|
||||
}
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.readFailure", new Object[] { e.getMessage() }, locale));
|
||||
} catch (GeneralException e) {
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.readFailure", new Object[] { e.getMessage() }, locale));
|
||||
}
|
||||
// for the 'DEFAULT' values find the related values in general properties and if found use those.
|
||||
Properties generalProperties = UtilProperties.getProperties("general");
|
||||
for (Map.Entry<String, Object> pairs: userPrefMap.entrySet()) {
|
||||
if ("DEFAULT".equals(pairs.getValue())) {
|
||||
if (UtilValidate.isNotEmpty(generalProperties.get(pairs.getKey()))) {
|
||||
userPrefMap.put(pairs.getKey(), generalProperties.get(pairs.getKey()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
result.put("userPrefMap", userPrefMap);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores a single user preference in persistent storage. Call with
|
||||
* userPrefTypeId, userPrefGroupTypeId, userPrefValue and optional userPrefLoginId.
|
||||
* If userPrefLoginId isn't specified, then the currently logged-in user's
|
||||
* userLoginId will be used.
|
||||
* @param ctx The DispatchContext that this service is operating in.
|
||||
* @param context Map containing the input arguments.
|
||||
* @return Map with the result of the service, the output parameters.
|
||||
*/
|
||||
public static Map<String, Object> setUserPreference(DispatchContext ctx, Map<String, ?> context) {
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
|
||||
String userLoginId = PreferenceWorker.getUserLoginId(context, false);
|
||||
String userPrefTypeId = (String) context.get("userPrefTypeId");
|
||||
Object userPrefValue = context.get("userPrefValue");
|
||||
if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefTypeId) || userPrefValue == null) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "setPreference.invalidArgument", locale));
|
||||
}
|
||||
String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
|
||||
String userPrefDataType = (String) context.get("userPrefDataType");
|
||||
|
||||
try {
|
||||
if (UtilValidate.isNotEmpty(userPrefDataType)) {
|
||||
userPrefValue = ObjectType.simpleTypeConvert(userPrefValue, userPrefDataType, null, null, false);
|
||||
}
|
||||
GenericValue rec = delegator.makeValidValue("UserPreference", PreferenceWorker.toFieldMap(userLoginId, userPrefTypeId, userPrefGroupTypeId, userPrefValue));
|
||||
delegator.createOrStore(rec);
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "setPreference.writeFailure", new Object[] { e.getMessage() }, locale));
|
||||
} catch (GeneralException e) {
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "setPreference.writeFailure", new Object[] { e.getMessage() }, locale));
|
||||
}
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
public static Map<String, Object> removeUserPreference(DispatchContext ctx, Map<String, ?> context) {
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
|
||||
String userLoginId = PreferenceWorker.getUserLoginId(context, false);
|
||||
String userPrefTypeId = (String) context.get("userPrefTypeId");
|
||||
//Debug.logError("In removeUserPreference userLoginId=" + userLoginId + ", userPrefTypeId=" + userPrefTypeId, module);
|
||||
if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefTypeId)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "setPreference.invalidArgument", locale));
|
||||
}
|
||||
|
||||
try {
|
||||
GenericValue rec = EntityQuery.use(delegator)
|
||||
.from("UserPreference")
|
||||
.where("userLoginId", userLoginId, "userPrefTypeId", userPrefTypeId)
|
||||
.queryOne();
|
||||
if (rec != null) {
|
||||
rec.remove();
|
||||
}
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "setPreference.writeFailure", new Object[] { e.getMessage() }, locale));
|
||||
}
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores a user preference group in persistent storage. Call with
|
||||
* userPrefMap, userPrefGroupTypeId and optional userPrefLoginId. If userPrefLoginId
|
||||
* isn't specified, then the currently logged-in user's userLoginId will be
|
||||
* used.
|
||||
* @param ctx The DispatchContext that this service is operating in.
|
||||
* @param context Map containing the input arguments.
|
||||
* @return Map with the result of the service, the output parameters.
|
||||
*/
|
||||
public static Map<String, Object> setUserPreferenceGroup(DispatchContext ctx, Map<String, ?> context) {
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
|
||||
String userLoginId = PreferenceWorker.getUserLoginId(context, false);
|
||||
Map<String, Object> userPrefMap = checkMap(context.get("userPrefMap"), String.class, Object.class);
|
||||
String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
|
||||
if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefGroupTypeId) || userPrefMap == null) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "setPreference.invalidArgument", locale));
|
||||
}
|
||||
|
||||
try {
|
||||
for (Map.Entry<String, Object> mapEntry: userPrefMap.entrySet()) {
|
||||
GenericValue rec = delegator.makeValidValue("UserPreference", PreferenceWorker.toFieldMap(userLoginId, mapEntry.getKey(), userPrefGroupTypeId, mapEntry.getValue()));
|
||||
delegator.createOrStore(rec);
|
||||
}
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "setPreference.writeFailure", new Object[] { e.getMessage() }, locale));
|
||||
} catch (GeneralException e) {
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "setPreference.writeFailure", new Object[] { e.getMessage() }, locale));
|
||||
}
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a user preference group. Call with
|
||||
* fromUserLoginId, userPrefGroupTypeId and optional userPrefLoginId. If userPrefLoginId
|
||||
* isn't specified, then the currently logged-in user's userLoginId will be
|
||||
* used.
|
||||
* @param ctx The DispatchContext that this service is operating in.
|
||||
* @param context Map containing the input arguments.
|
||||
* @return Map with the result of the service, the output parameters.
|
||||
*/
|
||||
public static Map<String, Object> copyUserPreferenceGroup(DispatchContext ctx, Map<String, ?> context) {
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
|
||||
String userLoginId = PreferenceWorker.getUserLoginId(context, false);
|
||||
String fromUserLoginId = (String) context.get("fromUserLoginId");
|
||||
String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
|
||||
if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefGroupTypeId) || UtilValidate.isEmpty(fromUserLoginId)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "copyPreference.invalidArgument", locale));
|
||||
}
|
||||
|
||||
try {
|
||||
List<GenericValue> resultList = EntityQuery.use(delegator)
|
||||
.from("UserPreference")
|
||||
.where("userLoginId", fromUserLoginId, "userPrefGroupTypeId", userPrefGroupTypeId)
|
||||
.queryList();
|
||||
if (resultList != null) {
|
||||
for (GenericValue preference: resultList) {
|
||||
preference.set("userLoginId", userLoginId);
|
||||
}
|
||||
delegator.storeAll(resultList);
|
||||
}
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "copyPreference.writeFailure", new Object[] { e.getMessage() }, locale));
|
||||
}
|
||||
|
||||
return ServiceUtil.returnSuccess();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.preferences;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.GeneralException;
|
||||
import org.ofbiz.base.util.ObjectType;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.security.Security;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
|
||||
/**
|
||||
* User preference worker methods.
|
||||
*/
|
||||
public final class PreferenceWorker {
|
||||
public static final String module = PreferenceWorker.class.getName();
|
||||
/**
|
||||
* User preference administrator permission. Currently set to "USERPREF_ADMIN".
|
||||
*/
|
||||
private static final String ADMIN_PERMISSION = "USERPREF_ADMIN";
|
||||
/** User login ID parameter name. Currently set to "userPrefLoginId". This
|
||||
* parameter name is used in preference service definitions to specify a user login ID
|
||||
* that is different than the currently logged in user.
|
||||
*/
|
||||
private static final String LOGINID_PARAMETER_NAME = "userPrefLoginId";
|
||||
|
||||
/** Default userLoginId. Currently set to "_NA_". This userLoginId is used to
|
||||
* retrieve default preferences when the user is not logged in.
|
||||
*/
|
||||
private static final String DEFAULT_UID = "_NA_";
|
||||
|
||||
private PreferenceWorker () {}
|
||||
|
||||
/**
|
||||
* Add a UserPreference GenericValue to a Map.
|
||||
* @param rec GenericValue to convert
|
||||
* @param userPrefMap user preference Map
|
||||
* @throws GeneralException
|
||||
* @return user preference map
|
||||
*/
|
||||
public static Map<String, Object> addPrefToMap(GenericValue rec, Map<String, Object> userPrefMap) throws GeneralException {
|
||||
String prefDataType = rec.getString("userPrefDataType");
|
||||
if (UtilValidate.isEmpty(prefDataType)) {
|
||||
// default to String
|
||||
userPrefMap.put(rec.getString("userPrefTypeId"), rec.getString("userPrefValue"));
|
||||
} else {
|
||||
userPrefMap.put(rec.getString("userPrefTypeId"), ObjectType.simpleTypeConvert(rec.get("userPrefValue"), prefDataType, null, null, false));
|
||||
}
|
||||
return userPrefMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks preference copy permissions. Returns hasPermission=true if permission
|
||||
* is granted.
|
||||
* <p>Users can copy from any set of preferences to their own preferences.
|
||||
* Copying to another user's preferences requires <a href="#ADMIN_PERMISSION">ADMIN_PERMISSION</a>
|
||||
* permission.</p>
|
||||
* @param ctx The DispatchContext that this service is operating in.
|
||||
* @param context Map containing the input arguments.
|
||||
* @return Map with the result of the service, the output parameters.
|
||||
*/
|
||||
public static Map<String, Object> checkCopyPermission(DispatchContext ctx, Map<String, ?> context) {
|
||||
boolean hasPermission = false;
|
||||
GenericValue userLogin = (GenericValue) context.get("userLogin");
|
||||
if (userLogin != null) {
|
||||
String userLoginId = userLogin.getString("userLoginId");
|
||||
String userLoginIdArg = (String) context.get(LOGINID_PARAMETER_NAME); // is an optional parameters which defaults to the logged on user
|
||||
if (userLoginIdArg == null || (userLoginIdArg != null && userLoginId.equals(userLoginIdArg))) {
|
||||
hasPermission = true; // users can copy to their own preferences
|
||||
} else {
|
||||
Security security = ctx.getSecurity();
|
||||
hasPermission = security.hasPermission(ADMIN_PERMISSION, userLogin);
|
||||
}
|
||||
}
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
result.put("hasPermission", hasPermission);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks preference get/set permissions. Returns hasPermission=true if
|
||||
* permission is granted.
|
||||
* <p>This method is a simple wrapper around the isValidxxxId methods.</p>
|
||||
* @param ctx The DispatchContext that this service is operating in.
|
||||
* @param context Map containing the input arguments.
|
||||
* @return Map with the result of the service, the output parameters.
|
||||
*/
|
||||
public static Map<String, Object> checkPermission(DispatchContext ctx, Map<String, ?> context) {
|
||||
boolean hasPermission = false;
|
||||
String mainAction = (String) context.get("mainAction");
|
||||
if ("VIEW".equals(mainAction)) {
|
||||
if (DEFAULT_UID.equals(context.get(LOGINID_PARAMETER_NAME))) {
|
||||
hasPermission = true;
|
||||
} else {
|
||||
hasPermission = isValidGetId(ctx, context);
|
||||
}
|
||||
} else if ("CREATE~UPDATE~DELETE".contains(mainAction)) {
|
||||
hasPermission = isValidSetId(ctx, context);
|
||||
} else {
|
||||
hasPermission = false;
|
||||
}
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
result.put("hasPermission", hasPermission);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a UserPreference GenericValue to a userPrefMap.
|
||||
* @param rec GenericValue to convert
|
||||
* @throws GeneralException
|
||||
* @return user preference map
|
||||
*/
|
||||
public static Map<String, Object> createUserPrefMap(GenericValue rec) throws GeneralException {
|
||||
return addPrefToMap(rec, new LinkedHashMap<String, Object>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a List of UserPreference GenericValues to a userPrefMap.
|
||||
* @param recList List of GenericValues to convert
|
||||
* @throws GeneralException
|
||||
* @return user preference map
|
||||
*/
|
||||
public static Map<String, Object> createUserPrefMap(List<GenericValue> recList) throws GeneralException {
|
||||
Map<String, Object> userPrefMap = new LinkedHashMap<String, Object>();
|
||||
if (recList != null) {
|
||||
for (GenericValue value: recList) {
|
||||
addPrefToMap(value, userPrefMap);
|
||||
}
|
||||
}
|
||||
return userPrefMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a valid userLoginId parameter from the context Map.
|
||||
* <p>This method searches the context Map for a userPrefLoginId key. If none is
|
||||
* found, the method attempts to get the current user's userLoginId. If the user
|
||||
* isn't logged in, then the method returns <a href="#DEFAULT_UID">DEFAULT_UID</a>
|
||||
* if returnDefault is set to true, otherwise the method returns a null or empty string.</p>
|
||||
*
|
||||
* @param context Map containing the input arguments.
|
||||
* @param returnDefault return <a href="#DEFAULT_UID">DEFAULT_UID</a> if no userLoginId is found.
|
||||
* @return userLoginId String
|
||||
*/
|
||||
public static String getUserLoginId(Map<String, ?> context, boolean returnDefault) {
|
||||
String userLoginId = (String) context.get(LOGINID_PARAMETER_NAME);
|
||||
if (UtilValidate.isEmpty(userLoginId)) {
|
||||
GenericValue userLogin = (GenericValue) context.get("userLogin");
|
||||
if (userLogin != null) {
|
||||
userLoginId = userLogin.getString("userLoginId");
|
||||
}
|
||||
}
|
||||
if (UtilValidate.isEmpty(userLoginId) && returnDefault) {
|
||||
userLoginId = DEFAULT_UID;
|
||||
}
|
||||
return userLoginId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for valid userLoginId to get preferences. Returns true if valid.
|
||||
* <p>This method applies a small rule set to determine if user preferences
|
||||
* can be retrieved by the current user:
|
||||
* <ul>
|
||||
* <li>If the user isn't logged in, then the method returns true</li>
|
||||
* <li>If the user is logged in and the userPrefLoginId specified in the context Map
|
||||
* matches the user's userLoginId, then the method returns true.</li>
|
||||
* <li>If the user is logged in and the userPrefLoginId specified in the context Map
|
||||
* is different than the user's userLoginId, then a security permission check is performed.
|
||||
* If the user has the <a href="#ADMIN_PERMISSION">ADMIN_PERMISSION</a> permission then the
|
||||
* method returns true.</li>
|
||||
* </ul></p>
|
||||
*
|
||||
* @param ctx The DispatchContext that this service is operating in.
|
||||
* @param context Map containing the input arguments.
|
||||
* @return true if the userLoginId arguments are valid
|
||||
*/
|
||||
public static boolean isValidGetId(DispatchContext ctx, Map<String, ?> context) {
|
||||
String currentUserLoginId = null;
|
||||
GenericValue userLogin = (GenericValue) context.get("userLogin");
|
||||
if (userLogin == null) {
|
||||
currentUserLoginId = DEFAULT_UID;
|
||||
} else {
|
||||
currentUserLoginId = userLogin.getString("userLoginId");
|
||||
}
|
||||
String userLoginIdArg = (String) context.get(LOGINID_PARAMETER_NAME);
|
||||
if (!currentUserLoginId.equals(DEFAULT_UID) && !currentUserLoginId.equals(userLoginIdArg)
|
||||
&& userLoginIdArg != null) {
|
||||
Security security = ctx.getSecurity();
|
||||
return security.hasPermission(ADMIN_PERMISSION, userLogin);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for valid userLoginId to set preferences. Returns true if valid.
|
||||
* <p>This method applies a small rule set to determine if user preferences
|
||||
* can be set by the current user:
|
||||
* <ul>
|
||||
* <li>If the user isn't logged in, then the method returns false</li>
|
||||
* <li>If the user is logged in and the userPrefLoginId specified in the context Map
|
||||
* matches the user's userLoginId, then the method returns true.</li>
|
||||
* <li>If the user is logged in and the userPrefLoginId specified in the context Map
|
||||
* is different than the user's userLoginId, then a security permission check is performed.
|
||||
* If the user has the <a href="#ADMIN_PERMISSION">ADMIN_PERMISSION</a>
|
||||
* permission then the method returns true.</li>
|
||||
* </ul></p>
|
||||
* @param ctx The DispatchContext that this service is operating in.
|
||||
* @param context Map containing the input arguments.
|
||||
* @return true if arguments are valid
|
||||
*/
|
||||
public static boolean isValidSetId(DispatchContext ctx, Map<String, ?> context) {
|
||||
GenericValue userLogin = (GenericValue) context.get("userLogin");
|
||||
if (userLogin == null) {
|
||||
return false;
|
||||
}
|
||||
String currentUserLoginId = userLogin.getString("userLoginId");
|
||||
String userLoginIdArg = (String) context.get(LOGINID_PARAMETER_NAME);
|
||||
if (!currentUserLoginId.equals(userLoginIdArg) && userLoginIdArg != null) {
|
||||
Security security = ctx.getSecurity();
|
||||
return security.hasPermission(ADMIN_PERMISSION, userLogin);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a field Map to be used in GenericValue create or store methods.
|
||||
* @param userLoginId The user's login ID
|
||||
* @param userPrefTypeId The preference ID
|
||||
* @param userPrefGroupTypeId The preference group ID (may be null or empty)
|
||||
* @param userPrefValue The preference value (will be converted to java.lang.String data type)
|
||||
* @throws GeneralException
|
||||
* @return field map
|
||||
*/
|
||||
public static Map<String, Object> toFieldMap(String userLoginId, String userPrefTypeId, String userPrefGroupTypeId, Object userPrefValue) throws GeneralException {
|
||||
Map<String, Object> fieldMap = UtilMisc.toMap("userLoginId", userLoginId, "userPrefTypeId", userPrefTypeId, "userPrefValue", ObjectType.simpleTypeConvert(userPrefValue, "String", null, null, false));
|
||||
if (UtilValidate.isNotEmpty(userPrefGroupTypeId)) {
|
||||
fieldMap.put("userPrefGroupTypeId", userPrefGroupTypeId);
|
||||
}
|
||||
String valueDataType = userPrefValue.getClass().getName();
|
||||
if (!"java.lang.String".equals(valueDataType)) {
|
||||
fieldMap.put("userPrefDataType", valueDataType);
|
||||
}
|
||||
return fieldMap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.qrcode;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.lang.Integer;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.ofbiz.base.util.UtilHttp;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.service.GenericServiceException;
|
||||
import org.ofbiz.service.LocalDispatcher;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
|
||||
/**
|
||||
* Events for QRCode.
|
||||
*/
|
||||
public class QRCodeEvents {
|
||||
|
||||
public static final String module = QRCodeEvents.class.getName();
|
||||
|
||||
/** Streams QR Code to the output. */
|
||||
public static String serveQRCodeImage(HttpServletRequest request, HttpServletResponse response) {
|
||||
HttpSession session = ((HttpServletRequest) request).getSession();
|
||||
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
|
||||
Map<String, Object> parameters = UtilHttp.getParameterMap(request);
|
||||
String message = (String) parameters.get("message");
|
||||
GenericValue userLogin = (GenericValue) request.getAttribute("userLogin");
|
||||
if (userLogin == null) userLogin = (GenericValue) session.getAttribute("userLogin");
|
||||
if (userLogin == null) userLogin = (GenericValue) session.getAttribute("autoUserLogin");
|
||||
Locale locale = UtilHttp.getLocale(request);
|
||||
|
||||
if (UtilValidate.isEmpty(message)) {
|
||||
message = "Error get message parameter.";
|
||||
}
|
||||
String format = (String) parameters.get("format");
|
||||
if (UtilValidate.isEmpty(format)) {
|
||||
format = "jpg";
|
||||
}
|
||||
String mimeType = "image/" + format;
|
||||
String width = (String) parameters.get("width");
|
||||
String height = (String) parameters.get("height");
|
||||
String encoding = (String) parameters.get("encoding");
|
||||
Boolean verifyOutput = Boolean.valueOf((String) parameters.get("verifyOutput"));
|
||||
String logoImageMaxWidth = (String) parameters.get("logoImageMaxWidth");
|
||||
String logoImageMaxHeight = (String) parameters.get("logoImageMaxHeight");
|
||||
|
||||
try {
|
||||
if (mimeType != null) {
|
||||
response.setContentType(mimeType);
|
||||
}
|
||||
OutputStream os = response.getOutputStream();
|
||||
Map<String, Object> context = UtilMisc.<String, Object>toMap("message", message, "format", format, "userLogin", userLogin, "locale", locale);
|
||||
if (UtilValidate.isNotEmpty(width)) {
|
||||
try {
|
||||
context.put("width", Integer.parseInt(width));
|
||||
} catch (NumberFormatException e) {
|
||||
// do nothing
|
||||
}
|
||||
if (UtilValidate.isEmpty(height)) {
|
||||
try {
|
||||
context.put("height", Integer.parseInt(width));
|
||||
} catch (NumberFormatException e) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(height)) {
|
||||
try {
|
||||
context.put("height", Integer.parseInt(height));
|
||||
} catch (NumberFormatException e) {
|
||||
// do nothing
|
||||
}
|
||||
if (UtilValidate.isEmpty(width)) {
|
||||
try {
|
||||
context.put("width", Integer.parseInt(height));
|
||||
} catch (NumberFormatException e) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(encoding)) {
|
||||
context.put("encoding", encoding);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(verifyOutput) && verifyOutput.booleanValue()) {
|
||||
context.put("verifyOutput", verifyOutput);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(logoImageMaxWidth)) {
|
||||
try {
|
||||
context.put("logoImageMaxWidth", Integer.parseInt(logoImageMaxWidth));
|
||||
} catch (NumberFormatException e) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(logoImageMaxHeight)) {
|
||||
try {
|
||||
context.put("logoImageMaxHeight", Integer.parseInt(logoImageMaxHeight));
|
||||
} catch (NumberFormatException e) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
Map<String, Object> results = dispatcher.runSync("generateQRCodeImage", context);
|
||||
if (!ServiceUtil.isError(results)) {
|
||||
BufferedImage bufferedImage = (BufferedImage) results.get("bufferedImage");
|
||||
if (!ImageIO.write(bufferedImage, format, os)) {
|
||||
String errMsg = UtilProperties.getMessage("QRCodeUiLabels", "ErrorWriteFormatToFile", new Object[] { format }, locale);
|
||||
request.setAttribute("_ERROR_MESSAGE_", errMsg);
|
||||
return "error";
|
||||
}
|
||||
os.flush();
|
||||
} else {
|
||||
String errMsg = ServiceUtil.getErrorMessage(results);
|
||||
request.setAttribute("_ERROR_MESSAGE_", errMsg);
|
||||
return "error";
|
||||
}
|
||||
} catch (IOException e) {
|
||||
String errMsg = UtilProperties.getMessage("QRCodeUiLabels", "ErrorGenerateQRCode", new Object[] { e.getMessage() }, locale);
|
||||
request.setAttribute("_ERROR_MESSAGE_", errMsg);
|
||||
return "error";
|
||||
} catch (GenericServiceException e) {
|
||||
String errMsg = UtilProperties.getMessage("QRCodeUiLabels", "ErrorGenerateQRCode", new Object[] { e.getMessage() }, locale);
|
||||
request.setAttribute("_ERROR_MESSAGE_", errMsg);
|
||||
return "error";
|
||||
}
|
||||
return "success";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.qrcode;
|
||||
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.image.AffineTransformOp;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.io.IOException;
|
||||
import java.lang.Integer;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.FileUtil;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.common.image.ImageTransform;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
|
||||
import com.google.zxing.BarcodeFormat;
|
||||
import com.google.zxing.ChecksumException;
|
||||
import com.google.zxing.DecodeHintType;
|
||||
import com.google.zxing.EncodeHintType;
|
||||
import com.google.zxing.FormatException;
|
||||
import com.google.zxing.MultiFormatWriter;
|
||||
import com.google.zxing.NotFoundException;
|
||||
import com.google.zxing.WriterException;
|
||||
import com.google.zxing.common.BitMatrix;
|
||||
import com.google.zxing.common.DecoderResult;
|
||||
import com.google.zxing.common.DetectorResult;
|
||||
import com.google.zxing.qrcode.decoder.Decoder;
|
||||
import com.google.zxing.qrcode.detector.Detector;
|
||||
|
||||
import freemarker.template.utility.StringUtil;
|
||||
|
||||
/**
|
||||
* Services for QRCode.
|
||||
*/
|
||||
public class QRCodeServices {
|
||||
|
||||
public static final String module = QRCodeServices.class.getName();
|
||||
|
||||
public static final String QRCODE_DEFAULT_WIDTH = UtilProperties.getPropertyValue("qrcode", "qrcode.default.width", "200");
|
||||
|
||||
public static final String QRCODE_DEFAULT_HEIGHT = UtilProperties.getPropertyValue("qrcode", "qrcode.default.height", "200");
|
||||
|
||||
public static final String QRCODE_DEFAULT_FORMAT = UtilProperties.getPropertyValue("qrcode", "qrcode.default.format", "jpg");
|
||||
|
||||
public static final String QRCODE_FORMAT_SUPPORTED = UtilProperties.getPropertyValue("qrcode", "qrcode.format.supported", "jpg|png|bmp");
|
||||
|
||||
public static final String QRCODE_DEFAULT_LOGOIMAGE = UtilProperties.getPropertyValue("qrcode", "qrcode.default.logoimage");
|
||||
|
||||
public static BufferedImage defaultLogoImage;
|
||||
|
||||
public static final String[] FORMAT_NAMES = StringUtil.split(QRCODE_FORMAT_SUPPORTED, '|');
|
||||
|
||||
public static final List<String> FORMATS_SUPPORTED = Arrays.asList(FORMAT_NAMES);
|
||||
|
||||
public static final int MIN_SIZE = 20;
|
||||
|
||||
public static final int MAX_SIZE = 500;
|
||||
|
||||
private static final int BLACK = 0xFF000000;
|
||||
|
||||
private static final int WHITE = 0xFFFFFFFF;
|
||||
|
||||
static {
|
||||
if (UtilValidate.isNotEmpty(QRCODE_DEFAULT_LOGOIMAGE)) {
|
||||
try {
|
||||
Map<String, Object> logoImageResult = ImageTransform.getBufferedImage(FileUtil.getFile(QRCODE_DEFAULT_LOGOIMAGE).getAbsolutePath(), Locale.getDefault());
|
||||
defaultLogoImage = (BufferedImage) logoImageResult.get("bufferedImage");
|
||||
if (UtilValidate.isEmpty(defaultLogoImage)) {
|
||||
Debug.logError("Your logo image file(" + QRCODE_DEFAULT_LOGOIMAGE + ") cannot be read by javax.imageio.ImageIO. Please use png, jpeg formats instead of ico and etc.", module);
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
defaultLogoImage = null;
|
||||
} catch (IOException e) {
|
||||
defaultLogoImage = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Streams QR Code to the result. */
|
||||
public static Map<String, Object> generateQRCodeImage(DispatchContext ctx,Map<String, Object> context) {
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
String message = (String) context.get("message");
|
||||
Integer width = (Integer) context.get("width");
|
||||
Integer height = (Integer) context.get("height");
|
||||
String format = (String) context.get("format");
|
||||
String encoding = (String) context.get("encoding");
|
||||
Boolean verifyOutput = (Boolean) context.get("verifyOutput");
|
||||
String logoImage = (String) context.get("logoImage");
|
||||
Integer logoImageMaxWidth = (Integer) context.get("logoImageMaxWidth");
|
||||
Integer logoImageMaxHeight = (Integer) context.get("logoImageMaxHeight");
|
||||
|
||||
if (UtilValidate.isEmpty(message)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ParameterCannotEmpty", new Object[] { "message" }, locale));
|
||||
}
|
||||
if (width == null) {
|
||||
width = Integer.parseInt(QRCODE_DEFAULT_WIDTH);
|
||||
}
|
||||
if (width.intValue() < MIN_SIZE || width.intValue() > MAX_SIZE) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "SizeOutOfBorderError", new Object[] {"width", String.valueOf(width), String.valueOf(MIN_SIZE), String.valueOf(MAX_SIZE)}, locale));
|
||||
}
|
||||
if (height == null) {
|
||||
height = Integer.parseInt(QRCODE_DEFAULT_HEIGHT);
|
||||
}
|
||||
if (height.intValue() < MIN_SIZE || height.intValue() > MAX_SIZE) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "SizeOutOfBorderError",
|
||||
new Object[] { "height", String.valueOf(height), String.valueOf(MIN_SIZE), String.valueOf(MAX_SIZE) }, locale));
|
||||
}
|
||||
if (UtilValidate.isEmpty(format)) {
|
||||
format = QRCODE_DEFAULT_FORMAT;
|
||||
}
|
||||
if (!FORMATS_SUPPORTED.contains(format)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorFormatNotSupported", new Object[] { format }, locale));
|
||||
}
|
||||
Map<EncodeHintType, Object> encodeHints = null;
|
||||
if (UtilValidate.isNotEmpty(encoding)) {
|
||||
encodeHints = new EnumMap<>(EncodeHintType.class);
|
||||
encodeHints.put(EncodeHintType.CHARACTER_SET, encoding);
|
||||
}
|
||||
|
||||
try {
|
||||
BitMatrix bitMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, width, height, encodeHints);
|
||||
BufferedImage bufferedImage = toBufferedImage(bitMatrix, format);
|
||||
BufferedImage logoBufferedImage = null;
|
||||
if (UtilValidate.isNotEmpty(logoImage)) {
|
||||
Map<String, Object> logoImageResult;
|
||||
try {
|
||||
logoImageResult = ImageTransform.getBufferedImage(FileUtil.getFile(logoImage).getAbsolutePath(), locale);
|
||||
logoBufferedImage = (BufferedImage) logoImageResult.get("bufferedImage");
|
||||
} catch (IllegalArgumentException e) {
|
||||
// do nothing
|
||||
} catch (IOException e) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
if (UtilValidate.isEmpty(logoBufferedImage)) {
|
||||
logoBufferedImage = defaultLogoImage;
|
||||
}
|
||||
|
||||
BufferedImage newBufferedImage = null;
|
||||
if (UtilValidate.isNotEmpty(logoBufferedImage)) {
|
||||
if (UtilValidate.isNotEmpty(logoImageMaxWidth) && UtilValidate.isNotEmpty(logoImageMaxHeight) && (logoBufferedImage.getWidth() > logoImageMaxWidth.intValue() || logoBufferedImage.getHeight() > logoImageMaxHeight.intValue())) {
|
||||
Map<String, String> typeMap = new HashMap<String, String>();
|
||||
typeMap.put("width", logoImageMaxWidth.toString());
|
||||
typeMap.put("height", logoImageMaxHeight.toString());
|
||||
Map<String, Map<String, String>> dimensionMap = new HashMap<String, Map<String, String>>();
|
||||
dimensionMap.put("QRCode", typeMap);
|
||||
Map<String, Object> logoImageResult = ImageTransform.scaleImage(logoBufferedImage, (double) logoBufferedImage.getWidth(), (double) logoBufferedImage.getHeight(), dimensionMap, "QRCode", locale);
|
||||
logoBufferedImage = (BufferedImage) logoImageResult.get("bufferedImage");
|
||||
}
|
||||
BitMatrix newBitMatrix = bitMatrix.clone();
|
||||
newBufferedImage = toBufferedImage(newBitMatrix, format);
|
||||
Graphics2D graphics = newBufferedImage.createGraphics();
|
||||
graphics.drawImage(logoBufferedImage, new AffineTransformOp(AffineTransform.getTranslateInstance(1, 1), null), (newBufferedImage.getWidth() - logoBufferedImage.getWidth())/2, (newBufferedImage.getHeight() - logoBufferedImage.getHeight())/2);
|
||||
graphics.dispose();
|
||||
}
|
||||
|
||||
if (UtilValidate.isNotEmpty(verifyOutput) && verifyOutput.booleanValue()) {
|
||||
// Debug.logInfo("Original Message:[" + message + "]", module);
|
||||
Decoder decoder = new Decoder();
|
||||
Map<DecodeHintType, Object> decodeHints = new EnumMap<>(DecodeHintType.class);
|
||||
decodeHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
|
||||
if (UtilValidate.isNotEmpty(encoding)) {
|
||||
decodeHints.put(DecodeHintType.CHARACTER_SET, encoding);
|
||||
}
|
||||
DetectorResult detectorResult = null;
|
||||
if (UtilValidate.isNotEmpty(newBufferedImage)) {
|
||||
BitMatrix newBitMatrix = createMatrixFromImage(newBufferedImage);
|
||||
DecoderResult result = null;
|
||||
try {
|
||||
detectorResult = new Detector(newBitMatrix).detect(decodeHints);
|
||||
result = decoder.decode(detectorResult.getBits(), decodeHints);
|
||||
} catch (ChecksumException e) {
|
||||
// do nothing
|
||||
} catch (FormatException e) {
|
||||
// do nothing
|
||||
} catch (NotFoundException e) {
|
||||
// do nothing
|
||||
}
|
||||
// Debug.logInfo("Text in QR Code with logo:[" + result.getText() + "]", module);
|
||||
if (UtilValidate.isNotEmpty(result) && !result.getText().equals(message)) {
|
||||
detectorResult = new Detector(bitMatrix).detect(decodeHints);
|
||||
result = decoder.decode(detectorResult.getBits(), decodeHints);
|
||||
// Debug.logInfo("Text in QR Code without logo:[" + result.getText() + "]", module);
|
||||
if (!result.getText().equals(message)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "GeneratedTextNotMatchOriginal", new Object[]{result.getText(), message}, locale));
|
||||
}
|
||||
} else {
|
||||
bufferedImage = newBufferedImage;
|
||||
}
|
||||
} else {
|
||||
detectorResult = new Detector(bitMatrix).detect(decodeHints);
|
||||
DecoderResult result = decoder.decode(detectorResult.getBits(), decodeHints);
|
||||
// Debug.logInfo("Text in QR Code:[" + result.getText() + "]", module);
|
||||
if (!result.getText().equals(message)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "GeneratedTextNotMatchOriginal", new Object[]{result.getText(), message}, locale));
|
||||
}
|
||||
}
|
||||
} else if (UtilValidate.isNotEmpty(newBufferedImage)) {
|
||||
bufferedImage = newBufferedImage;
|
||||
}
|
||||
|
||||
Map<String, Object> result = ServiceUtil.returnSuccess();
|
||||
result.put("bufferedImage", bufferedImage);
|
||||
return result;
|
||||
} catch (WriterException e) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorGenerateQRCode", new Object[] { e.toString() }, locale));
|
||||
} catch (ChecksumException e) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorVerifyQRCode", new Object[] { e.toString() }, locale));
|
||||
} catch (FormatException e) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorVerifyQRCode", new Object[] { e.toString() }, locale));
|
||||
} catch (NotFoundException e) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorVerifyQRCode", new Object[] { e.toString() }, locale));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a {@link BitMatrix} as an image, where "false" bits are rendered
|
||||
* as white, and "true" bits are rendered as black.
|
||||
*
|
||||
* This is to replace MatrixToImageWriter.toBufferedImage(bitMatrix) if you
|
||||
* find the output image is not right, you can change BufferedImage image =
|
||||
* new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); to
|
||||
* BufferedImage image = new BufferedImage(width, height,
|
||||
* BufferedImage.TYPE_INT_RGB); or others to make it work correctly.
|
||||
*/
|
||||
private static BufferedImage toBufferedImage(BitMatrix matrix, String format) {
|
||||
int width = matrix.getWidth();
|
||||
int height = matrix.getHeight();
|
||||
BufferedImage image = null;
|
||||
String osName = System.getProperty("os.name").toLowerCase();
|
||||
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
if (osName.startsWith("mac os") && format.equals("png")) {
|
||||
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
|
||||
}
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
private static BitMatrix createMatrixFromImage(BufferedImage image) {
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
int[] pixels = new int[width * height];
|
||||
image.getRGB(0, 0, width, height, pixels, 0, width);
|
||||
|
||||
BitMatrix matrix = new BitMatrix(width, height);
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
int pixel = pixels[y * width + x];
|
||||
int luminance = (306 * ((pixel >> 16) & 0xFF) +
|
||||
601 * ((pixel >> 8) & 0xFF) +
|
||||
117 * (pixel & 0xFF)) >> 10;
|
||||
if (luminance <= 0x7F) {
|
||||
matrix.set(x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
return matrix;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.scripting;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Locale;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import javax.script.ScriptContext;
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.ofbiz.base.util.Assert;
|
||||
import org.ofbiz.base.util.ScriptUtil;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.collections.FlexibleMapAccessor;
|
||||
import org.ofbiz.base.util.string.FlexibleStringExpander;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.security.Security;
|
||||
import org.ofbiz.service.LocalDispatcher;
|
||||
import org.ofbiz.service.ModelService;
|
||||
|
||||
/**
|
||||
* A set of <code>ScriptContext</code> convenience methods for scripting engines.
|
||||
*/
|
||||
public final class ContextHelper {
|
||||
|
||||
public static final String module = ContextHelper.class.getName();
|
||||
private static final int EVENT = 1;
|
||||
private static final int SERVICE = 2;
|
||||
private static final int UNKNOWN = 3;
|
||||
|
||||
private final ScriptContext context;
|
||||
private final int scriptType;
|
||||
|
||||
public ContextHelper(ScriptContext context) {
|
||||
Assert.notNull("context", context);
|
||||
this.context = context;
|
||||
if (context.getAttribute("request") != null) {
|
||||
this.scriptType = EVENT;
|
||||
} else if (context.getAttribute("dctx") != null) {
|
||||
this.scriptType = SERVICE;
|
||||
} else {
|
||||
this.scriptType = UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
public Object addBinding(String key, Object value) {
|
||||
return getBindings().put(key, value);
|
||||
}
|
||||
|
||||
/** Expands environment variables delimited with ${} */
|
||||
public String expandString(String original) {
|
||||
return FlexibleStringExpander.expandString(original, getBindings());
|
||||
}
|
||||
|
||||
public Map<String, Object> getBindings() {
|
||||
return this.context.getBindings(ScriptContext.ENGINE_SCOPE);
|
||||
}
|
||||
|
||||
public Delegator getDelegator() {
|
||||
return (Delegator) this.context.getAttribute("delegator");
|
||||
}
|
||||
|
||||
public LocalDispatcher getDispatcher() {
|
||||
return (LocalDispatcher) this.context.getAttribute("dispatcher");
|
||||
}
|
||||
|
||||
public <T> T getEnv(FlexibleMapAccessor<T> fma) {
|
||||
return fma.get(getBindings());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the named value from the environment. Supports the "." (dot) syntax to access
|
||||
* Map members and the "[]" (bracket) syntax to access List entries. This value is
|
||||
* expanded, supporting the insertion of other environment values using the "${}"
|
||||
* notation.
|
||||
*
|
||||
* @param key
|
||||
* The name of the environment value to get. Can contain "." and "[]"
|
||||
* syntax elements as described above.
|
||||
* @return The environment value if found, otherwise null.
|
||||
*/
|
||||
public <T> T getEnv(String key) {
|
||||
String ekey = this.expandString(key);
|
||||
FlexibleMapAccessor<T> fma = FlexibleMapAccessor.getInstance(ekey);
|
||||
return getEnv(fma);
|
||||
}
|
||||
|
||||
public List<String> getErrorMessages() {
|
||||
List<String> errorMessages = null;
|
||||
if (isService()) {
|
||||
errorMessages = UtilGenerics.checkList(getResults().get(ModelService.ERROR_MESSAGE_LIST));
|
||||
if (errorMessages == null) {
|
||||
errorMessages = new LinkedList<String>();
|
||||
getResults().put(ModelService.ERROR_MESSAGE_LIST, errorMessages);
|
||||
}
|
||||
} else {
|
||||
errorMessages = UtilGenerics.checkList(getResults().get("_error_message_list_"));
|
||||
if (errorMessages == null) {
|
||||
errorMessages = new LinkedList<String>();
|
||||
getResults().put("_error_message_list_", errorMessages);
|
||||
}
|
||||
}
|
||||
return errorMessages;
|
||||
}
|
||||
|
||||
public Iterator<Map.Entry<String, Object>> getEnvEntryIterator() {
|
||||
return getBindings().entrySet().iterator();
|
||||
}
|
||||
|
||||
public Locale getLocale() {
|
||||
return (Locale) this.context.getAttribute("locale");
|
||||
}
|
||||
|
||||
public Object getParameter(String key) {
|
||||
return getParameters().get(key);
|
||||
}
|
||||
|
||||
public Map<String, Object> getParameters() {
|
||||
Map<String, Object> parameters = UtilGenerics.checkMap(this.context.getAttribute(ScriptUtil.PARAMETERS_KEY));
|
||||
if (parameters == null) {
|
||||
parameters = new LinkedHashMap<String, Object>();
|
||||
this.context.setAttribute(ScriptUtil.PARAMETERS_KEY, parameters, ScriptContext.ENGINE_SCOPE);
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
public HttpServletRequest getRequest() {
|
||||
return (HttpServletRequest) this.context.getAttribute("request");
|
||||
}
|
||||
|
||||
public HttpServletResponse getResponse() {
|
||||
return (HttpServletResponse) this.context.getAttribute("response");
|
||||
}
|
||||
|
||||
public Object getResult(String key) {
|
||||
return getResults().get(key);
|
||||
}
|
||||
|
||||
public Map<String, Object> getResults() {
|
||||
Map<String, Object> results = UtilGenerics.checkMap(this.context.getAttribute(ScriptUtil.RESULT_KEY));
|
||||
if (results == null) {
|
||||
results = new LinkedHashMap<String, Object>();
|
||||
this.context.setAttribute(ScriptUtil.RESULT_KEY, results, ScriptContext.ENGINE_SCOPE);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public String getScriptName() {
|
||||
String scriptName = (String) this.context.getAttribute(ScriptEngine.FILENAME);
|
||||
return scriptName != null ? scriptName : "Unknown";
|
||||
}
|
||||
|
||||
public Security getSecurity() {
|
||||
return (Security) this.context.getAttribute("security");
|
||||
}
|
||||
|
||||
public TimeZone getTimeZone() {
|
||||
return (TimeZone) this.context.getAttribute("timeZone");
|
||||
}
|
||||
|
||||
public GenericValue getUserLogin() {
|
||||
return (GenericValue) this.context.getAttribute("userLogin");
|
||||
}
|
||||
|
||||
public boolean isEvent() {
|
||||
return this.scriptType == EVENT;
|
||||
}
|
||||
|
||||
public boolean isService() {
|
||||
return this.scriptType == SERVICE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls putEnv for each entry in the Map, thus allowing for the additional
|
||||
* flexibility in naming supported in that method.
|
||||
*/
|
||||
public void putAllEnv(Map<String, ? extends Object> values) {
|
||||
for (Map.Entry<String, ? extends Object> entry : values.entrySet()) {
|
||||
this.putEnv(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
public <T> void putEnv(FlexibleMapAccessor<T> fma, T value) {
|
||||
fma.put(getBindings(), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the named value in the environment. Supports the "." (dot) syntax to access
|
||||
* Map members and the "[]" (bracket) syntax to access List entries. If the brackets
|
||||
* for a list are empty the value will be appended to end of the list, otherwise the
|
||||
* value will be set in the position of the number in the brackets. If a "+" (plus
|
||||
* sign) is included inside the square brackets before the index number the value will
|
||||
* inserted/added at that index instead of set at that index. This value is expanded,
|
||||
* supporting the insertion of other environment values using the "${}" notation.
|
||||
*
|
||||
* @param key
|
||||
* The name of the environment value to get. Can contain "." syntax
|
||||
* elements as described above.
|
||||
* @param value
|
||||
* The value to set in the named environment location.
|
||||
*/
|
||||
public <T> void putEnv(String key, T value) {
|
||||
String ekey = this.expandString(key);
|
||||
FlexibleMapAccessor<T> fma = FlexibleMapAccessor.getInstance(ekey);
|
||||
this.putEnv(fma, value);
|
||||
}
|
||||
|
||||
public void putParameter(String key, Object value) {
|
||||
getParameters().put(key, value);
|
||||
}
|
||||
|
||||
public void putResult(String key, Object value) {
|
||||
getResults().put(key, value);
|
||||
}
|
||||
|
||||
public void putResults(Map<String, Object> results) {
|
||||
getResults().putAll(results);
|
||||
}
|
||||
|
||||
public Object removeBinding(String key) {
|
||||
return getBindings().remove(key);
|
||||
}
|
||||
|
||||
public <T> T removeEnv(FlexibleMapAccessor<T> fma) {
|
||||
return fma.remove(getBindings());
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the named value from the environment. Supports the "." (dot) syntax to
|
||||
* access Map members and the "[]" (bracket) syntax to access List entries. This value
|
||||
* is expanded, supporting the insertion of other environment values using the "${}"
|
||||
* notation.
|
||||
*
|
||||
* @param key
|
||||
* The name of the environment value to get. Can contain "." syntax
|
||||
* elements as described above.
|
||||
*/
|
||||
public <T> T removeEnv(String key) {
|
||||
String ekey = this.expandString(key);
|
||||
FlexibleMapAccessor<T> fma = FlexibleMapAccessor.getInstance(ekey);
|
||||
return removeEnv(fma);
|
||||
}
|
||||
|
||||
public void setUserLogin(GenericValue userLogin, String userLoginEnvName) {
|
||||
putEnv(userLoginEnvName, userLogin);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.scripting;
|
||||
|
||||
import javax.script.ScriptContext;
|
||||
|
||||
import org.ofbiz.base.util.ScriptHelper;
|
||||
import org.ofbiz.base.util.ScriptHelperFactory;
|
||||
|
||||
/**
|
||||
* An implementation of the <code>ScriptHelperFactory</code> interface.
|
||||
*/
|
||||
public final class ScriptHelperFactoryImpl implements ScriptHelperFactory {
|
||||
|
||||
@Override
|
||||
public ScriptHelper getInstance(ScriptContext context) {
|
||||
return new ScriptHelperImpl(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.scripting;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.script.ScriptContext;
|
||||
import javax.script.ScriptException;
|
||||
|
||||
import org.ofbiz.base.util.Assert;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.ScriptHelper;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericPK;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.ofbiz.service.GenericServiceException;
|
||||
import org.ofbiz.service.ModelService;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
|
||||
/**
|
||||
* An implementation of the <code>ScriptHelper</code> interface.
|
||||
*/
|
||||
public final class ScriptHelperImpl implements ScriptHelper {
|
||||
|
||||
public static final String module = ScriptHelperImpl.class.getName();
|
||||
private static final Map<String, ? extends Object> EMPTY_ARGS = Collections.unmodifiableMap(new HashMap<String, Object>());
|
||||
|
||||
private static GenericValue runFindByPrimaryKey(ModelEntity modelEntity, ContextHelper ctxHelper, boolean useCache, boolean autoFieldMap,
|
||||
Map<String, ? extends Object> fieldMap, List<String> selectFieldList) throws ScriptException {
|
||||
Map<String, Object> entityContext = new HashMap<String, Object>();
|
||||
Delegator delegator = ctxHelper.getDelegator();
|
||||
Map<String, Object> context = ctxHelper.getBindings();
|
||||
if (autoFieldMap) {
|
||||
GenericValue tempVal = delegator.makeValue(modelEntity.getEntityName());
|
||||
Object parametersObj = context.get("parameters");
|
||||
if (parametersObj != null && parametersObj instanceof Map<?, ?>) {
|
||||
tempVal.setAllFields(UtilGenerics.checkMap(parametersObj), true, null, Boolean.TRUE);
|
||||
}
|
||||
tempVal.setAllFields(context, true, null, Boolean.TRUE);
|
||||
entityContext.putAll(tempVal);
|
||||
}
|
||||
if (fieldMap != null) {
|
||||
entityContext.putAll(fieldMap);
|
||||
}
|
||||
entityContext.put("locale", context.get("locale"));
|
||||
entityContext.put("timeZone", context.get("timeZone"));
|
||||
modelEntity.convertFieldMapInPlace(entityContext, delegator);
|
||||
entityContext.remove("locale");
|
||||
entityContext.remove("timeZone");
|
||||
Set<String> fieldsToSelect = null;
|
||||
if (selectFieldList != null) {
|
||||
fieldsToSelect = new HashSet<String>(selectFieldList);
|
||||
}
|
||||
if (fieldsToSelect != null && useCache) {
|
||||
String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the findOne method: Cannot specify selectFieldList argument when useCache is set to true ";
|
||||
Debug.logWarning(errMsg, module);
|
||||
throw new ScriptException(errMsg);
|
||||
}
|
||||
GenericValue valueOut = null;
|
||||
GenericPK entityPK = delegator.makePK(modelEntity.getEntityName(), entityContext);
|
||||
if (entityPK.containsPrimaryKey(true)) {
|
||||
try {
|
||||
if (useCache) {
|
||||
valueOut = EntityQuery.use(delegator).from(entityPK.getEntityName()).where(entityPK).cache(true).queryOne();
|
||||
} else {
|
||||
if (fieldsToSelect != null) {
|
||||
valueOut = delegator.findByPrimaryKeyPartial(entityPK, fieldsToSelect);
|
||||
} else {
|
||||
valueOut = EntityQuery.use(delegator).from(entityPK.getEntityName()).where(entityPK).queryOne();
|
||||
}
|
||||
}
|
||||
} catch (GenericEntityException e) {
|
||||
String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the findOne method: " + e.getMessage();
|
||||
Debug.logWarning(e, errMsg, module);
|
||||
throw new ScriptException(errMsg);
|
||||
}
|
||||
} else {
|
||||
if (Debug.warningOn()) {
|
||||
Debug.logWarning("Error running script " + ctxHelper.getScriptName() + ": Returning null because found incomplete primary key in find: " + entityPK, module);
|
||||
}
|
||||
}
|
||||
return valueOut;
|
||||
}
|
||||
|
||||
private final ContextHelper ctxHelper;
|
||||
|
||||
public ScriptHelperImpl(ScriptContext context) {
|
||||
this.ctxHelper = new ContextHelper(context);
|
||||
}
|
||||
|
||||
public Map<String, ? extends Object> createServiceMap(String serviceName, Map<String, ? extends Object> inputMap) throws ScriptException {
|
||||
Assert.notNull("serviceName", serviceName, "inputMap", inputMap);
|
||||
Map<String, Object> toMap = new HashMap<String, Object>();
|
||||
ModelService modelService = null;
|
||||
try {
|
||||
modelService = ctxHelper.getDispatcher().getDispatchContext().getModelService(serviceName);
|
||||
} catch (GenericServiceException e) {
|
||||
String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the createServiceMap method: get service definition for service name [" + serviceName + "]: " + e.getMessage();
|
||||
Debug.logWarning(e, errMsg, module);
|
||||
throw new ScriptException(errMsg);
|
||||
}
|
||||
toMap.putAll(modelService.makeValid(inputMap, "IN", true, UtilGenerics.checkList(ctxHelper.getErrorMessages()), ctxHelper.getTimeZone(), ctxHelper.getLocale()));
|
||||
return toMap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String message) {
|
||||
if (ctxHelper.isEvent()) {
|
||||
ctxHelper.putResult("_error_message_", ctxHelper.expandString(message));
|
||||
ctxHelper.putResult("_response_code_", "error");
|
||||
} else if (ctxHelper.isService()) {
|
||||
ctxHelper.putResults(ServiceUtil.returnError(ctxHelper.expandString(message)));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String evalString(String original) {
|
||||
return ctxHelper.expandString(original);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failure(String message) {
|
||||
if (ctxHelper.isEvent()) {
|
||||
ctxHelper.putResult("_error_message_", ctxHelper.expandString(message));
|
||||
ctxHelper.putResult("_response_code_", "fail");
|
||||
} else if (ctxHelper.isService()) {
|
||||
ctxHelper.putResults(ServiceUtil.returnFailure(ctxHelper.expandString(message)));
|
||||
}
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findList(String entityName, Map<String, ? extends Object> fields) throws ScriptException {
|
||||
try {
|
||||
return UtilGenerics.checkList(ctxHelper.getDelegator().findByAnd(entityName, fields, null, false));
|
||||
} catch (GenericEntityException e) {
|
||||
String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the findList method: " + e.getMessage();
|
||||
Debug.logWarning(e, errMsg, module);
|
||||
throw new ScriptException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> findOne(String entityName) throws ScriptException {
|
||||
return findOne(entityName, null, EMPTY_ARGS);
|
||||
}
|
||||
|
||||
public Map<String, Object> findOne(String entityName, Map<String, ? extends Object> fields, Map<String, ? extends Object> args) throws ScriptException {
|
||||
Assert.notNull("entityName", entityName);
|
||||
if (args == null) {
|
||||
args = EMPTY_ARGS;
|
||||
}
|
||||
boolean useCache = "true".equals(args.get("useCache"));
|
||||
boolean autoFieldMap = !"false".equals(args.get("autoFieldMap"));
|
||||
List<String> selectFieldList = UtilGenerics.checkList(args.get("selectFieldList"));
|
||||
ModelEntity modelEntity = ctxHelper.getDelegator().getModelEntity(entityName);
|
||||
if (modelEntity == null) {
|
||||
throw new ScriptException("Error running script " + ctxHelper.getScriptName() + " - no entity definition found for entity name [" + entityName + "]");
|
||||
}
|
||||
return runFindByPrimaryKey(modelEntity, ctxHelper, useCache, autoFieldMap, fields, selectFieldList);
|
||||
}
|
||||
|
||||
public void logError(String message) {
|
||||
String expandedMessage = ctxHelper.expandString(message);
|
||||
Debug.logError("[".concat(ctxHelper.getScriptName()).concat("] ").concat(expandedMessage), module);
|
||||
}
|
||||
|
||||
public void logInfo(String message) {
|
||||
String expandedMessage = ctxHelper.expandString(message);
|
||||
Debug.logInfo("[".concat(ctxHelper.getScriptName()).concat("] ").concat(expandedMessage), module);
|
||||
}
|
||||
|
||||
public void logWarning(String message) {
|
||||
String expandedMessage = ctxHelper.expandString(message);
|
||||
Debug.logWarning("[".concat(ctxHelper.getScriptName()).concat("] ").concat(expandedMessage), module);
|
||||
}
|
||||
|
||||
public Map<String, Object> makeValue(String entityName) throws ScriptException {
|
||||
return ctxHelper.getDelegator().makeValidValue(entityName);
|
||||
}
|
||||
|
||||
public Map<String, Object> makeValue(String entityName, Map<String, Object> fields) throws ScriptException {
|
||||
return ctxHelper.getDelegator().makeValidValue(entityName, fields);
|
||||
}
|
||||
|
||||
public Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap) throws ScriptException {
|
||||
return runService(serviceName, inputMap, EMPTY_ARGS);
|
||||
}
|
||||
|
||||
public Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap, Map<String, ? extends Object> args) throws ScriptException {
|
||||
Assert.notNull("serviceName", serviceName, "args", args);
|
||||
boolean includeUserLogin = !"false".equals(args.get("includeUserLoginStr"));
|
||||
String requireNewTransactionStr = (String) args.get("requireNewTransaction");
|
||||
int transactionTimeout = -1;
|
||||
if (UtilValidate.isNotEmpty(requireNewTransactionStr)) {
|
||||
String timeoutStr = (String) args.get("transactionTimout");
|
||||
if (!UtilValidate.isEmpty(timeoutStr)) {
|
||||
try {
|
||||
transactionTimeout = Integer.parseInt(timeoutStr);
|
||||
} catch (NumberFormatException e) {
|
||||
Debug.logWarning(e, "Setting timeout to 0 (default)", module);
|
||||
transactionTimeout = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
Map<String, Object> inMap = new HashMap<String, Object>(inputMap);
|
||||
if (includeUserLogin && !inMap.containsKey("userLogin")) {
|
||||
GenericValue userLogin = ctxHelper.getUserLogin();
|
||||
if (userLogin != null) {
|
||||
inMap.put("userLogin", userLogin);
|
||||
}
|
||||
}
|
||||
if (!inMap.containsKey("locale") && ctxHelper.getLocale() != null) {
|
||||
inMap.put("locale", ctxHelper.getLocale());
|
||||
}
|
||||
if (!inMap.containsKey("timeZone") && ctxHelper.getTimeZone() != null) {
|
||||
inMap.put("timeZone", ctxHelper.getTimeZone());
|
||||
}
|
||||
Map<String, Object> result = null;
|
||||
try {
|
||||
if (UtilValidate.isEmpty(requireNewTransactionStr) && transactionTimeout < 0) {
|
||||
result = ctxHelper.getDispatcher().runSync(serviceName, inMap);
|
||||
} else {
|
||||
ModelService modelService = ctxHelper.getDispatcher().getDispatchContext().getModelService(serviceName);
|
||||
boolean requireNewTransaction = modelService.requireNewTransaction;
|
||||
int timeout = modelService.transactionTimeout;
|
||||
if (UtilValidate.isNotEmpty(requireNewTransactionStr)) {
|
||||
requireNewTransaction = "true".equals(requireNewTransactionStr);
|
||||
}
|
||||
if (transactionTimeout >= 0) {
|
||||
timeout = transactionTimeout;
|
||||
}
|
||||
result = ctxHelper.getDispatcher().runSync(serviceName, inMap, timeout, requireNewTransaction);
|
||||
}
|
||||
} catch (GenericServiceException e) {
|
||||
String errMsg = "Error running script " + ctxHelper.getScriptName() + " [problem invoking the [" + serviceName + "] service: " + e.getMessage();
|
||||
Debug.logWarning(e, errMsg, module);
|
||||
throw new ScriptException(errMsg);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void success() {
|
||||
if (ctxHelper.isEvent()) {
|
||||
ctxHelper.putResult("_response_code_", "success");
|
||||
} else if (ctxHelper.isService()) {
|
||||
ctxHelper.putResults(ServiceUtil.returnSuccess());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void success(String message) {
|
||||
if (ctxHelper.isEvent()) {
|
||||
ctxHelper.putResult("_event_message_", ctxHelper.expandString(message));
|
||||
ctxHelper.putResult("_response_code_", "success");
|
||||
} else if (ctxHelper.isService()) {
|
||||
ctxHelper.putResults(ServiceUtil.returnSuccess(ctxHelper.expandString(message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.status;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
|
||||
import static org.ofbiz.base.util.UtilGenerics.checkList;
|
||||
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.ofbiz.service.DispatchContext;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
|
||||
/**
|
||||
* StatusServices
|
||||
*/
|
||||
public class StatusServices {
|
||||
|
||||
public static final String module = StatusServices.class.getName();
|
||||
public static final String resource = "CommonUiLabels";
|
||||
|
||||
public static Map<String, Object> getStatusItems(DispatchContext ctx, Map<String, ?> context) {
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
List<String> statusTypes = checkList(context.get("statusTypeIds"), String.class);
|
||||
Locale locale = (Locale) context.get("locale");
|
||||
if (UtilValidate.isEmpty(statusTypes)) {
|
||||
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonStatusMandatory", locale));
|
||||
}
|
||||
|
||||
List<GenericValue> statusItems = new LinkedList<GenericValue>();
|
||||
for (String statusTypeId: statusTypes) {
|
||||
try {
|
||||
List<GenericValue> myStatusItems = EntityQuery.use(delegator)
|
||||
.from("StatusItem")
|
||||
.where("statusTypeId", statusTypeId)
|
||||
.orderBy("sequenceId")
|
||||
.cache(true)
|
||||
.queryList();
|
||||
statusItems.addAll(myStatusItems);
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
Map<String, Object> ret = new LinkedHashMap<String, Object>();
|
||||
ret.put("statusItems",statusItems);
|
||||
return ret;
|
||||
}
|
||||
|
||||
public static Map<String, Object> getStatusValidChangeToDetails(DispatchContext ctx, Map<String, ?> context) {
|
||||
Delegator delegator = ctx.getDelegator();
|
||||
List<GenericValue> statusValidChangeToDetails = null;
|
||||
String statusId = (String) context.get("statusId");
|
||||
try {
|
||||
statusValidChangeToDetails = EntityQuery.use(delegator)
|
||||
.from("StatusValidChangeToDetail")
|
||||
.where("statusId", statusId)
|
||||
.orderBy("sequenceId")
|
||||
.cache(true)
|
||||
.queryList();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
Map<String, Object> ret = ServiceUtil.returnSuccess();
|
||||
if (statusValidChangeToDetails != null) {
|
||||
ret.put("statusValidChangeToDetails", statusValidChangeToDetails);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.status;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.jsp.PageContext;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
|
||||
/**
|
||||
* StatusWorker
|
||||
*/
|
||||
public final class StatusWorker {
|
||||
|
||||
public static final String module = StatusWorker.class.getName();
|
||||
|
||||
private StatusWorker() {}
|
||||
|
||||
public static void getStatusItems(PageContext pageContext, String attributeName, String statusTypeId) {
|
||||
Delegator delegator = (Delegator) pageContext.getRequest().getAttribute("delegator");
|
||||
|
||||
try {
|
||||
List<GenericValue> statusItems = EntityQuery.use(delegator)
|
||||
.from("StatusItem")
|
||||
.where("statusTypeId", statusTypeId)
|
||||
.orderBy("sequenceId")
|
||||
.cache(true)
|
||||
.queryList();
|
||||
if (statusItems != null)
|
||||
pageContext.setAttribute(attributeName, statusItems);
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
|
||||
public static void getStatusItems(PageContext pageContext, String attributeName, String statusTypeIdOne, String statusTypeIdTwo) {
|
||||
Delegator delegator = (Delegator) pageContext.getRequest().getAttribute("delegator");
|
||||
List<GenericValue> statusItems = new LinkedList<GenericValue>();
|
||||
|
||||
try {
|
||||
List<GenericValue> calItems = EntityQuery.use(delegator)
|
||||
.from("StatusItem")
|
||||
.where("statusTypeId", statusTypeIdOne)
|
||||
.orderBy("sequenceId")
|
||||
.cache(true)
|
||||
.queryList();
|
||||
if (calItems != null)
|
||||
statusItems.addAll(calItems);
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
try {
|
||||
List<GenericValue> taskItems = EntityQuery.use(delegator)
|
||||
.from("StatusItem")
|
||||
.where("statusTypeId", statusTypeIdTwo)
|
||||
.orderBy("sequenceId")
|
||||
.cache(true)
|
||||
.queryList();
|
||||
if (taskItems != null)
|
||||
statusItems.addAll(taskItems);
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
|
||||
if (statusItems.size() > 0)
|
||||
pageContext.setAttribute(attributeName, statusItems);
|
||||
}
|
||||
|
||||
public static void getStatusValidChangeToDetails(PageContext pageContext, String attributeName, String statusId) {
|
||||
Delegator delegator = (Delegator) pageContext.getRequest().getAttribute("delegator");
|
||||
List<GenericValue> statusValidChangeToDetails = null;
|
||||
|
||||
try {
|
||||
statusValidChangeToDetails = EntityQuery.use(delegator)
|
||||
.from("StatusValidChangeToDetail")
|
||||
.where("statusId", statusId)
|
||||
.orderBy("sequenceId")
|
||||
.cache(true)
|
||||
.queryList();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
|
||||
if (statusValidChangeToDetails != null)
|
||||
pageContext.setAttribute(attributeName, statusValidChangeToDetails);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you 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 org.ofbiz.common.test;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilDateTime;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.util.EntityListIterator;
|
||||
import org.ofbiz.service.ServiceUtil;
|
||||
import org.ofbiz.service.testtools.OFBizTestCase;
|
||||
|
||||
public class PerformFindTests extends OFBizTestCase {
|
||||
|
||||
private static final String module = PerformFindTests.class.getName();
|
||||
public PerformFindTests(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
private List<GenericValue> getCompleteList(Map<String, Object> context) {
|
||||
EntityListIterator listIt = (EntityListIterator) context.get("listIt");
|
||||
List<GenericValue> foundElements = new LinkedList<GenericValue>();
|
||||
if (listIt != null) {
|
||||
try {
|
||||
foundElements = listIt.getCompleteList();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(" Failed to extract values from EntityListIterator after a performFind service", module);
|
||||
} finally {
|
||||
try {
|
||||
listIt.close();
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(" Failed to close EntityListIterator after a performFind service", module);
|
||||
}
|
||||
}
|
||||
}
|
||||
return foundElements;
|
||||
}
|
||||
|
||||
private void prepareData() throws Exception {
|
||||
if (delegator.findOne("TestingType", false, "testingTypeId", "PERFOMFINDTEST") == null) {
|
||||
delegator.create("TestingType", "testingTypeId", "PERFOMFINDTEST");
|
||||
delegator.create("Testing", "testingId", "PERF_TEST_1", "testingTypeId", "PERFOMFINDTEST", "testingName", "nice name one");
|
||||
delegator.create("Testing", "testingId", "PERF_TEST_2", "testingTypeId", "PERFOMFINDTEST", "testingName", "nice other name two");
|
||||
delegator.create("Testing", "testingId", "PERF_TEST_3", "testingTypeId", "PERFOMFINDTEST", "testingName", "medium name three");
|
||||
delegator.create("Testing", "testingId", "PERF_TEST_4", "testingTypeId", "PERFOMFINDTEST", "testingName", "bad nme four");
|
||||
delegator.create("Testing", "testingId", "PERF_TEST_5", "testingTypeId", "PERFOMFINDTEST", "testingName", "nice name one");
|
||||
delegator.create("Testing", "testingId", "PERF_TEST_6", "testingTypeId", "PERFOMFINDTEST");
|
||||
delegator.create("Testing", "testingId", "PERF_TEST_7", "testingTypeId", "PERFOMFINDTEST");
|
||||
delegator.create("Testing", "testingId", "PERF_TEST_8", "testingTypeId", "PERFOMFINDTEST");
|
||||
delegator.create("Testing", "testingId", "PERF_TEST_9", "testingTypeId", "PERFOMFINDTEST");
|
||||
|
||||
Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
|
||||
delegator.create("TestingNode", "testingNodeId", "NODE_1", "description", "Date Node");
|
||||
delegator.create("TestingNodeMember", "testingNodeId", "NODE_1", "testingId", "PERF_TEST_5",
|
||||
"fromDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, 1d),
|
||||
"thruDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, 3d),
|
||||
"extendFromDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -1d),
|
||||
"extendThruDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, 3d));
|
||||
delegator.create("TestingNodeMember", "testingNodeId", "NODE_1", "testingId", "PERF_TEST_6",
|
||||
"fromDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -1d),
|
||||
"thruDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, 1d),
|
||||
"extendFromDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -1d),
|
||||
"extendThruDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, 3d));
|
||||
delegator.create("TestingNodeMember", "testingNodeId", "NODE_1", "testingId", "PERF_TEST_7",
|
||||
"fromDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -1d),
|
||||
"thruDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, 1d),
|
||||
"extendFromDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -1d),
|
||||
"extendThruDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, 3d));
|
||||
delegator.create("TestingNodeMember", "testingNodeId", "NODE_1", "testingId", "PERF_TEST_8",
|
||||
"fromDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -3d),
|
||||
"thruDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, 1d),
|
||||
"extendFromDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -1d),
|
||||
"extendThruDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, 3d));
|
||||
delegator.create("TestingNodeMember", "testingNodeId", "NODE_1", "testingId", "PERF_TEST_9",
|
||||
"fromDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -3d),
|
||||
"thruDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -1d),
|
||||
"extendFromDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -1d),
|
||||
"extendThruDate", UtilDateTime.addDaysToTimestamp(nowTimestamp, -3d));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main test function to call other test.
|
||||
* If each function call by junit, it generate an random error with DBCP
|
||||
* See the issue OFBIZ-6218 Unit tests throw exception in DBCP for more details
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testPerformFind() throws Exception {
|
||||
performFindConditionFieldEquals();
|
||||
performFindConditionFieldLike();
|
||||
performFindConditionDistinct();
|
||||
performFindFilterByDate();
|
||||
performFindFilterByDateWithDedicateDateField();
|
||||
}
|
||||
|
||||
private void performFindConditionFieldEquals() throws Exception {
|
||||
GenericValue userLogin = delegator.findOne("UserLogin", true, "userLoginId", "system");
|
||||
prepareData();
|
||||
|
||||
Map<String, Object> inputFields = new HashMap<String, Object>();
|
||||
//first test without condition
|
||||
Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields);
|
||||
Map<String, Object> result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
List<GenericValue> foundElements = getCompleteList(result);
|
||||
assertTrue("performFind search without condition ", UtilValidate.isEmpty(foundElements));
|
||||
|
||||
//second test without condition and noConditionFind to Y
|
||||
performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields, "noConditionFind", "Y");
|
||||
result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search without condition with noConditionFind Y", 9, foundElements.size());
|
||||
|
||||
//third test with equals condition on testingTypeId
|
||||
inputFields = UtilMisc.toMap("testingTypeId", "PERFOMFINDTEST");
|
||||
performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields);
|
||||
result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
foundElements = getCompleteList(result);
|
||||
List<GenericValue> testingElements = delegator.findAll("Testing", false);
|
||||
assertEquals("performFind search without condition with equals on testingTypeId", testingElements.size(), foundElements.size());
|
||||
|
||||
//fourth test with equals condition on testingId
|
||||
inputFields = UtilMisc.toMap("testingId", "PERF_TEST_1");
|
||||
performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields);
|
||||
result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search without condition with equals on testingId", 1, foundElements.size());
|
||||
}
|
||||
|
||||
private void performFindConditionFieldLike() throws Exception {
|
||||
GenericValue userLogin = delegator.findOne("UserLogin", true, "userLoginId", "system");
|
||||
prepareData();
|
||||
|
||||
//first test like condition
|
||||
Map<String, Object> inputFields = UtilMisc.toMap("testingName", "nice", "testingName_op", "like");
|
||||
Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields);
|
||||
Map<String, Object> result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
List<GenericValue> foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search with like nice% condition", 3, foundElements.size());
|
||||
|
||||
//second test contains condition
|
||||
inputFields = UtilMisc.toMap("testingName", "name", "testingName_op", "contains");
|
||||
performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields);
|
||||
result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search with like %name% condition", 4, foundElements.size());
|
||||
|
||||
//third test not-like condition
|
||||
inputFields = UtilMisc.toMap("testingName", "bad", "testingName_op", "not-like");
|
||||
performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields);
|
||||
result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search with not like bad% condition", 4, foundElements.size());
|
||||
|
||||
//fourth test not-contains condition
|
||||
inputFields = UtilMisc.toMap("testingName", "name", "testingName_op", "not-contains");
|
||||
performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields);
|
||||
result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search with not like %name% condition", 1, foundElements.size());
|
||||
}
|
||||
|
||||
private void performFindConditionDistinct() throws Exception {
|
||||
GenericValue userLogin = delegator.findOne("UserLogin", true, "userLoginId", "system");
|
||||
prepareData();
|
||||
|
||||
//first test without distinct condition
|
||||
Map<String, Object> inputFields = UtilMisc.toMap("testingTypeId", "PERFOMFINDTEST");
|
||||
List<String> fieldList= UtilMisc.toList("testingName", "testingTypeId");
|
||||
Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields, "fieldList", fieldList, "distinct", "N");
|
||||
Map<String, Object> result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
List<GenericValue> foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search with distinct N", 9, foundElements.size());
|
||||
|
||||
//second test with distinct condition
|
||||
performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "Testing", "inputFields", inputFields, "fieldList", fieldList, "distinct", "Y");
|
||||
result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search with distinct Y", 5, foundElements.size());
|
||||
}
|
||||
|
||||
private void performFindFilterByDate() throws Exception {
|
||||
GenericValue userLogin = delegator.findOne("UserLogin", true, "userLoginId", "system");
|
||||
prepareData();
|
||||
|
||||
//first test without filterDate condition
|
||||
Map<String, Object> inputFields = UtilMisc.toMap("testingNodeId", "NODE_1");
|
||||
Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "TestingNodeMember", "inputFields", inputFields, "filterByDate", "N", "filterByDateValue", UtilDateTime.nowTimestamp());
|
||||
Map<String, Object> result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
List<GenericValue> foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search with filterDate N", 5, foundElements.size());
|
||||
|
||||
//second test with filterDate condition
|
||||
performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "TestingNodeMember", "inputFields", inputFields, "filterByDate", "Y", "filterByDateValue", UtilDateTime.nowTimestamp());
|
||||
result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search with filterDate Y", 3, foundElements.size());
|
||||
}
|
||||
|
||||
private void performFindFilterByDateWithDedicateDateField() throws Exception {
|
||||
GenericValue userLogin = delegator.findOne("UserLogin", true, "userLoginId", "system");
|
||||
prepareData();
|
||||
|
||||
//first test without filterDate condition
|
||||
Map<String, Object> inputFields = UtilMisc.toMap("testingNodeId", "NODE_1");
|
||||
Map<String, Object> performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "TestingNodeMember", "inputFields", inputFields,
|
||||
"filterByDate", "N", "filterByDateValue", UtilDateTime.nowTimestamp(),
|
||||
"fromDateName", "extendFromDate", "thruDateName", "extendThruDate");
|
||||
Map<String, Object> result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
List<GenericValue> foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search with filterDate N and specific date field name", 5, foundElements.size());
|
||||
|
||||
//second test with filterDate condition
|
||||
performFindMap = UtilMisc.toMap("userLogin", userLogin, "entityName", "TestingNodeMember", "inputFields", inputFields,
|
||||
"filterByDate", "Y", "filterByDateValue", UtilDateTime.nowTimestamp(),
|
||||
"fromDateName", "extendFromDate", "thruDateName", "extendThruDate");
|
||||
result = dispatcher.runSync("performFind", performFindMap);
|
||||
assertTrue(ServiceUtil.isSuccess(result));
|
||||
foundElements = getCompleteList(result);
|
||||
assertEquals("performFind search with filterDate Y and specific date field name", 4, foundElements.size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you 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 org.ofbiz.common.uom;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.service.GenericServiceException;
|
||||
import org.ofbiz.service.LocalDispatcher;
|
||||
import org.ofbiz.service.ModelService;
|
||||
|
||||
import com.ibm.icu.util.Calendar;
|
||||
|
||||
/**
|
||||
* UomWorker
|
||||
*/
|
||||
public class UomWorker {
|
||||
|
||||
public static final String module = UomWorker.class.getName();
|
||||
|
||||
private UomWorker () {}
|
||||
|
||||
public static int[] uomTimeToCalTime(String uomId) {
|
||||
if ("TF_ms".equals(uomId)) {
|
||||
return new int[] { Calendar.MILLISECOND, 1 };
|
||||
} else if ("TF_s".equals(uomId)) {
|
||||
return new int[] { Calendar.SECOND, 1 };
|
||||
} else if ("TF_min".equals(uomId)) {
|
||||
return new int[] { Calendar.MINUTE, 1 };
|
||||
} else if ("TF_hr".equals(uomId)) {
|
||||
return new int[] { Calendar.HOUR, 1 };
|
||||
} else if ("TF_day".equals(uomId)) {
|
||||
return new int[] { Calendar.DAY_OF_YEAR, 1 };
|
||||
} else if ("TF_wk".equals(uomId)) {
|
||||
return new int[] { Calendar.WEEK_OF_YEAR, 1 };
|
||||
} else if ("TF_mon".equals(uomId)) {
|
||||
return new int[] { Calendar.MONTH, 1 };
|
||||
} else if ("TF_yr".equals(uomId)) {
|
||||
return new int[] { Calendar.YEAR, 1 };
|
||||
} else if ("TF_decade".equals(uomId)) {
|
||||
return new int[] { Calendar.YEAR, 10 };
|
||||
} else if ("TF_score".equals(uomId)) {
|
||||
return new int[] { Calendar.YEAR, 20 };
|
||||
} else if ("TF_century".equals(uomId)) {
|
||||
return new int[] { Calendar.YEAR, 100 };
|
||||
} else if ("TF_millenium".equals(uomId)) {
|
||||
return new int[] { Calendar.YEAR, 1000 };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Calendar addUomTime(Calendar cal, Timestamp startTime, String uomId, int value) {
|
||||
if (cal == null) {
|
||||
cal = Calendar.getInstance();
|
||||
}
|
||||
if (startTime != null) {
|
||||
cal.setTimeInMillis(startTime.getTime());
|
||||
}
|
||||
int[] conv = uomTimeToCalTime(uomId);
|
||||
|
||||
// conversion multiplier * value by type
|
||||
cal.add(conv[0], (value * conv[1]));
|
||||
return cal;
|
||||
}
|
||||
|
||||
public static Calendar addUomTime(Calendar cal, String uomId, int value) {
|
||||
return addUomTime(cal, null, uomId, value);
|
||||
}
|
||||
|
||||
public static Calendar addUomTime(Timestamp startTime, String uomId, int value) {
|
||||
return addUomTime(null, startTime, uomId, value);
|
||||
}
|
||||
|
||||
/*
|
||||
* Convenience method to call the convertUom service
|
||||
*/
|
||||
public static BigDecimal convertUom(BigDecimal originalValue, String uomId, String uomIdTo, LocalDispatcher dispatcher) {
|
||||
if (originalValue == null || uomId == null || uomIdTo == null) return null;
|
||||
if (uomId.equals(uomIdTo)) return originalValue;
|
||||
|
||||
Map<String, Object> svcInMap = new LinkedHashMap<String, Object>();
|
||||
svcInMap.put("originalValue", originalValue);
|
||||
svcInMap.put("uomId", uomId);
|
||||
svcInMap.put("uomIdTo", uomIdTo);
|
||||
|
||||
Map<String, Object> svcOutMap = new LinkedHashMap<String, Object>();
|
||||
try {
|
||||
svcOutMap = dispatcher.runSync("convertUom", svcInMap);
|
||||
} catch (GenericServiceException ex) {
|
||||
Debug.logError(ex, module);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (svcOutMap.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS) && svcOutMap.get("convertedValue") != null) {
|
||||
return (BigDecimal) svcOutMap.get("convertedValue");
|
||||
}
|
||||
Debug.logError("Failed to perform conversion for value [" + originalValue.toPlainString() + "] from Uom [" + uomId + "] to Uom [" + uomIdTo + "]",module);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user