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:
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* 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.
|
||||
*******************************************************************************/
|
||||
|
||||
contribute(currentType(subType('groovy.lang.Script'))) {
|
||||
property name : 'parameters', type : 'java.util.Map'
|
||||
property name: 'context', type: 'java.util.Map'
|
||||
property name: 'delegator', type: 'org.ofbiz.entity.Delegator'
|
||||
property name: 'dispatcher', type: 'org.ofbiz.service.LocalDispatcher'
|
||||
|
||||
method name: 'runService', type: 'java.util.Map', params: [serviceName: 'String', inputMap: 'java.util.Map']
|
||||
method name: 'makeValue', type: 'java.util.Map', params: [entityName: 'String']
|
||||
method name: 'findOne', type: 'java.util.Map', params: [entityName: 'String', inputMap: 'java.util.Map']
|
||||
method name: 'findList', type: 'java.util.List', params: [entityName: 'String', inputMap: 'java.util.Map']
|
||||
method name: 'select', type: 'org.ofbiz.entity.util.EntityQuery', params: [entity: 'java.util.Set']
|
||||
method name: 'select', type: 'org.ofbiz.entity.util.EntityQuery', params: [entity: 'String...']
|
||||
method name: 'from', type: 'org.ofbiz.entity.util.EntityQuery', params: [entity: 'java.lang.Object']
|
||||
method name: 'success', type: 'def', params: [message: 'String']
|
||||
method name: 'failure', type: 'java.util.Map', params: [message: 'String']
|
||||
method name: 'error', type: 'def', params: [message: 'String']
|
||||
method name: 'logInfo', type: 'void', params: [message: 'String']
|
||||
method name: 'logWarning', type: 'void', params: [message: 'String']
|
||||
method name: 'logError', type: 'void', params: [message: 'String']
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*******************************************************************************
|
||||
* 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.base
|
||||
|
||||
def groovyContext = context(filetypes: ['groovy'], scope: scriptScope())
|
||||
|
||||
contributor(groovyContext) {
|
||||
provider = 'OFBiz DSL'
|
||||
property name: 'parameters', type: 'java.util.Map'
|
||||
property name: 'context', type: 'java.util.Map'
|
||||
property name: 'delegator', type: 'org.ofbiz.entity.Delegator'
|
||||
property name: 'dispatcher', type: 'org.ofbiz.service.LocalDispatcher'
|
||||
|
||||
method name: 'runService', type: 'java.util.Map', params: [serviceName: 'String', inputMap: 'java.util.Map']
|
||||
method name: 'run', type: 'java.util.Map', params: [args: 'java.util.Map']
|
||||
method name: 'makeValue', type: 'java.util.Map', params: [entityName: 'String']
|
||||
method name: 'select', type: 'org.ofbiz.entity.util.EntityQuery', params: [entity: 'java.util.Set']
|
||||
method name: 'select', type: 'org.ofbiz.entity.util.EntityQuery', params: [entity: 'String...']
|
||||
method name: 'from', type: 'org.ofbiz.entity.util.EntityQuery', params: [entity: 'java.lang.Object']
|
||||
|
||||
method name: 'success', type: 'def', params: [message: 'String']
|
||||
method name: 'failure', type: 'java.util.Map', params: [message: 'String']
|
||||
method name: 'error', type: 'def', params: [message: 'String']
|
||||
|
||||
method name: 'logInfo', type: 'void', params: [message: 'String']
|
||||
method name: 'logWarning', type: 'void', params: [message: 'String']
|
||||
method name: 'logError', type: 'void', params: [message: 'String']
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.component;
|
||||
|
||||
/**
|
||||
* Component Already Loaded Exception
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class AlreadyLoadedException extends ComponentException {
|
||||
|
||||
public AlreadyLoadedException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public AlreadyLoadedException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public AlreadyLoadedException(Throwable nested) {
|
||||
super(nested);
|
||||
}
|
||||
|
||||
public AlreadyLoadedException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,960 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.security.KeyStore;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import org.ofbiz.base.container.ContainerConfig;
|
||||
import org.ofbiz.base.container.ContainerConfig.Container;
|
||||
import org.ofbiz.base.container.ContainerException;
|
||||
import org.ofbiz.base.location.FlexibleLocation;
|
||||
import org.ofbiz.base.util.Assert;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.KeyStoreUtil;
|
||||
import org.ofbiz.base.util.UtilURL;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><ofbiz-component></code> element.
|
||||
*
|
||||
* @see <code>ofbiz-component.xsd</code>
|
||||
*
|
||||
*/
|
||||
public final class ComponentConfig {
|
||||
|
||||
public static final String module = ComponentConfig.class.getName();
|
||||
public static final String OFBIZ_COMPONENT_XML_FILENAME = "ofbiz-component.xml";
|
||||
/* Note: These Maps are not UtilCache instances because there is no strategy or implementation for reloading components.
|
||||
* Also, we are using LinkedHashMap to maintain insertion order - which client code depends on. This means
|
||||
* we will need to use synchronization code because there is no concurrent implementation of LinkedHashMap.
|
||||
*/
|
||||
private static final ComponentConfigCache componentConfigCache = new ComponentConfigCache();
|
||||
private static final Map<String, List<WebappInfo>> serverWebApps = new LinkedHashMap<String, List<WebappInfo>>();
|
||||
|
||||
public static Boolean componentExists(String componentName) {
|
||||
Assert.notEmpty("componentName", componentName);
|
||||
return componentConfigCache.fromGlobalName(componentName) != null;
|
||||
}
|
||||
|
||||
public static List<ClasspathInfo> getAllClasspathInfos() {
|
||||
return getAllClasspathInfos(null);
|
||||
}
|
||||
|
||||
public static List<ClasspathInfo> getAllClasspathInfos(String componentName) {
|
||||
List<ClasspathInfo> classpaths = new ArrayList<ClasspathInfo>();
|
||||
for (ComponentConfig cc : getAllComponents()) {
|
||||
if (componentName == null || componentName.equals(cc.getComponentName())) {
|
||||
classpaths.addAll(cc.getClasspathInfos());
|
||||
}
|
||||
}
|
||||
return classpaths;
|
||||
}
|
||||
|
||||
public static Collection<ComponentConfig> getAllComponents() {
|
||||
return componentConfigCache.values();
|
||||
}
|
||||
|
||||
public static List<ContainerConfig.Container> getAllContainers() {
|
||||
return getAllContainers(null);
|
||||
}
|
||||
|
||||
public static List<ContainerConfig.Container> getAllContainers(String componentName) {
|
||||
List<ContainerConfig.Container> containers = new ArrayList<ContainerConfig.Container>();
|
||||
for (ComponentConfig cc : getAllComponents()) {
|
||||
if (componentName == null || componentName.equals(cc.getComponentName())) {
|
||||
containers.addAll(cc.getContainers());
|
||||
}
|
||||
}
|
||||
return containers;
|
||||
}
|
||||
|
||||
public static List<EntityResourceInfo> getAllEntityResourceInfos(String type) {
|
||||
return getAllEntityResourceInfos(type, null);
|
||||
}
|
||||
|
||||
public static List<EntityResourceInfo> getAllEntityResourceInfos(String type, String componentName) {
|
||||
List<EntityResourceInfo> entityInfos = new ArrayList<EntityResourceInfo>();
|
||||
for (ComponentConfig cc : getAllComponents()) {
|
||||
if (componentName == null || componentName.equals(cc.getComponentName())) {
|
||||
List<EntityResourceInfo> ccEntityInfoList = cc.getEntityResourceInfos();
|
||||
if (UtilValidate.isEmpty(type)) {
|
||||
entityInfos.addAll(ccEntityInfoList);
|
||||
} else {
|
||||
for (EntityResourceInfo entityResourceInfo : ccEntityInfoList) {
|
||||
if (type.equals(entityResourceInfo.type)) {
|
||||
entityInfos.add(entityResourceInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return entityInfos;
|
||||
}
|
||||
|
||||
public static List<KeystoreInfo> getAllKeystoreInfos() {
|
||||
return getAllKeystoreInfos(null);
|
||||
}
|
||||
|
||||
public static List<KeystoreInfo> getAllKeystoreInfos(String componentName) {
|
||||
List<KeystoreInfo> keystoreInfos = new ArrayList<KeystoreInfo>();
|
||||
for (ComponentConfig cc : getAllComponents()) {
|
||||
if (componentName == null || componentName.equals(cc.getComponentName())) {
|
||||
keystoreInfos.addAll(cc.getKeystoreInfos());
|
||||
}
|
||||
}
|
||||
return keystoreInfos;
|
||||
}
|
||||
|
||||
public static List<ServiceResourceInfo> getAllServiceResourceInfos(String type) {
|
||||
return getAllServiceResourceInfos(type, null);
|
||||
}
|
||||
|
||||
public static List<ServiceResourceInfo> getAllServiceResourceInfos(String type, String componentName) {
|
||||
List<ServiceResourceInfo> serviceInfos = new ArrayList<ServiceResourceInfo>();
|
||||
for (ComponentConfig cc : getAllComponents()) {
|
||||
if (componentName == null || componentName.equals(cc.getComponentName())) {
|
||||
List<ServiceResourceInfo> ccServiceInfoList = cc.getServiceResourceInfos();
|
||||
if (UtilValidate.isEmpty(type)) {
|
||||
serviceInfos.addAll(ccServiceInfoList);
|
||||
} else {
|
||||
for (ServiceResourceInfo serviceResourceInfo : ccServiceInfoList) {
|
||||
if (type.equals(serviceResourceInfo.type)) {
|
||||
serviceInfos.add(serviceResourceInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return serviceInfos;
|
||||
}
|
||||
|
||||
public static List<TestSuiteInfo> getAllTestSuiteInfos() {
|
||||
return getAllTestSuiteInfos(null);
|
||||
}
|
||||
|
||||
public static List<TestSuiteInfo> getAllTestSuiteInfos(String componentName) {
|
||||
List<TestSuiteInfo> testSuiteInfos = new ArrayList<TestSuiteInfo>();
|
||||
for (ComponentConfig cc : getAllComponents()) {
|
||||
if (componentName == null || componentName.equals(cc.getComponentName())) {
|
||||
testSuiteInfos.addAll(cc.getTestSuiteInfos());
|
||||
}
|
||||
}
|
||||
return testSuiteInfos;
|
||||
}
|
||||
|
||||
public static List<WebappInfo> getAllWebappResourceInfos() {
|
||||
return getAllWebappResourceInfos(null);
|
||||
}
|
||||
|
||||
public static List<WebappInfo> getAllWebappResourceInfos(String componentName) {
|
||||
List<WebappInfo> webappInfos = new ArrayList<WebappInfo>();
|
||||
for (ComponentConfig cc : getAllComponents()) {
|
||||
if (componentName == null || componentName.equals(cc.getComponentName())) {
|
||||
webappInfos.addAll(cc.getWebappInfos());
|
||||
}
|
||||
}
|
||||
return webappInfos;
|
||||
}
|
||||
|
||||
public static List<WebappInfo> getAppBarWebInfos(String serverName) {
|
||||
return ComponentConfig.getAppBarWebInfos(serverName, null, null);
|
||||
}
|
||||
|
||||
public static List<WebappInfo> getAppBarWebInfos(String serverName, Comparator<? super String> comp, String menuName) {
|
||||
String serverWebAppsKey = serverName + menuName;
|
||||
List<WebappInfo> webInfos = null;
|
||||
synchronized (serverWebApps) {
|
||||
webInfos = serverWebApps.get(serverWebAppsKey);
|
||||
}
|
||||
if (webInfos == null) {
|
||||
Map<String, WebappInfo> tm = null;
|
||||
// use a TreeMap to sort the components alpha by title
|
||||
if (comp != null) {
|
||||
tm = new TreeMap<String, WebappInfo>(comp);
|
||||
} else {
|
||||
tm = new TreeMap<String, WebappInfo>();
|
||||
}
|
||||
for (ComponentConfig cc : getAllComponents()) {
|
||||
for (WebappInfo wInfo : cc.getWebappInfos()) {
|
||||
String key = UtilValidate.isNotEmpty(wInfo.position) ? wInfo.position : wInfo.title;
|
||||
if (serverName.equals(wInfo.server) && wInfo.getAppBarDisplay()) {
|
||||
if (UtilValidate.isNotEmpty(menuName)) {
|
||||
if (menuName.equals(wInfo.menuName)) {
|
||||
tm.put(key, wInfo);
|
||||
}
|
||||
} else {
|
||||
tm.put(key, wInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
webInfos = new ArrayList<WebappInfo>(tm.size());
|
||||
webInfos.addAll(tm.values());
|
||||
webInfos = Collections.unmodifiableList(webInfos);
|
||||
synchronized (serverWebApps) {
|
||||
// We are only preventing concurrent modification, we are not guaranteeing a singleton.
|
||||
serverWebApps.put(serverWebAppsKey, webInfos);
|
||||
}
|
||||
}
|
||||
return webInfos;
|
||||
}
|
||||
|
||||
public static List<WebappInfo> getAppBarWebInfos(String serverName, String menuName) {
|
||||
return getAppBarWebInfos(serverName, null, menuName);
|
||||
}
|
||||
|
||||
public static ComponentConfig getComponentConfig(String globalName) throws ComponentException {
|
||||
// TODO: we need to look up the rootLocation from the container config, or this will blow up
|
||||
return getComponentConfig(globalName, null);
|
||||
}
|
||||
|
||||
public static ComponentConfig getComponentConfig(String globalName, String rootLocation) throws ComponentException {
|
||||
ComponentConfig componentConfig = null;
|
||||
if (globalName != null && !globalName.isEmpty()) {
|
||||
componentConfig = componentConfigCache.fromGlobalName(globalName);
|
||||
if (componentConfig != null) {
|
||||
return componentConfig;
|
||||
}
|
||||
}
|
||||
if (rootLocation != null && !rootLocation.isEmpty()) {
|
||||
componentConfig = componentConfigCache.fromRootLocation(rootLocation);
|
||||
if (componentConfig != null) {
|
||||
return componentConfig;
|
||||
}
|
||||
}
|
||||
if (rootLocation != null) {
|
||||
componentConfig = new ComponentConfig(globalName, rootLocation);
|
||||
if (componentConfig.enabled()) {
|
||||
componentConfigCache.put(componentConfig);
|
||||
}
|
||||
return componentConfig;
|
||||
} else {
|
||||
// Do we really need to do this?
|
||||
throw new ComponentException("No component found named : " + globalName);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getFullLocation(String componentName, String resourceLoaderName, String location) throws ComponentException {
|
||||
ComponentConfig cc = getComponentConfig(componentName, null);
|
||||
if (cc == null) {
|
||||
throw new ComponentException("Could not find component with name: " + componentName);
|
||||
}
|
||||
return cc.getFullLocation(resourceLoaderName, location);
|
||||
}
|
||||
|
||||
public static KeystoreInfo getKeystoreInfo(String componentName, String keystoreName) {
|
||||
for (ComponentConfig cc : getAllComponents()) {
|
||||
if (componentName != null && componentName.equals(cc.getComponentName())) {
|
||||
for (KeystoreInfo ks : cc.getKeystoreInfos()) {
|
||||
if (keystoreName != null && keystoreName.equals(ks.getName())) {
|
||||
return ks;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getRootLocation(String componentName) throws ComponentException {
|
||||
ComponentConfig cc = getComponentConfig(componentName);
|
||||
if (cc == null) {
|
||||
throw new ComponentException("Could not find component with name: " + componentName);
|
||||
}
|
||||
return cc.getRootLocation();
|
||||
}
|
||||
|
||||
public static InputStream getStream(String componentName, String resourceLoaderName, String location) throws ComponentException {
|
||||
ComponentConfig cc = getComponentConfig(componentName);
|
||||
if (cc == null) {
|
||||
throw new ComponentException("Could not find component with name: " + componentName);
|
||||
}
|
||||
return cc.getStream(resourceLoaderName, location);
|
||||
}
|
||||
|
||||
public static URL getURL(String componentName, String resourceLoaderName, String location) throws ComponentException {
|
||||
ComponentConfig cc = getComponentConfig(componentName);
|
||||
if (cc == null) {
|
||||
throw new ComponentException("Could not find component with name: " + componentName);
|
||||
}
|
||||
return cc.getURL(resourceLoaderName, location);
|
||||
}
|
||||
|
||||
public static WebappInfo getWebAppInfo(String serverName, String contextRoot) {
|
||||
if (serverName == null || contextRoot == null) {
|
||||
return null;
|
||||
}
|
||||
ComponentConfig.WebappInfo info = null;
|
||||
for (ComponentConfig cc : getAllComponents()) {
|
||||
for (WebappInfo wInfo : cc.getWebappInfos()) {
|
||||
if (serverName.equals(wInfo.server) && contextRoot.equals(wInfo.getContextRoot())) {
|
||||
info = wInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
public static boolean isFileResourceLoader(String componentName, String resourceLoaderName) throws ComponentException {
|
||||
ComponentConfig cc = getComponentConfig(componentName);
|
||||
if (cc == null) {
|
||||
throw new ComponentException("Could not find component with name: " + componentName);
|
||||
}
|
||||
return cc.isFileResourceLoader(resourceLoaderName);
|
||||
}
|
||||
|
||||
// ========== ComponentConfig instance ==========
|
||||
|
||||
private final String globalName;
|
||||
private final String rootLocation;
|
||||
private final String componentName;
|
||||
private final boolean enabled;
|
||||
private final Map<String, ResourceLoaderInfo> resourceLoaderInfos;
|
||||
private final List<ClasspathInfo> classpathInfos;
|
||||
private final List<EntityResourceInfo> entityResourceInfos;
|
||||
private final List<ServiceResourceInfo> serviceResourceInfos;
|
||||
private final List<TestSuiteInfo> testSuiteInfos;
|
||||
private final List<KeystoreInfo> keystoreInfos;
|
||||
private final List<WebappInfo> webappInfos;
|
||||
private final List<ContainerConfig.Container> containers;
|
||||
|
||||
private ComponentConfig(String globalName, String rootLocation) throws ComponentException {
|
||||
if (!rootLocation.endsWith("/")) {
|
||||
rootLocation = rootLocation + "/";
|
||||
}
|
||||
this.rootLocation = rootLocation.replace('\\', '/');
|
||||
File rootLocationDir = new File(rootLocation);
|
||||
if (!rootLocationDir.exists()) {
|
||||
throw new ComponentException("The component root location does not exist: " + rootLocation);
|
||||
}
|
||||
if (!rootLocationDir.isDirectory()) {
|
||||
throw new ComponentException("The component root location is not a directory: " + rootLocation);
|
||||
}
|
||||
String xmlFilename = rootLocation + "/" + OFBIZ_COMPONENT_XML_FILENAME;
|
||||
URL xmlUrl = UtilURL.fromFilename(xmlFilename);
|
||||
if (xmlUrl == null) {
|
||||
throw new ComponentException("Could not find the " + OFBIZ_COMPONENT_XML_FILENAME + " configuration file in the component root location: " + rootLocation);
|
||||
}
|
||||
Document ofbizComponentDocument = null;
|
||||
try {
|
||||
ofbizComponentDocument = UtilXml.readXmlDocument(xmlUrl, true);
|
||||
} catch (Exception e) {
|
||||
throw new ComponentException("Error reading the component config file: " + xmlUrl, e);
|
||||
}
|
||||
Element ofbizComponentElement = ofbizComponentDocument.getDocumentElement();
|
||||
this.componentName = ofbizComponentElement.getAttribute("name");
|
||||
this.enabled = "true".equalsIgnoreCase(ofbizComponentElement.getAttribute("enabled"));
|
||||
if (UtilValidate.isEmpty(globalName)) {
|
||||
this.globalName = this.componentName;
|
||||
} else {
|
||||
this.globalName = globalName;
|
||||
}
|
||||
// resource-loader - resourceLoaderInfos
|
||||
List<? extends Element> childElements = UtilXml.childElementList(ofbizComponentElement, "resource-loader");
|
||||
if (!childElements.isEmpty()) {
|
||||
Map<String, ResourceLoaderInfo> resourceLoaderInfos = new LinkedHashMap<String, ResourceLoaderInfo>();
|
||||
for (Element curElement : childElements) {
|
||||
ResourceLoaderInfo resourceLoaderInfo = new ResourceLoaderInfo(curElement);
|
||||
resourceLoaderInfos.put(resourceLoaderInfo.name, resourceLoaderInfo);
|
||||
}
|
||||
this.resourceLoaderInfos = Collections.unmodifiableMap(resourceLoaderInfos);
|
||||
} else {
|
||||
this.resourceLoaderInfos = Collections.emptyMap();
|
||||
}
|
||||
// classpath - classpathInfos
|
||||
childElements = UtilXml.childElementList(ofbizComponentElement, "classpath");
|
||||
if (!childElements.isEmpty()) {
|
||||
List<ClasspathInfo> classpathInfos = new ArrayList<ClasspathInfo>(childElements.size());
|
||||
for (Element curElement : childElements) {
|
||||
ClasspathInfo classpathInfo = new ClasspathInfo(this, curElement);
|
||||
classpathInfos.add(classpathInfo);
|
||||
}
|
||||
this.classpathInfos = Collections.unmodifiableList(classpathInfos);
|
||||
} else {
|
||||
this.classpathInfos = Collections.emptyList();
|
||||
}
|
||||
// entity-resource - entityResourceInfos
|
||||
childElements = UtilXml.childElementList(ofbizComponentElement, "entity-resource");
|
||||
if (!childElements.isEmpty()) {
|
||||
List<EntityResourceInfo> entityResourceInfos = new ArrayList<EntityResourceInfo>(childElements.size());
|
||||
for (Element curElement : childElements) {
|
||||
EntityResourceInfo entityResourceInfo = new EntityResourceInfo(this, curElement);
|
||||
entityResourceInfos.add(entityResourceInfo);
|
||||
}
|
||||
this.entityResourceInfos = Collections.unmodifiableList(entityResourceInfos);
|
||||
} else {
|
||||
this.entityResourceInfos = Collections.emptyList();
|
||||
}
|
||||
// service-resource - serviceResourceInfos
|
||||
childElements = UtilXml.childElementList(ofbizComponentElement, "service-resource");
|
||||
if (!childElements.isEmpty()) {
|
||||
List<ServiceResourceInfo> serviceResourceInfos = new ArrayList<ServiceResourceInfo>(childElements.size());
|
||||
for (Element curElement : childElements) {
|
||||
ServiceResourceInfo serviceResourceInfo = new ServiceResourceInfo(this, curElement);
|
||||
serviceResourceInfos.add(serviceResourceInfo);
|
||||
}
|
||||
this.serviceResourceInfos = Collections.unmodifiableList(serviceResourceInfos);
|
||||
} else {
|
||||
this.serviceResourceInfos = Collections.emptyList();
|
||||
}
|
||||
// test-suite - serviceResourceInfos
|
||||
childElements = UtilXml.childElementList(ofbizComponentElement, "test-suite");
|
||||
if (!childElements.isEmpty()) {
|
||||
List<TestSuiteInfo> testSuiteInfos = new ArrayList<TestSuiteInfo>(childElements.size());
|
||||
for (Element curElement : childElements) {
|
||||
TestSuiteInfo testSuiteInfo = new TestSuiteInfo(this, curElement);
|
||||
testSuiteInfos.add(testSuiteInfo);
|
||||
}
|
||||
this.testSuiteInfos = Collections.unmodifiableList(testSuiteInfos);
|
||||
} else {
|
||||
this.testSuiteInfos = Collections.emptyList();
|
||||
}
|
||||
// keystore - (cert/trust store infos)
|
||||
childElements = UtilXml.childElementList(ofbizComponentElement, "keystore");
|
||||
if (!childElements.isEmpty()) {
|
||||
List<KeystoreInfo> keystoreInfos = new ArrayList<KeystoreInfo>(childElements.size());
|
||||
for (Element curElement : childElements) {
|
||||
KeystoreInfo keystoreInfo = new KeystoreInfo(this, curElement);
|
||||
keystoreInfos.add(keystoreInfo);
|
||||
}
|
||||
this.keystoreInfos = Collections.unmodifiableList(keystoreInfos);
|
||||
} else {
|
||||
this.keystoreInfos = Collections.emptyList();
|
||||
}
|
||||
// webapp - webappInfos
|
||||
childElements = UtilXml.childElementList(ofbizComponentElement, "webapp");
|
||||
if (!childElements.isEmpty()) {
|
||||
List<WebappInfo> webappInfos = new ArrayList<WebappInfo>(childElements.size());
|
||||
for (Element curElement : childElements) {
|
||||
WebappInfo webappInfo = new WebappInfo(this, curElement);
|
||||
webappInfos.add(webappInfo);
|
||||
}
|
||||
this.webappInfos = Collections.unmodifiableList(webappInfos);
|
||||
} else {
|
||||
this.webappInfos = Collections.emptyList();
|
||||
}
|
||||
// containers
|
||||
try {
|
||||
Collection<Container> containers = ContainerConfig.getContainers(xmlUrl);
|
||||
if (!containers.isEmpty()) {
|
||||
this.containers = Collections.unmodifiableList(new ArrayList<ContainerConfig.Container>(containers));
|
||||
} else {
|
||||
this.containers = Collections.emptyList();
|
||||
}
|
||||
} catch (ContainerException ce) {
|
||||
throw new ComponentException("Error reading containers for component: " + this.globalName, ce);
|
||||
}
|
||||
if (Debug.verboseOn())
|
||||
Debug.logVerbose("Read component config : [" + rootLocation + "]", module);
|
||||
}
|
||||
|
||||
public boolean enabled() {
|
||||
return this.enabled;
|
||||
}
|
||||
|
||||
public List<ClasspathInfo> getClasspathInfos() {
|
||||
return this.classpathInfos;
|
||||
}
|
||||
|
||||
public String getComponentName() {
|
||||
return this.componentName;
|
||||
}
|
||||
|
||||
public List<ContainerConfig.Container> getContainers() {
|
||||
return this.containers;
|
||||
}
|
||||
|
||||
public List<EntityResourceInfo> getEntityResourceInfos() {
|
||||
return this.entityResourceInfos;
|
||||
}
|
||||
|
||||
public String getFullLocation(String resourceLoaderName, String location) throws ComponentException {
|
||||
ResourceLoaderInfo resourceLoaderInfo = resourceLoaderInfos.get(resourceLoaderName);
|
||||
if (resourceLoaderInfo == null) {
|
||||
throw new ComponentException("Could not find resource-loader named: " + resourceLoaderName);
|
||||
}
|
||||
StringBuilder buf = new StringBuilder();
|
||||
// pre-pend component root location if this is a type component resource-loader
|
||||
if ("component".equals(resourceLoaderInfo.type)) {
|
||||
buf.append(rootLocation);
|
||||
}
|
||||
|
||||
if (UtilValidate.isNotEmpty(resourceLoaderInfo.prependEnv)) {
|
||||
String propValue = System.getProperty(resourceLoaderInfo.prependEnv);
|
||||
if (propValue == null) {
|
||||
String errMsg = "The Java environment (-Dxxx=yyy) variable with name " + resourceLoaderInfo.prependEnv + " is not set, cannot load resource.";
|
||||
Debug.logError(errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg);
|
||||
}
|
||||
buf.append(propValue);
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(resourceLoaderInfo.prefix)) {
|
||||
buf.append(resourceLoaderInfo.prefix);
|
||||
}
|
||||
buf.append(location);
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public String getGlobalName() {
|
||||
return this.globalName;
|
||||
}
|
||||
|
||||
public List<KeystoreInfo> getKeystoreInfos() {
|
||||
return this.keystoreInfos;
|
||||
}
|
||||
|
||||
public Map<String, ResourceLoaderInfo> getResourceLoaderInfos() {
|
||||
return this.resourceLoaderInfos;
|
||||
}
|
||||
|
||||
public String getRootLocation() {
|
||||
return this.rootLocation;
|
||||
}
|
||||
|
||||
public List<ServiceResourceInfo> getServiceResourceInfos() {
|
||||
return this.serviceResourceInfos;
|
||||
}
|
||||
|
||||
public InputStream getStream(String resourceLoaderName, String location) throws ComponentException {
|
||||
URL url = getURL(resourceLoaderName, location);
|
||||
try {
|
||||
return url.openStream();
|
||||
} catch (java.io.IOException e) {
|
||||
throw new ComponentException("Error opening resource at location [" + url.toExternalForm() + "]", e);
|
||||
}
|
||||
}
|
||||
|
||||
public List<TestSuiteInfo> getTestSuiteInfos() {
|
||||
return this.testSuiteInfos;
|
||||
}
|
||||
|
||||
public URL getURL(String resourceLoaderName, String location) throws ComponentException {
|
||||
ResourceLoaderInfo resourceLoaderInfo = resourceLoaderInfos.get(resourceLoaderName);
|
||||
if (resourceLoaderInfo == null) {
|
||||
throw new ComponentException("Could not find resource-loader named: " + resourceLoaderName);
|
||||
}
|
||||
if ("component".equals(resourceLoaderInfo.type) || "file".equals(resourceLoaderInfo.type)) {
|
||||
String fullLocation = getFullLocation(resourceLoaderName, location);
|
||||
URL fileUrl = UtilURL.fromFilename(fullLocation);
|
||||
if (fileUrl == null) {
|
||||
throw new ComponentException("File Resource not found: " + fullLocation);
|
||||
}
|
||||
return fileUrl;
|
||||
} else if ("classpath".equals(resourceLoaderInfo.type)) {
|
||||
String fullLocation = getFullLocation(resourceLoaderName, location);
|
||||
URL url = UtilURL.fromResource(fullLocation);
|
||||
if (url == null) {
|
||||
throw new ComponentException("Classpath Resource not found: " + fullLocation);
|
||||
}
|
||||
return url;
|
||||
} else if ("url".equals(resourceLoaderInfo.type)) {
|
||||
String fullLocation = getFullLocation(resourceLoaderName, location);
|
||||
URL url = null;
|
||||
try {
|
||||
url = FlexibleLocation.resolveLocation(location);
|
||||
} catch (java.net.MalformedURLException e) {
|
||||
throw new ComponentException("Error with malformed URL while trying to load URL resource at location [" + fullLocation + "]", e);
|
||||
}
|
||||
if (url == null) {
|
||||
throw new ComponentException("URL Resource not found: " + fullLocation);
|
||||
}
|
||||
return url;
|
||||
} else {
|
||||
throw new ComponentException("The resource-loader type is not recognized: " + resourceLoaderInfo.type);
|
||||
}
|
||||
}
|
||||
|
||||
public List<WebappInfo> getWebappInfos() {
|
||||
return this.webappInfos;
|
||||
}
|
||||
|
||||
public boolean isFileResource(ResourceInfo resourceInfo) throws ComponentException {
|
||||
return isFileResourceLoader(resourceInfo.loader);
|
||||
}
|
||||
|
||||
public boolean isFileResourceLoader(String resourceLoaderName) throws ComponentException {
|
||||
ResourceLoaderInfo resourceLoaderInfo = resourceLoaderInfos.get(resourceLoaderName);
|
||||
if (resourceLoaderInfo == null) {
|
||||
throw new ComponentException("Could not find resource-loader named: " + resourceLoaderName);
|
||||
}
|
||||
return "file".equals(resourceLoaderInfo.type) || "component".equals(resourceLoaderInfo.type);
|
||||
}
|
||||
|
||||
/**
|
||||
* An object that models the <code><classpath></code> element.
|
||||
*
|
||||
* @see <code>ofbiz-component.xsd</code>
|
||||
*
|
||||
*/
|
||||
public static final class ClasspathInfo {
|
||||
public final ComponentConfig componentConfig;
|
||||
public final String type;
|
||||
public final String location;
|
||||
|
||||
private ClasspathInfo(ComponentConfig componentConfig, Element element) {
|
||||
this.componentConfig = componentConfig;
|
||||
this.type = element.getAttribute("type");
|
||||
this.location = element.getAttribute("location");
|
||||
}
|
||||
}
|
||||
|
||||
// ComponentConfig instances need to be looked up by their global name and root location,
|
||||
// so this class encapsulates the Maps and synchronization code required to do that.
|
||||
private static final class ComponentConfigCache {
|
||||
// Key is the global name.
|
||||
private final Map<String, ComponentConfig> componentConfigs = new LinkedHashMap<String, ComponentConfig>();
|
||||
// Root location mapped to global name.
|
||||
private final Map<String, String> componentLocations = new HashMap<String, String>();
|
||||
|
||||
private synchronized ComponentConfig fromGlobalName(String globalName) {
|
||||
return componentConfigs.get(globalName);
|
||||
}
|
||||
|
||||
private synchronized ComponentConfig fromRootLocation(String rootLocation) {
|
||||
String globalName = componentLocations.get(rootLocation);
|
||||
if (globalName == null) {
|
||||
return null;
|
||||
}
|
||||
return componentConfigs.get(globalName);
|
||||
}
|
||||
|
||||
private synchronized ComponentConfig put(ComponentConfig config) {
|
||||
String globalName = config.getGlobalName();
|
||||
String fileLocation = config.getRootLocation();
|
||||
componentLocations.put(fileLocation, globalName);
|
||||
return componentConfigs.put(globalName, config);
|
||||
}
|
||||
|
||||
private synchronized Collection<ComponentConfig> values() {
|
||||
return Collections.unmodifiableList(new ArrayList<ComponentConfig>(componentConfigs.values()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An object that models the <code><entity-resource></code> element.
|
||||
*
|
||||
* @see <code>ofbiz-component.xsd</code>
|
||||
*
|
||||
*/
|
||||
public static final class EntityResourceInfo extends ResourceInfo {
|
||||
public final String type;
|
||||
public final String readerName;
|
||||
|
||||
private EntityResourceInfo(ComponentConfig componentConfig, Element element) {
|
||||
super(componentConfig, element);
|
||||
this.type = element.getAttribute("type");
|
||||
this.readerName = element.getAttribute("reader-name");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An object that models the <code><keystore></code> element.
|
||||
*
|
||||
* @see <code>ofbiz-component.xsd</code>
|
||||
*
|
||||
*/
|
||||
public static final class KeystoreInfo extends ResourceInfo {
|
||||
private final String name;
|
||||
private final String type;
|
||||
private final String password;
|
||||
private final boolean isCertStore;
|
||||
private final boolean isTrustStore;
|
||||
|
||||
private KeystoreInfo(ComponentConfig componentConfig, Element element) {
|
||||
super(componentConfig, element);
|
||||
this.name = element.getAttribute("name");
|
||||
this.type = element.getAttribute("type");
|
||||
this.password = element.getAttribute("password");
|
||||
this.isCertStore = "true".equalsIgnoreCase(element.getAttribute("is-certstore"));
|
||||
this.isTrustStore = "true".equalsIgnoreCase(element.getAttribute("is-truststore"));
|
||||
}
|
||||
|
||||
public KeyStore getKeyStore() {
|
||||
ComponentResourceHandler rh = this.createResourceHandler();
|
||||
if (rh != null) {
|
||||
try {
|
||||
return KeyStoreUtil.getStore(rh.getURL(), this.getPassword(), this.getType());
|
||||
} catch (Exception e) {
|
||||
Debug.logWarning(e, module);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public boolean isCertStore() {
|
||||
return isCertStore;
|
||||
}
|
||||
|
||||
public boolean isTrustStore() {
|
||||
return isTrustStore;
|
||||
}
|
||||
}
|
||||
|
||||
public static abstract class ResourceInfo {
|
||||
private final ComponentConfig componentConfig;
|
||||
private final String loader;
|
||||
private final String location;
|
||||
|
||||
protected ResourceInfo(ComponentConfig componentConfig, Element element) {
|
||||
this.componentConfig = componentConfig;
|
||||
this.loader = element.getAttribute("loader");
|
||||
this.location = element.getAttribute("location");
|
||||
}
|
||||
|
||||
public ComponentResourceHandler createResourceHandler() {
|
||||
return new ComponentResourceHandler(componentConfig.getGlobalName(), loader, location);
|
||||
}
|
||||
|
||||
public ComponentConfig getComponentConfig() {
|
||||
return componentConfig;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return location;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An object that models the <code><resource-loader></code> element.
|
||||
*
|
||||
* @see <code>ofbiz-component.xsd</code>
|
||||
*
|
||||
*/
|
||||
public static final class ResourceLoaderInfo {
|
||||
public final String name;
|
||||
public final String type;
|
||||
public final String prependEnv;
|
||||
public final String prefix;
|
||||
|
||||
private ResourceLoaderInfo(Element element) {
|
||||
this.name = element.getAttribute("name");
|
||||
this.type = element.getAttribute("type");
|
||||
this.prependEnv = element.getAttribute("prepend-env");
|
||||
this.prefix = element.getAttribute("prefix");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An object that models the <code><service-resource></code> element.
|
||||
*
|
||||
* @see <code>ofbiz-component.xsd</code>
|
||||
*
|
||||
*/
|
||||
public static final class ServiceResourceInfo extends ResourceInfo {
|
||||
public final String type;
|
||||
|
||||
private ServiceResourceInfo(ComponentConfig componentConfig, Element element) {
|
||||
super(componentConfig, element);
|
||||
this.type = element.getAttribute("type");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An object that models the <code><test-suite></code> element.
|
||||
*
|
||||
* @see <code>ofbiz-component.xsd</code>
|
||||
*
|
||||
*/
|
||||
public static final class TestSuiteInfo extends ResourceInfo {
|
||||
public TestSuiteInfo(ComponentConfig componentConfig, Element element) {
|
||||
super(componentConfig, element);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An object that models the <code><webapp></code> element.
|
||||
*
|
||||
* @see <code>ofbiz-component.xsd</code>
|
||||
*
|
||||
*/
|
||||
public static final class WebappInfo {
|
||||
// FIXME: These fields should be private - since we have accessors - but
|
||||
// client code accesses the fields directly.
|
||||
public final ComponentConfig componentConfig;
|
||||
public final List<String> virtualHosts;
|
||||
public final Map<String, String> initParameters;
|
||||
public final String name;
|
||||
public final String title;
|
||||
public final String description;
|
||||
public final String menuName;
|
||||
public final String server;
|
||||
public final String mountPoint;
|
||||
public final String contextRoot;
|
||||
public final String location;
|
||||
public final String[] basePermission;
|
||||
public final String position;
|
||||
public final boolean privileged;
|
||||
// CatalinaContainer modifies this field.
|
||||
private volatile boolean appBarDisplay;
|
||||
private final String accessPermission;
|
||||
|
||||
private WebappInfo(ComponentConfig componentConfig, Element element) {
|
||||
this.componentConfig = componentConfig;
|
||||
this.name = element.getAttribute("name");
|
||||
String title = element.getAttribute("title");
|
||||
if (title.isEmpty()) {
|
||||
// default title is name w/ upper-cased first letter
|
||||
title = Character.toUpperCase(name.charAt(0)) + name.substring(1).toLowerCase();
|
||||
}
|
||||
this.title = title;
|
||||
String description = element.getAttribute("description");
|
||||
if (description.isEmpty()) {
|
||||
description = this.title;
|
||||
}
|
||||
this.description = description;
|
||||
this.server = element.getAttribute("server");
|
||||
String mountPoint = element.getAttribute("mount-point");
|
||||
// check the mount point and make sure it is properly formatted
|
||||
if (!mountPoint.isEmpty()) {
|
||||
if (!mountPoint.startsWith("/")) {
|
||||
mountPoint = "/" + mountPoint;
|
||||
}
|
||||
if (!mountPoint.endsWith("/*")) {
|
||||
if (!mountPoint.endsWith("/")) {
|
||||
mountPoint = mountPoint + "/";
|
||||
}
|
||||
mountPoint = mountPoint + "*";
|
||||
}
|
||||
}
|
||||
this.mountPoint = mountPoint;
|
||||
if (this.mountPoint.endsWith("/*")) {
|
||||
this.contextRoot = this.mountPoint.substring(0, this.mountPoint.length() - 2);
|
||||
} else {
|
||||
this.contextRoot = this.mountPoint;
|
||||
}
|
||||
this.location = element.getAttribute("location");
|
||||
this.appBarDisplay = !"false".equals(element.getAttribute("app-bar-display"));
|
||||
this.privileged = !"false".equals(element.getAttribute("privileged"));
|
||||
this.accessPermission = element.getAttribute("access-permission");
|
||||
String basePermStr = element.getAttribute("base-permission");
|
||||
if (!basePermStr.isEmpty()) {
|
||||
this.basePermission = basePermStr.split(",");
|
||||
} else {
|
||||
// default base permission is NONE
|
||||
this.basePermission = new String[] { "NONE" };
|
||||
}
|
||||
// trim the permissions (remove spaces)
|
||||
for (int i = 0; i < this.basePermission.length; i++) {
|
||||
this.basePermission[i] = this.basePermission[i].trim();
|
||||
if (this.basePermission[i].indexOf('_') != -1) {
|
||||
this.basePermission[i] = this.basePermission[i].substring(0, this.basePermission[i].indexOf('_'));
|
||||
}
|
||||
}
|
||||
String menuNameStr = element.getAttribute("menu-name");
|
||||
if (UtilValidate.isNotEmpty(menuNameStr)) {
|
||||
this.menuName = menuNameStr;
|
||||
} else {
|
||||
this.menuName = "main";
|
||||
}
|
||||
this.position = element.getAttribute("position");
|
||||
// load the virtual hosts
|
||||
List<? extends Element> virtHostList = UtilXml.childElementList(element, "virtual-host");
|
||||
if (!virtHostList.isEmpty()) {
|
||||
List<String> virtualHosts = new ArrayList<String>(virtHostList.size());
|
||||
for (Element e : virtHostList) {
|
||||
virtualHosts.add(e.getAttribute("host-name"));
|
||||
}
|
||||
this.virtualHosts = Collections.unmodifiableList(virtualHosts);
|
||||
} else {
|
||||
this.virtualHosts = Collections.emptyList();
|
||||
}
|
||||
// load the init parameters
|
||||
List<? extends Element> initParamList = UtilXml.childElementList(element, "init-param");
|
||||
if (!initParamList.isEmpty()) {
|
||||
Map<String, String> initParameters = new LinkedHashMap<String, String>();
|
||||
for (Element e : initParamList) {
|
||||
initParameters.put(e.getAttribute("name"), e.getAttribute("value"));
|
||||
}
|
||||
this.initParameters = Collections.unmodifiableMap(initParameters);
|
||||
} else {
|
||||
this.initParameters = Collections.emptyMap();
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized boolean getAppBarDisplay() {
|
||||
return this.appBarDisplay;
|
||||
}
|
||||
|
||||
public String getAccessPermission() {
|
||||
return this.accessPermission;
|
||||
}
|
||||
|
||||
public String[] getBasePermission() {
|
||||
return this.basePermission;
|
||||
}
|
||||
|
||||
public String getContextRoot() {
|
||||
return contextRoot;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public Map<String, String> getInitParameters() {
|
||||
return initParameters;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return componentConfig.getRootLocation() + location;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public List<String> getVirtualHosts() {
|
||||
return virtualHosts;
|
||||
}
|
||||
|
||||
public synchronized void setAppBarDisplay(boolean appBarDisplay) {
|
||||
this.appBarDisplay = appBarDisplay;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.component;
|
||||
|
||||
import org.ofbiz.base.config.GenericConfigException;
|
||||
|
||||
/**
|
||||
* ComponentException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class ComponentException extends GenericConfigException {
|
||||
|
||||
public ComponentException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ComponentException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public ComponentException(Throwable nested) {
|
||||
super(nested);
|
||||
}
|
||||
|
||||
public ComponentException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.UtilURL;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.base.util.string.FlexibleStringExpander;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
/**
|
||||
* ComponentLoaderConfig - Component Loader configuration
|
||||
*
|
||||
*/
|
||||
public class ComponentLoaderConfig {
|
||||
|
||||
public static final String module = ComponentLoaderConfig.class.getName();
|
||||
public static final String COMPONENT_LOAD_XML_FILENAME = "component-load.xml";
|
||||
public static final int SINGLE_COMPONENT = 0;
|
||||
public static final int COMPONENT_DIRECTORY = 1;
|
||||
private static final AtomicReference<List<ComponentDef>> componentDefsRef = new AtomicReference<List<ComponentDef>>(null);
|
||||
|
||||
public static List<ComponentDef> getRootComponents(String configFile) throws ComponentException {
|
||||
List<ComponentDef> existingInstance = componentDefsRef.get();
|
||||
if (existingInstance == null) {
|
||||
if (configFile == null) {
|
||||
configFile = COMPONENT_LOAD_XML_FILENAME;
|
||||
}
|
||||
URL xmlUrl = UtilURL.fromResource(configFile);
|
||||
List<ComponentDef> newInstance = getComponentsFromConfig(xmlUrl);
|
||||
if (componentDefsRef.compareAndSet(existingInstance, newInstance)) {
|
||||
existingInstance = newInstance;
|
||||
} else {
|
||||
existingInstance = componentDefsRef.get();
|
||||
}
|
||||
}
|
||||
return existingInstance;
|
||||
}
|
||||
|
||||
public static List<ComponentDef> getComponentsFromConfig(URL configUrl) throws ComponentException {
|
||||
if (configUrl == null) {
|
||||
throw new IllegalArgumentException("configUrl cannot be null");
|
||||
}
|
||||
Document document = null;
|
||||
try {
|
||||
document = UtilXml.readXmlDocument(configUrl, true);
|
||||
} catch (SAXException e) {
|
||||
throw new ComponentException("Error reading the component config file: " + configUrl, e);
|
||||
} catch (ParserConfigurationException e) {
|
||||
throw new ComponentException("Error reading the component config file: " + configUrl, e);
|
||||
} catch (IOException e) {
|
||||
throw new ComponentException("Error reading the component config file: " + configUrl, e);
|
||||
}
|
||||
Element root = document.getDocumentElement();
|
||||
List<? extends Element> toLoad = UtilXml.childElementList(root);
|
||||
List<ComponentDef> componentsFromConfig = null;
|
||||
if (!toLoad.isEmpty()) {
|
||||
componentsFromConfig = new ArrayList<ComponentDef>(toLoad.size());
|
||||
Map<String, ? extends Object> systemProps = UtilGenerics.<String, Object> checkMap(System.getProperties());
|
||||
for (Element element : toLoad) {
|
||||
String nodeName = element.getNodeName();
|
||||
String name = null;
|
||||
String location = null;
|
||||
int type = SINGLE_COMPONENT;
|
||||
if ("load-component".equals(nodeName)) {
|
||||
name = element.getAttribute("component-name");
|
||||
location = FlexibleStringExpander.expandString(element.getAttribute("component-location"), systemProps);
|
||||
} else if ("load-components".equals(nodeName)) {
|
||||
location = FlexibleStringExpander.expandString(element.getAttribute("parent-directory"), systemProps);
|
||||
type = COMPONENT_DIRECTORY;
|
||||
} else {
|
||||
throw new ComponentException("Invalid element '" + nodeName + "' found in component config file " + configUrl);
|
||||
}
|
||||
componentsFromConfig.add(new ComponentDef(name, location, type));
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableList(componentsFromConfig);
|
||||
}
|
||||
|
||||
public static class ComponentDef {
|
||||
public String name;
|
||||
public final String location;
|
||||
public final int type;
|
||||
|
||||
private ComponentDef(String name, String location, int type) {
|
||||
this.name = name;
|
||||
this.location = location;
|
||||
this.type = type;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.component;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
|
||||
import org.ofbiz.base.config.GenericConfigException;
|
||||
import org.ofbiz.base.config.ResourceHandler;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Contains resource information and provides for loading data
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class ComponentResourceHandler implements ResourceHandler {
|
||||
|
||||
public static final String module = ComponentResourceHandler.class.getName();
|
||||
protected String componentName;
|
||||
protected String loaderName;
|
||||
protected String location;
|
||||
|
||||
public ComponentResourceHandler(String componentName, Element element) {
|
||||
this.componentName = componentName;
|
||||
this.loaderName = element.getAttribute("loader");
|
||||
this.location = element.getAttribute("location");
|
||||
}
|
||||
|
||||
public ComponentResourceHandler(String componentName, String loaderName, String location) {
|
||||
this.componentName = componentName;
|
||||
this.loaderName = loaderName;
|
||||
this.location = location;
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Created " + this.toString(), module);
|
||||
}
|
||||
|
||||
public String getLoaderName() {
|
||||
return this.loaderName;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
|
||||
public Document getDocument() throws GenericConfigException {
|
||||
try {
|
||||
return UtilXml.readXmlDocument(this.getStream(), this.getFullLocation(), true);
|
||||
} catch (org.xml.sax.SAXException e) {
|
||||
throw new GenericConfigException("Error reading " + this.toString(), e);
|
||||
} catch (javax.xml.parsers.ParserConfigurationException e) {
|
||||
throw new GenericConfigException("Error reading " + this.toString(), e);
|
||||
} catch (java.io.IOException e) {
|
||||
throw new GenericConfigException("Error reading " + this.toString(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public InputStream getStream() throws GenericConfigException {
|
||||
return ComponentConfig.getStream(componentName, loaderName, location);
|
||||
}
|
||||
|
||||
public URL getURL() throws GenericConfigException {
|
||||
return ComponentConfig.getURL(componentName, loaderName, location);
|
||||
}
|
||||
|
||||
public boolean isFileResource() throws GenericConfigException {
|
||||
return ComponentConfig.isFileResourceLoader(componentName, loaderName);
|
||||
}
|
||||
|
||||
public String getFullLocation() throws GenericConfigException {
|
||||
return ComponentConfig.getFullLocation(componentName, loaderName, location);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof ComponentResourceHandler) {
|
||||
ComponentResourceHandler other = (ComponentResourceHandler) obj;
|
||||
|
||||
if (this.loaderName.equals(other.loaderName) &&
|
||||
this.componentName.equals(other.componentName) &&
|
||||
this.location.equals(other.location)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// the hashCode will weight by a combination componentName and the combination of loaderName and location
|
||||
return (this.componentName.hashCode() + ((this.loaderName.hashCode() + this.location.hashCode()) >> 1)) >> 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ComponentResourceHandler from XML file [" + this.componentName + "] with loaderName [" + loaderName + "] and location [" + location + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.concurrent;
|
||||
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class ConstantFuture<V> implements Future<V> {
|
||||
private final V value;
|
||||
|
||||
public ConstantFuture(V value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public boolean cancel(boolean mayInterruptIfRunning) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public V get() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public V get(long timeout, TimeUnit unit) {
|
||||
return value;
|
||||
}
|
||||
|
||||
public boolean isCancelled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDone() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.concurrent;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.DelayQueue;
|
||||
import java.util.concurrent.Delayed;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.SynchronousQueue;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.ofbiz.base.lang.SourceMonitored;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
|
||||
@SourceMonitored
|
||||
public final class ExecutionPool {
|
||||
public static final String module = ExecutionPool.class.getName();
|
||||
public static final ExecutorService GLOBAL_BATCH = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 5, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ExecutionPoolThreadFactory(null, "OFBiz-batch"));
|
||||
public static final ForkJoinPool GLOBAL_FORK_JOIN = new ForkJoinPool();
|
||||
private static final ExecutorService pulseExecutionPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ExecutionPoolThreadFactory(null, "OFBiz-ExecutionPoolPulseWorker"));
|
||||
|
||||
protected static class ExecutionPoolThreadFactory implements ThreadFactory {
|
||||
private final ThreadGroup group;
|
||||
private final String namePrefix;
|
||||
private volatile int count = 1;
|
||||
|
||||
protected ExecutionPoolThreadFactory(ThreadGroup group, String namePrefix) {
|
||||
this.group = group;
|
||||
this.namePrefix = namePrefix;
|
||||
}
|
||||
|
||||
public Thread newThread(Runnable r) {
|
||||
Thread t = new Thread(group, r);
|
||||
t.setDaemon(true);
|
||||
t.setPriority(Thread.NORM_PRIORITY);
|
||||
t.setName(namePrefix + "-" + count++);
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
public static ScheduledExecutorService getScheduledExecutor(ThreadGroup group, String namePrefix, int threadCount, long keepAliveSeconds, boolean preStart) {
|
||||
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(threadCount, new ExecutionPoolThreadFactory(group, namePrefix));
|
||||
if (keepAliveSeconds > 0) {
|
||||
executor.setKeepAliveTime(keepAliveSeconds, TimeUnit.SECONDS);
|
||||
executor.allowCoreThreadTimeOut(true);
|
||||
}
|
||||
if (preStart) {
|
||||
executor.prestartAllCoreThreads();
|
||||
}
|
||||
return executor;
|
||||
}
|
||||
|
||||
public static <F> List<F> getAllFutures(Collection<Future<F>> futureList) {
|
||||
List<F> result = new LinkedList<F>();
|
||||
for (Future<F> future: futureList) {
|
||||
try {
|
||||
result.add(future.get());
|
||||
} catch (ExecutionException e) {
|
||||
Debug.logError(e, module);
|
||||
} catch (InterruptedException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void addPulse(Pulse pulse) {
|
||||
delayQueue.put(pulse);
|
||||
}
|
||||
|
||||
public static void removePulse(Pulse pulse) {
|
||||
delayQueue.remove(pulse);
|
||||
}
|
||||
|
||||
static {
|
||||
int numberOfExecutionPoolPulseWorkers = Runtime.getRuntime().availableProcessors();
|
||||
for (int i = 0; i < numberOfExecutionPoolPulseWorkers; i++) {
|
||||
pulseExecutionPool.execute(new ExecutionPoolPulseWorker());
|
||||
}
|
||||
}
|
||||
|
||||
private static final DelayQueue<Pulse> delayQueue = new DelayQueue<Pulse>();
|
||||
|
||||
public static class ExecutionPoolPulseWorker implements Runnable {
|
||||
public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
delayQueue.take().run();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static abstract class Pulse implements Delayed, Runnable {
|
||||
protected final long expireTimeNanos;
|
||||
protected final long loadTimeNanos;
|
||||
|
||||
protected Pulse(long delayNanos) {
|
||||
this(System.nanoTime(), delayNanos);
|
||||
}
|
||||
|
||||
protected Pulse(long loadTimeNanos, long delayNanos) {
|
||||
this.loadTimeNanos = loadTimeNanos;
|
||||
expireTimeNanos = loadTimeNanos + delayNanos;
|
||||
}
|
||||
|
||||
public long getLoadTimeNanos() {
|
||||
return loadTimeNanos;
|
||||
}
|
||||
|
||||
public long getExpireTimeNanos() {
|
||||
return expireTimeNanos;
|
||||
}
|
||||
|
||||
public final long getDelay(TimeUnit unit) {
|
||||
return unit.convert(expireTimeNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
|
||||
}
|
||||
|
||||
public final int compareTo(Delayed other) {
|
||||
long r = (expireTimeNanos - ((Pulse) other).expireTimeNanos);
|
||||
if (r < 0) return -1;
|
||||
if (r > 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.config;
|
||||
|
||||
import java.net.URL;
|
||||
import java.io.InputStream;
|
||||
import org.ofbiz.base.util.UtilURL;
|
||||
|
||||
/**
|
||||
* Loads resources from the file system
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class FileLoader extends ResourceLoader implements java.io.Serializable {
|
||||
|
||||
@Override
|
||||
public URL getURL(String location) throws GenericConfigException {
|
||||
String fullLocation = fullLocation(location);
|
||||
URL fileUrl = null;
|
||||
|
||||
fileUrl = UtilURL.fromFilename(fullLocation);
|
||||
if (fileUrl == null) {
|
||||
throw new GenericConfigException("File Resource not found: " + fullLocation);
|
||||
}
|
||||
return fileUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream loadResource(String location) throws GenericConfigException {
|
||||
URL fileUrl = getURL(location);
|
||||
try {
|
||||
return fileUrl.openStream();
|
||||
} catch (java.io.IOException e) {
|
||||
throw new GenericConfigException("Error opening file at location [" + fileUrl.toExternalForm() + "]", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.config;
|
||||
|
||||
import org.ofbiz.base.util.GeneralException;
|
||||
|
||||
/**
|
||||
* GenericConfigException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericConfigException extends GeneralException {
|
||||
|
||||
public GenericConfigException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericConfigException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericConfigException(Throwable nested) {
|
||||
super(nested);
|
||||
}
|
||||
|
||||
public GenericConfigException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.config;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* JNDIConfigUtil
|
||||
*
|
||||
*/
|
||||
public class JNDIConfigUtil {
|
||||
|
||||
public static final String module = JNDIConfigUtil.class.getName();
|
||||
public static final String JNDI_CONFIG_XML_FILENAME = "jndiservers.xml";
|
||||
private static final ConcurrentHashMap<String, JndiServerInfo> jndiServerInfos = new ConcurrentHashMap<String, JndiServerInfo>();
|
||||
|
||||
private static Element getXmlRootElement() throws GenericConfigException {
|
||||
try {
|
||||
return ResourceLoader.readXmlRootElement(JNDIConfigUtil.JNDI_CONFIG_XML_FILENAME);
|
||||
} catch (GenericConfigException e) {
|
||||
throw new GenericConfigException("Could not get JNDI XML root element", e);
|
||||
}
|
||||
}
|
||||
|
||||
static {
|
||||
try {
|
||||
initialize(getXmlRootElement());
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, "Error loading JNDI config XML file " + JNDI_CONFIG_XML_FILENAME, module);
|
||||
}
|
||||
}
|
||||
public static void initialize(Element rootElement) throws GenericConfigException {
|
||||
// jndi-server - jndiServerInfos
|
||||
for (Element curElement: UtilXml.childElementList(rootElement, "jndi-server")) {
|
||||
JndiServerInfo jndiServerInfo = new JndiServerInfo(curElement);
|
||||
|
||||
jndiServerInfos.putIfAbsent(jndiServerInfo.name, jndiServerInfo);
|
||||
}
|
||||
}
|
||||
|
||||
public static JndiServerInfo getJndiServerInfo(String name) {
|
||||
return jndiServerInfos.get(name);
|
||||
}
|
||||
|
||||
public static final class JndiServerInfo {
|
||||
public final String name;
|
||||
public final String contextProviderUrl;
|
||||
public final String initialContextFactory;
|
||||
public final String urlPkgPrefixes;
|
||||
public final String securityPrincipal;
|
||||
public final String securityCredentials;
|
||||
|
||||
public JndiServerInfo(Element element) {
|
||||
this.name = element.getAttribute("name");
|
||||
this.contextProviderUrl = element.getAttribute("context-provider-url");
|
||||
this.initialContextFactory = element.getAttribute("initial-context-factory");
|
||||
this.urlPkgPrefixes = element.getAttribute("url-pkg-prefixes");
|
||||
this.securityPrincipal = element.getAttribute("security-principal");
|
||||
this.securityCredentials = element.getAttribute("security-credentials");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.config;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Contains resource information and provides for loading data
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public final class MainResourceHandler implements ResourceHandler {
|
||||
|
||||
public static final String module = MainResourceHandler.class.getName();
|
||||
protected final String xmlFilename;
|
||||
protected final String loaderName;
|
||||
protected final String location;
|
||||
|
||||
public MainResourceHandler(String xmlFilename, Element element) {
|
||||
this.xmlFilename = xmlFilename;
|
||||
this.loaderName = element.getAttribute("loader");
|
||||
this.location = element.getAttribute("location");
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Created " + this.toString(), module);
|
||||
}
|
||||
|
||||
public MainResourceHandler(String xmlFilename, String loaderName, String location) {
|
||||
this.xmlFilename = xmlFilename;
|
||||
this.loaderName = loaderName;
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
public String getLoaderName() {
|
||||
return this.loaderName;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
|
||||
public Document getDocument() throws GenericConfigException {
|
||||
try {
|
||||
return UtilXml.readXmlDocument(this.getStream(), this.xmlFilename, true);
|
||||
} catch (org.xml.sax.SAXException e) {
|
||||
throw new GenericConfigException("Error reading " + this.toString(), e);
|
||||
} catch (javax.xml.parsers.ParserConfigurationException e) {
|
||||
throw new GenericConfigException("Error reading " + this.toString(), e);
|
||||
} catch (java.io.IOException e) {
|
||||
throw new GenericConfigException("Error reading " + this.toString(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public InputStream getStream() throws GenericConfigException {
|
||||
return ResourceLoader.loadResource(this.xmlFilename, this.location, this.loaderName);
|
||||
}
|
||||
|
||||
public URL getURL() throws GenericConfigException {
|
||||
return ResourceLoader.getURL(this.xmlFilename, this.location, this.loaderName);
|
||||
}
|
||||
|
||||
public boolean isFileResource() throws GenericConfigException {
|
||||
ResourceLoader loader = ResourceLoader.getLoader(this.xmlFilename, this.loaderName);
|
||||
|
||||
if (loader instanceof FileLoader) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public String getFullLocation() throws GenericConfigException {
|
||||
ResourceLoader loader = ResourceLoader.getLoader(this.xmlFilename, this.loaderName);
|
||||
|
||||
return loader.fullLocation(location);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof MainResourceHandler) {
|
||||
MainResourceHandler other = (MainResourceHandler) obj;
|
||||
|
||||
if (this.loaderName.equals(other.loaderName) &&
|
||||
this.xmlFilename.equals(other.xmlFilename) &&
|
||||
this.location.equals(other.location)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// the hashCode will weight by a combination xmlFilename and the combination of loaderName and location
|
||||
return (this.xmlFilename.hashCode() + ((this.loaderName.hashCode() + this.location.hashCode()) >> 1)) >> 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ResourceHandler from XML file [" + this.xmlFilename + "] with loaderName [" + loaderName + "] and location [" + location + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.config;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.Serializable;
|
||||
import java.net.URL;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
/**
|
||||
* Contains resource information and provides for loading data
|
||||
*
|
||||
*/
|
||||
public interface ResourceHandler extends Serializable {
|
||||
|
||||
public String getLoaderName();
|
||||
|
||||
public String getLocation();
|
||||
|
||||
public Document getDocument() throws GenericConfigException;
|
||||
|
||||
public InputStream getStream() throws GenericConfigException;
|
||||
|
||||
public URL getURL() throws GenericConfigException;
|
||||
|
||||
public boolean isFileResource() throws GenericConfigException;
|
||||
|
||||
public String getFullLocation() throws GenericConfigException;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.config;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilURL;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.base.util.cache.UtilCache;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Loads resources using dynamically specified resource loader classes.
|
||||
*/
|
||||
public abstract class ResourceLoader {
|
||||
|
||||
public static final String module = ResourceLoader.class.getName();
|
||||
private static final UtilCache<String, ResourceLoader> loaderCache = UtilCache.createUtilCache("resource.ResourceLoaders", 0, 0);
|
||||
// This cache is temporary - we will use it until the framework has been refactored to eliminate DOM tree caching, then it can be removed.
|
||||
private static final UtilCache<String, Document> domCache = UtilCache.createUtilCache("resource.DomTrees", 0, 0);
|
||||
|
||||
public static InputStream loadResource(String xmlFilename, String location, String loaderName) throws GenericConfigException {
|
||||
ResourceLoader loader = getLoader(xmlFilename, loaderName);
|
||||
if (loader == null) {
|
||||
throw new IllegalArgumentException("ResourceLoader not found with name [" + loaderName + "] in " + xmlFilename);
|
||||
}
|
||||
return loader.loadResource(location);
|
||||
}
|
||||
|
||||
public static URL getURL(String xmlFilename, String location, String loaderName) throws GenericConfigException {
|
||||
ResourceLoader loader = getLoader(xmlFilename, loaderName);
|
||||
if (loader == null) {
|
||||
throw new IllegalArgumentException("ResourceLoader not found with name [" + loaderName + "] in " + xmlFilename);
|
||||
}
|
||||
return loader.getURL(location);
|
||||
}
|
||||
|
||||
public static ResourceLoader getLoader(String xmlFilename, String loaderName) throws GenericConfigException {
|
||||
String cacheKey = xmlFilename.concat("#").concat(loaderName);
|
||||
ResourceLoader loader = loaderCache.get(cacheKey);
|
||||
if (loader == null) {
|
||||
Element rootElement = null;
|
||||
URL xmlUrl = UtilURL.fromResource(xmlFilename);
|
||||
if (xmlUrl == null) {
|
||||
throw new GenericConfigException("Could not find the " + xmlFilename + " file");
|
||||
}
|
||||
try {
|
||||
rootElement = UtilXml.readXmlDocument(xmlUrl, true, true).getDocumentElement();
|
||||
} catch (Exception e) {
|
||||
throw new GenericConfigException("Exception thrown while reading " + xmlFilename + ": ", e);
|
||||
}
|
||||
Element loaderElement = UtilXml.firstChildElement(rootElement, "resource-loader", "name", loaderName);
|
||||
if (loaderElement == null) {
|
||||
throw new GenericConfigException("The " + xmlFilename + " file is missing the <resource-loader> element with the name " + loaderName);
|
||||
}
|
||||
if (loaderElement.getAttribute("class").isEmpty()) {
|
||||
throw new GenericConfigException("The " + xmlFilename + " file <resource-loader> element with the name " + loaderName + " is missing the class attribute");
|
||||
}
|
||||
loader = loaderCache.putIfAbsentAndGet(cacheKey, makeLoader(loaderElement));
|
||||
}
|
||||
return loader;
|
||||
}
|
||||
|
||||
/** This method should be avoided. DOM object trees take a lot of memory and they are not
|
||||
* thread-safe, so they should not be cached.
|
||||
* @deprecated use {@link #readXmlRootElement(String)}
|
||||
*/
|
||||
@Deprecated
|
||||
public static Element getXmlRootElement(String xmlFilename) throws GenericConfigException {
|
||||
Document document = ResourceLoader.getXmlDocument(xmlFilename);
|
||||
|
||||
if (document != null) {
|
||||
return document.getDocumentElement();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Element readXmlRootElement(String xmlFilename) throws GenericConfigException {
|
||||
Document document = ResourceLoader.readXmlDocument(xmlFilename);
|
||||
|
||||
if (document != null) {
|
||||
return document.getDocumentElement();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void invalidateDocument(String xmlFilename) throws GenericConfigException {
|
||||
UtilCache.clearCachesThatStartWith(xmlFilename);
|
||||
}
|
||||
|
||||
/** This method should be avoided. DOM object trees take a lot of memory and they are not
|
||||
* thread-safe, so they should not be cached.
|
||||
* @deprecated use {@link #readXmlDocument(String)}
|
||||
*/
|
||||
@Deprecated
|
||||
public static Document getXmlDocument(String xmlFilename) throws GenericConfigException {
|
||||
Document document = domCache.get(xmlFilename);
|
||||
|
||||
if (document == null) {
|
||||
document = readXmlDocument(xmlFilename);
|
||||
|
||||
if (document != null) {
|
||||
document = (Document) domCache.putIfAbsentAndGet(xmlFilename, document);
|
||||
}
|
||||
}
|
||||
return document;
|
||||
}
|
||||
|
||||
public static Document readXmlDocument(String xmlFilename) throws GenericConfigException {
|
||||
URL confUrl = UtilURL.fromResource(xmlFilename);
|
||||
|
||||
if (confUrl == null) {
|
||||
throw new GenericConfigException("ERROR: could not find the [" + xmlFilename + "] XML file on the classpath");
|
||||
}
|
||||
|
||||
try {
|
||||
return UtilXml.readXmlDocument(confUrl, true, true);
|
||||
} catch (org.xml.sax.SAXException e) {
|
||||
throw new GenericConfigException("Error reading " + xmlFilename + "", e);
|
||||
} catch (javax.xml.parsers.ParserConfigurationException e) {
|
||||
throw new GenericConfigException("Error reading " + xmlFilename + "", e);
|
||||
} catch (java.io.IOException e) {
|
||||
throw new GenericConfigException("Error reading " + xmlFilename + "", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static ResourceLoader makeLoader(Element loaderElement) throws GenericConfigException {
|
||||
String loaderName = loaderElement.getAttribute("name");
|
||||
String className = loaderElement.getAttribute("class");
|
||||
ResourceLoader loader = null;
|
||||
try {
|
||||
Class<?> lClass = null;
|
||||
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
|
||||
lClass = classLoader.loadClass(className);
|
||||
loader = (ResourceLoader) lClass.newInstance();
|
||||
loader.init(loaderName, loaderElement.getAttribute("prefix"), loaderElement.getAttribute("prepend-env"));
|
||||
return loader;
|
||||
} catch (Exception e) {
|
||||
throw new GenericConfigException("Exception thrown while loading ResourceLoader class \"" + className + "\" ", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String prefix;
|
||||
private String envName;
|
||||
|
||||
protected ResourceLoader() {}
|
||||
|
||||
private void init(String name, String prefix, String envName) {
|
||||
this.prefix = prefix;
|
||||
this.envName = envName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Just a utility method to be used in loadResource by the implementing class.
|
||||
* @param location
|
||||
* @return the built-up full location
|
||||
*/
|
||||
public String fullLocation(String location) {
|
||||
StringBuilder buf = new StringBuilder();
|
||||
if (!envName.isEmpty()) {
|
||||
String propValue = System.getProperty(envName);
|
||||
if (propValue == null) {
|
||||
String errMsg = "The Java environment (-Dxxx=yyy) variable with name " + envName + " is not set, cannot load resource.";
|
||||
Debug.logError(errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg);
|
||||
}
|
||||
buf.append(propValue);
|
||||
}
|
||||
buf.append(prefix);
|
||||
buf.append(location);
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public abstract InputStream loadResource(String location) throws GenericConfigException;
|
||||
public abstract URL getURL(String location) throws GenericConfigException;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.config;
|
||||
|
||||
import java.net.URL;
|
||||
import java.io.InputStream;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Loads resources from a URL
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class UrlLoader extends ResourceLoader implements Serializable {
|
||||
|
||||
@Override
|
||||
public URL getURL(String location) throws GenericConfigException {
|
||||
String fullLocation = fullLocation(location);
|
||||
|
||||
URL url = null;
|
||||
|
||||
try {
|
||||
url = new URL(fullLocation);
|
||||
} catch (java.net.MalformedURLException e) {
|
||||
throw new GenericConfigException("Error with malformed URL while trying to load URL resource at location [" + fullLocation + "]", e);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream loadResource(String location) throws GenericConfigException {
|
||||
URL url = getURL(location);
|
||||
|
||||
try {
|
||||
return url.openStream();
|
||||
} catch (java.io.IOException e) {
|
||||
throw new GenericConfigException("Error opening URL resource at location [" + url.toExternalForm() + "]", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.container;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.ofbiz.base.component.ComponentConfig;
|
||||
import org.ofbiz.base.component.ComponentException;
|
||||
import org.ofbiz.base.component.ComponentLoaderConfig;
|
||||
import org.ofbiz.base.start.Classpath;
|
||||
import org.ofbiz.base.start.NativeLibClassLoader;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.FileUtil;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
|
||||
/**
|
||||
* ComponentContainer - StartupContainer implementation for Components
|
||||
* <p/>
|
||||
* Example ofbiz-container.xml configuration:
|
||||
* <pre>
|
||||
* <container name="component-container" class="org.ofbiz.base.component.ComponentContainer"/>
|
||||
* </pre>
|
||||
*/
|
||||
public class ComponentContainer implements Container {
|
||||
|
||||
public static final String module = ComponentContainer.class.getName();
|
||||
|
||||
protected String configFileLocation = null;
|
||||
private String name;
|
||||
private final AtomicBoolean loaded = new AtomicBoolean(false);
|
||||
|
||||
@Override
|
||||
public void init(String[] args, String name, String configFile) throws ContainerException {
|
||||
if (!loaded.compareAndSet(false, true)) {
|
||||
throw new ContainerException("Components already loaded, cannot start");
|
||||
}
|
||||
this.name = name;
|
||||
this.configFileLocation = configFile;
|
||||
|
||||
// get the config for this container
|
||||
ContainerConfig.Container cc = ContainerConfig.getContainer(name, configFileLocation);
|
||||
|
||||
// check for an override loader config
|
||||
String loaderConfig = null;
|
||||
if (cc.getProperty("loader-config") != null) {
|
||||
loaderConfig = cc.getProperty("loader-config").value;
|
||||
}
|
||||
|
||||
// load the components
|
||||
try {
|
||||
loadComponents(loaderConfig);
|
||||
} catch (ComponentException e) {
|
||||
throw new ContainerException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.ofbiz.base.container.Container#start()
|
||||
*/
|
||||
public boolean start() throws ContainerException {
|
||||
return loaded.get();
|
||||
}
|
||||
|
||||
public void loadComponents(String loaderConfig) throws ComponentException {
|
||||
// get the components to load
|
||||
List<ComponentLoaderConfig.ComponentDef> components = ComponentLoaderConfig.getRootComponents(loaderConfig);
|
||||
String parentPath;
|
||||
try {
|
||||
parentPath = FileUtil.getFile(System.getProperty("ofbiz.home")).getCanonicalFile().toString().replaceAll("\\\\", "/");
|
||||
// load each component
|
||||
if (components != null) {
|
||||
for (ComponentLoaderConfig.ComponentDef def: components) {
|
||||
loadComponentFromConfig(parentPath, def);
|
||||
}
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
throw new ComponentException(e.getMessage(), e);
|
||||
} catch (IOException e) {
|
||||
throw new ComponentException(e.getMessage(), e);
|
||||
}
|
||||
Debug.logInfo("All components loaded", module);
|
||||
}
|
||||
|
||||
private void loadComponentFromConfig(String parentPath, ComponentLoaderConfig.ComponentDef def) throws IOException {
|
||||
String location;
|
||||
if (def.location.startsWith("/")) {
|
||||
location = def.location;
|
||||
} else {
|
||||
location = parentPath + "/" + def.location;
|
||||
}
|
||||
if (def.type == ComponentLoaderConfig.SINGLE_COMPONENT) {
|
||||
ComponentConfig config = null;
|
||||
try {
|
||||
config = ComponentConfig.getComponentConfig(def.name, location);
|
||||
if (UtilValidate.isEmpty(def.name)) {
|
||||
def.name = config.getGlobalName();
|
||||
}
|
||||
} catch (ComponentException e) {
|
||||
Debug.logError("Cannot load component : " + def.name + " @ " + def.location + " : " + e.getMessage(), module);
|
||||
}
|
||||
if (config == null) {
|
||||
Debug.logError("Cannot load component : " + def.name + " @ " + def.location, module);
|
||||
} else {
|
||||
this.loadComponent(config);
|
||||
}
|
||||
} else if (def.type == ComponentLoaderConfig.COMPONENT_DIRECTORY) {
|
||||
this.loadComponentDirectory(location);
|
||||
}
|
||||
}
|
||||
|
||||
private void loadComponentDirectory(String directoryName) throws IOException {
|
||||
Debug.logInfo("Auto-Loading component directory : [" + directoryName + "]", module);
|
||||
File parentPath = FileUtil.getFile(directoryName);
|
||||
if (!parentPath.exists() || !parentPath.isDirectory()) {
|
||||
Debug.logError("Auto-Load Component directory not found : " + directoryName, module);
|
||||
} else {
|
||||
File componentLoadConfig = new File(parentPath, ComponentLoaderConfig.COMPONENT_LOAD_XML_FILENAME);
|
||||
if (componentLoadConfig != null && componentLoadConfig.exists()) {
|
||||
URL configUrl = null;
|
||||
try {
|
||||
configUrl = componentLoadConfig.toURI().toURL();
|
||||
List<ComponentLoaderConfig.ComponentDef> componentsToLoad = ComponentLoaderConfig.getComponentsFromConfig(configUrl);
|
||||
if (componentsToLoad != null) {
|
||||
for (ComponentLoaderConfig.ComponentDef def: componentsToLoad) {
|
||||
this.loadComponentFromConfig(parentPath.toString(), def);
|
||||
}
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
Debug.logError(e, "Unable to locate URL for component loading file: " + componentLoadConfig.getAbsolutePath(), module);
|
||||
} catch (ComponentException e) {
|
||||
Debug.logError(e, "Unable to load components from URL: " + configUrl.toExternalForm(), module);
|
||||
}
|
||||
} else {
|
||||
String[] fileNames = parentPath.list();
|
||||
Arrays.sort(fileNames);
|
||||
for (String sub: fileNames) {
|
||||
try {
|
||||
File componentPath = FileUtil.getFile(parentPath.getCanonicalPath() + File.separator + sub);
|
||||
if (componentPath.isDirectory() && !sub.equals("CVS") && !sub.equals(".svn")) {
|
||||
// make sure we have a component configuration file
|
||||
String componentLocation = componentPath.getCanonicalPath();
|
||||
File configFile = FileUtil.getFile(componentLocation.concat(File.separator).concat(ComponentConfig.OFBIZ_COMPONENT_XML_FILENAME));
|
||||
if (configFile.exists()) {
|
||||
ComponentConfig config = null;
|
||||
try {
|
||||
// pass null for the name, will default to the internal component name
|
||||
config = ComponentConfig.getComponentConfig(null, componentLocation);
|
||||
} catch (ComponentException e) {
|
||||
Debug.logError(e, "Cannot load component : " + componentPath.getName() + " @ " + componentLocation + " : " + e.getMessage(), module);
|
||||
}
|
||||
if (config == null) {
|
||||
Debug.logError("Cannot load component : " + componentPath.getName() + " @ " + componentLocation, module);
|
||||
} else {
|
||||
loadComponent(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException ioe) {
|
||||
Debug.logError(ioe, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void loadComponent(ComponentConfig config) throws IOException {
|
||||
// make sure the component is enabled
|
||||
if (!config.enabled()) {
|
||||
Debug.logInfo("Not loading component [" + config.getComponentName() + "] because it is disabled", module);
|
||||
return;
|
||||
}
|
||||
List<ComponentConfig.ClasspathInfo> classpathInfos = config.getClasspathInfos();
|
||||
String configRoot = config.getRootLocation();
|
||||
configRoot = configRoot.replace('\\', '/');
|
||||
// set the root to have a trailing slash
|
||||
if (!configRoot.endsWith("/")) {
|
||||
configRoot = configRoot + "/";
|
||||
}
|
||||
if (classpathInfos != null) {
|
||||
Classpath classPath = new Classpath();
|
||||
// TODO: If any components change the class loader, then this will need to be changed.
|
||||
NativeLibClassLoader classloader = (NativeLibClassLoader) Thread.currentThread().getContextClassLoader();
|
||||
for (ComponentConfig.ClasspathInfo cp: classpathInfos) {
|
||||
String location = cp.location.replace('\\', '/');
|
||||
// set the location to not have a leading slash
|
||||
if (location.startsWith("/")) {
|
||||
location = location.substring(1);
|
||||
}
|
||||
if (!"jar".equals(cp.type) && !"dir".equals(cp.type)) {
|
||||
Debug.logError("Classpath type '" + cp.type + "' is not supported; '" + location + "' not loaded", module);
|
||||
continue;
|
||||
}
|
||||
String dirLoc = location;
|
||||
if (dirLoc.endsWith("/*")) {
|
||||
// strip off the slash splat
|
||||
dirLoc = location.substring(0, location.length() - 2);
|
||||
}
|
||||
File path = FileUtil.getFile(configRoot + dirLoc);
|
||||
if (path.exists()) {
|
||||
if (path.isDirectory()) {
|
||||
if ("dir".equals(cp.type)) {
|
||||
classPath.addComponent(configRoot + location);
|
||||
}
|
||||
classPath.addFilesFromPath(path);
|
||||
} else {
|
||||
// add a single file
|
||||
classPath.addComponent(configRoot + location);
|
||||
}
|
||||
} else {
|
||||
Debug.logWarning("Location '" + configRoot + dirLoc + "' does not exist", module);
|
||||
}
|
||||
}
|
||||
for (URL url : classPath.getUrls()) {
|
||||
classloader.addURL(url);
|
||||
}
|
||||
for (File folder : classPath.getNativeFolders()) {
|
||||
classloader.addNativeClassPath(folder);
|
||||
}
|
||||
}
|
||||
Debug.logInfo("Loaded component : [" + config.getComponentName() + "]", module);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.ofbiz.base.container.Container#stop()
|
||||
*/
|
||||
public void stop() throws ContainerException {
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.container;
|
||||
|
||||
/**
|
||||
* An OFBiz container. A container can be thought of as a background process.
|
||||
*
|
||||
* <p>
|
||||
* When OFBiz starts, the main thread will create the <code>Container</code> instance and
|
||||
* then call the container's <code>init</code> method. If the method returns without
|
||||
* throwing an exception the container will be added to a list of initialized containers.
|
||||
* After all instances have been created and initialized, the main thread will call the
|
||||
* <code>start</code> method of each container in the list. When OFBiz shuts down, a
|
||||
* separate shutdown thread will call the <code>stop</code> method of each container.
|
||||
* Implementations should anticipate asynchronous calls to the methods by different
|
||||
* threads.
|
||||
* </p>
|
||||
*
|
||||
* <p>Containers might be loaded more than once (have more than one instance).<p>
|
||||
*/
|
||||
public interface Container {
|
||||
|
||||
/** Initialize the container. This method must not block - implementations
|
||||
* should initialize internal structures and then return.
|
||||
*
|
||||
* @param args Command-line arguments.
|
||||
* @param name Unique name of the container's instance.
|
||||
* @param configFile Location of the configuration file used to load this container.
|
||||
* @throws ContainerException If an error was encountered. Throwing this exception
|
||||
* will halt container loading, so it should be thrown only when other containers
|
||||
* might depend on this one.
|
||||
*/
|
||||
public void init(String[] args, String name, String configFile) throws ContainerException;
|
||||
|
||||
/**
|
||||
* Start the container process. This method must not block - implementations
|
||||
* that require thread blocking must create a separate thread and then return.
|
||||
*
|
||||
* @return <code>true</code> if the process started.
|
||||
* @throws ContainerException If an error was encountered.
|
||||
*/
|
||||
public boolean start() throws ContainerException;
|
||||
|
||||
/**
|
||||
* Stop the container process. This method must not block.
|
||||
*
|
||||
* @throws ContainerException If an error was encountered.
|
||||
*/
|
||||
public void stop() throws ContainerException;
|
||||
|
||||
/**
|
||||
* Return the container name.
|
||||
*
|
||||
* @return Name of the container's instance.
|
||||
*/
|
||||
public String getName();
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.container;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.ofbiz.base.lang.LockedBy;
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
import org.ofbiz.base.util.UtilURL;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
/**
|
||||
* ContainerConfig - Container configuration for ofbiz.xml
|
||||
*
|
||||
*/
|
||||
public class ContainerConfig {
|
||||
|
||||
public static final String module = ContainerConfig.class.getName();
|
||||
|
||||
@LockedBy("ContainerConfig.class")
|
||||
private static Map<String, Container> containers = new LinkedHashMap<String, Container>();
|
||||
|
||||
public static Container getContainer(String containerName, String configFile) throws ContainerException {
|
||||
Container container = containers.get(containerName);
|
||||
if (container == null) {
|
||||
getContainers(configFile);
|
||||
container = containers.get(containerName);
|
||||
}
|
||||
if (container == null) {
|
||||
throw new ContainerException("No container found with the name : " + containerName);
|
||||
}
|
||||
return container;
|
||||
}
|
||||
|
||||
public static Collection<Container> getContainers(String configFile) throws ContainerException {
|
||||
if (UtilValidate.isEmpty(configFile)) {
|
||||
throw new ContainerException("configFile argument cannot be null or empty");
|
||||
}
|
||||
URL xmlUrl = UtilURL.fromResource(configFile);
|
||||
if (xmlUrl == null) {
|
||||
throw new ContainerException("Could not find container config file " + configFile);
|
||||
}
|
||||
return getContainers(xmlUrl);
|
||||
}
|
||||
|
||||
public static Collection<Container> getContainers(URL xmlUrl) throws ContainerException {
|
||||
if (xmlUrl == null) {
|
||||
throw new ContainerException("xmlUrl argument cannot be null");
|
||||
}
|
||||
Collection<Container> result = getContainerPropsFromXml(xmlUrl);
|
||||
synchronized (ContainerConfig.class) {
|
||||
for (Container container : result) {
|
||||
containers.put(container.name, container);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String getPropertyValue(ContainerConfig.Container parentProp, String name, String defaultValue) {
|
||||
ContainerConfig.Container.Property prop = parentProp.getProperty(name);
|
||||
if (prop == null || UtilValidate.isEmpty(prop.value)) {
|
||||
return defaultValue;
|
||||
} else {
|
||||
return prop.value;
|
||||
}
|
||||
}
|
||||
|
||||
public static int getPropertyValue(ContainerConfig.Container parentProp, String name, int defaultValue) {
|
||||
ContainerConfig.Container.Property prop = parentProp.getProperty(name);
|
||||
if (prop == null || UtilValidate.isEmpty(prop.value)) {
|
||||
return defaultValue;
|
||||
} else {
|
||||
int num = defaultValue;
|
||||
try {
|
||||
num = Integer.parseInt(prop.value);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
return num;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean getPropertyValue(ContainerConfig.Container parentProp, String name, boolean defaultValue) {
|
||||
ContainerConfig.Container.Property prop = parentProp.getProperty(name);
|
||||
if (prop == null || UtilValidate.isEmpty(prop.value)) {
|
||||
return defaultValue;
|
||||
} else {
|
||||
return "true".equalsIgnoreCase(prop.value);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getPropertyValue(ContainerConfig.Container.Property parentProp, String name, String defaultValue) {
|
||||
ContainerConfig.Container.Property prop = parentProp.getProperty(name);
|
||||
if (prop == null || UtilValidate.isEmpty(prop.value)) {
|
||||
return defaultValue;
|
||||
} else {
|
||||
return prop.value;
|
||||
}
|
||||
}
|
||||
|
||||
public static int getPropertyValue(ContainerConfig.Container.Property parentProp, String name, int defaultValue) {
|
||||
ContainerConfig.Container.Property prop = parentProp.getProperty(name);
|
||||
if (prop == null || UtilValidate.isEmpty(prop.value)) {
|
||||
return defaultValue;
|
||||
} else {
|
||||
int num = defaultValue;
|
||||
try {
|
||||
num = Integer.parseInt(prop.value);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
return num;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean getPropertyValue(ContainerConfig.Container.Property parentProp, String name, boolean defaultValue) {
|
||||
ContainerConfig.Container.Property prop = parentProp.getProperty(name);
|
||||
if (prop == null || UtilValidate.isEmpty(prop.value)) {
|
||||
return defaultValue;
|
||||
} else {
|
||||
return "true".equalsIgnoreCase(prop.value);
|
||||
}
|
||||
}
|
||||
|
||||
private ContainerConfig() {}
|
||||
|
||||
private static Collection<Container> getContainerPropsFromXml(URL xmlUrl) throws ContainerException {
|
||||
Document containerDocument = null;
|
||||
try {
|
||||
containerDocument = UtilXml.readXmlDocument(xmlUrl, true);
|
||||
} catch (SAXException e) {
|
||||
throw new ContainerException("Error reading the container config file: " + xmlUrl, e);
|
||||
} catch (ParserConfigurationException e) {
|
||||
throw new ContainerException("Error reading the container config file: " + xmlUrl, e);
|
||||
} catch (IOException e) {
|
||||
throw new ContainerException("Error reading the container config file: " + xmlUrl, e);
|
||||
}
|
||||
Element root = containerDocument.getDocumentElement();
|
||||
List<Container> result = new ArrayList<Container>();
|
||||
for (Element curElement: UtilXml.childElementList(root, "container")) {
|
||||
result.add(new Container(curElement));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static class Container {
|
||||
public final String name;
|
||||
public final String className;
|
||||
public final List<String> loaders;
|
||||
public final Map<String, Property> properties;
|
||||
|
||||
public Container(Element element) {
|
||||
this.name = element.getAttribute("name");
|
||||
this.className = element.getAttribute("class");
|
||||
this.loaders = StringUtil.split(element.getAttribute("loaders"), ",");
|
||||
|
||||
properties = new LinkedHashMap<String, Property>();
|
||||
for (Element curElement: UtilXml.childElementList(element, "property")) {
|
||||
Property property = new Property(curElement);
|
||||
properties.put(property.name, property);
|
||||
}
|
||||
}
|
||||
|
||||
public Property getProperty(String name) {
|
||||
return properties.get(name);
|
||||
}
|
||||
|
||||
public List<Property> getPropertiesWithValue(String value) {
|
||||
List<Property> props = new LinkedList<Property>();
|
||||
if (UtilValidate.isNotEmpty(properties)) {
|
||||
for (Property p: properties.values()) {
|
||||
if (p != null && value.equals(p.value)) {
|
||||
props.add(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
public static class Property {
|
||||
public String name;
|
||||
public String value;
|
||||
public Map<String, Property> properties;
|
||||
|
||||
public Property(Element element) {
|
||||
this.name = element.getAttribute("name");
|
||||
this.value = element.getAttribute("value");
|
||||
if (UtilValidate.isEmpty(this.value)) {
|
||||
this.value = UtilXml.childElementValue(element, "property-value");
|
||||
}
|
||||
|
||||
properties = new LinkedHashMap<String, Property>();
|
||||
for (Element curElement: UtilXml.childElementList(element, "property")) {
|
||||
Property property = new Property(curElement);
|
||||
properties.put(property.name, property);
|
||||
}
|
||||
}
|
||||
|
||||
public Property getProperty(String name) {
|
||||
return properties.get(name);
|
||||
}
|
||||
|
||||
public List<Property> getPropertiesWithValue(String value) {
|
||||
List<Property> props = new LinkedList<Property>();
|
||||
if (UtilValidate.isNotEmpty(properties)) {
|
||||
for (Property p: properties.values()) {
|
||||
if (p != null && value.equals(p.value)) {
|
||||
props.add(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
return props;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.container;
|
||||
|
||||
import org.ofbiz.base.config.GenericConfigException;
|
||||
|
||||
/**
|
||||
* ContainerException
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class ContainerException extends GenericConfigException {
|
||||
|
||||
public ContainerException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ContainerException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public ContainerException(Throwable t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
public ContainerException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.container;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.net.URL;
|
||||
import java.util.Collection;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.component.ComponentConfig;
|
||||
import org.ofbiz.base.start.Config;
|
||||
import org.ofbiz.base.start.StartupException;
|
||||
import org.ofbiz.base.start.StartupLoader;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
|
||||
/**
|
||||
* An object that loads containers (background processes).
|
||||
*
|
||||
* <p>Normally, instances of this class are created by OFBiz startup code, and
|
||||
* client code should not create instances of this class. Client code is
|
||||
* responsible for making sure containers are shut down properly. </p>
|
||||
*
|
||||
*/
|
||||
public class ContainerLoader implements StartupLoader {
|
||||
|
||||
public static final String module = ContainerLoader.class.getName();
|
||||
|
||||
private String configFile = null;
|
||||
private final List<Container> loadedContainers = new LinkedList<Container>();
|
||||
private boolean unloading = false;
|
||||
private boolean loaded = false;
|
||||
|
||||
/**
|
||||
* @see org.ofbiz.base.start.StartupLoader#load(Config, String[])
|
||||
*/
|
||||
@Override
|
||||
public synchronized void load(Config config, String args[]) throws StartupException {
|
||||
if (this.loaded || this.unloading) {
|
||||
return;
|
||||
}
|
||||
this.loadedContainers.clear();
|
||||
// get this loader's configuration file
|
||||
this.configFile = config.containerConfig;
|
||||
|
||||
List<String> loaders = null;
|
||||
for (Map loaderMap: config.loaders) {
|
||||
if (module.equals(loaderMap.get("class"))) {
|
||||
loaders = StringUtil.split((String)loaderMap.get("profiles"), ",");
|
||||
}
|
||||
}
|
||||
|
||||
Debug.logInfo("[Startup] Loading containers from " + configFile + " for loaders " + loaders, module);
|
||||
Collection<ContainerConfig.Container> containers = null;
|
||||
try {
|
||||
containers = ContainerConfig.getContainers(configFile);
|
||||
} catch (ContainerException e) {
|
||||
throw new StartupException(e);
|
||||
}
|
||||
for (ContainerConfig.Container containerCfg : containers) {
|
||||
if (this.unloading) {
|
||||
return;
|
||||
}
|
||||
boolean matchingLoaderFound = false;
|
||||
if (UtilValidate.isEmpty(containerCfg.loaders) && UtilValidate.isEmpty(loaders)) {
|
||||
matchingLoaderFound = true;
|
||||
} else {
|
||||
for (String loader: loaders) {
|
||||
if (UtilValidate.isEmpty(containerCfg.loaders) || containerCfg.loaders.contains(loader)) {
|
||||
matchingLoaderFound = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (matchingLoaderFound) {
|
||||
Debug.logInfo("Loading container: " + containerCfg.name, module);
|
||||
Container tmpContainer = loadContainer(containerCfg, args);
|
||||
this.loadedContainers.add(tmpContainer);
|
||||
Debug.logInfo("Loaded container: " + containerCfg.name, module);
|
||||
}
|
||||
}
|
||||
if (this.unloading) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<ContainerConfig.Container> containersDefinedInComponents = ComponentConfig.getAllContainers();
|
||||
for (ContainerConfig.Container containerCfg: containersDefinedInComponents) {
|
||||
boolean matchingLoaderFound = false;
|
||||
if (UtilValidate.isEmpty(containerCfg.loaders) && UtilValidate.isEmpty(loaders)) {
|
||||
matchingLoaderFound = true;
|
||||
} else {
|
||||
for (String loader: loaders) {
|
||||
if (UtilValidate.isEmpty(containerCfg.loaders) || containerCfg.loaders.contains(loader)) {
|
||||
matchingLoaderFound = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (matchingLoaderFound) {
|
||||
Debug.logInfo("Loading component's container: " + containerCfg.name, module);
|
||||
Container tmpContainer = loadContainer(containerCfg, args);
|
||||
this.loadedContainers.add(tmpContainer);
|
||||
Debug.logInfo("Loaded component's container: " + containerCfg.name, module);
|
||||
}
|
||||
}
|
||||
// Get hot-deploy container configuration files
|
||||
ClassLoader loader = Thread.currentThread().getContextClassLoader();
|
||||
Enumeration<URL> resources;
|
||||
try {
|
||||
resources = loader.getResources("hot-deploy-containers.xml");
|
||||
while (resources.hasMoreElements() && !this.unloading) {
|
||||
URL xmlUrl = resources.nextElement();
|
||||
Debug.logInfo("Loading hot-deploy containers from " + xmlUrl, module);
|
||||
Collection<ContainerConfig.Container> hotDeployContainers = ContainerConfig.getContainers(xmlUrl);
|
||||
for (ContainerConfig.Container containerCfg : hotDeployContainers) {
|
||||
if (this.unloading) {
|
||||
return;
|
||||
}
|
||||
Container tmpContainer = loadContainer(containerCfg, args);
|
||||
this.loadedContainers.add(tmpContainer);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, "Could not load hot-deploy-containers.xml", module);
|
||||
throw new StartupException(e);
|
||||
}
|
||||
loaded = true;
|
||||
}
|
||||
|
||||
private Container loadContainer(ContainerConfig.Container containerCfg, String[] args) throws StartupException {
|
||||
// load the container class
|
||||
ClassLoader loader = Thread.currentThread().getContextClassLoader();
|
||||
if (loader == null) {
|
||||
Debug.logWarning("Unable to get context classloader; using system", module);
|
||||
loader = ClassLoader.getSystemClassLoader();
|
||||
}
|
||||
Class<?> containerClass = null;
|
||||
try {
|
||||
containerClass = loader.loadClass(containerCfg.className);
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new StartupException("Cannot locate container class", e);
|
||||
}
|
||||
if (containerClass == null) {
|
||||
throw new StartupException("Component container class not loaded");
|
||||
}
|
||||
|
||||
// create a new instance of the container object
|
||||
Container containerObj = null;
|
||||
try {
|
||||
containerObj = (Container) containerClass.newInstance();
|
||||
} catch (InstantiationException e) {
|
||||
throw new StartupException("Cannot create " + containerCfg.name, e);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new StartupException("Cannot create " + containerCfg.name, e);
|
||||
} catch (ClassCastException e) {
|
||||
throw new StartupException("Cannot create " + containerCfg.name, e);
|
||||
}
|
||||
|
||||
if (containerObj == null) {
|
||||
throw new StartupException("Unable to create instance of component container");
|
||||
}
|
||||
|
||||
// initialize the container object
|
||||
try {
|
||||
containerObj.init(args, containerCfg.name, configFile);
|
||||
} catch (ContainerException e) {
|
||||
throw new StartupException("Cannot init() " + containerCfg.name, e);
|
||||
} catch (java.lang.AbstractMethodError e) {
|
||||
throw new StartupException("Cannot init() " + containerCfg.name, e);
|
||||
}
|
||||
|
||||
return containerObj;
|
||||
}
|
||||
|
||||
private void printThreadDump() {
|
||||
Thread currentThread = Thread.currentThread();
|
||||
ThreadGroup group = currentThread.getThreadGroup();
|
||||
while (group.getParent() != null) {
|
||||
group = group.getParent();
|
||||
}
|
||||
Thread threadArr[] = new Thread[1000];
|
||||
group.enumerate(threadArr);
|
||||
|
||||
StringWriter writer = new StringWriter();
|
||||
PrintWriter out = new PrintWriter(writer);
|
||||
out.println("Thread dump:");
|
||||
for (Thread t: threadArr) {
|
||||
if (t != null) {
|
||||
ThreadGroup g = t.getThreadGroup();
|
||||
out.println("Thread: " + t.getName() + " [" + t.getId() + "] @ " + (g != null ? g.getName() : "[none]") + " : " + t.getPriority() + " [" + t.getState().name() + "]");
|
||||
out.println("--- Alive: " + t.isAlive() + " Daemon: " + t.isDaemon());
|
||||
for (StackTraceElement stack: t.getStackTrace()) {
|
||||
out.println("### " + stack.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
Debug.logInfo(writer.toString(), module);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.ofbiz.base.start.StartupLoader#start()
|
||||
*/
|
||||
@Override
|
||||
public synchronized void start() throws StartupException {
|
||||
if (!this.loaded || this.unloading) {
|
||||
throw new IllegalStateException("start() called on unloaded containers");
|
||||
}
|
||||
Debug.logInfo("[Startup] Starting containers...", module);
|
||||
// start each container object
|
||||
for (Container container: this.loadedContainers) {
|
||||
if (this.unloading) {
|
||||
return;
|
||||
}
|
||||
Debug.logInfo("Starting container " + container.getName(), module);
|
||||
try {
|
||||
container.start();
|
||||
} catch (ContainerException e) {
|
||||
throw new StartupException("Cannot start() " + container.getClass().getName(), e);
|
||||
} catch (java.lang.AbstractMethodError e) {
|
||||
throw new StartupException("Cannot start() " + container.getClass().getName(), e);
|
||||
}
|
||||
Debug.logInfo("Started container " + container.getName(), module);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.ofbiz.base.start.StartupLoader#unload()
|
||||
*/
|
||||
@Override
|
||||
public void unload() throws StartupException {
|
||||
if (!this.unloading) {
|
||||
this.unloading = true;
|
||||
synchronized (this) {
|
||||
Debug.logInfo("Shutting down containers", module);
|
||||
if (Debug.verboseOn()) {
|
||||
printThreadDump();
|
||||
}
|
||||
// shutting down in reverse order
|
||||
for (int i = this.loadedContainers.size(); i > 0; i--) {
|
||||
Container container = this.loadedContainers.get(i-1);
|
||||
Debug.logInfo("Stopping container " + container.getName(), module);
|
||||
try {
|
||||
container.stop();
|
||||
} catch (ContainerException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
Debug.logInfo("Stopped container " + container.getName(), module);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.container;
|
||||
|
||||
import org.ofbiz.base.component.AlreadyLoadedException;
|
||||
import org.ofbiz.base.component.ComponentException;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
|
||||
/**
|
||||
* A Container implementation to run the tests configured through this testtools stuff.
|
||||
*/
|
||||
public class JustLoadComponentsContainer implements Container {
|
||||
|
||||
public static final String module = JustLoadComponentsContainer.class.getName();
|
||||
|
||||
private String name;
|
||||
|
||||
@Override
|
||||
public void init(String[] args, String name, String configFile) {
|
||||
this.name = name;
|
||||
try {
|
||||
ComponentContainer cc = new ComponentContainer();
|
||||
cc.loadComponents(null);
|
||||
} catch (AlreadyLoadedException e) {
|
||||
Debug.logError(e, module);
|
||||
} catch (ComponentException e) {
|
||||
Debug.logError(e, module);
|
||||
//throw UtilMisc.initCause(new ContainerException(e.getMessage()), e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean start() throws ContainerException {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void stop() throws ContainerException {
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.container;
|
||||
|
||||
import java.net.UnknownHostException;
|
||||
import java.rmi.NoSuchObjectException;
|
||||
import java.rmi.RemoteException;
|
||||
import java.rmi.registry.LocateRegistry;
|
||||
import java.rmi.registry.Registry;
|
||||
import java.rmi.server.UnicastRemoteObject;
|
||||
|
||||
import org.ofbiz.base.start.Start;
|
||||
import org.ofbiz.base.util.RMIExtendedSocketFactory;
|
||||
|
||||
/**
|
||||
* NamingServiceContainer
|
||||
*
|
||||
*/
|
||||
|
||||
public class NamingServiceContainer implements Container {
|
||||
|
||||
public static final String module = NamingServiceContainer.class.getName();
|
||||
|
||||
protected String configFileLocation = null;
|
||||
protected boolean isRunning = false;
|
||||
protected Registry registry = null;
|
||||
protected int namingPort = 1099;
|
||||
protected String namingHost = null;
|
||||
|
||||
protected RMIExtendedSocketFactory rmiSocketFactory;
|
||||
|
||||
private String name;
|
||||
|
||||
public void init(String[] args, String name, String configFile) throws ContainerException {
|
||||
this.name =name;
|
||||
this.configFileLocation = configFile;
|
||||
|
||||
ContainerConfig.Container cfg = ContainerConfig.getContainer(name, configFileLocation);
|
||||
|
||||
// get the naming (JNDI) port
|
||||
|
||||
ContainerConfig.Container.Property port = cfg.getProperty("port");
|
||||
if (port.value != null) {
|
||||
try {
|
||||
this.namingPort = Integer.parseInt(port.value) + Start.getInstance().getConfig().portOffset;
|
||||
} catch (Exception e) {
|
||||
throw new ContainerException("Invalid port defined in container [naming-container] configuration or as portOffset; not a valid int");
|
||||
}
|
||||
}
|
||||
|
||||
// get the naming (JNDI) server
|
||||
ContainerConfig.Container.Property host = cfg.getProperty("host");
|
||||
if (host != null && host.value != null) {
|
||||
this.namingHost = host.value ;
|
||||
}
|
||||
|
||||
try {
|
||||
rmiSocketFactory = new RMIExtendedSocketFactory( namingHost );
|
||||
} catch ( UnknownHostException uhEx ) {
|
||||
throw new ContainerException("Invalid host defined in container [naming-container] configuration; not a valid IP address", uhEx);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public boolean start() throws ContainerException {
|
||||
try {
|
||||
registry = LocateRegistry.createRegistry(namingPort, rmiSocketFactory, rmiSocketFactory);
|
||||
} catch (RemoteException e) {
|
||||
throw new ContainerException("Unable to locate naming service", e);
|
||||
}
|
||||
|
||||
isRunning = true;
|
||||
return isRunning;
|
||||
}
|
||||
|
||||
public void stop() throws ContainerException {
|
||||
if (isRunning) {
|
||||
try {
|
||||
isRunning = !UnicastRemoteObject.unexportObject(registry, true);
|
||||
} catch (NoSuchObjectException e) {
|
||||
throw new ContainerException("Unable to shutdown naming registry");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import org.ofbiz.base.util.ObjectType;
|
||||
|
||||
/** Abstract Converter class. This class handles converter registration
|
||||
* and it implements the <code>canConvert</code>, <code>getSourceClass</code>,
|
||||
* and <code>getTargetClass</code> methods.
|
||||
*/
|
||||
public abstract class AbstractConverter<S, T> implements Converter<S, T>, ConverterLoader {
|
||||
private final Class<? super S> sourceClass;
|
||||
private final Class<? super T> targetClass;
|
||||
|
||||
protected AbstractConverter(Class<? super S> sourceClass, Class<? super T> targetClass) {
|
||||
this.sourceClass = sourceClass;
|
||||
this.targetClass = targetClass;
|
||||
}
|
||||
|
||||
public void loadConverters() {
|
||||
Converters.registerConverter(this);
|
||||
}
|
||||
|
||||
public T convert(Class<? extends T> targetClass, S obj) throws ConversionException {
|
||||
return convert(obj);
|
||||
}
|
||||
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && ObjectType.instanceOf(targetClass, this.getTargetClass());
|
||||
}
|
||||
|
||||
public Class<? super S> getSourceClass() {
|
||||
return sourceClass;
|
||||
}
|
||||
|
||||
public Class<? super T> getTargetClass() {
|
||||
return targetClass;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
/** Abstract LocalizedConverter class. This class handles converter registration
|
||||
* and it implements the <code>canConvert</code>, <code>getSourceClass</code>,
|
||||
* and <code>getTargetClass</code> methods.
|
||||
*/
|
||||
public abstract class AbstractLocalizedConverter<S, T> extends AbstractConverter<S, T> implements LocalizedConverter<S, T> {
|
||||
protected AbstractLocalizedConverter(Class<? super S> sourceClass, Class<? super T> targetClass) {
|
||||
super(sourceClass, targetClass);
|
||||
}
|
||||
|
||||
public T convert(Class<? extends T> targetClass, S obj, Locale locale, TimeZone timeZone) throws ConversionException {
|
||||
return convert(obj, locale, timeZone);
|
||||
}
|
||||
|
||||
public T convert(Class<? extends T> targetClass, S obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
return convert(obj, locale, timeZone, formatString);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
|
||||
/** Boolean Converter classes. */
|
||||
public class BooleanConverters implements ConverterLoader {
|
||||
public static class BooleanToInteger extends AbstractConverter<Boolean, Integer> {
|
||||
public BooleanToInteger() {
|
||||
super(Boolean.class, Integer.class);
|
||||
}
|
||||
|
||||
public Integer convert(Boolean obj) throws ConversionException {
|
||||
return obj.booleanValue() ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static class BooleanToList extends GenericSingletonToList<Boolean> {
|
||||
public BooleanToList() {
|
||||
super(Boolean.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class BooleanToSet extends GenericSingletonToSet<Boolean> {
|
||||
public BooleanToSet() {
|
||||
super(Boolean.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class BooleanToString extends AbstractConverter<Boolean, String> {
|
||||
public BooleanToString() {
|
||||
super(Boolean.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(Boolean obj) throws ConversionException {
|
||||
return obj.booleanValue() ? "true" : "false";
|
||||
}
|
||||
}
|
||||
|
||||
public static class IntegerToBoolean extends AbstractConverter<Integer, Boolean> {
|
||||
public IntegerToBoolean() {
|
||||
super(Integer.class, Boolean.class);
|
||||
}
|
||||
|
||||
public Boolean convert(Integer obj) throws ConversionException {
|
||||
return obj.intValue() == 0 ? false : true;
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToBoolean extends AbstractConverter<String, Boolean> {
|
||||
public StringToBoolean() {
|
||||
super(String.class, Boolean.class);
|
||||
}
|
||||
|
||||
public Boolean convert(String obj) throws ConversionException {
|
||||
return "TRUE".equals(obj.trim().toUpperCase());
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConverters() {
|
||||
Converters.loadContainedConverters(BooleanConverters.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
|
||||
/** Collection Converter classes. */
|
||||
public class CollectionConverters implements ConverterLoader {
|
||||
public static class ArrayCreator implements ConverterCreator, ConverterLoader {
|
||||
public void loadConverters() {
|
||||
Converters.registerCreator(this);
|
||||
}
|
||||
|
||||
public <S, T> Converter<S, T> createConverter(Class<S> sourceClass, Class<T> targetClass) {
|
||||
if (!sourceClass.isArray()) {
|
||||
return null;
|
||||
}
|
||||
if (targetClass != List.class) {
|
||||
return null;
|
||||
}
|
||||
if (!(sourceClass.getComponentType() instanceof Object)) {
|
||||
return null;
|
||||
}
|
||||
return UtilGenerics.cast(new ArrayClassToList<S, T>(sourceClass, targetClass));
|
||||
}
|
||||
}
|
||||
|
||||
private static class ArrayClassToList<S, T> extends AbstractConverter<S, T> {
|
||||
public ArrayClassToList(Class<S> sourceClass, Class<T> targetClass) {
|
||||
super(sourceClass, targetClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public T convert(S obj) throws ConversionException {
|
||||
List<Object> list = new LinkedList<Object>();
|
||||
int len = Array.getLength(obj);
|
||||
for (int i = 0; i < len; i++) {
|
||||
list.add(Array.get(obj, i));
|
||||
}
|
||||
return UtilGenerics.<T>cast(list);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ArrayToList<T> extends AbstractConverter<T[], List<T>> {
|
||||
public ArrayToList() {
|
||||
super(Object[].class, List.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
if (!sourceClass.isArray()) {
|
||||
return false;
|
||||
}
|
||||
if (!List.class.isAssignableFrom(targetClass)) {
|
||||
return false;
|
||||
}
|
||||
if (Object[].class.isAssignableFrom(sourceClass)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public List<T> convert(T[] obj) throws ConversionException {
|
||||
return Arrays.asList(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ListToString<T> extends AbstractConverter<List<T>, String> {
|
||||
public ListToString() {
|
||||
super(List.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(List<T> obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static class MapToList<K, V> extends AbstractConverter<Map<K, V>, List<Map<K, V>>> {
|
||||
public MapToList() {
|
||||
super(Map.class, List.class);
|
||||
}
|
||||
|
||||
public List<Map<K, V>> convert(Map<K, V> obj) throws ConversionException {
|
||||
List<Map<K, V>> tempList = new LinkedList<Map<K, V>>();
|
||||
tempList.add(obj);
|
||||
return tempList;
|
||||
}
|
||||
}
|
||||
|
||||
public static class MapToSet<K, V> extends AbstractConverter<Map<K, V>, Set<Map<K, V>>> {
|
||||
public MapToSet() {
|
||||
super(Map.class, Set.class);
|
||||
}
|
||||
|
||||
public Set<Map<K, V>> convert(Map<K, V> obj) throws ConversionException {
|
||||
Set<Map<K, V>> tempSet = new HashSet<Map<K, V>>();
|
||||
tempSet.add(obj);
|
||||
return tempSet;
|
||||
}
|
||||
}
|
||||
|
||||
public static class MapToString<K, V> extends AbstractConverter<Map<K, V>, String> {
|
||||
public MapToString() {
|
||||
super(Map.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(Map<K, V> obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToList extends GenericSingletonToList<String> {
|
||||
public StringToList() {
|
||||
super(String.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> convert(String obj) throws ConversionException {
|
||||
if (obj.startsWith("[") && obj.endsWith("]")) {
|
||||
return StringUtil.toList(obj);
|
||||
} else {
|
||||
return super.convert(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToMap extends AbstractConverter<String, Map<String, String>> {
|
||||
public StringToMap() {
|
||||
super(String.class, Map.class);
|
||||
}
|
||||
|
||||
public Map<String, String> convert(String obj) throws ConversionException {
|
||||
if (obj.startsWith("{") && obj.endsWith("}")) {
|
||||
return StringUtil.toMap(obj);
|
||||
}
|
||||
throw new ConversionException("Could not convert " + obj + " to Map: ");
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToSet extends GenericSingletonToSet<String> {
|
||||
public StringToSet() {
|
||||
super(String.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> convert(String obj) throws ConversionException {
|
||||
if (obj.startsWith("[") && obj.endsWith("]")) {
|
||||
return StringUtil.toSet(obj);
|
||||
} else {
|
||||
return super.convert(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConverters() {
|
||||
Converters.loadContainedConverters(CollectionConverters.class);
|
||||
}
|
||||
}
|
||||
@@ -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.base.conversion;
|
||||
|
||||
/** ConversionException class. */
|
||||
@SuppressWarnings("serial")
|
||||
public class ConversionException extends Exception {
|
||||
public ConversionException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public ConversionException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ConversionException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
/** Converter interface. Classes implement this interface to convert one
|
||||
* Java object type to another.
|
||||
*
|
||||
* @param <S> The source object type
|
||||
* @param <T> The target object type
|
||||
*/
|
||||
public interface Converter<S, T> {
|
||||
/** Returns <code>true</code> if this object can convert
|
||||
* <code>sourceClass</code> to <code>targetClass</code>.
|
||||
* <p>Implementations can accomodate class hierarchy ranges
|
||||
* by converting super classes or interfaces.</p>
|
||||
*
|
||||
* @param sourceClass The source <code>Class</code>
|
||||
* @param targetClass The target <code>Class</code>
|
||||
* @return <code>true</code> if this object can convert
|
||||
* <code>sourceClass</code> to <code>targetClass</code>.
|
||||
*/
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass);
|
||||
|
||||
/** Converts <code>obj</code> to <code>T</code>.
|
||||
*
|
||||
* @param obj The source <code>Object</code> to convert
|
||||
* @return The converted <code>Object</code>
|
||||
* @throws ConversionException
|
||||
*/
|
||||
public T convert(S obj) throws ConversionException;
|
||||
|
||||
/** Converts <code>obj</code> to <code>T</code>.
|
||||
*
|
||||
* @param targetClass The <code>Class</code> to convert to
|
||||
* @param obj The source <code>Object</code> to convert
|
||||
* @return The converted <code>Object</code>
|
||||
* @throws ConversionException
|
||||
*/
|
||||
public T convert(Class<? extends T> targetClass, S obj) throws ConversionException;
|
||||
|
||||
/** Returns the source <code>Class</code> for this converter.
|
||||
*
|
||||
* @return The source <code>Class</code> for this converter
|
||||
*/
|
||||
public Class<?> getSourceClass();
|
||||
|
||||
/** Returns the target <code>Class</code> for this converter.
|
||||
*
|
||||
* @return The target <code>Class</code> for this converter
|
||||
*/
|
||||
public Class<?> getTargetClass();
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
/** ConverterCreator interface. Classes implement this interface to create a
|
||||
* converter that can convert one Java object type to another.
|
||||
*/
|
||||
public interface ConverterCreator {
|
||||
/** Creates a Converter that can convert the <code>sourceClass</code> to
|
||||
* the <code>targetClass</code>. Returns <code>null</code> if this creater
|
||||
* doesn't support the class pair.
|
||||
*
|
||||
* @param sourceClass The source <code>Class</code> to convert
|
||||
* @param targetClass The target <code>Class</code> to convert to
|
||||
* @return a converter that can convert <code>Object</code>s
|
||||
*/
|
||||
public <S, T> Converter<S, T> createConverter(Class<S> sourceClass, Class<T> targetClass);
|
||||
}
|
||||
@@ -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.base.conversion;
|
||||
|
||||
/** Converter loader interface. Applications implement this
|
||||
* interface to load their Java object converters.
|
||||
*
|
||||
*/
|
||||
public interface ConverterLoader {
|
||||
/** Create and register converters with the Java object type
|
||||
* conversion framework. If the converter extends one of the
|
||||
* converter abstract classes, then the converter will register
|
||||
* itself when an instance is created. Otherwise, call
|
||||
* {@link org.ofbiz.base.conversion.Converters#registerConverter(Converter)}
|
||||
* with the <code>Converter</code> instance.
|
||||
*
|
||||
*/
|
||||
public void loadConverters();
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.ServiceLoader;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.ofbiz.base.lang.SourceMonitored;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.ObjectType;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
|
||||
/** A <code>Converter</code> factory and repository. */
|
||||
@SourceMonitored
|
||||
public class Converters {
|
||||
protected static final String module = Converters.class.getName();
|
||||
protected static final String DELIMITER = "->";
|
||||
protected static final ConcurrentHashMap<String, Converter<?, ?>> converterMap = new ConcurrentHashMap<String, Converter<?, ?>>();
|
||||
protected static final Set<ConverterCreator> creators = new HashSet<ConverterCreator>();
|
||||
protected static final Set<String> noConversions = new HashSet<String>();
|
||||
|
||||
static {
|
||||
registerCreator(new PassThruConverterCreator());
|
||||
ClassLoader loader = Thread.currentThread().getContextClassLoader();
|
||||
Iterator<ConverterLoader> converterLoaders = ServiceLoader.load(ConverterLoader.class, loader).iterator();
|
||||
while (converterLoaders.hasNext()) {
|
||||
try {
|
||||
ConverterLoader converterLoader = converterLoaders.next();
|
||||
converterLoader.loadConverters();
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Converters() {}
|
||||
|
||||
/** Returns an appropriate <code>Converter</code> instance for
|
||||
* <code>sourceClass</code> and <code>targetClass</code>. If no matching
|
||||
* <code>Converter</code> is found, the method throws
|
||||
* <code>ClassNotFoundException</code>.
|
||||
*
|
||||
* <p>This method is intended to be used when the source or
|
||||
* target <code>Object</code> types are unknown at compile time.
|
||||
* If the source and target <code>Object</code> types are known
|
||||
* at compile time, then one of the "ready made" converters should be used.</p>
|
||||
*
|
||||
* @param sourceClass The object class to convert from
|
||||
* @param targetClass The object class to convert to
|
||||
* @return A matching <code>Converter</code> instance
|
||||
* @throws ClassNotFoundException
|
||||
*/
|
||||
public static <S, T> Converter<S, T> getConverter(Class<S> sourceClass, Class<T> targetClass) throws ClassNotFoundException {
|
||||
String key = sourceClass.getName().concat(DELIMITER).concat(targetClass.getName());
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Getting converter: " + key, module);
|
||||
}
|
||||
OUTER:
|
||||
do {
|
||||
Converter<?, ?> result = converterMap.get(key);
|
||||
if (result != null) {
|
||||
return UtilGenerics.cast(result);
|
||||
}
|
||||
if (noConversions.contains(key)) {
|
||||
throw new ClassNotFoundException("No converter found for " + key);
|
||||
}
|
||||
Class<?> foundSourceClass = null;
|
||||
Converter<?, ?> foundConverter = null;
|
||||
for (Converter<?, ?> value : converterMap.values()) {
|
||||
if (value.canConvert(sourceClass, targetClass)) {
|
||||
// this converter can deal with the source/target pair
|
||||
if (foundSourceClass == null || foundSourceClass.isAssignableFrom(value.getSourceClass())) {
|
||||
// remember the current target source class; if we find another converter, check
|
||||
// to see if it's source class is assignable to this one, and if so, it means it's
|
||||
// a child class, so we'll then take that converter.
|
||||
foundSourceClass = value.getSourceClass();
|
||||
foundConverter = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (foundConverter != null) {
|
||||
converterMap.putIfAbsent(key, foundConverter);
|
||||
continue OUTER;
|
||||
}
|
||||
for (ConverterCreator value : creators) {
|
||||
result = createConverter(value, sourceClass, targetClass);
|
||||
if (result != null) {
|
||||
converterMap.putIfAbsent(key, result);
|
||||
continue OUTER;
|
||||
}
|
||||
}
|
||||
boolean addedToSet = false;
|
||||
synchronized (noConversions) {
|
||||
addedToSet = noConversions.add(key);
|
||||
}
|
||||
if (addedToSet) {
|
||||
Debug.logWarning("*** No converter found, converting from " +
|
||||
sourceClass.getName() + " to " + targetClass.getName() +
|
||||
". Please report this message to the developer community so " +
|
||||
"a suitable converter can be created. ***", module);
|
||||
}
|
||||
throw new ClassNotFoundException("No converter found for " + key);
|
||||
} while (true);
|
||||
}
|
||||
|
||||
private static <S, SS extends S, T, TT extends T> Converter<SS, TT> createConverter(ConverterCreator creater, Class<SS> sourceClass, Class<TT> targetClass) {
|
||||
return creater.createConverter(sourceClass, targetClass);
|
||||
}
|
||||
|
||||
/** Load all classes that implement <code>Converter</code> and are
|
||||
* contained in <code>containerClass</code>.
|
||||
*
|
||||
* @param containerClass
|
||||
*/
|
||||
public static void loadContainedConverters(Class<?> containerClass) {
|
||||
// This only returns -public- classes and interfaces
|
||||
for (Class<?> clz: containerClass.getClasses()) {
|
||||
try {
|
||||
// non-abstract, which means no interfaces or abstract classes
|
||||
if ((clz.getModifiers() & Modifier.ABSTRACT) == 0) {
|
||||
Object value;
|
||||
try {
|
||||
value = clz.getConstructor().newInstance();
|
||||
} catch (NoSuchMethodException e) {
|
||||
// ignore this, as this class might be some other helper class,
|
||||
// with a non-pubilc constructor
|
||||
continue;
|
||||
}
|
||||
if (value instanceof ConverterLoader) {
|
||||
ConverterLoader loader = (ConverterLoader) value;
|
||||
loader.loadConverters();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Registers a <code>ConverterCreater</code> instance to be used by the
|
||||
* {@link org.ofbiz.base.conversion.Converters#getConverter(Class, Class)}
|
||||
* method, when a converter can't be found.
|
||||
*
|
||||
* @param <S> The source object type
|
||||
* @param <T> The target object type
|
||||
* @param creator The <code>ConverterCreater</code> instance to register
|
||||
*/
|
||||
public static <S, T> void registerCreator(ConverterCreator creator) {
|
||||
synchronized (creators) {
|
||||
creators.add(creator);
|
||||
}
|
||||
}
|
||||
|
||||
/** Registers a <code>Converter</code> instance to be used by the
|
||||
* {@link org.ofbiz.base.conversion.Converters#getConverter(Class, Class)}
|
||||
* method.
|
||||
*
|
||||
* @param <S> The source object type
|
||||
* @param <T> The target object type
|
||||
* @param converter The <code>Converter</code> instance to register
|
||||
*/
|
||||
public static <S, T> void registerConverter(Converter<S, T> converter) {
|
||||
registerConverter(converter, converter.getSourceClass(), converter.getTargetClass());
|
||||
}
|
||||
|
||||
public static <S, T> void registerConverter(Converter<S, T> converter, Class<?> sourceClass, Class<?> targetClass) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (sourceClass != null) {
|
||||
sb.append(sourceClass.getName());
|
||||
} else {
|
||||
sb.append("<null>");
|
||||
}
|
||||
sb.append(DELIMITER);
|
||||
sb.append(targetClass.getName());
|
||||
String key = sb.toString();
|
||||
if (converterMap.putIfAbsent(key, converter) == null) {
|
||||
Debug.logVerbose("Registered converter " + converter.getClass().getName(), module);
|
||||
}
|
||||
}
|
||||
|
||||
protected static class PassThruConverterCreator implements ConverterCreator{
|
||||
protected PassThruConverterCreator() {
|
||||
}
|
||||
|
||||
public <S, T> Converter<S, T> createConverter(Class<S> sourceClass, Class<T> targetClass) {
|
||||
if (ObjectType.instanceOf(sourceClass, targetClass)) {
|
||||
return new PassThruConverter<S, T>(sourceClass, targetClass);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Pass thru converter used when the source and target java object
|
||||
* types are the same. The <code>convert</code> method returns the
|
||||
* source object.
|
||||
*
|
||||
*/
|
||||
protected static class PassThruConverter<S, T> implements Converter<S, T> {
|
||||
private final Class<S> sourceClass;
|
||||
private final Class<T> targetClass;
|
||||
|
||||
public PassThruConverter(Class<S> sourceClass, Class<T> targetClass) {
|
||||
this.sourceClass = sourceClass;
|
||||
this.targetClass = targetClass;
|
||||
}
|
||||
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return this.sourceClass == sourceClass && this.targetClass == targetClass;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public T convert(S obj) throws ConversionException {
|
||||
return (T) obj;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public T convert(Class<? extends T> targetClass, S obj) throws ConversionException {
|
||||
return (T) obj;
|
||||
}
|
||||
|
||||
public Class<?> getSourceClass() {
|
||||
return sourceClass;
|
||||
}
|
||||
|
||||
public Class<?> getTargetClass() {
|
||||
return targetClass;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,783 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.text.DateFormat;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.ofbiz.base.util.ObjectType;
|
||||
import org.ofbiz.base.util.TimeDuration;
|
||||
import org.ofbiz.base.util.UtilDateTime;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
|
||||
import com.ibm.icu.util.Calendar;
|
||||
|
||||
/** Date/time Converter classes. */
|
||||
public class DateTimeConverters implements ConverterLoader {
|
||||
public static class CalendarToDate extends AbstractConverter<Calendar, Date> {
|
||||
public CalendarToDate() {
|
||||
super(Calendar.class, Date.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public Date convert(Calendar obj) throws ConversionException {
|
||||
return obj.getTime();
|
||||
}
|
||||
}
|
||||
|
||||
public static class CalendarToLong extends AbstractConverter<Calendar, Long> {
|
||||
public CalendarToLong() {
|
||||
super(Calendar.class, Long.class);
|
||||
}
|
||||
|
||||
public Long convert(Calendar obj) throws ConversionException {
|
||||
return obj.getTimeInMillis();
|
||||
}
|
||||
}
|
||||
|
||||
public static class CalendarToString extends AbstractConverter<Calendar, String> {
|
||||
public CalendarToString() {
|
||||
super(Calendar.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(Calendar obj) throws ConversionException {
|
||||
Locale locale = obj.getLocale(com.ibm.icu.util.ULocale.VALID_LOCALE).toLocale();
|
||||
TimeZone timeZone = UtilDateTime.toTimeZone(obj.getTimeZone().getID());
|
||||
DateFormat df = UtilDateTime.toDateTimeFormat(UtilDateTime.getDateTimeFormat(), timeZone, locale);
|
||||
return df.format(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CalendarToTimestamp extends AbstractConverter<Calendar, Timestamp> {
|
||||
public CalendarToTimestamp() {
|
||||
super(Calendar.class, Timestamp.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public Timestamp convert(Calendar obj) throws ConversionException {
|
||||
return new Timestamp(obj.getTimeInMillis());
|
||||
}
|
||||
}
|
||||
|
||||
public static class DateToCalendar extends GenericLocalizedConverter<Date, Calendar> {
|
||||
public DateToCalendar() {
|
||||
super(Date.class, Calendar.class);
|
||||
}
|
||||
|
||||
public Calendar convert(Date obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
return UtilDateTime.toCalendar(obj, timeZone, locale);
|
||||
}
|
||||
}
|
||||
|
||||
public static class DateToLong extends AbstractConverter<java.util.Date, Long> {
|
||||
public DateToLong() {
|
||||
super(java.util.Date.class, Long.class);
|
||||
}
|
||||
|
||||
public Long convert(java.util.Date obj) throws ConversionException {
|
||||
return obj.getTime();
|
||||
}
|
||||
}
|
||||
|
||||
public static class DateToSqlDate extends AbstractConverter<java.util.Date, java.sql.Date> {
|
||||
public DateToSqlDate() {
|
||||
super(java.util.Date.class, java.sql.Date.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Date convert(java.util.Date obj) throws ConversionException {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(obj);
|
||||
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
|
||||
cal.set(Calendar.MILLISECOND, 0);
|
||||
return new java.sql.Date(cal.getTimeInMillis());
|
||||
}
|
||||
}
|
||||
|
||||
public static class DateToSqlTime extends AbstractConverter<java.util.Date, java.sql.Time> {
|
||||
public DateToSqlTime() {
|
||||
super(java.util.Date.class, java.sql.Time.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Time convert(java.util.Date obj) throws ConversionException {
|
||||
return new java.sql.Time(obj.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
public static class DateToString extends GenericLocalizedConverter<java.util.Date, String> {
|
||||
public DateToString() {
|
||||
super(java.util.Date.class, String.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convert(Date obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
public String convert(java.util.Date obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
DateFormat df = null;
|
||||
if (UtilValidate.isEmpty(formatString)) {
|
||||
df = UtilDateTime.toDateTimeFormat(UtilDateTime.getDateTimeFormat(), timeZone, locale);
|
||||
} else {
|
||||
df = UtilDateTime.toDateTimeFormat(formatString, timeZone, locale);
|
||||
}
|
||||
return df.format(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class DateToTimestamp extends AbstractConverter<java.util.Date, java.sql.Timestamp> {
|
||||
public DateToTimestamp() {
|
||||
super(java.util.Date.class, java.sql.Timestamp.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Timestamp convert(java.util.Date obj) throws ConversionException {
|
||||
return new java.sql.Timestamp(obj.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
public static class DurationToBigDecimal extends AbstractConverter<TimeDuration, java.math.BigDecimal> {
|
||||
public DurationToBigDecimal() {
|
||||
super(TimeDuration.class, java.math.BigDecimal.class);
|
||||
}
|
||||
|
||||
public java.math.BigDecimal convert(TimeDuration obj) throws ConversionException {
|
||||
return new java.math.BigDecimal(TimeDuration.toLong(obj));
|
||||
}
|
||||
}
|
||||
|
||||
public static class DurationToDouble extends AbstractConverter<TimeDuration, Double> {
|
||||
public DurationToDouble() {
|
||||
super(TimeDuration.class, Double.class);
|
||||
}
|
||||
|
||||
public Double convert(TimeDuration obj) throws ConversionException {
|
||||
return Double.valueOf(TimeDuration.toLong(obj));
|
||||
}
|
||||
}
|
||||
|
||||
public static class DurationToFloat extends AbstractConverter<TimeDuration, Float> {
|
||||
public DurationToFloat() {
|
||||
super(TimeDuration.class, Float.class);
|
||||
}
|
||||
|
||||
public Float convert(TimeDuration obj) throws ConversionException {
|
||||
return Float.valueOf(TimeDuration.toLong(obj));
|
||||
}
|
||||
}
|
||||
|
||||
public static class DurationToList extends GenericSingletonToList<TimeDuration> {
|
||||
public DurationToList() {
|
||||
super(TimeDuration.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class DurationToLong extends AbstractConverter<TimeDuration, Long> {
|
||||
public DurationToLong() {
|
||||
super(TimeDuration.class, Long.class);
|
||||
}
|
||||
|
||||
public Long convert(TimeDuration obj) throws ConversionException {
|
||||
return TimeDuration.toLong(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class DurationToSet extends GenericSingletonToSet<TimeDuration> {
|
||||
public DurationToSet() {
|
||||
super(TimeDuration.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class DurationToString extends AbstractConverter<TimeDuration, String> {
|
||||
public DurationToString() {
|
||||
super(TimeDuration.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(TimeDuration obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static abstract class GenericLocalizedConverter<S, T> extends AbstractLocalizedConverter<S, T> {
|
||||
protected GenericLocalizedConverter(Class<S> sourceClass, Class<T> targetClass) {
|
||||
super(sourceClass, targetClass);
|
||||
}
|
||||
|
||||
public T convert(S obj) throws ConversionException {
|
||||
return convert(obj, Locale.getDefault(), TimeZone.getDefault(), null);
|
||||
}
|
||||
|
||||
public T convert(S obj, Locale locale, TimeZone timeZone) throws ConversionException {
|
||||
return convert(obj, locale, timeZone, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class LongToCalendar extends AbstractLocalizedConverter<Long, Calendar> {
|
||||
public LongToCalendar() {
|
||||
super(Long.class, Calendar.class);
|
||||
}
|
||||
|
||||
public Calendar convert(Long obj) throws ConversionException {
|
||||
return convert(obj, Locale.getDefault(), TimeZone.getDefault());
|
||||
}
|
||||
|
||||
public Calendar convert(Long obj, Locale locale, TimeZone timeZone) throws ConversionException {
|
||||
return UtilDateTime.toCalendar(new java.util.Date(obj.longValue()), timeZone, locale);
|
||||
}
|
||||
|
||||
public Calendar convert(Long obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
return convert(obj, Locale.getDefault(), TimeZone.getDefault());
|
||||
}
|
||||
}
|
||||
|
||||
public static class NumberToDate extends AbstractConverter<Number, java.util.Date> {
|
||||
public NumberToDate() {
|
||||
super(Number.class, java.util.Date.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.util.Date convert(Number obj) throws ConversionException {
|
||||
return new java.util.Date(obj.longValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class NumberToDuration extends AbstractConverter<Number, TimeDuration> {
|
||||
public NumberToDuration() {
|
||||
super(Number.class, TimeDuration.class);
|
||||
}
|
||||
|
||||
public TimeDuration convert(Number obj) throws ConversionException {
|
||||
return TimeDuration.fromNumber(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class NumberToSqlDate extends AbstractConverter<Number, java.sql.Date> {
|
||||
public NumberToSqlDate() {
|
||||
super(Number.class, java.sql.Date.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Date convert(Number obj) throws ConversionException {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTimeInMillis(obj.longValue());
|
||||
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
|
||||
cal.set(Calendar.MILLISECOND, 0);
|
||||
return new java.sql.Date(cal.getTimeInMillis());
|
||||
}
|
||||
}
|
||||
|
||||
public static class NumberToSqlTime extends AbstractConverter<Number, java.sql.Time> {
|
||||
public NumberToSqlTime() {
|
||||
super(Number.class, java.sql.Time.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Time convert(Number obj) throws ConversionException {
|
||||
return new java.sql.Time(obj.longValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class NumberToTimestamp extends AbstractConverter<Number, java.sql.Timestamp> {
|
||||
public NumberToTimestamp() {
|
||||
super(Number.class, java.sql.Timestamp.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Timestamp convert(Number obj) throws ConversionException {
|
||||
return new java.sql.Timestamp(obj.longValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class SqlDateToDate extends AbstractConverter<java.sql.Date, java.util.Date> {
|
||||
public SqlDateToDate() {
|
||||
super(java.sql.Date.class, java.util.Date.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.util.Date convert(java.sql.Date obj) throws ConversionException {
|
||||
return new java.util.Date(obj.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
public static class SqlDateToList extends GenericSingletonToList<java.sql.Date> {
|
||||
public SqlDateToList() {
|
||||
super(java.sql.Date.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class SqlDateToSet extends GenericSingletonToSet<java.sql.Date> {
|
||||
public SqlDateToSet() {
|
||||
super(java.sql.Date.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class SqlDateToString extends GenericLocalizedConverter<java.sql.Date, String> {
|
||||
public SqlDateToString() {
|
||||
super(java.sql.Date.class, String.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convert(java.sql.Date obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
public String convert(java.sql.Date obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
DateFormat df = null;
|
||||
if (UtilValidate.isEmpty(formatString)) {
|
||||
df = UtilDateTime.toDateFormat(UtilDateTime.getDateFormat(), timeZone, locale);
|
||||
} else {
|
||||
df = UtilDateTime.toDateFormat(formatString, timeZone, locale);
|
||||
}
|
||||
return df.format(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class SqlDateToTime extends AbstractConverter<java.sql.Date, java.sql.Time> {
|
||||
public SqlDateToTime() {
|
||||
super(java.sql.Date.class, java.sql.Time.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Time convert(java.sql.Date obj) throws ConversionException {
|
||||
throw new ConversionException("Conversion from Date to Time not supported");
|
||||
}
|
||||
}
|
||||
|
||||
public static class SqlDateToTimestamp extends AbstractConverter<java.sql.Date, java.sql.Timestamp> {
|
||||
public SqlDateToTimestamp() {
|
||||
super(java.sql.Date.class, java.sql.Timestamp.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Timestamp convert(java.sql.Date obj) throws ConversionException {
|
||||
return new java.sql.Timestamp(obj.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
public static class SqlTimeToList extends GenericSingletonToList<java.sql.Time> {
|
||||
public SqlTimeToList() {
|
||||
super(java.sql.Time.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class SqlTimeToSet extends GenericSingletonToSet<java.sql.Time> {
|
||||
public SqlTimeToSet() {
|
||||
super(java.sql.Time.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class SqlTimeToSqlDate extends AbstractConverter<java.sql.Time, java.sql.Date> {
|
||||
public SqlTimeToSqlDate() {
|
||||
super(java.sql.Time.class, java.sql.Date.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Date convert(java.sql.Time obj) throws ConversionException {
|
||||
throw new ConversionException("Conversion from Time to Date not supported");
|
||||
}
|
||||
}
|
||||
|
||||
public static class SqlTimeToString extends GenericLocalizedConverter<java.sql.Time, String> {
|
||||
public SqlTimeToString() {
|
||||
super(java.sql.Time.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(java.sql.Time obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
DateFormat df = null;
|
||||
if (UtilValidate.isEmpty(formatString)) {
|
||||
df = UtilDateTime.toTimeFormat(UtilDateTime.getTimeFormat(), timeZone, locale);
|
||||
} else {
|
||||
df = UtilDateTime.toTimeFormat(formatString, timeZone, locale);
|
||||
}
|
||||
return df.format(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToCalendar extends AbstractLocalizedConverter<String, Calendar> {
|
||||
public StringToCalendar() {
|
||||
super(String.class, Calendar.class);
|
||||
}
|
||||
|
||||
public Calendar convert(String obj) throws ConversionException {
|
||||
return convert(obj, Locale.getDefault(), TimeZone.getDefault(), null);
|
||||
}
|
||||
|
||||
public Calendar convert(String obj, Locale locale, TimeZone timeZone) throws ConversionException {
|
||||
return convert(obj, Locale.getDefault(), TimeZone.getDefault(), null);
|
||||
}
|
||||
|
||||
public Calendar convert(String obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
String trimStr = obj.trim();
|
||||
if (trimStr.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
DateFormat df = null;
|
||||
if (UtilValidate.isEmpty(formatString)) {
|
||||
df = UtilDateTime.toDateTimeFormat(UtilDateTime.getDateTimeFormat(), timeZone, locale);
|
||||
} else {
|
||||
df = UtilDateTime.toDateTimeFormat(formatString, timeZone, locale);
|
||||
}
|
||||
try {
|
||||
java.util.Date date = df.parse(trimStr);
|
||||
return UtilDateTime.toCalendar(date, timeZone, locale);
|
||||
} catch (ParseException e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToDate extends GenericLocalizedConverter<String, java.util.Date> {
|
||||
public StringToDate() {
|
||||
super(String.class, java.util.Date.class);
|
||||
}
|
||||
|
||||
public java.util.Date convert(String obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
String trimStr = obj.trim();
|
||||
if (trimStr.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
DateFormat df = null;
|
||||
if (UtilValidate.isEmpty(formatString)) {
|
||||
df = UtilDateTime.toDateTimeFormat(obj.contains("-") ? UtilDateTime.getDateTimeFormat() : null, timeZone, locale);
|
||||
} else {
|
||||
df = UtilDateTime.toDateTimeFormat(formatString, timeZone, locale);
|
||||
}
|
||||
try {
|
||||
return df.parse(trimStr);
|
||||
} catch (ParseException e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToDuration extends AbstractLocalizedConverter<String, TimeDuration> {
|
||||
public StringToDuration() {
|
||||
super(String.class, TimeDuration.class);
|
||||
}
|
||||
|
||||
public TimeDuration convert(String obj) throws ConversionException {
|
||||
return TimeDuration.parseDuration(obj);
|
||||
}
|
||||
|
||||
public TimeDuration convert(String obj, Locale locale, TimeZone timeZone) throws ConversionException {
|
||||
if (!obj.contains(":")) {
|
||||
// Encoded duration
|
||||
try {
|
||||
NumberFormat nf = NumberFormat.getNumberInstance(locale);
|
||||
nf.setMaximumFractionDigits(0);
|
||||
Number number = nf.parse(obj);
|
||||
return TimeDuration.fromNumber(number);
|
||||
} catch (ParseException e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
return convert(obj);
|
||||
}
|
||||
|
||||
public TimeDuration convert(String obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
return convert(obj, locale, timeZone);
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToSqlDate extends GenericLocalizedConverter<String, java.sql.Date> {
|
||||
public StringToSqlDate() {
|
||||
super(String.class, java.sql.Date.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Date convert(String obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
String trimStr = obj.trim();
|
||||
if (trimStr.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
DateFormat df = null;
|
||||
if (UtilValidate.isEmpty(formatString)) {
|
||||
df = UtilDateTime.toDateFormat(UtilDateTime.getDateFormat(), timeZone, locale);
|
||||
} else {
|
||||
df = UtilDateTime.toDateFormat(formatString, timeZone, locale);
|
||||
}
|
||||
try {
|
||||
java.util.Date parsedDate = df.parse(trimStr);
|
||||
Calendar cal = UtilDateTime.toCalendar(parsedDate, timeZone, locale);
|
||||
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
|
||||
cal.set(Calendar.MILLISECOND, 0);
|
||||
return new java.sql.Date(cal.getTimeInMillis());
|
||||
} catch (ParseException e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToSqlTime extends GenericLocalizedConverter<String, java.sql.Time> {
|
||||
public StringToSqlTime() {
|
||||
super(String.class, java.sql.Time.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Time convert(String obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
String trimStr = obj.trim();
|
||||
if (trimStr.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
DateFormat df = null;
|
||||
if (UtilValidate.isEmpty(formatString)) {
|
||||
df = UtilDateTime.toTimeFormat(UtilDateTime.getTimeFormat(), timeZone, locale);
|
||||
} else {
|
||||
df = UtilDateTime.toTimeFormat(formatString, timeZone, locale);
|
||||
}
|
||||
try {
|
||||
return new java.sql.Time(df.parse(trimStr).getTime());
|
||||
} catch (ParseException e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToTimestamp extends GenericLocalizedConverter<String, java.sql.Timestamp> {
|
||||
public StringToTimestamp() {
|
||||
super(String.class, java.sql.Timestamp.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return ObjectType.instanceOf(sourceClass, this.getSourceClass()) && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Timestamp convert(String obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
String str = obj.trim();
|
||||
if (str.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
DateFormat df = null;
|
||||
if (UtilValidate.isEmpty(formatString)) {
|
||||
// These hacks are a bad idea, but they are included
|
||||
// for backward compatibility.
|
||||
if (str.length() > 0 && !str.contains(":")) {
|
||||
str = str + " 00:00:00.00";
|
||||
}
|
||||
// hack to mimic Timestamp.valueOf() method
|
||||
if (str.length() > 0 && !str.contains(".")) {
|
||||
str = str + ".0";
|
||||
} else {
|
||||
// DateFormat has a funny way of parsing milliseconds:
|
||||
// 00:00:00.2 parses to 00:00:00.002
|
||||
// so we'll add zeros to the end to get 00:00:00.200
|
||||
String[] timeSplit = str.split("[.]");
|
||||
if (timeSplit.length > 1 && timeSplit[1].length() < 3) {
|
||||
str = str + "000".substring(timeSplit[1].length());
|
||||
}
|
||||
}
|
||||
df = UtilDateTime.toDateTimeFormat(UtilDateTime.getDateTimeFormat(), timeZone, locale);
|
||||
} else {
|
||||
df = UtilDateTime.toDateTimeFormat(formatString, timeZone, locale);
|
||||
}
|
||||
try {
|
||||
return new java.sql.Timestamp(df.parse(str).getTime());
|
||||
} catch (ParseException e) {
|
||||
// FIXME: This change needs to be reverted. The Timestamp format is
|
||||
// defined by the JDBC specification. Passing an invalid format is an
|
||||
// application error and the application needs to be fixed.
|
||||
//
|
||||
// before throwing an exception, try a generic format first
|
||||
df = DateFormat.getDateTimeInstance();
|
||||
if (timeZone != null) {
|
||||
df.setTimeZone(timeZone);
|
||||
}
|
||||
try {
|
||||
return new java.sql.Timestamp(df.parse(str).getTime());
|
||||
} catch (ParseException e2) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToTimeZone extends AbstractConverter<String, TimeZone> {
|
||||
public StringToTimeZone() {
|
||||
super(String.class, TimeZone.class);
|
||||
}
|
||||
|
||||
public TimeZone convert(String obj) throws ConversionException {
|
||||
TimeZone tz = UtilDateTime.toTimeZone(obj);
|
||||
if (tz != null) {
|
||||
return tz;
|
||||
} else {
|
||||
throw new ConversionException("Could not convert " + obj + " to TimeZone: ");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class TimestampToDate extends AbstractConverter<java.sql.Timestamp, java.util.Date> {
|
||||
public TimestampToDate() {
|
||||
super(java.sql.Timestamp.class, java.util.Date.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.util.Date convert(java.sql.Timestamp obj) throws ConversionException {
|
||||
return new java.sql.Timestamp(obj.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
public static class TimestampToList extends GenericSingletonToList<java.sql.Timestamp> {
|
||||
public TimestampToList() {
|
||||
super(java.sql.Timestamp.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class TimestampToSet extends GenericSingletonToSet<java.sql.Timestamp> {
|
||||
public TimestampToSet() {
|
||||
super(java.sql.Timestamp.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class TimestampToSqlDate extends AbstractConverter<java.sql.Timestamp, java.sql.Date> {
|
||||
public TimestampToSqlDate() {
|
||||
super(java.sql.Timestamp.class, java.sql.Date.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Date convert(java.sql.Timestamp obj) throws ConversionException {
|
||||
return new java.sql.Date(obj.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
public static class TimestampToSqlTime extends AbstractConverter<java.sql.Timestamp, java.sql.Time> {
|
||||
public TimestampToSqlTime() {
|
||||
super(java.sql.Timestamp.class, java.sql.Time.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
|
||||
}
|
||||
|
||||
public java.sql.Time convert(java.sql.Timestamp obj) throws ConversionException {
|
||||
return new java.sql.Time(obj.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
public static class TimestampToString extends GenericLocalizedConverter<java.sql.Timestamp, String> {
|
||||
public TimestampToString() {
|
||||
super(java.sql.Timestamp.class, String.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convert(java.sql.Timestamp obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
public String convert(java.sql.Timestamp obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
DateFormat df = null;
|
||||
if (UtilValidate.isEmpty(formatString)) {
|
||||
df = UtilDateTime.toDateTimeFormat(UtilDateTime.getDateTimeFormat(), timeZone, locale);
|
||||
} else {
|
||||
df = UtilDateTime.toDateTimeFormat(formatString, timeZone, locale);
|
||||
}
|
||||
return df.format(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class TimeZoneToString extends AbstractConverter<TimeZone, String> {
|
||||
public TimeZoneToString() {
|
||||
super(TimeZone.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(TimeZone obj) throws ConversionException {
|
||||
return obj.getID();
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConverters() {
|
||||
Converters.loadContainedConverters(DateTimeConverters.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class GenericSingletonToList<T> extends AbstractConverter<T, List<T>> {
|
||||
public GenericSingletonToList(Class<T> sourceClass) {
|
||||
super(sourceClass, List.class);
|
||||
}
|
||||
|
||||
public List<T> convert(T obj) throws ConversionException {
|
||||
List<T> tempList = new LinkedList<T>();
|
||||
tempList.add(obj);
|
||||
return tempList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class GenericSingletonToSet<T> extends AbstractConverter<T, Set<T>> {
|
||||
public GenericSingletonToSet(Class<T> sourceClass) {
|
||||
super(sourceClass, Set.class);
|
||||
}
|
||||
|
||||
public Set<T> convert(T obj) throws ConversionException {
|
||||
Set<T> tempSet = new HashSet<T>();
|
||||
tempSet.add(obj);
|
||||
return tempSet;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.lang.JSON;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
|
||||
/** JSON Converter classes. */
|
||||
public class JSONConverters implements ConverterLoader {
|
||||
|
||||
public static class JSONToList extends AbstractConverter<JSON, List<Object>> {
|
||||
public JSONToList() {
|
||||
super(JSON.class, List.class);
|
||||
}
|
||||
|
||||
public List<Object> convert(JSON obj) throws ConversionException {
|
||||
try {
|
||||
return UtilGenerics.<List<Object>>cast(obj.toObject(List.class));
|
||||
} catch (IOException e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class JSONToMap extends AbstractConverter<JSON, Map<String, Object>> {
|
||||
public JSONToMap() {
|
||||
super(JSON.class, Map.class);
|
||||
}
|
||||
|
||||
public Map<String, Object> convert(JSON obj) throws ConversionException {
|
||||
try {
|
||||
return UtilGenerics.<Map<String, Object>>cast(obj.toObject(Map.class));
|
||||
} catch (IOException e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ListToJSON extends AbstractConverter<List<Object>, JSON> {
|
||||
public ListToJSON() {
|
||||
super(List.class, JSON.class);
|
||||
}
|
||||
|
||||
public JSON convert(List<Object> obj) throws ConversionException {
|
||||
try {
|
||||
return JSON.from(obj);
|
||||
} catch (IOException e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class MapToJSON extends AbstractConverter<Map<String, Object>, JSON> {
|
||||
public MapToJSON() {
|
||||
super(Map.class, JSON.class);
|
||||
}
|
||||
|
||||
public JSON convert(Map<String, Object> obj) throws ConversionException {
|
||||
try {
|
||||
return JSON.from(obj);
|
||||
} catch (IOException e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConverters() {
|
||||
Converters.loadContainedConverters(JSONConverters.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
/** Localized converter interface. Classes implement this interface
|
||||
* to convert one object type to another. Methods are provided to
|
||||
* localize the conversion.
|
||||
*/
|
||||
public interface LocalizedConverter<S, T> extends Converter<S, T> {
|
||||
/** Converts <code>obj</code> to <code>T</code>.
|
||||
*
|
||||
* @param obj The source <code>Object</code> to convert
|
||||
* @param locale The locale used for conversion - must not be <code>null</code>
|
||||
* @param timeZone The time zone used for conversion - must not be <code>null</code>
|
||||
* @return The converted <code>Object</code>
|
||||
* @throws ConversionException
|
||||
*/
|
||||
public T convert(S obj, Locale locale, TimeZone timeZone) throws ConversionException;
|
||||
|
||||
/** Converts <code>obj</code> to <code>T</code>.
|
||||
*
|
||||
* @param targetClass The <code>Class</code> to convert to
|
||||
* @param obj The source <code>Object</code> to convert
|
||||
* @param locale The locale used for conversion - must not be <code>null</code>
|
||||
* @param timeZone The time zone used for conversion - must not be <code>null</code>
|
||||
* @return The converted <code>Object</code>
|
||||
* @throws ConversionException
|
||||
*/
|
||||
public T convert(Class<? extends T> targetClass, S obj, Locale locale, TimeZone timeZone) throws ConversionException;
|
||||
|
||||
/** Converts <code>obj</code> to <code>T</code>.
|
||||
*
|
||||
* @param obj The source <code>Object</code> to convert
|
||||
* @param locale The locale used for conversion - must not be <code>null</code>
|
||||
* @param timeZone The time zone used for conversion - must not be <code>null</code>
|
||||
* @param formatString Optional formatting string
|
||||
* @return The converted <code>Object</code>
|
||||
* @throws ConversionException
|
||||
*/
|
||||
public T convert(S obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException;
|
||||
|
||||
/** Converts <code>obj</code> to <code>T</code>.
|
||||
*
|
||||
* @param targetClass The <code>Class</code> to convert to
|
||||
* @param obj The source <code>Object</code> to convert
|
||||
* @param locale The locale used for conversion - must not be <code>null</code>
|
||||
* @param timeZone The time zone used for conversion - must not be <code>null</code>
|
||||
* @param formatString Optional formatting string
|
||||
* @return The converted <code>Object</code>
|
||||
* @throws ConversionException
|
||||
*/
|
||||
public T convert(Class<? extends T> targetClass, S obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException;
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.Charset;
|
||||
import java.sql.Blob;
|
||||
import java.sql.Clob;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
|
||||
/** Miscellaneous Converter classes. */
|
||||
public class MiscConverters implements ConverterLoader {
|
||||
|
||||
public static final int CHAR_BUFFER_SIZE = 4096;
|
||||
|
||||
public static class BlobToBlob extends AbstractConverter<Blob, Blob> {
|
||||
public BlobToBlob() {
|
||||
super(Blob.class, Blob.class);
|
||||
}
|
||||
|
||||
public Blob convert(Blob obj) throws ConversionException {
|
||||
try {
|
||||
return new javax.sql.rowset.serial.SerialBlob(obj.getBytes(1, (int) obj.length()));
|
||||
} catch (Exception e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class BlobToByteArray extends AbstractConverter<Blob, byte[]> {
|
||||
public BlobToByteArray() {
|
||||
super(Blob.class, byte[].class);
|
||||
}
|
||||
|
||||
public byte[] convert(Blob obj) throws ConversionException {
|
||||
try {
|
||||
return obj.getBytes(1, (int) obj.length());
|
||||
} catch (Exception e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ByteArrayToBlob extends AbstractConverter<byte[], Blob> {
|
||||
public ByteArrayToBlob() {
|
||||
super(byte[].class, Blob.class);
|
||||
}
|
||||
|
||||
public Blob convert(byte[] obj) throws ConversionException {
|
||||
try {
|
||||
return new javax.sql.rowset.serial.SerialBlob(obj);
|
||||
} catch (Exception e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ByteBufferToByteArray extends AbstractConverter<ByteBuffer, byte[]> {
|
||||
public ByteBufferToByteArray() {
|
||||
super(ByteBuffer.class, byte[].class);
|
||||
}
|
||||
|
||||
public byte[] convert(ByteBuffer obj) throws ConversionException {
|
||||
try {
|
||||
return obj.hasArray() ? obj.array() : null;
|
||||
} catch (Exception e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ByteArrayToByteBuffer extends AbstractConverter<byte[], ByteBuffer> {
|
||||
public ByteArrayToByteBuffer() {
|
||||
super(byte[].class, ByteBuffer.class);
|
||||
}
|
||||
|
||||
public ByteBuffer convert(byte[] obj) throws ConversionException {
|
||||
try {
|
||||
return ByteBuffer.wrap(obj);
|
||||
} catch (Exception e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ClobToString extends AbstractConverter<Clob, String> {
|
||||
public ClobToString() {
|
||||
super(Clob.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(Clob obj) throws ConversionException {
|
||||
StringBuilder strBuf = new StringBuilder();
|
||||
char[] inCharBuffer = new char[CHAR_BUFFER_SIZE];
|
||||
int charsRead = 0;
|
||||
Reader clobReader = null;
|
||||
try {
|
||||
clobReader = obj.getCharacterStream();
|
||||
while ((charsRead = clobReader.read(inCharBuffer, 0, CHAR_BUFFER_SIZE)) > 0) {
|
||||
strBuf.append(inCharBuffer, 0, charsRead);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
finally {
|
||||
if (clobReader != null) {
|
||||
try {
|
||||
clobReader.close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
}
|
||||
return strBuf.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static class EnumToString extends AbstractConverter<Enum<?>, String> {
|
||||
public EnumToString() {
|
||||
super(Enum.class, String.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return Enum.class.isAssignableFrom(sourceClass) && String.class.isAssignableFrom(targetClass);
|
||||
}
|
||||
|
||||
public String convert(Enum<?> obj) throws ConversionException {
|
||||
return obj.name();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convert(Class<? extends String> targetClass, Enum<?> obj) throws ConversionException {
|
||||
return convert(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<? super Enum<?>> getSourceClass() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToEnumConverterCreator<E extends Enum<E>> implements ConverterCreator, ConverterLoader {
|
||||
public void loadConverters() {
|
||||
Converters.registerCreator(this);
|
||||
}
|
||||
|
||||
public <S, T> Converter<S, T> createConverter(Class<S> sourceClass, Class<T> targetClass) {
|
||||
if (String.class == sourceClass && Enum.class.isAssignableFrom(targetClass)) {
|
||||
return UtilGenerics.cast(new StringToEnum<E>());
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class StringToEnum<E extends Enum<E>> extends AbstractConverter<String, E> {
|
||||
public StringToEnum() {
|
||||
super(String.class, Enum.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConvert(Class<?> sourceClass, Class<?> targetClass) {
|
||||
return String.class.isAssignableFrom(sourceClass) && Enum.class.isAssignableFrom(targetClass);
|
||||
}
|
||||
|
||||
public E convert(String obj) throws ConversionException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public E convert(Class<? extends E> targetClass, String obj) throws ConversionException {
|
||||
return Enum.valueOf(UtilGenerics.<Class<E>>cast(targetClass), obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<? super Enum<?>> getTargetClass() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static class LocaleToString extends AbstractConverter<Locale, String> {
|
||||
public LocaleToString() {
|
||||
super(Locale.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(Locale obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToClob extends AbstractConverter<String, Clob> {
|
||||
public StringToClob() {
|
||||
super(String.class, Clob.class);
|
||||
}
|
||||
|
||||
public Clob convert(String obj) throws ConversionException {
|
||||
try {
|
||||
return new javax.sql.rowset.serial.SerialClob(obj.toCharArray());
|
||||
} catch (Exception e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToLocale extends AbstractConverter<String, Locale> {
|
||||
public StringToLocale() {
|
||||
super(String.class, Locale.class);
|
||||
}
|
||||
|
||||
public Locale convert(String obj) throws ConversionException {
|
||||
Locale loc = UtilMisc.parseLocale(obj);
|
||||
if (loc != null) {
|
||||
return loc;
|
||||
} else {
|
||||
throw new ConversionException("Could not convert " + obj + " to Locale: ");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class DecimalFormatToString extends AbstractConverter<DecimalFormat, String> {
|
||||
public DecimalFormatToString() {
|
||||
super(DecimalFormat.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(DecimalFormat obj) throws ConversionException {
|
||||
return obj.toPattern();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToDecimalFormat extends AbstractConverter<String, DecimalFormat> {
|
||||
public StringToDecimalFormat() {
|
||||
super(String.class, DecimalFormat.class);
|
||||
}
|
||||
|
||||
public DecimalFormat convert(String obj) throws ConversionException {
|
||||
return new DecimalFormat(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class SimpleDateFormatToString extends AbstractConverter<SimpleDateFormat, String> {
|
||||
public SimpleDateFormatToString() {
|
||||
super(SimpleDateFormat.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(SimpleDateFormat obj) throws ConversionException {
|
||||
return obj.toPattern();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToSimpleDateFormat extends AbstractConverter<String, SimpleDateFormat> {
|
||||
public StringToSimpleDateFormat() {
|
||||
super(String.class, SimpleDateFormat.class);
|
||||
}
|
||||
|
||||
public SimpleDateFormat convert(String obj) throws ConversionException {
|
||||
return new SimpleDateFormat(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CharsetToString extends AbstractConverter<Charset, String> {
|
||||
public CharsetToString() {
|
||||
super(Charset.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(Charset obj) throws ConversionException {
|
||||
return obj.name();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToCharset extends AbstractConverter<String, Charset> {
|
||||
public StringToCharset() {
|
||||
super(String.class, Charset.class);
|
||||
}
|
||||
|
||||
public Charset convert(String obj) throws ConversionException {
|
||||
return Charset.forName(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class UUIDToString extends AbstractConverter<UUID, String> {
|
||||
public UUIDToString() {
|
||||
super(UUID.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(UUID obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToUUID extends AbstractConverter<String, UUID> {
|
||||
public StringToUUID() {
|
||||
super(String.class, UUID.class);
|
||||
}
|
||||
|
||||
public UUID convert(String obj) throws ConversionException {
|
||||
return UUID.fromString(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class RegexPatternToString extends AbstractConverter<Pattern, String> {
|
||||
public RegexPatternToString() {
|
||||
super(Pattern.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(Pattern obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToRegexPattern extends AbstractConverter<String, Pattern> {
|
||||
public StringToRegexPattern() {
|
||||
super(String.class, Pattern.class);
|
||||
}
|
||||
|
||||
public Pattern convert(String obj) throws ConversionException {
|
||||
return Pattern.compile(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class NotAConverter_Helper {
|
||||
protected NotAConverter_Helper() {
|
||||
throw new Error("Should not be loaded");
|
||||
}
|
||||
}
|
||||
|
||||
public static class NotAConverter {
|
||||
public NotAConverter() {
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConverters() {
|
||||
Converters.loadContainedConverters(MiscConverters.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
|
||||
/** Net Converter classes. */
|
||||
public class NetConverters implements ConverterLoader {
|
||||
public static final String module = NetConverters.class.getName();
|
||||
|
||||
public static class StringToInetAddress extends AbstractConverter<String, InetAddress> {
|
||||
public StringToInetAddress() {
|
||||
super(String.class, InetAddress.class);
|
||||
}
|
||||
|
||||
public InetAddress convert(String obj) throws ConversionException {
|
||||
try {
|
||||
return InetAddress.getByName(obj);
|
||||
} catch (IOException e) {
|
||||
throw (ConversionException) new ConversionException(e.getMessage()).initCause(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class InetAddressToString extends AbstractConverter<InetAddress, String> {
|
||||
public InetAddressToString() {
|
||||
super(InetAddress.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(InetAddress obj) throws ConversionException {
|
||||
String hostName = obj.getHostName();
|
||||
if (hostName != null) return hostName;
|
||||
return obj.getHostAddress();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToURI extends AbstractConverter<String, URI> {
|
||||
public StringToURI() {
|
||||
super(String.class, URI.class);
|
||||
}
|
||||
|
||||
public URI convert(String obj) throws ConversionException {
|
||||
try {
|
||||
return new URI(obj);
|
||||
} catch (URISyntaxException e) {
|
||||
throw (ConversionException) new ConversionException(e.getMessage()).initCause(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class URIToString extends AbstractConverter<URI, String> {
|
||||
public URIToString() {
|
||||
super(URI.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(URI obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToURL extends AbstractConverter<String, URL> {
|
||||
public StringToURL() {
|
||||
super(String.class, URL.class);
|
||||
}
|
||||
|
||||
public URL convert(String obj) throws ConversionException {
|
||||
try {
|
||||
return new URL(obj);
|
||||
} catch (MalformedURLException e) {
|
||||
throw (ConversionException) new ConversionException(e.getMessage()).initCause(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class URLToString extends AbstractConverter<URL, String> {
|
||||
public URLToString() {
|
||||
super(URL.class, String.class);
|
||||
}
|
||||
|
||||
public String convert(URL obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static class URIToURL extends AbstractConverter<URI, URL> {
|
||||
public URIToURL() {
|
||||
super(URI.class, URL.class);
|
||||
}
|
||||
|
||||
public URL convert(URI obj) throws ConversionException {
|
||||
try {
|
||||
return obj.toURL();
|
||||
} catch (MalformedURLException e) {
|
||||
throw (ConversionException) new ConversionException(e.getMessage()).initCause(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class URLToURI extends AbstractConverter<URL, URI> {
|
||||
public URLToURI() {
|
||||
super(URL.class, URI.class);
|
||||
}
|
||||
|
||||
public URI convert(URL obj) throws ConversionException {
|
||||
try {
|
||||
return obj.toURI();
|
||||
} catch (URISyntaxException e) {
|
||||
throw (ConversionException) new ConversionException(e.getMessage()).initCause(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConverters() {
|
||||
Converters.loadContainedConverters(NetConverters.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
|
||||
/** Number Converter classes. */
|
||||
public class NumberConverters implements ConverterLoader {
|
||||
|
||||
protected static Number fromString(String str, Locale locale) throws ConversionException {
|
||||
NumberFormat nf = NumberFormat.getNumberInstance(locale);
|
||||
if (nf instanceof DecimalFormat) {
|
||||
((DecimalFormat) nf).setParseBigDecimal(true);
|
||||
}
|
||||
try {
|
||||
return nf.parse(str);
|
||||
} catch (ParseException e) {
|
||||
throw new ConversionException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static abstract class AbstractStringToNumberConverter<N extends Number> extends AbstractNumberConverter<String, N> {
|
||||
public AbstractStringToNumberConverter(Class<N> targetClass) {
|
||||
super(String.class, targetClass);
|
||||
}
|
||||
|
||||
public N convert(String obj, Locale locale, TimeZone timeZone) throws ConversionException {
|
||||
String trimStr = StringUtil.removeSpaces(obj);
|
||||
if (trimStr.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
return convert(fromString(trimStr, locale));
|
||||
}
|
||||
|
||||
protected abstract N convert(Number number) throws ConversionException;
|
||||
}
|
||||
|
||||
public static abstract class AbstractNumberConverter<S, T> extends AbstractLocalizedConverter<S, T> {
|
||||
protected AbstractNumberConverter(Class<S> sourceClass, Class<T> targetClass) {
|
||||
super(sourceClass, targetClass);
|
||||
}
|
||||
|
||||
public T convert(S obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
|
||||
return convert(obj, locale, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static abstract class AbstractNumberToStringConverter<N extends Number> extends AbstractNumberConverter<N, String> {
|
||||
public AbstractNumberToStringConverter(Class<N> sourceClass) {
|
||||
super(sourceClass, String.class);
|
||||
}
|
||||
|
||||
public String convert(N obj) throws ConversionException {
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
public String convert(N obj, Locale locale, TimeZone timeZone) throws ConversionException {
|
||||
return format(obj, NumberFormat.getNumberInstance(locale));
|
||||
}
|
||||
|
||||
protected abstract String format(N obj, NumberFormat nf) throws ConversionException;
|
||||
}
|
||||
|
||||
public static class GenericNumberToDouble<N extends Number> extends AbstractConverter<N, Double> {
|
||||
public GenericNumberToDouble(Class<N> sourceClass) {
|
||||
super(sourceClass, Double.class);
|
||||
}
|
||||
|
||||
public Double convert(N obj) throws ConversionException {
|
||||
return obj.doubleValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class GenericNumberToFloat<N extends Number> extends AbstractConverter<N, Float> {
|
||||
public GenericNumberToFloat(Class<N> sourceClass) {
|
||||
super(sourceClass, Float.class);
|
||||
}
|
||||
|
||||
public Float convert(N obj) throws ConversionException {
|
||||
return obj.floatValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class GenericNumberToInteger<N extends Number> extends AbstractConverter<N, Integer> {
|
||||
public GenericNumberToInteger(Class<N> sourceClass) {
|
||||
super(sourceClass, Integer.class);
|
||||
}
|
||||
|
||||
public Integer convert(N obj) throws ConversionException {
|
||||
return obj.intValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class GenericNumberToLong<N extends Number> extends AbstractConverter<N, Long> {
|
||||
public GenericNumberToLong(Class<N> sourceClass) {
|
||||
super(sourceClass, Long.class);
|
||||
}
|
||||
|
||||
public Long convert(N obj) throws ConversionException {
|
||||
return obj.longValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class GenericNumberToShort<N extends Number> extends AbstractConverter<N, Short> {
|
||||
public GenericNumberToShort(Class<N> sourceClass) {
|
||||
super(sourceClass, Short.class);
|
||||
}
|
||||
|
||||
public Short convert(N obj) throws ConversionException {
|
||||
return obj.shortValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class BigDecimalToString extends AbstractNumberToStringConverter<BigDecimal> {
|
||||
public BigDecimalToString() {
|
||||
super(BigDecimal.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String format(BigDecimal obj, NumberFormat nf) throws ConversionException {
|
||||
return nf.format(obj.doubleValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class DoubleToBigDecimal extends AbstractConverter<Double, BigDecimal> {
|
||||
public DoubleToBigDecimal() {
|
||||
super(Double.class, BigDecimal.class);
|
||||
}
|
||||
|
||||
public BigDecimal convert(Double obj) throws ConversionException {
|
||||
return BigDecimal.valueOf(obj.doubleValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class BigIntegerToString extends AbstractNumberToStringConverter<BigInteger> {
|
||||
public BigIntegerToString() {
|
||||
super(BigInteger.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String format(BigInteger obj, NumberFormat nf) throws ConversionException {
|
||||
return nf.format(obj.doubleValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class ByteToString extends AbstractNumberToStringConverter<Byte> {
|
||||
public ByteToString() {
|
||||
super(Byte.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String format(Byte obj, NumberFormat nf) throws ConversionException {
|
||||
return nf.format(obj.floatValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToBigInteger extends AbstractStringToNumberConverter<BigInteger> {
|
||||
public StringToBigInteger() {
|
||||
super(BigInteger.class);
|
||||
}
|
||||
|
||||
public BigInteger convert(String obj) throws ConversionException {
|
||||
return new BigInteger(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BigInteger convert(Number number) throws ConversionException {
|
||||
return BigInteger.valueOf(number.longValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class DoubleToString extends AbstractNumberToStringConverter<Double> {
|
||||
public DoubleToString() {
|
||||
super(Double.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String format(Double obj, NumberFormat nf) throws ConversionException {
|
||||
return nf.format(obj.doubleValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class FloatToBigDecimal extends AbstractConverter<Float, BigDecimal> {
|
||||
public FloatToBigDecimal() {
|
||||
super(Float.class, BigDecimal.class);
|
||||
}
|
||||
|
||||
public BigDecimal convert(Float obj) throws ConversionException {
|
||||
return BigDecimal.valueOf(obj.doubleValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class FloatToString extends AbstractNumberToStringConverter<Float> {
|
||||
public FloatToString() {
|
||||
super(Float.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String format(Float obj, NumberFormat nf) throws ConversionException {
|
||||
return nf.format(obj.floatValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class IntegerToBigDecimal extends AbstractConverter<Integer, BigDecimal> {
|
||||
public IntegerToBigDecimal() {
|
||||
super(Integer.class, BigDecimal.class);
|
||||
}
|
||||
|
||||
public BigDecimal convert(Integer obj) throws ConversionException {
|
||||
return BigDecimal.valueOf(obj.intValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class IntegerToByte extends AbstractConverter<Integer, Byte> {
|
||||
public IntegerToByte() {
|
||||
super(Integer.class, Byte.class);
|
||||
}
|
||||
|
||||
public Byte convert(Integer obj) throws ConversionException {
|
||||
return obj.byteValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class IntegerToString extends AbstractNumberToStringConverter<Integer> {
|
||||
public IntegerToString() {
|
||||
super(Integer.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String format(Integer obj, NumberFormat nf) throws ConversionException {
|
||||
return nf.format(obj.intValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class LongToBigDecimal extends AbstractConverter<Long, BigDecimal> {
|
||||
public LongToBigDecimal() {
|
||||
super(Long.class, BigDecimal.class);
|
||||
}
|
||||
|
||||
public BigDecimal convert(Long obj) throws ConversionException {
|
||||
return BigDecimal.valueOf(obj.longValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class LongToByte extends AbstractConverter<Long, Byte> {
|
||||
public LongToByte() {
|
||||
super(Long.class, Byte.class);
|
||||
}
|
||||
|
||||
public Byte convert(Long obj) throws ConversionException {
|
||||
return obj.byteValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class LongToString extends AbstractNumberToStringConverter<Long> {
|
||||
public LongToString() {
|
||||
super(Long.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String format(Long obj, NumberFormat nf) throws ConversionException {
|
||||
return nf.format(obj.longValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class ShortToString extends AbstractNumberToStringConverter<Short> {
|
||||
public ShortToString() {
|
||||
super(Short.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String format(Short obj, NumberFormat nf) throws ConversionException {
|
||||
return nf.format(obj.floatValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToBigDecimal extends AbstractStringToNumberConverter<BigDecimal> {
|
||||
public StringToBigDecimal() {
|
||||
super(BigDecimal.class);
|
||||
}
|
||||
|
||||
public BigDecimal convert(String obj) throws ConversionException {
|
||||
return new BigDecimal(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BigDecimal convert(Number number) throws ConversionException {
|
||||
if (number instanceof BigDecimal) {
|
||||
return (BigDecimal) number;
|
||||
}
|
||||
return BigDecimal.valueOf(number.doubleValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToByte extends AbstractConverter<String, Byte> {
|
||||
public StringToByte() {
|
||||
super(String.class, Byte.class);
|
||||
}
|
||||
|
||||
public Byte convert(String obj) throws ConversionException {
|
||||
return Byte.valueOf(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToDouble extends AbstractStringToNumberConverter<Double> {
|
||||
public StringToDouble() {
|
||||
super(Double.class);
|
||||
}
|
||||
|
||||
public Double convert(String obj) throws ConversionException {
|
||||
return Double.valueOf(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Double convert(Number number) throws ConversionException {
|
||||
return number.doubleValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToFloat extends AbstractStringToNumberConverter<Float> {
|
||||
public StringToFloat() {
|
||||
super(Float.class);
|
||||
}
|
||||
|
||||
public Float convert(String obj) throws ConversionException {
|
||||
return Float.valueOf(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Float convert(Number number) throws ConversionException {
|
||||
return number.floatValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToInteger extends AbstractStringToNumberConverter<Integer> {
|
||||
public StringToInteger() {
|
||||
super(Integer.class);
|
||||
}
|
||||
|
||||
public Integer convert(String obj) throws ConversionException {
|
||||
return Integer.valueOf(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Integer convert(Number number) throws ConversionException {
|
||||
return number.intValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToLong extends AbstractStringToNumberConverter<Long> {
|
||||
public StringToLong() {
|
||||
super(Long.class);
|
||||
}
|
||||
|
||||
public Long convert(String obj) throws ConversionException {
|
||||
return Long.valueOf(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Long convert(Number number) throws ConversionException {
|
||||
return number.longValue();
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToShort extends AbstractConverter<String, Short> {
|
||||
public StringToShort() {
|
||||
super(String.class, Short.class);
|
||||
}
|
||||
|
||||
public Short convert(String obj) throws ConversionException {
|
||||
return Short.valueOf(obj);
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConverters() {
|
||||
Converters.loadContainedConverters(NumberConverters.class);
|
||||
|
||||
Converters.registerConverter(new GenericNumberToDouble<BigDecimal>(BigDecimal.class));
|
||||
Converters.registerConverter(new GenericNumberToDouble<BigInteger>(BigInteger.class));
|
||||
Converters.registerConverter(new GenericNumberToDouble<Byte>(Byte.class));
|
||||
Converters.registerConverter(new GenericNumberToDouble<Float>(Float.class));
|
||||
Converters.registerConverter(new GenericNumberToDouble<Integer>(Integer.class));
|
||||
Converters.registerConverter(new GenericNumberToDouble<Long>(Long.class));
|
||||
Converters.registerConverter(new GenericNumberToDouble<Short>(Short.class));
|
||||
|
||||
Converters.registerConverter(new GenericNumberToFloat<BigDecimal>(BigDecimal.class));
|
||||
Converters.registerConverter(new GenericNumberToFloat<BigInteger>(BigInteger.class));
|
||||
Converters.registerConverter(new GenericNumberToFloat<Byte>(Byte.class));
|
||||
Converters.registerConverter(new GenericNumberToFloat<Double>(Double.class));
|
||||
Converters.registerConverter(new GenericNumberToFloat<Integer>(Integer.class));
|
||||
Converters.registerConverter(new GenericNumberToFloat<Long>(Long.class));
|
||||
Converters.registerConverter(new GenericNumberToFloat<Short>(Short.class));
|
||||
|
||||
Converters.registerConverter(new GenericNumberToInteger<BigDecimal>(BigDecimal.class));
|
||||
Converters.registerConverter(new GenericNumberToInteger<BigInteger>(BigInteger.class));
|
||||
Converters.registerConverter(new GenericNumberToInteger<Byte>(Byte.class));
|
||||
Converters.registerConverter(new GenericNumberToInteger<Double>(Double.class));
|
||||
Converters.registerConverter(new GenericNumberToInteger<Float>(Float.class));
|
||||
Converters.registerConverter(new GenericNumberToInteger<Long>(Long.class));
|
||||
Converters.registerConverter(new GenericNumberToInteger<Short>(Short.class));
|
||||
|
||||
Converters.registerConverter(new GenericSingletonToList<BigDecimal>(BigDecimal.class));
|
||||
Converters.registerConverter(new GenericSingletonToList<BigInteger>(BigInteger.class));
|
||||
Converters.registerConverter(new GenericSingletonToList<Byte>(Byte.class));
|
||||
Converters.registerConverter(new GenericSingletonToList<Double>(Double.class));
|
||||
Converters.registerConverter(new GenericSingletonToList<Float>(Float.class));
|
||||
Converters.registerConverter(new GenericSingletonToList<Integer>(Integer.class));
|
||||
Converters.registerConverter(new GenericSingletonToList<Long>(Long.class));
|
||||
Converters.registerConverter(new GenericSingletonToList<Short>(Short.class));
|
||||
|
||||
Converters.registerConverter(new GenericNumberToLong<BigDecimal>(BigDecimal.class));
|
||||
Converters.registerConverter(new GenericNumberToLong<BigInteger>(BigInteger.class));
|
||||
Converters.registerConverter(new GenericNumberToLong<Byte>(Byte.class));
|
||||
Converters.registerConverter(new GenericNumberToLong<Double>(Double.class));
|
||||
Converters.registerConverter(new GenericNumberToLong<Float>(Float.class));
|
||||
Converters.registerConverter(new GenericNumberToLong<Integer>(Integer.class));
|
||||
Converters.registerConverter(new GenericNumberToLong<Short>(Short.class));
|
||||
|
||||
Converters.registerConverter(new GenericSingletonToSet<BigDecimal>(BigDecimal.class));
|
||||
Converters.registerConverter(new GenericSingletonToSet<BigInteger>(BigInteger.class));
|
||||
Converters.registerConverter(new GenericSingletonToSet<Byte>(Byte.class));
|
||||
Converters.registerConverter(new GenericSingletonToSet<Double>(Double.class));
|
||||
Converters.registerConverter(new GenericSingletonToSet<Float>(Float.class));
|
||||
Converters.registerConverter(new GenericSingletonToSet<Integer>(Integer.class));
|
||||
Converters.registerConverter(new GenericSingletonToSet<Long>(Long.class));
|
||||
Converters.registerConverter(new GenericSingletonToSet<Short>(Short.class));
|
||||
|
||||
Converters.registerConverter(new GenericNumberToShort<Integer>(Integer.class));
|
||||
Converters.registerConverter(new GenericNumberToShort<Long>(Long.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion.test;
|
||||
|
||||
import org.ofbiz.base.conversion.Converter;
|
||||
import org.ofbiz.base.conversion.DateTimeConverters;
|
||||
import org.ofbiz.base.lang.SourceMonitored;
|
||||
import org.ofbiz.base.test.GenericTestCaseBase;
|
||||
|
||||
import com.ibm.icu.util.Calendar;
|
||||
|
||||
@SourceMonitored
|
||||
public class DateTimeTests extends GenericTestCaseBase {
|
||||
|
||||
public DateTimeTests(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public static <S, T> void assertConversion(String label, Converter<S, T> converter, S source, T target) throws Exception {
|
||||
assertTrue(label + " can convert", converter.canConvert(source.getClass(), target.getClass()));
|
||||
assertEquals(label + " converted", target, converter.convert(source));
|
||||
}
|
||||
|
||||
public void testDateTimeConverters() throws Exception {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
long currentTime = cal.getTimeInMillis();
|
||||
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
|
||||
cal.set(Calendar.MILLISECOND, 0);
|
||||
long longTime = cal.getTimeInMillis(); // Start of day today
|
||||
assertNotEquals("currentTime and longTime are not equal", currentTime, longTime);
|
||||
java.util.Date utilDate = new java.util.Date(longTime);
|
||||
java.sql.Date sqlDate = new java.sql.Date(longTime);
|
||||
java.sql.Timestamp timestamp = new java.sql.Timestamp(longTime);
|
||||
// Source class = java.util.Date
|
||||
assertConversion("DateToLong", new DateTimeConverters.DateToLong(), utilDate, longTime);
|
||||
assertConversion("DateToSqlDate", new DateTimeConverters.DateToSqlDate(), utilDate, new java.sql.Date(longTime));
|
||||
assertConversion("DateToString", new DateTimeConverters.DateToString(), utilDate, utilDate.toString());
|
||||
assertConversion("DateToTimestamp", new DateTimeConverters.DateToTimestamp(), utilDate, timestamp);
|
||||
// Source class = java.sql.Date
|
||||
assertConversion("SqlDateToLong", new DateTimeConverters.DateToLong(), sqlDate, longTime);
|
||||
assertConversion("SqlDateToDate", new DateTimeConverters.SqlDateToDate(), sqlDate, utilDate);
|
||||
assertConversion("SqlDateToString", new DateTimeConverters.SqlDateToString(), sqlDate, sqlDate.toString());
|
||||
assertConversion("SqlDateToTimestamp", new DateTimeConverters.SqlDateToTimestamp(), sqlDate, timestamp);
|
||||
// Source class = java.sql.Timestamp
|
||||
assertConversion("TimestampToLong", new DateTimeConverters.DateToLong(), timestamp, longTime);
|
||||
assertConversion("TimestampToDate", new DateTimeConverters.TimestampToDate(), timestamp, utilDate);
|
||||
assertConversion("TimestampToSqlDate", new DateTimeConverters.TimestampToSqlDate(), timestamp, sqlDate);
|
||||
assertConversion("TimestampToString", new DateTimeConverters.TimestampToString(), timestamp, timestamp.toString());
|
||||
// Source class = java.lang.Long
|
||||
assertConversion("LongToDate", new DateTimeConverters.NumberToDate(), longTime, utilDate);
|
||||
assertConversion("LongToSqlDate", new DateTimeConverters.NumberToSqlDate(), longTime, sqlDate);
|
||||
assertConversion("LongToSqlDate", new DateTimeConverters.NumberToSqlDate(), currentTime, sqlDate); //Test conversion to start of day
|
||||
assertConversion("LongToTimestamp", new DateTimeConverters.NumberToTimestamp(), longTime, timestamp);
|
||||
// Source class = java.lang.String
|
||||
assertConversion("StringToTimestamp", new DateTimeConverters.StringToTimestamp(), timestamp.toString(), timestamp);
|
||||
//assertConversion("StringToDate", new DateTimeConverters.StringToDate(), utilDate.toString(), utilDate);
|
||||
//assertConversion("StringToSqlDate", new DateTimeConverters.StringToSqlDate(), sqlDate.toString(), sqlDate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion.test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.conversion.Converter;
|
||||
import org.ofbiz.base.conversion.ConverterLoader;
|
||||
import org.ofbiz.base.conversion.Converters;
|
||||
import org.ofbiz.base.lang.SourceMonitored;
|
||||
import org.ofbiz.base.test.GenericTestCaseBase;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
|
||||
@SourceMonitored
|
||||
public class MiscTests extends GenericTestCaseBase {
|
||||
|
||||
public MiscTests(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public void testStaticHelperClass() throws Exception {
|
||||
assertStaticHelperClass(Converters.class);
|
||||
}
|
||||
|
||||
public static class ConverterLoaderImpl implements ConverterLoader {
|
||||
public void loadConverters() {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
public void testLoadContainedConvertersIgnoresException() {
|
||||
Converters.loadContainedConverters(MiscTests.class);
|
||||
}
|
||||
|
||||
public static <S> void assertPassThru(Object wanted, Class<S> sourceClass) throws Exception {
|
||||
assertPassThru(wanted, sourceClass, sourceClass);
|
||||
}
|
||||
|
||||
public static <S> void assertPassThru(Object wanted, Class<S> sourceClass, Class<? super S> targetClass) throws Exception {
|
||||
Converter<S, ? super S> converter = Converters.getConverter(sourceClass, targetClass);
|
||||
Object result = converter.convert(UtilGenerics.<S>cast(wanted));
|
||||
assertEquals("pass thru convert", wanted, result);
|
||||
assertSame("pass thru exact equals", wanted, result);
|
||||
assertTrue("pass thru can convert wanted", converter.canConvert(wanted.getClass(), targetClass));
|
||||
assertTrue("pass thru can convert source", converter.canConvert(sourceClass, targetClass));
|
||||
assertEquals("pass thru source class", wanted.getClass(), converter.getSourceClass());
|
||||
assertEquals("pass thru target class", targetClass, converter.getTargetClass());
|
||||
}
|
||||
|
||||
public void testPassthru() throws Exception {
|
||||
String string = "ofbiz";
|
||||
BigDecimal bigDecimal = new BigDecimal("1.234");
|
||||
URL url = new URL("http://ofbiz.apache.org");
|
||||
List<String> baseList = UtilMisc.toList("a", "1", "b", "2", "c", "3");
|
||||
ArrayList<String> arrayList = new ArrayList<String>();
|
||||
arrayList.addAll(baseList);
|
||||
List<String> fastList = new LinkedList<String>();
|
||||
fastList.addAll(baseList);
|
||||
Map<String, String> baseMap = UtilMisc.toMap("a", "1", "b", "2", "c", "3");
|
||||
HashMap<String, String> hashMap = new HashMap<String, String>();
|
||||
hashMap.putAll(baseMap);
|
||||
Map<String, String> fastMap = new HashMap<String, String>();
|
||||
fastMap.putAll(baseMap);
|
||||
Object[] testObjects = new Object[] {
|
||||
string,
|
||||
bigDecimal,
|
||||
url,
|
||||
arrayList,
|
||||
fastList,
|
||||
hashMap,
|
||||
fastMap,
|
||||
};
|
||||
for (Object testObject: testObjects) {
|
||||
assertPassThru(testObject, testObject.getClass());
|
||||
}
|
||||
assertPassThru(fastList, fastList.getClass(), List.class);
|
||||
assertPassThru(fastMap, fastMap.getClass(), Map.class);
|
||||
assertPassThru(hashMap, hashMap.getClass(), Map.class);
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion.test;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.ofbiz.base.conversion.BooleanConverters;
|
||||
import org.ofbiz.base.conversion.Converter;
|
||||
import org.ofbiz.base.conversion.ConverterLoader;
|
||||
import org.ofbiz.base.conversion.Converters;
|
||||
|
||||
public class TestBooleanConverters extends TestCase {
|
||||
|
||||
public TestBooleanConverters(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public static <T> void assertFromBoolean(String label, Converter<Boolean, T> converter, T trueResult, T falseResult) throws Exception {
|
||||
assertTrue(label + " can convert", converter.canConvert(Boolean.class, trueResult.getClass()));
|
||||
assertEquals(label + " registered", converter.getClass(), Converters.getConverter(Boolean.class, trueResult.getClass()).getClass());
|
||||
assertEquals(label + " converted", trueResult, converter.convert(true));
|
||||
assertEquals(label + " converted", falseResult, converter.convert(false));
|
||||
}
|
||||
|
||||
public static <S> void assertToBoolean(String label, Converter<S, Boolean> converter, S trueSource, S falseSource) throws Exception {
|
||||
assertTrue(label + " can convert", converter.canConvert(trueSource.getClass(), Boolean.class));
|
||||
assertEquals(label + " registered", converter.getClass(), Converters.getConverter(trueSource.getClass(), Boolean.class).getClass());
|
||||
assertEquals(label + " converted", Boolean.TRUE, converter.convert(trueSource));
|
||||
assertEquals(label + " converted", Boolean.FALSE, converter.convert(falseSource));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <S> void assertToCollection(String label, S source) throws Exception {
|
||||
Converter<S, ? extends Collection> toList = (Converter<S, ? extends Collection>) Converters.getConverter(source.getClass(), List.class);
|
||||
Collection<S> listResult = toList.convert(source);
|
||||
assertEquals(label + " converted to List", source, listResult.toArray()[0]);
|
||||
Converter<S, ? extends Collection> toSet = (Converter<S, ? extends Collection>) Converters.getConverter(source.getClass(), Set.class);
|
||||
Collection<S> setResult = toSet.convert(source);
|
||||
assertEquals(label + " converted to Set", source, setResult.toArray()[0]);
|
||||
}
|
||||
|
||||
public void testBooleanConverters() throws Exception {
|
||||
ConverterLoader loader = new BooleanConverters();
|
||||
loader.loadConverters();
|
||||
assertFromBoolean("BooleanToInteger", new BooleanConverters.BooleanToInteger(), 1, 0);
|
||||
assertFromBoolean("BooleanToString", new BooleanConverters.BooleanToString(), "true", "false");
|
||||
assertToBoolean("IntegerToBoolean", new BooleanConverters.IntegerToBoolean(), 1, 0);
|
||||
assertToBoolean("StringToBoolean", new BooleanConverters.StringToBoolean(), "true", "false");
|
||||
assertToCollection("BooleanToCollection", Boolean.TRUE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.conversion.test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.ofbiz.base.conversion.Converter;
|
||||
import org.ofbiz.base.conversion.ConverterLoader;
|
||||
import org.ofbiz.base.conversion.Converters;
|
||||
import org.ofbiz.base.conversion.JSONConverters;
|
||||
import org.ofbiz.base.lang.JSON;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
|
||||
public class TestJSONConverters extends TestCase {
|
||||
public TestJSONConverters(String name) {
|
||||
super(name);
|
||||
ConverterLoader loader = new JSONConverters();
|
||||
loader.loadConverters();
|
||||
}
|
||||
|
||||
public void testJSONToMap() throws Exception {
|
||||
Converter<JSON, Map<String,String>> converter = UtilGenerics.cast(Converters.getConverter(JSON.class, Map.class));
|
||||
Map<String,String> map, convertedMap;
|
||||
map = new HashMap<String,String>();
|
||||
map.put("field1", "value1");
|
||||
JSON json = JSON.from(map);
|
||||
convertedMap = UtilGenerics.toMap(converter.convert(json));
|
||||
assertEquals("JSON to Map", map, convertedMap);
|
||||
}
|
||||
|
||||
public void testJSONToList() throws Exception {
|
||||
Converter<JSON, List<Object>> converter = UtilGenerics.cast(Converters.getConverter(JSON.class, List.class));
|
||||
List<Object> list, convertedList;
|
||||
list = new ArrayList<Object>();
|
||||
list.add("field1");
|
||||
list.add("field2");
|
||||
JSON json = JSON.from(list);
|
||||
convertedList = UtilGenerics.toList(converter.convert(json));
|
||||
assertEquals("JSON to List", list, convertedList);
|
||||
}
|
||||
|
||||
public void testMapToJSON() throws Exception {
|
||||
Converter<Map<String,Object>, JSON> converter = UtilGenerics.cast(Converters.getConverter(Map.class, JSON.class));
|
||||
JSON json;
|
||||
Map<String,Object> map = new LinkedHashMap<String,Object>();
|
||||
map.put("field1", "value1");
|
||||
map.put("field2", new BigDecimal("3.7"));
|
||||
json = converter.convert(map);
|
||||
assertEquals("Map to JSON", "{\"field1\":\"value1\",\"field2\":3.7}", json.toString());
|
||||
}
|
||||
|
||||
public void testListToJSON() throws Exception {
|
||||
Converter<List<String>, JSON> converter = UtilGenerics.cast(Converters.getConverter(List.class, JSON.class));
|
||||
JSON json;
|
||||
List<String> list = new ArrayList<String>();
|
||||
list.add("field1");
|
||||
list.add("field2");
|
||||
json = converter.convert(list);
|
||||
assertEquals("List to JSON", "[\"field1\",\"field2\"]", json.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.crypto;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* Blowfish (Two-Way) Byte/String encryption
|
||||
*
|
||||
*/
|
||||
public class BlowFishCrypt {
|
||||
|
||||
private SecretKeySpec secretKeySpec = null;
|
||||
|
||||
/**
|
||||
* Creates a new BlowFishCrypt object.
|
||||
* @param secretKeySpec A SecretKeySpec object.
|
||||
*/
|
||||
public BlowFishCrypt(SecretKeySpec secretKeySpec) {
|
||||
this.secretKeySpec = secretKeySpec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new BlowFishCrypt object.
|
||||
* @param key An encoded secret key
|
||||
*/
|
||||
public BlowFishCrypt(byte[] key) {
|
||||
try {
|
||||
secretKeySpec = new SecretKeySpec(key, "Blowfish");
|
||||
} catch (Exception e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new BlowFishCrypt object.
|
||||
* @param keyFile A file object containing the secret key as a String object.
|
||||
*/
|
||||
public BlowFishCrypt(File keyFile) {
|
||||
try {
|
||||
FileInputStream is = new FileInputStream(keyFile);
|
||||
ObjectInputStream os = new ObjectInputStream(is);
|
||||
String keyString = (String) os.readObject();
|
||||
|
||||
is.close();
|
||||
|
||||
byte[] keyBytes = keyString.getBytes();
|
||||
|
||||
secretKeySpec = new SecretKeySpec(keyBytes, "Blowfish");
|
||||
} catch (Exception e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt the string with the secret key.
|
||||
* @param string The string to encrypt.
|
||||
*/
|
||||
public byte[] encrypt(String string) {
|
||||
return encrypt(string.getBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt the string with the secret key.
|
||||
* @param string The string to decrypt.
|
||||
*/
|
||||
public byte[] decrypt(String string) {
|
||||
return decrypt(string.getBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt the byte array with the secret key.
|
||||
* @param bytes The array of bytes to encrypt.
|
||||
*/
|
||||
public byte[] encrypt(byte[] bytes) {
|
||||
byte[] resp = null;
|
||||
|
||||
try {
|
||||
resp = crypt(bytes, Cipher.ENCRYPT_MODE);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt the byte array with the secret key.
|
||||
* @param bytes The array of bytes to decrypt.
|
||||
*/
|
||||
public byte[] decrypt(byte[] bytes) {
|
||||
byte[] resp = null;
|
||||
|
||||
try {
|
||||
resp = crypt(bytes, Cipher.DECRYPT_MODE);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
|
||||
private byte[] crypt(byte[] bytes, int mode) throws Exception {
|
||||
if (secretKeySpec == null)
|
||||
throw new Exception("SecretKey cannot be null.");
|
||||
Cipher cipher = Cipher.getInstance("Blowfish");
|
||||
|
||||
cipher.init(mode, secretKeySpec);
|
||||
return cipher.doFinal(bytes);
|
||||
}
|
||||
|
||||
public static byte[] generateKey() throws NoSuchAlgorithmException {
|
||||
KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish");
|
||||
keyGen.init(448);
|
||||
|
||||
SecretKey secretKey = keyGen.generateKey();
|
||||
byte[] keyBytes = secretKey.getEncoded();
|
||||
|
||||
return keyBytes;
|
||||
}
|
||||
|
||||
public static boolean testKey(byte[] key) {
|
||||
String testString = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstufwxyz";
|
||||
BlowFishCrypt c = new BlowFishCrypt(key);
|
||||
byte[] encryptedBytes = c.encrypt(testString);
|
||||
String encryptedMessage = new String(encryptedBytes);
|
||||
|
||||
byte[] decryptedBytes = c.decrypt(encryptedMessage);
|
||||
String decryptedMessage = new String(decryptedBytes);
|
||||
|
||||
if (testString.equals(decryptedMessage)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void main(String args[]) throws Exception {
|
||||
if (args[0] == null) {
|
||||
args[0] = "ofbkey";
|
||||
}
|
||||
|
||||
byte[] key = generateKey();
|
||||
if (testKey(key)) {
|
||||
FileOutputStream fos = new FileOutputStream(args[0]);
|
||||
ObjectOutputStream os = new ObjectOutputStream(fos);
|
||||
String keyString = new String(key);
|
||||
os.writeObject(keyString);
|
||||
fos.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.crypto;
|
||||
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.Key;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.DESedeKeySpec;
|
||||
|
||||
import org.ofbiz.base.util.GeneralException;
|
||||
|
||||
/**
|
||||
* Utility class for doing DESded (3DES) Two-Way Encryption
|
||||
*
|
||||
*/
|
||||
public class DesCrypt {
|
||||
|
||||
public static final String module = DesCrypt.class.getName();
|
||||
|
||||
public static Key generateKey() throws NoSuchAlgorithmException {
|
||||
KeyGenerator keyGen = KeyGenerator.getInstance("DESede");
|
||||
|
||||
// generate the DES3 key
|
||||
return keyGen.generateKey();
|
||||
}
|
||||
|
||||
public static byte[] encrypt(Key key, byte[] bytes) throws GeneralException {
|
||||
Cipher cipher = DesCrypt.getCipher(key, Cipher.ENCRYPT_MODE);
|
||||
byte[] encBytes = null;
|
||||
try {
|
||||
encBytes = cipher.doFinal(bytes);
|
||||
} catch (IllegalStateException e) {
|
||||
throw new GeneralException(e);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
throw new GeneralException(e);
|
||||
} catch (BadPaddingException e) {
|
||||
throw new GeneralException(e);
|
||||
}
|
||||
return encBytes;
|
||||
}
|
||||
|
||||
public static byte[] decrypt(Key key, byte[] bytes) throws GeneralException {
|
||||
Cipher cipher = DesCrypt.getCipher(key, Cipher.DECRYPT_MODE);
|
||||
byte[] decBytes = null;
|
||||
try {
|
||||
decBytes = cipher.doFinal(bytes);
|
||||
} catch (IllegalStateException e) {
|
||||
throw new GeneralException(e);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
throw new GeneralException(e);
|
||||
} catch (BadPaddingException e) {
|
||||
throw new GeneralException(e);
|
||||
}
|
||||
return decBytes;
|
||||
}
|
||||
|
||||
public static Key getDesKey(byte[] rawKey) throws GeneralException {
|
||||
SecretKeyFactory skf = null;
|
||||
try {
|
||||
skf = SecretKeyFactory.getInstance("DESede");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new GeneralException(e);
|
||||
}
|
||||
|
||||
// load the raw key
|
||||
if (rawKey.length > 0) {
|
||||
DESedeKeySpec desedeSpec1 = null;
|
||||
try {
|
||||
desedeSpec1 = new DESedeKeySpec(rawKey);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new GeneralException(e);
|
||||
}
|
||||
|
||||
// create the SecretKey Object
|
||||
Key key = null;
|
||||
try {
|
||||
key = skf.generateSecret(desedeSpec1);
|
||||
} catch (InvalidKeySpecException e) {
|
||||
throw new GeneralException(e);
|
||||
}
|
||||
return key;
|
||||
} else {
|
||||
throw new GeneralException("Not a valid DESede key!");
|
||||
}
|
||||
}
|
||||
|
||||
// return a cipher for a key - DESede/CBC/PKCS5Padding IV = 0
|
||||
protected static Cipher getCipher(Key key, int mode) throws GeneralException {
|
||||
byte[] zeros = { 0, 0, 0, 0, 0, 0, 0, 0 };
|
||||
IvParameterSpec iv = new IvParameterSpec(zeros);
|
||||
|
||||
// create the Cipher - DESede/CBC/NoPadding
|
||||
Cipher encCipher = null;
|
||||
try {
|
||||
encCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new GeneralException(e);
|
||||
} catch (NoSuchPaddingException e) {
|
||||
throw new GeneralException(e);
|
||||
}
|
||||
try {
|
||||
encCipher.init(mode, key, iv);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new GeneralException(e);
|
||||
} catch (InvalidAlgorithmParameterException e) {
|
||||
throw new GeneralException(e);
|
||||
}
|
||||
return encCipher;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.crypto;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
import org.apache.commons.lang.RandomStringUtils;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.GeneralRuntimeException;
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.base.util.UtilIO;
|
||||
|
||||
/**
|
||||
* Utility class for doing SHA-1/MD5 One-Way Hash Encryption
|
||||
*
|
||||
*/
|
||||
public class HashCrypt {
|
||||
|
||||
public static final String module = HashCrypt.class.getName();
|
||||
public static final String CRYPT_CHAR_SET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
|
||||
|
||||
public static MessageDigest getMessageDigest(String type) {
|
||||
try {
|
||||
return MessageDigest.getInstance(type);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new GeneralRuntimeException("Could not load digestor(" + type + ")", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean comparePassword(String crypted, String defaultCrypt, String password) {
|
||||
if (crypted.startsWith("{")) {
|
||||
// FIXME: should have been getBytes("UTF-8") originally
|
||||
return doCompareTypePrefix(crypted, defaultCrypt, password.getBytes());
|
||||
} else if (crypted.startsWith("$")) {
|
||||
return doComparePosix(crypted, defaultCrypt, password.getBytes(UtilIO.getUtf8()));
|
||||
} else {
|
||||
// FIXME: should have been getBytes("UTF-8") originally
|
||||
return doCompareBare(crypted, defaultCrypt, password.getBytes());
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean doCompareTypePrefix(String crypted, String defaultCrypt, byte[] bytes) {
|
||||
int typeEnd = crypted.indexOf("}");
|
||||
String hashType = crypted.substring(1, typeEnd);
|
||||
String hashed = crypted.substring(typeEnd + 1);
|
||||
MessageDigest messagedigest = getMessageDigest(hashType);
|
||||
messagedigest.update(bytes);
|
||||
byte[] digestBytes = messagedigest.digest();
|
||||
char[] digestChars = Hex.encodeHex(digestBytes);
|
||||
String checkCrypted = new String(digestChars);
|
||||
if (hashed.equals(checkCrypted)) {
|
||||
return true;
|
||||
}
|
||||
// This next block should be removed when all {prefix}oldFunnyHex are fixed.
|
||||
if (hashed.equals(oldFunnyHex(digestBytes))) {
|
||||
Debug.logWarning("Warning: detected oldFunnyHex password prefixed with a hashType; this is not valid, please update the value in the database with ({%s}%s)", module, hashType, checkCrypted);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean doComparePosix(String crypted, String defaultCrypt, byte[] bytes) {
|
||||
int typeEnd = crypted.indexOf("$", 1);
|
||||
int saltEnd = crypted.indexOf("$", typeEnd + 1);
|
||||
String hashType = crypted.substring(1, typeEnd);
|
||||
String salt = crypted.substring(typeEnd + 1, saltEnd);
|
||||
String hashed = crypted.substring(saltEnd + 1);
|
||||
return hashed.equals(getCryptedBytes(hashType, salt, bytes));
|
||||
}
|
||||
|
||||
private static boolean doCompareBare(String crypted, String defaultCrypt, byte[] bytes) {
|
||||
String hashType = defaultCrypt;
|
||||
String hashed = crypted;
|
||||
MessageDigest messagedigest = getMessageDigest(hashType);
|
||||
messagedigest.update(bytes);
|
||||
return hashed.equals(oldFunnyHex(messagedigest.digest()));
|
||||
}
|
||||
|
||||
/*
|
||||
* @deprecated use cryptBytes(hashType, salt, password); eventually, use
|
||||
* cryptUTF8(hashType, salt, password) after all existing installs are
|
||||
* salt-based. If the call-site of cryptPassword is just used to create a *new*
|
||||
* value, then you can switch to cryptUTF8 directly.
|
||||
*/
|
||||
@Deprecated
|
||||
public static String cryptPassword(String hashType, String salt, String password) {
|
||||
// FIXME: should have been getBytes("UTF-8") originally
|
||||
return password != null ? cryptBytes(hashType, salt, password.getBytes()) : null;
|
||||
}
|
||||
|
||||
public static String cryptUTF8(String hashType, String salt, String value) {
|
||||
return value != null ? cryptBytes(hashType, salt, value.getBytes(UtilIO.getUtf8())) : null;
|
||||
}
|
||||
|
||||
public static String cryptValue(String hashType, String salt, String value) {
|
||||
return value != null ? cryptBytes(hashType, salt, value.getBytes()) : null;
|
||||
}
|
||||
|
||||
public static String cryptBytes(String hashType, String salt, byte[] bytes) {
|
||||
if (hashType == null) {
|
||||
hashType = "SHA";
|
||||
}
|
||||
if (salt == null) {
|
||||
salt = RandomStringUtils.random(new SecureRandom().nextInt(15) + 1, CRYPT_CHAR_SET);
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("$").append(hashType).append("$").append(salt).append("$");
|
||||
sb.append(getCryptedBytes(hashType, salt, bytes));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String getCryptedBytes(String hashType, String salt, byte[] bytes) {
|
||||
try {
|
||||
MessageDigest messagedigest = MessageDigest.getInstance(hashType);
|
||||
messagedigest.update(salt.getBytes(UtilIO.getUtf8()));
|
||||
messagedigest.update(bytes);
|
||||
return Base64.encodeBase64URLSafeString(messagedigest.digest()).replace('+', '.');
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new GeneralRuntimeException("Error while comparing password", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use digestHash("SHA", null, str)
|
||||
*/
|
||||
@Deprecated
|
||||
public static String getDigestHash(String str) {
|
||||
return digestHash("SHA", null, str);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use digestHash(hashType, null, str))
|
||||
*/
|
||||
@Deprecated
|
||||
public static String getDigestHash(String str, String hashType) {
|
||||
return digestHash(hashType, null, str);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use digestHash(hashType, code, str);
|
||||
*/
|
||||
@Deprecated
|
||||
public static String getDigestHash(String str, String code, String hashType) {
|
||||
return digestHash(hashType, code, str);
|
||||
}
|
||||
|
||||
public static String digestHash(String hashType, String code, String str) {
|
||||
if (str == null) return null;
|
||||
byte[] codeBytes;
|
||||
try {
|
||||
if (code == null) codeBytes = str.getBytes();
|
||||
else codeBytes = str.getBytes(code);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new GeneralRuntimeException("Error while computing hash of type " + hashType, e);
|
||||
}
|
||||
return digestHash(hashType, codeBytes);
|
||||
}
|
||||
|
||||
public static String digestHash(String hashType, byte[] bytes) {
|
||||
try {
|
||||
MessageDigest messagedigest = MessageDigest.getInstance(hashType);
|
||||
messagedigest.update(bytes);
|
||||
byte[] digestBytes = messagedigest.digest();
|
||||
char[] digestChars = Hex.encodeHex(digestBytes);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("{").append(hashType).append("}");
|
||||
sb.append(digestChars, 0, digestChars.length);
|
||||
return sb.toString();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new GeneralRuntimeException("Error while computing hash of type " + hashType, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String digestHash64(String hashType, byte[] bytes) {
|
||||
if (hashType == null) {
|
||||
hashType = "SHA";
|
||||
}
|
||||
try {
|
||||
MessageDigest messagedigest = MessageDigest.getInstance(hashType);
|
||||
messagedigest.update(bytes);
|
||||
byte[] digestBytes = messagedigest.digest();
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("{").append(hashType).append("}");
|
||||
sb.append(Base64.encodeBase64URLSafeString(digestBytes).replace('+', '.'));
|
||||
return sb.toString();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new GeneralRuntimeException("Error while computing hash of type " + hashType, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use cryptPassword
|
||||
*/
|
||||
@Deprecated
|
||||
public static String getHashTypeFromPrefix(String hashString) {
|
||||
if (UtilValidate.isEmpty(hashString) || hashString.charAt(0) != '{') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return hashString.substring(1, hashString.indexOf('}'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use cryptPassword
|
||||
*/
|
||||
@Deprecated
|
||||
public static String removeHashTypePrefix(String hashString) {
|
||||
if (UtilValidate.isEmpty(hashString) || hashString.charAt(0) != '{') {
|
||||
return hashString;
|
||||
}
|
||||
|
||||
return hashString.substring(hashString.indexOf('}') + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use digestHashOldFunnyHex(hashType, str)
|
||||
*/
|
||||
@Deprecated
|
||||
public static String getDigestHashOldFunnyHexEncode(String str, String hashType) {
|
||||
return digestHashOldFunnyHex(hashType, str);
|
||||
}
|
||||
|
||||
public static String digestHashOldFunnyHex(String hashType, String str) {
|
||||
if (UtilValidate.isEmpty(hashType)) hashType = "SHA";
|
||||
if (str == null) return null;
|
||||
try {
|
||||
MessageDigest messagedigest = MessageDigest.getInstance(hashType);
|
||||
byte[] strBytes = str.getBytes();
|
||||
|
||||
messagedigest.update(strBytes);
|
||||
return oldFunnyHex(messagedigest.digest());
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, "Error while computing hash of type " + hashType, module);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
// This next block should be removed when all {prefix}oldFunnyHex are fixed.
|
||||
private static String oldFunnyHex(byte[] bytes) {
|
||||
int k = 0;
|
||||
char[] digestChars = new char[bytes.length * 2];
|
||||
for (int l = 0; l < bytes.length; l++) {
|
||||
int i1 = bytes[l];
|
||||
|
||||
if (i1 < 0) {
|
||||
i1 = 127 + i1 * -1;
|
||||
}
|
||||
StringUtil.encodeInt(i1, k, digestChars);
|
||||
k += 2;
|
||||
}
|
||||
return new String(digestChars);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.crypto;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.shiro.crypto.AesCipherService;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args[0].equals("-crypt")) {
|
||||
System.out.println(HashCrypt.cryptUTF8(args[1], null, args[2]));
|
||||
} else if (args[0].equals("-digest")) {
|
||||
@SuppressWarnings("deprecation")
|
||||
String digest = HashCrypt.getDigestHash(args[1]);
|
||||
System.out.println(digest);
|
||||
} else if (args[0].equals("-kek")) {
|
||||
AesCipherService cs = new AesCipherService();
|
||||
System.out.println(Base64.encodeBase64String(cs.generateNewKey().getEncoded()));
|
||||
} else if (args[0].equals("-kek-old")) {
|
||||
System.out.println(Base64.encodeBase64String(DesCrypt.generateKey().getEncoded()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* 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.base.lang;
|
||||
|
||||
public interface Appender<T> {
|
||||
T appendTo(T target);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* 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.base.lang;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/** Identifies the valid state(s) of a field or variable. */
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
@Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE})
|
||||
public @interface ClassInvariant {
|
||||
String value();
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.lang;
|
||||
|
||||
/** A range of values. */
|
||||
@SourceMonitored
|
||||
public class ComparableRange<T extends Comparable<T>> implements Range<T>, Comparable<ComparableRange<T>> {
|
||||
|
||||
protected final T start;
|
||||
protected final T end;
|
||||
protected final boolean isPoint;
|
||||
|
||||
public ComparableRange(T start, T end) {
|
||||
if (start.getClass() != end.getClass()) {
|
||||
throw new IllegalArgumentException("start Class and end Class must be the same");
|
||||
}
|
||||
if (end.compareTo(start) >= 0) {
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
} else {
|
||||
this.start = end;
|
||||
this.end = start;
|
||||
}
|
||||
this.isPoint = start.equals(end);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean after(Range<T> range) {
|
||||
return this.start.compareTo(range.end()) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean after(T value) {
|
||||
return this.start.compareTo(value) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean before(Range<T> range) {
|
||||
return this.end.compareTo(range.start()) < 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean before(T value) {
|
||||
return this.end.compareTo(value) < 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T end() {
|
||||
return this.end;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
ComparableRange<?> that = (ComparableRange<?>) obj;
|
||||
return this.start.equals(that.start()) && this.end.equals(that.end());
|
||||
} catch (Exception e) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
public int compareTo(ComparableRange<T> range) {
|
||||
if (this == range) {
|
||||
return 0;
|
||||
}
|
||||
return this.start.equals(range.start()) ? this.end.compareTo(range.end()) : this.start.compareTo(range.start());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includes(Range<T> range) {
|
||||
return this.includes(range.start()) && this.includes(range.end());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includes(T value) {
|
||||
if (this.isPoint) {
|
||||
return value.equals(this.start());
|
||||
}
|
||||
return value.compareTo(this.start()) >= 0 && value.compareTo(this.end()) <= 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPoint() {
|
||||
return this.isPoint;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean overlaps(Range<T> range) {
|
||||
return range.includes(this.start()) || range.includes(this.end()) || this.includes(range);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T start() {
|
||||
return this.start;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.start + " - " + this.end;
|
||||
}
|
||||
}
|
||||
@@ -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.base.lang;
|
||||
|
||||
/** Factory interface. */
|
||||
public interface Factory<R, A> {
|
||||
|
||||
/** Returns an instance of <code>R</code>. This is a basic factory interface
|
||||
* that is meant to be extended. Sub-interfaces declare types for
|
||||
* <code>A</code> (the <code>getInstance</code> argument), and
|
||||
* <code>R</code> (the type returned by <code>getInstance</code>).
|
||||
*
|
||||
* @param obj Optional object to be used in <code>R</code>'s construction,
|
||||
* or to be used as a selector key
|
||||
* @return An instance of <code>R</code>
|
||||
*/
|
||||
public R getInstance(A obj);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* 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.base.lang;
|
||||
|
||||
public interface IsEmpty {
|
||||
boolean isEmpty();
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.lang;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.ofbiz.base.util.Assert;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/** A JSON object. */
|
||||
@ThreadSafe
|
||||
public final class JSON {
|
||||
|
||||
// TODO: Find a generic way to modify mapper options
|
||||
private static final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* Creates a <code>JSON</code> instance from an <code>InputStream</code>.
|
||||
* The method assumes the character set is UTF-8.
|
||||
*
|
||||
* @param inStream
|
||||
* @return a <code>JSON</code> instance
|
||||
* @throws IOException
|
||||
*/
|
||||
public static JSON from(InputStream inStream) throws IOException {
|
||||
Assert.notNull("inStream", inStream);
|
||||
String jsonString = IOUtils.toString(inStream, "UTF-8");
|
||||
return from(jsonString);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a <code>JSON</code> instance from an unknown data type.
|
||||
*
|
||||
* @param object
|
||||
* @return a <code>JSON</code> instance
|
||||
* @throws IOException
|
||||
*/
|
||||
public static JSON from(Object object) throws IOException {
|
||||
Assert.notNull("object", object);
|
||||
try {
|
||||
return from(mapper.writeValueAsString(object));
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a <code>JSON</code> instance from a <code>Reader</code>.
|
||||
*
|
||||
* @param reader
|
||||
* @return a <code>JSON</code> instance
|
||||
* @throws IOException
|
||||
*/
|
||||
public static JSON from(Reader reader) throws IOException {
|
||||
Assert.notNull("reader", reader);
|
||||
String jsonString = IOUtils.toString(reader);
|
||||
return from(jsonString);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a <code>JSON</code> instance from a <code>String</code>.
|
||||
*
|
||||
* @param jsonString
|
||||
* @return a <code>JSON</code> instance
|
||||
*/
|
||||
public static JSON from(String jsonString) {
|
||||
Assert.notNull("jsonString", jsonString);
|
||||
// TODO: Validate String
|
||||
return new JSON(jsonString);
|
||||
}
|
||||
|
||||
private final String jsonString;
|
||||
|
||||
private JSON(String jsonString) {
|
||||
this.jsonString = jsonString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this) {
|
||||
return true;
|
||||
}
|
||||
if (obj instanceof JSON) {
|
||||
return jsonString.equals(((JSON)obj).jsonString);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return jsonString.hashCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts this <code>JSON</code> object to the specified type.
|
||||
*
|
||||
* @param targetClass
|
||||
* @return an object of the specified type
|
||||
* @throws IOException
|
||||
*/
|
||||
public <T> T toObject(Class<T> targetClass) throws IOException {
|
||||
Assert.notNull("targetClass", targetClass);
|
||||
try {
|
||||
return mapper.readValue(jsonString, targetClass);
|
||||
} catch (IOException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return jsonString;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* 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.base.lang;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/** This annotation is meant to be used to describe how some variable
|
||||
* or method is protected by some other locking mechanism. Its value
|
||||
* is free-form, and can contain anything. It will generally contain
|
||||
* the name of an instance variable, including <code>this</code>.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
@Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD})
|
||||
public @interface LockedBy {
|
||||
String value();
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.lang;
|
||||
|
||||
/** A range of values. */
|
||||
public interface Range<T> {
|
||||
/** Returns <code>true</code> if the lowest value in this range
|
||||
* occurs after the greatest value in <code>range</code>.
|
||||
*
|
||||
* @param range The range to test
|
||||
* @return <code>true</code> if the lowest value in this range
|
||||
* occurs after the greatest value in <code>range</code>
|
||||
*/
|
||||
boolean after(Range<T> range);
|
||||
|
||||
/** Returns <code>true</code> if this range occurs after <code>value</code>.
|
||||
*
|
||||
* @param value The value to test
|
||||
* @return <code>true</code> if this range occurs after <code>value</code>
|
||||
*/
|
||||
boolean after(T value);
|
||||
|
||||
/** Returns <code>true</code> if the greatest value in this range
|
||||
* occurs before the lowest value in <code>range</code>.
|
||||
*
|
||||
* @param range The range to test
|
||||
* @return <code>true</code> if the greatest value in this range
|
||||
* occurs before the lowest value in <code>range</code>
|
||||
*/
|
||||
boolean before(Range<T> range);
|
||||
|
||||
/** Returns <code>true</code> if this range occurs before <code>value</code>.
|
||||
*
|
||||
* @param value The value to test
|
||||
* @return <code>true</code> if this range occurs before <code>value</code>
|
||||
*/
|
||||
boolean before(T value);
|
||||
|
||||
/** Returns the ending value of this range.
|
||||
*
|
||||
* @return Ending value
|
||||
*/
|
||||
T end();
|
||||
|
||||
/** Returns <code>true</code> if this range includes <code>range</code>.
|
||||
*
|
||||
* @param range The range to test
|
||||
* @return <code>true</code> if this range includes <code>range</code>
|
||||
*/
|
||||
boolean includes(Range<T> range);
|
||||
|
||||
/** Returns <code>true</code> if <code>value</code> occurs within this range.
|
||||
*
|
||||
* @param value The value to test
|
||||
* @return <code>true</code> if <code>value</code> occurs within this range
|
||||
*/
|
||||
boolean includes(T value);
|
||||
|
||||
/** Returns <code>true</code> if the starting and ending values are equal.
|
||||
*
|
||||
* @return <code>true</code> if the starting and ending values are equal
|
||||
*/
|
||||
boolean isPoint();
|
||||
|
||||
/** Returns <code>true</code> if this range overlaps <code>range</code>.
|
||||
*
|
||||
* @param range The range to test
|
||||
* @return <code>true</code> if this range overlaps <code>range</code>
|
||||
*/
|
||||
boolean overlaps(Range<T> range);
|
||||
|
||||
/** Returns the starting value of this range.
|
||||
*
|
||||
* @return Starting value
|
||||
*/
|
||||
T start();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.lang;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE})
|
||||
public @interface SourceMonitored {
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* 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.base.lang;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/** Identifies thread safe classes. */
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface ThreadSafe {}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.lang.test;
|
||||
|
||||
import org.ofbiz.base.test.GenericTestCaseBase;
|
||||
import org.ofbiz.base.lang.ComparableRange;
|
||||
import org.ofbiz.base.lang.SourceMonitored;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
@SourceMonitored
|
||||
public class ComparableRangeTests extends GenericTestCaseBase {
|
||||
|
||||
public ComparableRangeTests(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <L extends Comparable<L>, R extends Comparable<R>> void comparableRangeConstructorTest(L left, R right) {
|
||||
new ComparableRange<L>(left, left);
|
||||
new ComparableRange<R>(right, right);
|
||||
IllegalArgumentException caught = null;
|
||||
try {
|
||||
new ComparableRange(left, right);
|
||||
} catch (IllegalArgumentException e) {
|
||||
caught = e;
|
||||
} finally {
|
||||
assertNotNull("expected exception", caught);
|
||||
}
|
||||
caught = null;
|
||||
try {
|
||||
new ComparableRange(right, left);
|
||||
} catch (IllegalArgumentException e) {
|
||||
caught = e;
|
||||
} finally {
|
||||
assertNotNull("expected exception", caught);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T extends Comparable<T>, B extends Comparable<B>> void comparableRangeTest(String label, B bad, T a, T b, T c, T d) {
|
||||
comparableRangeConstructorTest(bad, a);
|
||||
assertTrue(label + ":a-isPoint", new ComparableRange<T>(a, a).isPoint());
|
||||
assertTrue(label + ":b-isPoint", new ComparableRange<T>(b, b).isPoint());
|
||||
assertTrue(label + ":c-isPoint", new ComparableRange<T>(c, c).isPoint());
|
||||
ComparableRange<T> first = new ComparableRange<T>(a, b);
|
||||
ComparableRange<T> second = new ComparableRange<T>(c, d);
|
||||
ComparableRange<T> all = new ComparableRange<T>(a, d);
|
||||
assertEquals(label + ":a-b toString", a + " - " + b, first.toString());
|
||||
assertEquals(label + ":c-d toString", c + " - " + d, second.toString());
|
||||
assertEquals(label + ":a-d toString", a + " - " + d, all.toString());
|
||||
assertFalse(label + ":a-b isPoint", first.isPoint());
|
||||
assertFalse(label + ":c-d isPoint", second.isPoint());
|
||||
assertFalse(label + ":a-d isPoint", all.isPoint());
|
||||
assertEquals(label + ":a-b == a-b", first, first);
|
||||
assertEquals(label + ":a-b.compareTo(a-b)", 0, first.compareTo(first));
|
||||
assertEquals(label + ":a-b equals a-b", first, new ComparableRange<T>(a, b));
|
||||
assertEquals(label + ":a-b.compareTo(new a-b)", 0, first.compareTo(new ComparableRange<T>(a, b)));
|
||||
assertEquals(label + ":a-b equals b-a", first, new ComparableRange<T>(b, a));
|
||||
assertEquals(label + ":a-b.compareTo(new b-a)", 0, first.compareTo(new ComparableRange<T>(b, a)));
|
||||
assertNotEquals(label + ":a-b not-equal other", first, ComparableRangeTests.class);
|
||||
assertFalse(label + ":a-d equals null", all.equals(null));
|
||||
ClassCastException caught = null;
|
||||
try {
|
||||
UtilGenerics.<Comparable<Object>>cast(first).compareTo(ComparableRangeTests.class);
|
||||
} catch (ClassCastException e) {
|
||||
caught = e;
|
||||
} finally {
|
||||
assertNotNull(label + " compareTo CCE", caught);
|
||||
}
|
||||
assertNotEquals(label + ":a-a != a-b", new ComparableRange<T>(a, a), first);
|
||||
assertThat(label + ":a-a.compareTo(a-b) < 0", 0, greaterThan(new ComparableRange<T>(a, a).compareTo(first)));
|
||||
assertNotEquals(label + ":a-a != c-d", new ComparableRange<T>(a, a), second);
|
||||
assertThat(label + ":a-a.compareTo(c-d) < 0", 0, greaterThan(new ComparableRange<T>(a, a).compareTo(second)));
|
||||
assertNotEquals(label + ":a-a != a-d", new ComparableRange<T>(a, a), all);
|
||||
assertThat(label + ":a-a.compareTo(a-d) < 0", 0, greaterThan(new ComparableRange<T>(a, a).compareTo(all)));
|
||||
assertTrue(label + ":b-c after a-b", second.after(first));
|
||||
assertThat(label + ":b-c.compareTo(a-b)", 0, lessThan(second.compareTo(first)));
|
||||
assertFalse(label + ":c-d !after c-d", second.after(second));
|
||||
assertEquals(label + ":c-d.compareTo(c-d)", 0, second.compareTo(second));
|
||||
assertTrue(label + ":a-b before c-d", first.before(second));
|
||||
assertThat(label + ":a-b.compareTo(c-d)", 0, greaterThan(first.compareTo(second)));
|
||||
assertFalse(label + ":a-b !before a-b", first.before(first));
|
||||
assertEquals(label + ":a-b.compareTo(a-b)", 0, first.compareTo(first));
|
||||
assertTrue(label + ":a-d includes a-b", all.includes(first));
|
||||
assertTrue(label + ":a-b overlaps b-c", first.overlaps(new ComparableRange<T>(b, c)));
|
||||
assertTrue(label + ":b-c overlaps c-d", new ComparableRange<T>(b, c).overlaps(second));
|
||||
assertTrue(label + ":a-b overlaps a-d", first.overlaps(all));
|
||||
assertTrue(label + ":a-d overlaps a-b", all.overlaps(first));
|
||||
assertTrue(label + ":a-d overlaps b-c", all.overlaps(new ComparableRange<T>(b, c)));
|
||||
assertTrue(label + ":b-c overlaps a-d", new ComparableRange<T>(b, c).overlaps(all));
|
||||
assertFalse(label + ":a-b overlaps c-d", first.overlaps(second));
|
||||
assertFalse(label + ":c-d overlaps a-b", second.overlaps(first));
|
||||
assertTrue(label + ":a-b includes a", first.includes(a));
|
||||
assertTrue(label + ":a-b includes b", first.includes(b));
|
||||
assertFalse(label + ":a-b includes c", first.includes(c));
|
||||
assertFalse(label + ":a includes a-b", new ComparableRange<T>(a, a).includes(first));
|
||||
assertTrue(label + ":c-d after a", second.after(a));
|
||||
assertTrue(label + ":c-d after b", second.after(b));
|
||||
assertFalse(label + ":c-d after c", second.after(c));
|
||||
assertFalse(label + ":c-d after d", second.after(d));
|
||||
assertFalse(label + ":a-b after a", first.before(a));
|
||||
assertFalse(label + ":a-b after b", first.before(b));
|
||||
assertTrue(label + ":a-b after c", first.before(c));
|
||||
assertTrue(label + ":a-b after d", first.before(d));
|
||||
}
|
||||
|
||||
public void testComparableRange() {
|
||||
comparableRangeTest("integer", 20L, 1, 2, 3, 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.location;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.ofbiz.base.util.UtilURL;
|
||||
|
||||
/**
|
||||
* A special location resolver that uses Strings like URLs, but with more options
|
||||
*
|
||||
*/
|
||||
|
||||
public class ClasspathLocationResolver implements LocationResolver {
|
||||
public URL resolveLocation(String location) throws MalformedURLException {
|
||||
return resolveLocation(location, null);
|
||||
}
|
||||
|
||||
public URL resolveLocation(String location, ClassLoader loader) throws MalformedURLException {
|
||||
String baseLocation = FlexibleLocation.stripLocationType(location);
|
||||
// if there is a leading forward slash, remove it
|
||||
if (baseLocation.charAt(0) == '/') {
|
||||
baseLocation = baseLocation.substring(1);
|
||||
}
|
||||
return UtilURL.fromResource(baseLocation, loader);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.location;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.ofbiz.base.component.ComponentConfig;
|
||||
import org.ofbiz.base.component.ComponentException;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
|
||||
/**
|
||||
* A special location resolver that uses Strings like URLs, but with more options
|
||||
*
|
||||
*/
|
||||
|
||||
public class ComponentLocationResolver implements LocationResolver {
|
||||
|
||||
public static final String module = ComponentLocationResolver.class.getName();
|
||||
|
||||
public URL resolveLocation(String location) throws MalformedURLException {
|
||||
String baseLocation = getBaseLocation(location).toString();
|
||||
if (File.separatorChar != '/') {
|
||||
baseLocation = baseLocation.replace(File.separatorChar, '/');
|
||||
}
|
||||
if (!baseLocation.startsWith("/")) {
|
||||
baseLocation = "/".concat(baseLocation);
|
||||
}
|
||||
try {
|
||||
return new URI("file", null, baseLocation, null).toURL();
|
||||
} catch (URISyntaxException e) {
|
||||
throw new MalformedURLException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static StringBuilder getBaseLocation(String location) throws MalformedURLException {
|
||||
StringBuilder baseLocation = new StringBuilder(FlexibleLocation.stripLocationType(location));
|
||||
// componentName is between the first slash and the second
|
||||
int firstSlash = baseLocation.indexOf("/");
|
||||
int secondSlash = baseLocation.indexOf("/", firstSlash + 1);
|
||||
if (firstSlash != 0 || secondSlash == -1) {
|
||||
throw new MalformedURLException("Bad component location [" + location + "]: base location missing slashes [" + baseLocation + "], first = " + firstSlash + ", second = " + secondSlash + "; should be like: component://{component-name}/relative/path");
|
||||
}
|
||||
String componentName = baseLocation.substring(firstSlash + 1, secondSlash);
|
||||
// got the componentName, now remove it from the baseLocation, removing the second slash too (just in case the rootLocation has one)
|
||||
baseLocation.delete(0, secondSlash + 1);
|
||||
try {
|
||||
String rootLocation = ComponentConfig.getRootLocation(componentName);
|
||||
// if there is not a forward slash between the two, add it
|
||||
if (baseLocation.charAt(0) != '/' && rootLocation.charAt(rootLocation.length() - 1) != '/') {
|
||||
baseLocation.insert(0, '/');
|
||||
}
|
||||
// insert the root location and we're done
|
||||
baseLocation.insert(0, rootLocation);
|
||||
return baseLocation;
|
||||
} catch (ComponentException e) {
|
||||
String errMsg = "Could not get root location for component with name [" + componentName + "], error was: " + e.toString();
|
||||
Debug.logError(e, errMsg, module);
|
||||
throw new MalformedURLException(errMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.location;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
|
||||
/**
|
||||
* A special location resolver that uses Strings like URLs, but with more options.
|
||||
*
|
||||
*/
|
||||
public final class FlexibleLocation {
|
||||
|
||||
private static final Map<String, LocationResolver> locationResolvers;
|
||||
|
||||
static {
|
||||
Map<String, LocationResolver> resolverMap = new HashMap<String, LocationResolver>(8);
|
||||
LocationResolver standardUrlResolver = new StandardUrlLocationResolver();
|
||||
resolverMap.put("http", standardUrlResolver);
|
||||
resolverMap.put("https", standardUrlResolver);
|
||||
resolverMap.put("ftp", standardUrlResolver);
|
||||
resolverMap.put("jar", standardUrlResolver);
|
||||
resolverMap.put("file", standardUrlResolver);
|
||||
resolverMap.put("classpath", new ClasspathLocationResolver());
|
||||
resolverMap.put("ofbizhome", new OFBizHomeLocationResolver());
|
||||
resolverMap.put("component", new ComponentLocationResolver());
|
||||
try {
|
||||
/* Note that the file must be placed in framework/base/config -
|
||||
* because this class may be initialized before all components
|
||||
* are loaded.
|
||||
*/
|
||||
Properties properties = UtilProperties.createProperties("locationresolvers.properties");
|
||||
if (properties != null) {
|
||||
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
|
||||
for (Entry<Object, Object> entry : properties.entrySet()) {
|
||||
String locationType = (String) entry.getKey();
|
||||
String locationResolverName = (String) entry.getValue();
|
||||
Class<?> lClass = classLoader.loadClass(locationResolverName);
|
||||
resolverMap.put(locationType, (LocationResolver) lClass.newInstance());
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
System.out.println("Exception thrown while loading locationresolvers.properties: " + e);
|
||||
}
|
||||
locationResolvers = Collections.unmodifiableMap(resolverMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the location type descriptor for the passed location String;
|
||||
* generally is all text before the first ":" character.
|
||||
* If no type descriptor is found, defaults to "classpath".
|
||||
*/
|
||||
private static String getLocationType(String location) {
|
||||
int colonIndex = location.indexOf(":");
|
||||
if (colonIndex > 0) {
|
||||
return location.substring(0, colonIndex);
|
||||
} else {
|
||||
return "classpath";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the gives location into a URL object for use in various ways.
|
||||
*
|
||||
* The general format of the location is like a URL: {locationType}://location/path/file.ext
|
||||
*
|
||||
* Supports standard locationTypes like http, https, ftp, jar, & file
|
||||
* Supports a classpath location type for when desired to be used like any other URL
|
||||
* Supports OFBiz specific location types like ofbizhome and component
|
||||
* Supports additional locationTypes specified in the locationresolvers.properties file
|
||||
*
|
||||
* @param location The location String to parse and create a URL from
|
||||
* @return URL object corresponding to the location String passed in
|
||||
* @throws MalformedURLException
|
||||
*/
|
||||
public static URL resolveLocation(String location) throws MalformedURLException {
|
||||
return resolveLocation(location, null);
|
||||
}
|
||||
|
||||
public static URL resolveLocation(String location, ClassLoader loader) throws MalformedURLException {
|
||||
if (UtilValidate.isEmpty(location)) {
|
||||
return null;
|
||||
}
|
||||
String locationType = getLocationType(location);
|
||||
LocationResolver resolver = locationResolvers.get(locationType);
|
||||
if (resolver != null) {
|
||||
if (loader != null && resolver instanceof ClasspathLocationResolver) {
|
||||
ClasspathLocationResolver cplResolver = (ClasspathLocationResolver) resolver;
|
||||
return cplResolver.resolveLocation(location, loader);
|
||||
} else {
|
||||
return resolver.resolveLocation(location);
|
||||
}
|
||||
} else {
|
||||
throw new MalformedURLException("Could not find a LocationResolver for the location type: " + locationType);
|
||||
}
|
||||
}
|
||||
|
||||
public static String stripLocationType(String location) {
|
||||
if (UtilValidate.isEmpty(location)) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder strippedSoFar = new StringBuilder(location);
|
||||
// first take care of the colon and everything before it
|
||||
int colonIndex = strippedSoFar.indexOf(":");
|
||||
if (colonIndex == 0) {
|
||||
strippedSoFar.deleteCharAt(0);
|
||||
} else if (colonIndex > 0) {
|
||||
strippedSoFar.delete(0, colonIndex + 1);
|
||||
}
|
||||
// now remove any extra forward slashes, ie as long as the first two are forward slashes remove the first one
|
||||
while (strippedSoFar.charAt(0) == '/' && strippedSoFar.charAt(1) == '/') {
|
||||
strippedSoFar.deleteCharAt(0);
|
||||
}
|
||||
return strippedSoFar.toString();
|
||||
}
|
||||
|
||||
private FlexibleLocation() {}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.location;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* A special location resolver that uses Strings like URLs, but with more options
|
||||
*
|
||||
*/
|
||||
|
||||
public interface LocationResolver {
|
||||
public URL resolveLocation(String location) throws MalformedURLException;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.location;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* A special location resolver that uses Strings like URLs, but with more options
|
||||
*
|
||||
*/
|
||||
|
||||
public class OFBizHomeLocationResolver implements LocationResolver {
|
||||
|
||||
public static final String envName = "ofbiz.home";
|
||||
|
||||
public URL resolveLocation(String location) throws MalformedURLException {
|
||||
String propValue = System.getProperty(envName);
|
||||
if (propValue == null) {
|
||||
String errMsg = "The Java environment (-Dxxx=yyy) variable with name " + envName + " is not set, cannot resolve location.";
|
||||
throw new MalformedURLException(errMsg);
|
||||
}
|
||||
StringBuilder baseLocation = new StringBuilder(FlexibleLocation.stripLocationType(location));
|
||||
// if there is not a forward slash between the two, add it
|
||||
if (baseLocation.charAt(0) != '/' && propValue.charAt(propValue.length() - 1) != '/') {
|
||||
baseLocation.insert(0, '/');
|
||||
}
|
||||
baseLocation.insert(0, propValue);
|
||||
String fileLocation = baseLocation.toString();
|
||||
if (File.separatorChar != '/') {
|
||||
fileLocation = fileLocation.replace(File.separatorChar, '/');
|
||||
}
|
||||
if (!fileLocation.startsWith("/")) {
|
||||
fileLocation = "/".concat(fileLocation);
|
||||
}
|
||||
try {
|
||||
return new URI("file", null, fileLocation, null).toURL();
|
||||
} catch (URISyntaxException e) {
|
||||
throw new MalformedURLException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.location;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* A special location resolver that uses Strings like URLs, but with more options
|
||||
*
|
||||
*/
|
||||
|
||||
public class StandardUrlLocationResolver implements LocationResolver {
|
||||
public URL resolveLocation(String location) throws MalformedURLException {
|
||||
return new URL(location);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
Copyright (c) 2002 by Matt Welsh and The Regents of the University of California. All rights reserved.
|
||||
|
||||
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA
|
||||
HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE
|
||||
UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
|
||||
*/
|
||||
package org.ofbiz.base.metrics;
|
||||
|
||||
|
||||
/**
|
||||
* An object that tracks service metrics.
|
||||
* <p>This interface and its default implementation are based on the
|
||||
* <code>seda.sandstorm.internal.StageStats</code> class written by
|
||||
* Matt Welsh.</code>
|
||||
* @see <a href="http://www.eecs.harvard.edu/~mdw/proj/seda/">SEDA</a>
|
||||
*/
|
||||
public interface Metrics {
|
||||
/**
|
||||
* Returns the name of the metric.
|
||||
*/
|
||||
String getName();
|
||||
|
||||
/**
|
||||
* Returns a moving average of the service rate in milliseconds. The default
|
||||
* implementation divides the total time by the total number of events and then
|
||||
* applies a smoothing factor.
|
||||
*/
|
||||
double getServiceRate();
|
||||
|
||||
/** Returns the metric threshold. The meaning of the threshold is
|
||||
* determined by client code.
|
||||
* <p>The idea is for client code to compare {@link #getServiceRate()} to
|
||||
* the threshold and perform some action based on the comparison.</p>
|
||||
*/
|
||||
double getThreshold();
|
||||
|
||||
/** Returns the total number of processed events. */
|
||||
long getTotalEvents();
|
||||
|
||||
/**
|
||||
* Records the service time for <code>numEvents</code> taking
|
||||
* <code>time</code> milliseconds to be processed.
|
||||
*/
|
||||
void recordServiceRate(int numEvents, long time);
|
||||
|
||||
/** Resets all metrics. */
|
||||
void reset();
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
Copyright (c) 2002 by Matt Welsh and The Regents of the University of California. All rights reserved.
|
||||
|
||||
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA
|
||||
HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE
|
||||
UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
|
||||
*/
|
||||
package org.ofbiz.base.metrics;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import org.ofbiz.base.lang.LockedBy;
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.base.util.Assert;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.cache.UtilCache;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* A {@link org.ofbiz.base.metrics.Metrics} factory.
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class MetricsFactory {
|
||||
private static final UtilCache<String, Metrics> METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0);
|
||||
/**
|
||||
* A "do-nothing" <code>Metrics</code> instance.
|
||||
*/
|
||||
public static final Metrics NULL_METRICS = new NullMetrics();
|
||||
|
||||
/**
|
||||
* Creates a <code>Metrics</code> instance based on <code>element</code> attributes.
|
||||
* If an instance with the same name already exists, it will be returned.
|
||||
* <p><strong>Element Attributes</strong>
|
||||
* <table border="1">
|
||||
* <tr><th>Attribute Name</th><th>Requirements</th><th>Description</th><th>Notes</th></tr>
|
||||
* <tr><td>name</td><td>Required</td><td>The metric name.</td><td> </td></tr>
|
||||
* <tr><td>estimation-size</td><td>Optional</td><td>Positive integer number of events to include in the metrics calculation.</td><td>Defaults to "100".</td></tr>
|
||||
* <tr><td>estimation-time</td><td>Optional</td><td>Positive integer number of milliseconds to include in the metrics calculation.</td><td>Defaults to "1000".</td></tr>
|
||||
* <tr><td>smoothing</td><td>Optional</td><td>Smoothing factor - used to smooth the differences between calculations.</td><td>A value of "1" disables smoothing. Defaults to "0.7".</td></tr>
|
||||
* <tr><td>threshold</td><td>Optional</td><td>The metric threshold. The meaning of the threshold is determined by client code.</td><td>Defaults to "0.0".</td></tr>
|
||||
* </table></p>
|
||||
*
|
||||
* @param element The element whose attributes will be used to create the <code>Metrics</code> instance
|
||||
* @return A <code>Metrics</code> instance based on <code>element</code> attributes
|
||||
* @throws IllegalArgumentException if <code>element</code> is null or if the name attribute is empty
|
||||
* @throws NumberFormatException if any of the numeric attribute values are unparsable
|
||||
*/
|
||||
public static Metrics getInstance(Element element) {
|
||||
Assert.notNull("element", element);
|
||||
String name = element.getAttribute("name");
|
||||
Assert.notEmpty("name attribute", name);
|
||||
Metrics result = METRICS_CACHE.get(name);
|
||||
if (result == null) {
|
||||
int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100);
|
||||
String attributeValue = element.getAttribute("estimation-size");
|
||||
if (!attributeValue.isEmpty()) {
|
||||
estimationSize = Integer.parseInt(attributeValue);
|
||||
}
|
||||
long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000);
|
||||
attributeValue = element.getAttribute("estimation-time");
|
||||
if (!attributeValue.isEmpty()) {
|
||||
estimationTime = Long.parseLong(attributeValue);
|
||||
}
|
||||
double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7);
|
||||
attributeValue = element.getAttribute("smoothing");
|
||||
if (!attributeValue.isEmpty()) {
|
||||
smoothing = Double.parseDouble(attributeValue);
|
||||
}
|
||||
double threshold = 0.0;
|
||||
attributeValue = element.getAttribute("threshold");
|
||||
if (!attributeValue.isEmpty()) {
|
||||
threshold = Double.parseDouble(attributeValue);
|
||||
}
|
||||
result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold);
|
||||
METRICS_CACHE.putIfAbsent(name, result);
|
||||
result = METRICS_CACHE.get(name);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a <code>Metrics</code> instance.
|
||||
* If an instance with the same name already exists, it will be returned.
|
||||
* @param name The metric name.
|
||||
* @param estimationSize Positive integer number of events to include in the metrics calculation.
|
||||
* @param estimationTime Positive integer number of milliseconds to include in the metrics calculation.
|
||||
* @param smoothing Smoothing factor - used to smooth the differences between calculations.
|
||||
* @return A <code>Metrics</code> instance
|
||||
*/
|
||||
public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) {
|
||||
Assert.notNull("name", name);
|
||||
Metrics result = METRICS_CACHE.get(name);
|
||||
if (result == null) {
|
||||
result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold);
|
||||
METRICS_CACHE.putIfAbsent(name, result);
|
||||
result = METRICS_CACHE.get(name);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an existing <code>Metric</code> instance with the specified name.
|
||||
* Returns <code>null</code> if the metric does not exist.
|
||||
* @param name The metric name
|
||||
*/
|
||||
public static Metrics getMetric(String name) {
|
||||
Assert.notNull("name", name);
|
||||
return METRICS_CACHE.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all <code>Metric</code> instances, sorted by name.
|
||||
*/
|
||||
public static Collection<Metrics> getMetrics() {
|
||||
return new TreeSet<Metrics>(METRICS_CACHE.values());
|
||||
}
|
||||
|
||||
private static final class MetricsImpl implements Metrics, Comparable<Metrics> {
|
||||
@LockedBy("this")
|
||||
private int count = 0;
|
||||
@LockedBy("this")
|
||||
private long lastTime = System.currentTimeMillis();
|
||||
@LockedBy("this")
|
||||
private double serviceRate = 0.0;
|
||||
@LockedBy("this")
|
||||
private long totalServiceTime = 0;
|
||||
@LockedBy("this")
|
||||
private long totalEvents = 0;
|
||||
@LockedBy("this")
|
||||
private long cumulativeEvents = 0;
|
||||
private final String name;
|
||||
private final int estimationSize;
|
||||
private final long estimationTime;
|
||||
private final double smoothing;
|
||||
private final double threshold;
|
||||
|
||||
private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) {
|
||||
this.name = name;
|
||||
this.estimationSize = estimationSize;
|
||||
this.estimationTime = estimationTime;
|
||||
this.smoothing = smoothing;
|
||||
this.threshold = threshold;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Metrics other) {
|
||||
return this.name.compareTo(other.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
MetricsImpl that = (MetricsImpl) obj;
|
||||
return this.name.equals(that.name);
|
||||
} catch (Exception e) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized double getServiceRate() {
|
||||
return serviceRate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getThreshold() {
|
||||
return threshold;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized long getTotalEvents() {
|
||||
return cumulativeEvents;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return name.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void recordServiceRate(int numEvents, long time) {
|
||||
totalEvents += numEvents;
|
||||
cumulativeEvents += numEvents;
|
||||
totalServiceTime += time;
|
||||
count++;
|
||||
long curTime = System.currentTimeMillis();
|
||||
if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) {
|
||||
if (totalEvents == 0) {
|
||||
totalEvents = 1;
|
||||
}
|
||||
double rate = totalServiceTime / totalEvents;
|
||||
serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing));
|
||||
count = 0;
|
||||
lastTime = curTime;
|
||||
totalEvents = totalServiceTime = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void reset() {
|
||||
serviceRate = 0.0;
|
||||
count = 0;
|
||||
lastTime = System.currentTimeMillis();
|
||||
totalEvents = totalServiceTime = cumulativeEvents = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class NullMetrics implements Metrics {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "NULL";
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getServiceRate() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getThreshold() {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getTotalEvents() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordServiceRate(int numEvents, long time) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
}
|
||||
}
|
||||
|
||||
private MetricsFactory() {}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.splash;
|
||||
|
||||
import java.awt.EventQueue;
|
||||
|
||||
import org.ofbiz.base.start.Config;
|
||||
import org.ofbiz.base.start.StartupException;
|
||||
import org.ofbiz.base.start.StartupLoader;
|
||||
|
||||
public class SplashLoader implements StartupLoader, Runnable {
|
||||
|
||||
public static final String module = SplashLoader.class.getName();
|
||||
private static SplashScreen screen = null;
|
||||
private Config config = null;
|
||||
|
||||
/**
|
||||
* Load a startup class
|
||||
*
|
||||
* @param config Startup config
|
||||
* @param args Input arguments
|
||||
* @throws org.ofbiz.base.start.StartupException
|
||||
*
|
||||
*/
|
||||
public void load(Config config, String args[]) throws StartupException {
|
||||
this.config = config;
|
||||
|
||||
Thread t = new Thread(this);
|
||||
t.setName(this.toString());
|
||||
t.setDaemon(false);
|
||||
t.run();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the startup class
|
||||
*
|
||||
* @throws org.ofbiz.base.start.StartupException
|
||||
*
|
||||
*/
|
||||
public void start() throws StartupException {
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the container
|
||||
*
|
||||
* @throws org.ofbiz.base.start.StartupException
|
||||
*
|
||||
*/
|
||||
public void unload() throws StartupException {
|
||||
SplashLoader.close();
|
||||
}
|
||||
|
||||
public static SplashScreen getSplashScreen() {
|
||||
return screen;
|
||||
}
|
||||
|
||||
public static void close() {
|
||||
if (screen != null) {
|
||||
EventQueue.invokeLater(new SplashScreenCloser());
|
||||
}
|
||||
}
|
||||
|
||||
public void run() {
|
||||
if (config.splashLogo != null) {
|
||||
screen = new SplashScreen(config.splashLogo);
|
||||
screen.splash();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class SplashScreenCloser implements Runnable {
|
||||
public void run() {
|
||||
screen.close();
|
||||
screen = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.splash;
|
||||
|
||||
import java.awt.Dimension;
|
||||
import java.awt.Frame;
|
||||
import java.awt.Graphics;
|
||||
import java.awt.Image;
|
||||
import java.awt.MediaTracker;
|
||||
import java.awt.Rectangle;
|
||||
import java.awt.Toolkit;
|
||||
import java.awt.Window;
|
||||
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public final class SplashScreen extends Frame {
|
||||
|
||||
private final String fImageId;
|
||||
private MediaTracker fMediaTracker;
|
||||
private Window splashWindow;
|
||||
private Image fImage;
|
||||
|
||||
public SplashScreen(String aImageId) {
|
||||
if (UtilValidate.isEmpty(aImageId)) {
|
||||
throw new IllegalArgumentException("Image Id does not have content.");
|
||||
}
|
||||
fImageId = aImageId;
|
||||
}
|
||||
|
||||
public void splash() {
|
||||
initImageAndTracker();
|
||||
setSize(fImage.getWidth(null), fImage.getHeight(null));
|
||||
center();
|
||||
|
||||
fMediaTracker.addImage(fImage, 0);
|
||||
try {
|
||||
fMediaTracker.waitForID(0);
|
||||
} catch (InterruptedException ie) {
|
||||
System.out.println("Cannot track image load.");
|
||||
}
|
||||
|
||||
splashWindow = new SplashWindow(this, fImage);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
this.dispose();
|
||||
splashWindow.dispose();
|
||||
splashWindow = null;
|
||||
}
|
||||
|
||||
private void initImageAndTracker() {
|
||||
fMediaTracker = new MediaTracker(this);
|
||||
fImage = Toolkit.getDefaultToolkit().getImage(fImageId);
|
||||
}
|
||||
|
||||
private void center() {
|
||||
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
|
||||
Rectangle frame = getBounds();
|
||||
setLocation((screen.width - frame.width) / 2, (screen.height - frame.height) / 2);
|
||||
}
|
||||
|
||||
private class SplashWindow extends Window {
|
||||
|
||||
private Image fImage;
|
||||
|
||||
public SplashWindow(Frame aParent, Image aImage) {
|
||||
super(aParent);
|
||||
fImage = aImage;
|
||||
setSize(fImage.getWidth(null), fImage.getHeight(null));
|
||||
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
|
||||
Rectangle window = getBounds();
|
||||
setLocation((screen.width - window.width) / 2, (screen.height - window.height) / 2);
|
||||
setVisible(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void paint(Graphics graphics) {
|
||||
if (fImage != null) {
|
||||
graphics.drawImage(fImage, 0, 0, this);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.test;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
import org.ofbiz.base.util.UtilFormatOut;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
|
||||
public class BaseUnitTests extends TestCase {
|
||||
|
||||
public BaseUnitTests(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public void testDebug() {
|
||||
boolean debugVerbose = Debug.get(Debug.VERBOSE);
|
||||
boolean debugInfo = Debug.get(Debug.INFO);
|
||||
try {
|
||||
Debug.set(Debug.VERBOSE, true);
|
||||
assertTrue(Debug.verboseOn());
|
||||
Debug.set(Debug.VERBOSE, false);
|
||||
assertFalse(Debug.verboseOn());
|
||||
Debug.set(Debug.INFO, true);
|
||||
assertTrue(Debug.infoOn());
|
||||
} finally {
|
||||
Debug.set(Debug.VERBOSE, debugVerbose);
|
||||
Debug.set(Debug.INFO, debugInfo);
|
||||
}
|
||||
}
|
||||
|
||||
public void testFormatPrintableCreditCard_1() {
|
||||
assertEquals("test 4111111111111111 to ************111",
|
||||
"************1111",
|
||||
UtilFormatOut.formatPrintableCreditCard("4111111111111111"));
|
||||
}
|
||||
|
||||
public void testFormatPrintableCreditCard_2() {
|
||||
assertEquals("test 4111 to 4111",
|
||||
"4111",
|
||||
UtilFormatOut.formatPrintableCreditCard("4111"));
|
||||
}
|
||||
|
||||
public void testFormatPrintableCreditCard_3() {
|
||||
assertEquals("test null to null",
|
||||
null,
|
||||
UtilFormatOut.formatPrintableCreditCard(null));
|
||||
}
|
||||
public void testIsDouble_1() {
|
||||
assertFalse(UtilValidate.isDouble("10.0", true, true, 2, 2));
|
||||
}
|
||||
public void testIsFloat_1() {
|
||||
assertFalse(UtilValidate.isFloat("10.0", true, true, 2, 2));
|
||||
}
|
||||
public void testIsDouble_2() {
|
||||
assertTrue(UtilValidate.isDouble("10.000", true, true, 3, 3));
|
||||
}
|
||||
public void testIsFloat_2() {
|
||||
assertTrue(UtilValidate.isFloat("10.000", true, true, 3, 3));
|
||||
}
|
||||
|
||||
public void testStringUtil() {
|
||||
byte[] testArray = {-1};
|
||||
byte[] result = StringUtil.fromHexString(StringUtil.toHexString(testArray));
|
||||
assertEquals("Hex conversions", testArray[0], result[0]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.test;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
// This class can not use any other ofbiz helper methods, because it
|
||||
// may be used to test those helper methods.
|
||||
public abstract class GenericTestCaseBase extends TestCase {
|
||||
protected GenericTestCaseBase(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public static void useAllMemory() throws Exception {
|
||||
LinkedList<long[]> dummy = new LinkedList<long[]>();
|
||||
try {
|
||||
do {
|
||||
dummy.add(new long[1048576]);
|
||||
} while (true);
|
||||
} catch (OutOfMemoryError e) {
|
||||
System.gc();
|
||||
Thread.sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
public static void assertStaticHelperClass(Class<?> clz) throws Exception {
|
||||
Constructor<?>[] constructors = clz.getDeclaredConstructors();
|
||||
assertEquals(clz.getName() + " constructor count", 1, constructors.length);
|
||||
assertEquals(clz.getName() + " private declared constructor", 1 << Constructor.DECLARED, constructors[0].getModifiers() & ~(1 << Constructor.PUBLIC) & (1 << Constructor.DECLARED));
|
||||
constructors[0].setAccessible(true);
|
||||
constructors[0].newInstance();
|
||||
}
|
||||
|
||||
public static void assertComparison(String label, int wanted, int result) {
|
||||
if (wanted == 0) {
|
||||
assertEquals(label, wanted, result);
|
||||
} else {
|
||||
assertEquals(label, wanted, result / Math.abs(result));
|
||||
}
|
||||
}
|
||||
|
||||
public static <V, E extends Exception> void assertFuture(String label, Future<V> future, V wanted, boolean interruptable, Class<E> thrownClass, String thrownMessage) {
|
||||
try {
|
||||
assertEquals(label + ": future return", wanted, future.get());
|
||||
} catch (InterruptedException e) {
|
||||
assertTrue(label + ": expected interruption", interruptable);
|
||||
} catch (ExecutionException e) {
|
||||
assertNotNull(label + ": expecting an exception", thrownClass);
|
||||
Throwable caught = e.getCause();
|
||||
assertNotNull(label + ": captured exception", caught);
|
||||
assertEquals(label + ": correct thrown class", thrownClass, caught.getClass());
|
||||
if (thrownMessage != null) {
|
||||
assertEquals(label + ": exception message", thrownMessage, caught.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void assertNotEquals(Object wanted, Object got) {
|
||||
assertNotEquals(null, wanted, got);
|
||||
}
|
||||
|
||||
public static <T> void assertNotEquals(String msg, Object wanted, Object got) {
|
||||
if (wanted == null) {
|
||||
if (got != null) {
|
||||
return;
|
||||
}
|
||||
failEquals(msg, wanted, got);
|
||||
} else if (wanted.equals(got)) {
|
||||
failEquals(msg, wanted, got);
|
||||
}
|
||||
}
|
||||
|
||||
private static void failEquals(String msg, Object wanted, Object got) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (msg != null) {
|
||||
sb.append(msg).append(' ');
|
||||
}
|
||||
sb.append(" expected value: ").append(wanted);
|
||||
sb.append(" actual value: ").append(got);
|
||||
fail(sb.toString());
|
||||
}
|
||||
|
||||
public static <T> void assertEquals(List<T> wanted, Object got) {
|
||||
assertEquals(null, wanted, got);
|
||||
}
|
||||
|
||||
public static <T> void assertEquals(String msg, List<T> wanted, Object got) {
|
||||
msg = msg == null ? "" : msg + ' ';
|
||||
assertNotNull(msg + "expected a value", got);
|
||||
if (got.getClass().isArray()) {
|
||||
assertEqualsListArray(msg, wanted, got);
|
||||
return;
|
||||
}
|
||||
if (!(got instanceof Collection<?>)) fail(msg + "expected a collection, got a " + got.getClass());
|
||||
Iterator<T> leftIt = wanted.iterator();
|
||||
Iterator<?> rightIt = ((Collection<?>) got).iterator();
|
||||
int i = 0;
|
||||
while (leftIt.hasNext() && rightIt.hasNext()) {
|
||||
T left = leftIt.next();
|
||||
Object right = rightIt.next();
|
||||
assertEquals(msg + "item " + i, left, right);
|
||||
i++;
|
||||
}
|
||||
assertFalse(msg + "not enough items", leftIt.hasNext());
|
||||
assertFalse(msg + "too many items", rightIt.hasNext());
|
||||
}
|
||||
|
||||
public static <T> void assertEquals(Collection<T> wanted, Object got) {
|
||||
assertEquals(null, wanted, got);
|
||||
}
|
||||
|
||||
public static <T> void assertEquals(String msg, Collection<T> wanted, Object got) {
|
||||
if (wanted instanceof List<?> || wanted instanceof Set<?>) {
|
||||
// list.equals(list) and set.equals(set), see docs for Collection.equals
|
||||
if (got instanceof Set<?>) fail("Not a collection, is a set");
|
||||
if (got instanceof List<?>) fail("Not a collection, is a list");
|
||||
}
|
||||
if (wanted.equals(got)) return;
|
||||
if (!(got instanceof Collection<?>)) fail(msg + "not a collection");
|
||||
// Need to check the reverse, wanted may not implement equals,
|
||||
// which is the case for HashMap.values()
|
||||
if (got.equals(wanted)) return;
|
||||
msg = msg == null ? "" : msg + ' ';
|
||||
assertNotNull(msg + "expected a value", got);
|
||||
List<T> list = new ArrayList<T>(wanted);
|
||||
Iterator<?> rightIt = ((Collection<?>) got).iterator();
|
||||
OUTER:
|
||||
while (rightIt.hasNext()) {
|
||||
Object right = rightIt.next();
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
T left = list.get(i);
|
||||
if (left == null) {
|
||||
if (right == null) {
|
||||
list.remove(i);
|
||||
continue OUTER;
|
||||
}
|
||||
} else if (left.equals(right)) {
|
||||
list.remove(i);
|
||||
continue OUTER;
|
||||
}
|
||||
}
|
||||
fail(msg + "couldn't find " + right);
|
||||
}
|
||||
if (!list.isEmpty()) fail(msg + "not enough items: " + list);
|
||||
}
|
||||
|
||||
public static <T> void assertEquals(Set<T> wanted, Object got) {
|
||||
assertEquals(null, wanted, got);
|
||||
}
|
||||
|
||||
public static <T> void assertEquals(String msg, Set<T> wanted, Object got) {
|
||||
if (wanted.equals(got)) return;
|
||||
if (!(got instanceof Set<?>)) fail(msg + "not a set");
|
||||
// Need to check the reverse, wanted may not implement equals,
|
||||
// which is the case for HashMap.values()
|
||||
if (got.equals(wanted)) return;
|
||||
msg = msg == null ? "" : msg + ' ';
|
||||
assertNotNull(msg + "expected a value", got);
|
||||
Set<T> wantedSet = new HashSet<T>(wanted);
|
||||
Iterator<?> rightIt = ((Set<?>) got).iterator();
|
||||
while (rightIt.hasNext()) {
|
||||
Object right = rightIt.next();
|
||||
if (wantedSet.contains(right)) {
|
||||
wantedSet.remove(right);
|
||||
} else {
|
||||
fail(msg + "couldn't find " + right);
|
||||
}
|
||||
}
|
||||
if (!wantedSet.isEmpty()) fail(msg + "not enough items: " + wantedSet);
|
||||
}
|
||||
|
||||
private static <T> void assertEqualsArrayArray(String msg, Object wanted, Object got) {
|
||||
int i = 0;
|
||||
while (i < Array.getLength(wanted) && i < Array.getLength(got)) {
|
||||
Object left = Array.get(wanted, i);
|
||||
Object right = Array.get(got, i);
|
||||
assertEquals(msg + "item " + i, left, right);
|
||||
i++;
|
||||
}
|
||||
assertFalse(msg + "not enough items", i < Array.getLength(wanted));
|
||||
assertFalse(msg + "too many items", i < Array.getLength(got));
|
||||
}
|
||||
|
||||
private static <T> void assertEqualsArrayList(String msg, Object wanted, List<T> got) {
|
||||
Iterator<T> rightIt = got.iterator();
|
||||
int i = 0;
|
||||
while (i < Array.getLength(wanted) && rightIt.hasNext()) {
|
||||
Object left = Array.get(wanted, i);
|
||||
T right = rightIt.next();
|
||||
assertEquals(msg + "item " + i, left, right);
|
||||
i++;
|
||||
}
|
||||
assertFalse(msg + "too enough items", i < Array.getLength(wanted));
|
||||
assertFalse(msg + "not many items", rightIt.hasNext());
|
||||
}
|
||||
|
||||
private static <T> void assertEqualsListArray(String msg, List<T> wanted, Object got) {
|
||||
Iterator<T> leftIt = wanted.iterator();
|
||||
int i = 0;
|
||||
while (leftIt.hasNext() && i < Array.getLength(got)) {
|
||||
T left = leftIt.next();
|
||||
Object right = Array.get(got, i);
|
||||
assertEquals(msg + "item " + i, left, right);
|
||||
i++;
|
||||
}
|
||||
assertFalse(msg + "not enough items", leftIt.hasNext());
|
||||
assertFalse(msg + "too many items", i < Array.getLength(got));
|
||||
}
|
||||
|
||||
public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, I got) {
|
||||
assertEqualsIterable(label, wanted, 0, got, 0);
|
||||
}
|
||||
|
||||
public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, int wantedExtra, I got, int gotExtra) {
|
||||
Iterator<? extends V> wantedIt = wanted.iterator();
|
||||
Iterator<V> gotIt = got.iterator();
|
||||
while (wantedIt.hasNext() && gotIt.hasNext()) {
|
||||
assertEquals(label + ":iterate", wantedIt.next(), gotIt.next());
|
||||
}
|
||||
while (wantedExtra > 0) {
|
||||
assertTrue(label + ":wanted-extra(" + wantedExtra + ")", wantedIt.hasNext());
|
||||
wantedExtra--;
|
||||
}
|
||||
assertFalse(label + ":wanted-done", wantedIt.hasNext());
|
||||
while (gotExtra > 0) {
|
||||
assertTrue(label + ":got-extra(" + gotExtra + ")", gotIt.hasNext());
|
||||
gotExtra--;
|
||||
}
|
||||
assertFalse(label + ":got-done", gotIt.hasNext());
|
||||
}
|
||||
|
||||
public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, List<? extends V> wantedExtra, I got, List<? extends V> gotExtra) {
|
||||
assertEqualsIterable(label, wanted, wantedExtra, false, got, gotExtra, false);
|
||||
}
|
||||
|
||||
public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, List<? extends V> wantedExtra, boolean removeWanted, I got, List<? extends V> gotExtra, boolean removeGot) {
|
||||
Iterator<? extends V> wantedIt = wanted.iterator();
|
||||
Iterator<V> gotIt = got.iterator();
|
||||
while (wantedIt.hasNext() && gotIt.hasNext()) {
|
||||
assertEquals(label + ":iterate", wantedIt.next(), gotIt.next());
|
||||
}
|
||||
while (wantedExtra.size() > 0) {
|
||||
assertTrue(label + ":wanted-extra(" + wantedExtra + ")-hasNext", wantedIt.hasNext());
|
||||
assertEquals(label + ":wanted-extra(" + wantedExtra + ")", wantedExtra.remove(0), wantedIt.next());
|
||||
if (removeWanted) {
|
||||
wantedIt.remove();
|
||||
}
|
||||
}
|
||||
assertFalse(label + ":wanted-done", wantedIt.hasNext());
|
||||
while (gotExtra.size() > 0) {
|
||||
assertTrue(label + ":got-extra(" + gotExtra + ")-hasNext", gotIt.hasNext());
|
||||
assertEquals(label + ":got-extra(" + gotExtra + ")", gotExtra.remove(0), gotIt.next());
|
||||
if (removeGot) {
|
||||
gotIt.remove();
|
||||
}
|
||||
}
|
||||
assertFalse(label + ":got-done", gotIt.hasNext());
|
||||
}
|
||||
|
||||
public static <T> void assertEquals(Map<T, ?> wanted, Object got) {
|
||||
assertEquals(null, wanted, got);
|
||||
}
|
||||
|
||||
public static <T> void assertEquals(String msg, Map<T, ?> wanted, Object got) {
|
||||
msg = msg == null ? "" : msg + ' ';
|
||||
assertNotNull(msg + "expected a value", got);
|
||||
if (!(got instanceof Map<?, ?>)) fail(msg + "expected a map");
|
||||
Map<?, ?> gotMap = (Map<?, ?>) got;
|
||||
if (!got.equals(wanted)) {
|
||||
Set<T> leftKeys = new LinkedHashSet<T>(wanted.keySet());
|
||||
HashSet<Object> rightKeys = new HashSet<Object>(gotMap.keySet());
|
||||
for (T key: leftKeys) {
|
||||
assertTrue(msg + "got key(" + key + ")", rightKeys.remove(key));
|
||||
assertEquals(msg + "key(" + key + ") value", wanted.get(key), gotMap.get(key));
|
||||
}
|
||||
assertTrue(msg + "extra entries", rightKeys.isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
public static void assertEquals(String msg, String wanted, String got) {
|
||||
TestCase.assertEquals(msg, wanted, got);
|
||||
}
|
||||
|
||||
public static void assertEquals(Object wanted, Object got) {
|
||||
assertEquals(null, wanted, got);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void assertEquals(String msg, Object wanted, Object got) {
|
||||
if (wanted instanceof List) {
|
||||
assertEquals(msg, (List<?>) wanted, got);
|
||||
} else if (wanted instanceof Map) {
|
||||
assertEquals(msg, (Map<?, ?>) wanted, got);
|
||||
} else if (wanted == null) {
|
||||
TestCase.assertEquals(msg, wanted, got);
|
||||
} else if (wanted instanceof Set) {
|
||||
assertEquals(msg, (Set<?>) wanted, got);
|
||||
} else if (wanted instanceof Collection) {
|
||||
assertEquals(msg, (Collection<?>) wanted, got);
|
||||
} else if (wanted.getClass().isArray()) {
|
||||
if (got == null) {
|
||||
TestCase.assertEquals(msg, wanted, got);
|
||||
} else if (got.getClass().isArray()) {
|
||||
assertEqualsArrayArray(msg, wanted, got);
|
||||
} else if (got instanceof List) {
|
||||
assertEqualsArrayList(msg, wanted, (List) got);
|
||||
} else {
|
||||
TestCase.assertEquals(msg, wanted, got);
|
||||
}
|
||||
} else {
|
||||
TestCase.assertEquals(msg, wanted, got);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> List<T> list(T value) {
|
||||
ArrayList<T> list = new ArrayList<T>(1);
|
||||
list.add(value);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static <T> List<T> list(T... list) {
|
||||
return new ArrayList<T>(Arrays.asList(list));
|
||||
}
|
||||
|
||||
public static <T> Set<T> set(T value) {
|
||||
HashSet<T> set = new HashSet<T>(1);
|
||||
set.add(value);
|
||||
return set;
|
||||
}
|
||||
|
||||
public static <T> Set<T> set(T... list) {
|
||||
return new HashSet<T>(Arrays.asList(list));
|
||||
}
|
||||
|
||||
public static <T> Set<T> set(Iterable<T> iterable) {
|
||||
return set(iterable.iterator());
|
||||
}
|
||||
|
||||
public static <T> Set<T> set(Iterator<T> it) {
|
||||
HashSet<T> set = new HashSet<T>();
|
||||
while (it.hasNext()) {
|
||||
T item = it.next();
|
||||
set.add(item);
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <K, V> Map<K, V> map(Object... list) {
|
||||
assertEquals("list has even number of elements", 0, list.length % 2);
|
||||
Map<K, V> map = new LinkedHashMap<K, V>();
|
||||
for (int i = 0; i < list.length; i += 2) {
|
||||
map.put((K) list[i], (V) list[i + 1]);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.net.Socket;
|
||||
|
||||
import javax.net.ssl.X509KeyManager;
|
||||
|
||||
/**
|
||||
* AliasKeyManager - KeyManager used to specify a certificate alias
|
||||
*
|
||||
*/
|
||||
public class AliasKeyManager implements X509KeyManager {
|
||||
public static final String module = X509KeyManager.class.getName();
|
||||
|
||||
protected X509KeyManager keyManager = null;
|
||||
protected String alias = null;
|
||||
|
||||
protected AliasKeyManager() {}
|
||||
|
||||
public AliasKeyManager(X509KeyManager keyManager, String alias) {
|
||||
this.keyManager = keyManager;
|
||||
this.alias = alias;
|
||||
}
|
||||
|
||||
// this is where the customization comes in
|
||||
public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
|
||||
for (String keyType: keyTypes) {
|
||||
String[] aliases = keyManager.getClientAliases(keyType, null); // ignoring the issuers
|
||||
if (aliases != null && aliases.length > 0) {
|
||||
for (String alias: aliases) {
|
||||
if (this.alias.equals(alias)) {
|
||||
if (Debug.verboseOn()) Debug.logVerbose("chooseClientAlias for keyType [" + keyType + "] got alias " + this.alias, module);
|
||||
//Debug.logInfo(new Exception(), "Location where chooseClientAlias is called", module);
|
||||
return this.alias;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// these just pass through the keyManager
|
||||
public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
|
||||
return keyManager.chooseServerAlias(keyType, issuers, socket);
|
||||
}
|
||||
|
||||
// these just pass through the keyManager
|
||||
public String chooseServerAlias(String keyType, Socket socket, Principal... issuers) {
|
||||
return keyManager.chooseServerAlias(keyType, issuers, socket);
|
||||
}
|
||||
|
||||
public X509Certificate[] getCertificateChain(String alias) {
|
||||
X509Certificate[] certArray = keyManager.getCertificateChain(alias);
|
||||
if (Debug.verboseOn()) Debug.logVerbose("getCertificateChain for alias [" + alias + "] got " + certArray.length + " results", module);
|
||||
return certArray;
|
||||
}
|
||||
|
||||
public String[] getClientAliases(String keyType, Principal[] issuers) {
|
||||
return keyManager.getClientAliases(keyType, issuers);
|
||||
}
|
||||
|
||||
public PrivateKey getPrivateKey(String alias) {
|
||||
PrivateKey pk = keyManager.getPrivateKey(alias);
|
||||
if (Debug.verboseOn()) Debug.logVerbose("getPrivateKey for alias [" + alias + "] got " + (pk == null ? "[Not Found!]" : "[alg:" + pk.getAlgorithm() + ";format:" + pk.getFormat() + "]"), module);
|
||||
//Debug.logInfo(new Exception(), "Location where getPrivateKey is called", module);
|
||||
return pk;
|
||||
}
|
||||
|
||||
public String[] getServerAliases(String keyType, Principal[] issuers) {
|
||||
return keyManager.getServerAliases(keyType, issuers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
/*
|
||||
* 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.base.util;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
|
||||
/** Basic assertions. The static methods in this class provide a convenient way
|
||||
* to test method arguments. All of the methods in this class throw <code>
|
||||
* IllegalArgumentException</code> if the method arguments are invalid.
|
||||
*
|
||||
*/
|
||||
@ThreadSafe
|
||||
public class Assert {
|
||||
|
||||
/**
|
||||
* Tests if an argument is not null and can be cast to a specified class.
|
||||
* <p><code>Assert.isAssignableTo("foo", foo, Foo.class);</code></p>
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @param targetClass
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static void isAssignableTo(String argumentName, Object argumentObject, Class<?> targetClass) {
|
||||
notNull(argumentName, argumentObject);
|
||||
if (!targetClass.isAssignableFrom(argumentObject.getClass())) {
|
||||
throw new IllegalArgumentException(argumentName + " cannot be assigned to " + targetClass.getName());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an argument is not null and is an instance of a specified class.
|
||||
* <p><code>Assert.isInstanceOf("foo", foo, Foo.class);</code></p>
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @param targetClass
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static void isInstanceOf(String argumentName, Object argumentObject, Class<?> targetClass) {
|
||||
notNull(argumentName, argumentObject);
|
||||
if (!targetClass.isInstance(argumentObject)) {
|
||||
throw new IllegalArgumentException(argumentName + " is not an instance of " + targetClass.getName());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an argument is not null and is an instance of one of the specified classes.
|
||||
* <p><code>Assert.isInstanceOf("foo", foo, Foo.class, Bar.class, ...);</code></p>
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @param targetClasses
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static void isInstanceOf(String argumentName, Object argumentObject, Class<?>... targetClasses) {
|
||||
notNull(argumentName, argumentObject);
|
||||
for (int i = 0; i < targetClasses.length;) {
|
||||
if (targetClasses[i++].isInstance(argumentObject)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(argumentName);
|
||||
sb.append(" must be an instance of");
|
||||
for (int i = 0; i < targetClasses.length;) {
|
||||
if (i != 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append(" ").append(targetClasses[i++].getName());
|
||||
}
|
||||
throw new IllegalArgumentException(sb.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an argument is not null and is not an instance of a specified class.
|
||||
* <p><code>Assert.isNotInstanceOf("foo", foo, Foo.class);</code></p>
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @param targetClass
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static void isNotInstanceOf(String argumentName, Object argumentObject, Class<?> targetClass) {
|
||||
notNull(argumentName, argumentObject);
|
||||
if (targetClass.isInstance(argumentObject)) {
|
||||
throw new IllegalArgumentException(argumentName + " cannot be an instance of " + targetClass.getName());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an argument is not null and is not an instance of one of the specified classes.
|
||||
* <p><code>Assert.isNotInstanceOf("foo", foo, Foo.class, Bar.class, ...);</code></p>
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @param targetClasses
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static void isNotInstanceOf(String argumentName, Object argumentObject, Class<?>... targetClasses) {
|
||||
notNull(argumentName, argumentObject);
|
||||
for (int i = 0; i < targetClasses.length;) {
|
||||
Class<?> targetClass = targetClasses[i++];
|
||||
if (targetClass.isInstance(argumentObject)) {
|
||||
throw new IllegalArgumentException(argumentName + " cannot be an instance of " + targetClass.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an argument is not null and is not empty.
|
||||
* <p><code>Assert.notEmpty("foo", foo);</code></p>
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static void notEmpty(String argumentName, String argumentObject) {
|
||||
notNull(argumentName, argumentObject);
|
||||
if (argumentObject.length() == 0) {
|
||||
throw new IllegalArgumentException(argumentName + " cannot be empty");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an argument is not null and is not empty.
|
||||
* <p><code>Assert.notEmpty("foo", foo);</code></p>
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static <T extends Map<?, ?>> void notEmpty(String argumentName, T argumentObject) {
|
||||
notNull(argumentName, argumentObject);
|
||||
if (argumentObject.size() == 0) {
|
||||
throw new IllegalArgumentException(argumentName + " cannot be empty");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an argument is not null and is not empty.
|
||||
* <p><code>Assert.notEmpty("foo", foo);</code></p>
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static <T extends Collection<?>> void notEmpty(String argumentName, T argumentObject) {
|
||||
notNull(argumentName, argumentObject);
|
||||
if (argumentObject.size() == 0) {
|
||||
throw new IllegalArgumentException(argumentName + " cannot be empty");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an argument is not null and is not empty.
|
||||
* <p><code>Assert.notEmpty("foo", foo);</code></p>
|
||||
*
|
||||
* @param argumentName
|
||||
* @param argumentObject
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static <T> void notEmpty(String argumentName, T[] argumentObject) {
|
||||
notNull(argumentName, argumentObject);
|
||||
if (argumentObject.length == 0) {
|
||||
throw new IllegalArgumentException(argumentName + " cannot be empty");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests a list of arguments for <code>null</code>.
|
||||
* <p><code>Assert.notNull("foo", foo, "bar", bar, ...);</code></p>
|
||||
*
|
||||
* @param arguments
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static void notNull(Object... arguments) {
|
||||
for (int i = 0; i < arguments.length;) {
|
||||
notNull((String) arguments[i++], arguments[i++]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests an argument for <code>null</code>.
|
||||
* <p><code>Assert.notNull("foo", foo);</code></p>
|
||||
*
|
||||
* @param argumentName
|
||||
* @param objectToTest
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static void notNull(String argumentName, Object objectToTest) {
|
||||
if (objectToTest == null) {
|
||||
throw new IllegalArgumentException(argumentName + " cannot be null");
|
||||
}
|
||||
}
|
||||
|
||||
private Assert() {}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
/**
|
||||
* Base64 implements Base64 encoding and Base 64 decoding.
|
||||
*
|
||||
*/
|
||||
|
||||
public class Base64 {
|
||||
|
||||
private static byte[] Base64EncMap, Base64DecMap;
|
||||
static {
|
||||
// rfc-2045: Base64 Alphabet
|
||||
byte[] map =
|
||||
{
|
||||
(byte) 'A',
|
||||
(byte) 'B',
|
||||
(byte) 'C',
|
||||
(byte) 'D',
|
||||
(byte) 'E',
|
||||
(byte) 'F',
|
||||
(byte) 'G',
|
||||
(byte) 'H',
|
||||
(byte) 'I',
|
||||
(byte) 'J',
|
||||
(byte) 'K',
|
||||
(byte) 'L',
|
||||
(byte) 'M',
|
||||
(byte) 'N',
|
||||
(byte) 'O',
|
||||
(byte) 'P',
|
||||
(byte) 'Q',
|
||||
(byte) 'R',
|
||||
(byte) 'S',
|
||||
(byte) 'T',
|
||||
(byte) 'U',
|
||||
(byte) 'V',
|
||||
(byte) 'W',
|
||||
(byte) 'X',
|
||||
(byte) 'Y',
|
||||
(byte) 'Z',
|
||||
(byte) 'a',
|
||||
(byte) 'b',
|
||||
(byte) 'c',
|
||||
(byte) 'd',
|
||||
(byte) 'e',
|
||||
(byte) 'f',
|
||||
(byte) 'g',
|
||||
(byte) 'h',
|
||||
(byte) 'i',
|
||||
(byte) 'j',
|
||||
(byte) 'k',
|
||||
(byte) 'l',
|
||||
(byte) 'm',
|
||||
(byte) 'n',
|
||||
(byte) 'o',
|
||||
(byte) 'p',
|
||||
(byte) 'q',
|
||||
(byte) 'r',
|
||||
(byte) 's',
|
||||
(byte) 't',
|
||||
(byte) 'u',
|
||||
(byte) 'v',
|
||||
(byte) 'w',
|
||||
(byte) 'x',
|
||||
(byte) 'y',
|
||||
(byte) 'z',
|
||||
(byte) '0',
|
||||
(byte) '1',
|
||||
(byte) '2',
|
||||
(byte) '3',
|
||||
(byte) '4',
|
||||
(byte) '5',
|
||||
(byte) '6',
|
||||
(byte) '7',
|
||||
(byte) '8',
|
||||
(byte) '9',
|
||||
(byte) '+',
|
||||
(byte) '/' };
|
||||
Base64EncMap = map;
|
||||
Base64DecMap = new byte[128];
|
||||
for (int idx = 0; idx < Base64EncMap.length; idx++) {
|
||||
Base64DecMap[Base64EncMap[idx]] = (byte) idx;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method decodes the given byte[] using the base64-encoding
|
||||
* specified in RFC-2045 (Section 6.8).
|
||||
*
|
||||
* @param data the base64-encoded data.
|
||||
* @return the decoded data.
|
||||
*/
|
||||
public final static byte[] base64Decode(byte[] data) {
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int tail = data.length;
|
||||
while (data[tail - 1] == '=') {
|
||||
tail--;
|
||||
}
|
||||
|
||||
byte dest[] = new byte[tail - data.length / 4];
|
||||
|
||||
// ascii printable to 0-63 conversion
|
||||
for (int idx = 0; idx < data.length; idx++) {
|
||||
data[idx] = Base64DecMap[data[idx]];
|
||||
}
|
||||
|
||||
// 4-byte to 3-byte conversion
|
||||
int sidx, didx;
|
||||
for (sidx = 0, didx = 0; didx < dest.length - 2; sidx += 4, didx += 3) {
|
||||
dest[didx] = (byte) (((data[sidx] << 2) & 255) | ((data[sidx + 1] >>> 4) & 003));
|
||||
dest[didx + 1] = (byte) (((data[sidx + 1] << 4) & 255) | ((data[sidx + 2] >>> 2) & 017));
|
||||
dest[didx + 2] = (byte) (((data[sidx + 2] << 6) & 255) | (data[sidx + 3] & 077));
|
||||
}
|
||||
if (didx < dest.length) {
|
||||
dest[didx] = (byte) (((data[sidx] << 2) & 255) | ((data[sidx + 1] >>> 4) & 003));
|
||||
}
|
||||
if (++didx < dest.length) {
|
||||
dest[didx] = (byte) (((data[sidx + 1] << 4) & 255) | ((data[sidx + 2] >>> 2) & 017));
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method decodes the given string using the base64-encoding
|
||||
* specified in RFC-2045 (Section 6.8).
|
||||
*
|
||||
* @param str the base64-encoded string.
|
||||
* @return the decoded str.
|
||||
*/
|
||||
public final static String base64Decode(String str) {
|
||||
if (str == null) return null;
|
||||
|
||||
return new String(base64Decode(str.getBytes()));
|
||||
}
|
||||
|
||||
/**
|
||||
* This method encodes the given byte[] using the base64-encoding
|
||||
* specified in RFC-2045 (Section 6.8).
|
||||
*
|
||||
* @param data the data
|
||||
* @return the base64-encoded data
|
||||
*/
|
||||
public final static byte[] base64Encode(byte[] data) {
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int sidx, didx;
|
||||
byte dest[] = new byte[((data.length + 2) / 3) * 4];
|
||||
|
||||
// 3-byte to 4-byte conversion + 0-63 to ascii printable conversion
|
||||
for (sidx = 0, didx = 0; sidx < data.length - 2; sidx += 3) {
|
||||
dest[didx++] = Base64EncMap[(data[sidx] >>> 2) & 077];
|
||||
dest[didx++] = Base64EncMap[(data[sidx + 1] >>> 4) & 017 | (data[sidx] << 4) & 077];
|
||||
dest[didx++] = Base64EncMap[(data[sidx + 2] >>> 6) & 003 | (data[sidx + 1] << 2) & 077];
|
||||
dest[didx++] = Base64EncMap[data[sidx + 2] & 077];
|
||||
}
|
||||
if (sidx < data.length) {
|
||||
dest[didx++] = Base64EncMap[(data[sidx] >>> 2) & 077];
|
||||
if (sidx < data.length - 1) {
|
||||
dest[didx++] = Base64EncMap[(data[sidx + 1] >>> 4) & 017 | (data[sidx] << 4) & 077];
|
||||
dest[didx++] = Base64EncMap[(data[sidx + 1] << 2) & 077];
|
||||
} else
|
||||
dest[didx++] = Base64EncMap[(data[sidx] << 4) & 077];
|
||||
}
|
||||
|
||||
// add padding
|
||||
for (; didx < dest.length; didx++) {
|
||||
dest[didx] = (byte) '=';
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method encodes the given string using the base64-encoding
|
||||
* specified in RFC-2045 (Section 6.8).
|
||||
*
|
||||
* @param str the string
|
||||
* @return the base64-encoded str
|
||||
*/
|
||||
public final static String base64Encode(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return new String(base64Encode(str.getBytes()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Date;
|
||||
|
||||
import org.ofbiz.base.lang.ComparableRange;
|
||||
|
||||
/** An immutable range of dates. This class is here for backward compatibility -
|
||||
* new code should use <code>ComparableRange<Date></code> instead.
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class DateRange extends ComparableRange<Date> implements Serializable {
|
||||
/** A <code>Date</code> instance initialized to the earliest possible date.*/
|
||||
public static final Date MIN_DATE = UtilDateTime.unmodifiableDate(UtilDateTime.getEarliestDate());
|
||||
/** A <code>Date</code> instance initialized to the latest possible date.*/
|
||||
public static final Date MAX_DATE = UtilDateTime.unmodifiableDate(UtilDateTime.getLatestDate());
|
||||
/** A <code>DateRange</code> instance initialized to the widest possible range of dates.*/
|
||||
public static final DateRange FullRange = new DateRange(MIN_DATE, MAX_DATE);
|
||||
|
||||
protected static Date timestampToDate(Date date) {
|
||||
// Testing for equality between a Date instance and a Timestamp instance
|
||||
// will always return false.
|
||||
if (date instanceof Timestamp) {
|
||||
return new Date(date.getTime());
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param start If null, defaults to <a href="#MIN_DATE">MIN_DATE</a>
|
||||
* @param end If null, defaults to <a href="#MAX_DATE">MAX_DATE</a>
|
||||
*/
|
||||
public DateRange(Date start, Date end) {
|
||||
super(start == null ? MIN_DATE : UtilDateTime.unmodifiableDate(timestampToDate(start)), end == null ? MAX_DATE
|
||||
: UtilDateTime.unmodifiableDate(timestampToDate(end)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean after(Date date) {
|
||||
return super.after(timestampToDate(date));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean before(Date date) {
|
||||
return super.before(timestampToDate(date));
|
||||
}
|
||||
|
||||
/** Returns this range's duration as a millisecond value.
|
||||
* @return Range duration in milliseconds
|
||||
*/
|
||||
public long durationInMillis() {
|
||||
return this.end.getTime() - this.start.getTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date end() {
|
||||
return (Date) this.end.clone();
|
||||
}
|
||||
|
||||
/** Returns the ending date of this range as a <code>Timestamp</code> instance.
|
||||
* @return Range ending date <code>Timestamp</code>
|
||||
*/
|
||||
public Timestamp endStamp() {
|
||||
return new Timestamp(this.end.getTime());
|
||||
}
|
||||
|
||||
/** Returns <code>true</code> if <code>date</code> occurs within this range.
|
||||
* @param date
|
||||
* @return <code>true</code> if <code>date</code> occurs within this range
|
||||
*/
|
||||
public boolean includesDate(Date date) {
|
||||
return super.includes(timestampToDate(date));
|
||||
}
|
||||
|
||||
/** Returns <code>true</code> if <code>start</code> and <code>end</code>
|
||||
* intersect this range.
|
||||
* @param start If null, defaults to <a href="#MIN_DATE">MIN_DATE</a>
|
||||
* @param end If null, defaults to <a href="#MAX_DATE">MAX_DATE</a>
|
||||
* @return <code>true</code> if <code>start</code> and <code>end</code>
|
||||
* intersect this range
|
||||
*/
|
||||
public boolean intersectsRange(Date start, Date end) {
|
||||
return intersectsRange(new DateRange(start, end));
|
||||
}
|
||||
|
||||
/** Returns <code>true</code> if <code>range</code> intersects this range.
|
||||
* @param range
|
||||
* @return <code>true</code> if <code>range</code> intersects this range
|
||||
*/
|
||||
public boolean intersectsRange(DateRange range) {
|
||||
if (isPoint() && range.isPoint() && this.start.equals(range.start)) {
|
||||
return true;
|
||||
}
|
||||
return !before(range) && !after(range);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date start() {
|
||||
return (Date) this.start.clone();
|
||||
}
|
||||
|
||||
/** Returns the starting date of this range as a <code>Timestamp</code> instance.
|
||||
* @return Range starting date <code>Timestamp</code>
|
||||
*/
|
||||
public Timestamp startStamp() {
|
||||
return new Timestamp(this.start.getTime());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.util.Formatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.logging.log4j.Level;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
/**
|
||||
* Configurable Debug logging wrapper class
|
||||
*
|
||||
*/
|
||||
public final class Debug {
|
||||
|
||||
private static final String noModuleModule = "NoModule"; // set to null for previous behavior
|
||||
private static final Object[] emptyParams = new Object[0];
|
||||
|
||||
public static final int ALWAYS = 0;
|
||||
public static final int VERBOSE = 1;
|
||||
public static final int TIMING = 2;
|
||||
public static final int INFO = 3;
|
||||
public static final int IMPORTANT = 4;
|
||||
public static final int WARNING = 5;
|
||||
public static final int ERROR = 6;
|
||||
public static final int FATAL = 7;
|
||||
|
||||
private static final String[] levelProps = {"", "print.verbose", "print.timing", "print.info", "print.important", "print.warning", "print.error", "print.fatal"};
|
||||
private static final Level[] levelObjs = {Level.FATAL, Level.DEBUG, Level.TRACE, Level.INFO, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL};
|
||||
|
||||
private static final Map<String, Integer> levelStringMap = new HashMap<String, Integer>();
|
||||
|
||||
private static final boolean levelOnCache[] = new boolean[8]; // this field is not thread safe
|
||||
|
||||
private static final Logger root = LogManager.getRootLogger();
|
||||
|
||||
static {
|
||||
levelStringMap.put("verbose", Debug.VERBOSE);
|
||||
levelStringMap.put("timing", Debug.TIMING);
|
||||
levelStringMap.put("info", Debug.INFO);
|
||||
levelStringMap.put("important", Debug.IMPORTANT);
|
||||
levelStringMap.put("warning", Debug.WARNING);
|
||||
levelStringMap.put("error", Debug.ERROR);
|
||||
levelStringMap.put("fatal", Debug.FATAL);
|
||||
levelStringMap.put("always", Debug.ALWAYS);
|
||||
|
||||
// initialize levelOnCache
|
||||
Properties properties = UtilProperties.createProperties("debug.properties");
|
||||
if (properties != null) {
|
||||
for (int i = 0; i < levelOnCache.length; i++) {
|
||||
levelOnCache[i] = (i == Debug.ALWAYS || "true".equalsIgnoreCase(properties.getProperty(levelProps[i])));
|
||||
}
|
||||
} else {
|
||||
throw new IllegalStateException("debug.properties file not found");
|
||||
}
|
||||
}
|
||||
|
||||
public static Logger getLogger(String module) {
|
||||
if (UtilValidate.isNotEmpty(module)) {
|
||||
return LogManager.getLogger(module);
|
||||
} else {
|
||||
return root;
|
||||
}
|
||||
}
|
||||
|
||||
/** Gets an Integer representing the level number from a String representing the level name; will return null if not found */
|
||||
public static Integer getLevelFromString(String levelName) {
|
||||
if (levelName == null) return null;
|
||||
return levelStringMap.get(levelName.toLowerCase());
|
||||
}
|
||||
|
||||
public static void log(int level, Throwable t, String msg, String module) {
|
||||
log(level, t, msg, module, "org.ofbiz.base.util.Debug", emptyParams);
|
||||
}
|
||||
|
||||
public static void log(int level, Throwable t, String msg, String module, Object... params) {
|
||||
log(level, t, msg, module, "org.ofbiz.base.util.Debug", params);
|
||||
}
|
||||
|
||||
public static void log(int level, Throwable t, String msg, String module, String callingClass) {
|
||||
log(level, t, msg, module, callingClass, new Object[0]);
|
||||
}
|
||||
|
||||
public static void log(int level, Throwable t, String msg, String module, String callingClass, Object... params) {
|
||||
if (isOn(level)) {
|
||||
if (msg != null && params.length > 0) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Formatter formatter = new Formatter(sb);
|
||||
formatter.format(msg, params);
|
||||
msg = sb.toString();
|
||||
}
|
||||
|
||||
// log
|
||||
Logger logger = getLogger(module);
|
||||
logger.log(levelObjs[level], msg, t);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isOn(int level) {
|
||||
return levelOnCache[level];
|
||||
}
|
||||
|
||||
// leaving these here
|
||||
public static void log(String msg) {
|
||||
log(Debug.ALWAYS, null, msg, noModuleModule, emptyParams);
|
||||
}
|
||||
|
||||
public static void log(String msg, Object... params) {
|
||||
log(Debug.ALWAYS, null, msg, noModuleModule, params);
|
||||
}
|
||||
|
||||
public static void log(Throwable t) {
|
||||
log(Debug.ALWAYS, t, null, noModuleModule, emptyParams);
|
||||
}
|
||||
|
||||
public static void log(String msg, String module) {
|
||||
log(Debug.ALWAYS, null, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void log(String msg, String module, Object... params) {
|
||||
log(Debug.ALWAYS, null, msg, module, params);
|
||||
}
|
||||
|
||||
public static void log(Throwable t, String module) {
|
||||
log(Debug.ALWAYS, t, null, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void log(Throwable t, String msg, String module) {
|
||||
log(Debug.ALWAYS, t, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void log(Throwable t, String msg, String module, Object... params) {
|
||||
log(Debug.ALWAYS, t, msg, module, params);
|
||||
}
|
||||
|
||||
public static boolean verboseOn() {
|
||||
return isOn(Debug.VERBOSE);
|
||||
}
|
||||
|
||||
public static void logVerbose(String msg, String module) {
|
||||
log(Debug.VERBOSE, null, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logVerbose(String msg, String module, Object... params) {
|
||||
log(Debug.VERBOSE, null, msg, module, params);
|
||||
}
|
||||
|
||||
public static void logVerbose(Throwable t, String module) {
|
||||
log(Debug.VERBOSE, t, null, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logVerbose(Throwable t, String msg, String module) {
|
||||
log(Debug.VERBOSE, t, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logVerbose(Throwable t, String msg, String module, Object... params) {
|
||||
log(Debug.VERBOSE, t, msg, module, params);
|
||||
}
|
||||
|
||||
public static boolean timingOn() {
|
||||
return isOn(Debug.TIMING);
|
||||
}
|
||||
|
||||
public static void logTiming(String msg, String module) {
|
||||
log(Debug.TIMING, null, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logTiming(String msg, String module, Object... params) {
|
||||
log(Debug.TIMING, null, msg, module, params);
|
||||
}
|
||||
|
||||
public static void logTiming(Throwable t, String module) {
|
||||
log(Debug.TIMING, t, null, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logTiming(Throwable t, String msg, String module) {
|
||||
log(Debug.TIMING, t, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logTiming(Throwable t, String msg, String module, Object... params) {
|
||||
log(Debug.TIMING, t, msg, module, params);
|
||||
}
|
||||
|
||||
public static boolean infoOn() {
|
||||
return isOn(Debug.INFO);
|
||||
}
|
||||
|
||||
public static void logInfo(String msg, String module) {
|
||||
log(Debug.INFO, null, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logInfo(String msg, String module, Object... params) {
|
||||
log(Debug.INFO, null, msg, module, params);
|
||||
}
|
||||
|
||||
public static void logInfo(Throwable t, String module) {
|
||||
log(Debug.INFO, t, null, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logInfo(Throwable t, String msg, String module) {
|
||||
log(Debug.INFO, t, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logInfo(Throwable t, String msg, String module, Object... params) {
|
||||
log(Debug.INFO, t, msg, module, params);
|
||||
}
|
||||
|
||||
public static boolean importantOn() {
|
||||
return isOn(Debug.IMPORTANT);
|
||||
}
|
||||
|
||||
public static void logImportant(String msg, String module) {
|
||||
log(Debug.IMPORTANT, null, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logImportant(String msg, String module, Object... params) {
|
||||
log(Debug.IMPORTANT, null, msg, module, params);
|
||||
}
|
||||
|
||||
public static void logImportant(Throwable t, String module) {
|
||||
log(Debug.IMPORTANT, t, null, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logImportant(Throwable t, String msg, String module) {
|
||||
log(Debug.IMPORTANT, t, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logImportant(Throwable t, String msg, String module, Object... params) {
|
||||
log(Debug.IMPORTANT, t, msg, module, params);
|
||||
}
|
||||
|
||||
public static boolean warningOn() {
|
||||
return isOn(Debug.WARNING);
|
||||
}
|
||||
|
||||
public static void logWarning(String msg, String module) {
|
||||
log(Debug.WARNING, null, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logWarning(String msg, String module, Object... params) {
|
||||
log(Debug.WARNING, null, msg, module, params);
|
||||
}
|
||||
|
||||
public static void logWarning(Throwable t, String module) {
|
||||
log(Debug.WARNING, t, null, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logWarning(Throwable t, String msg, String module) {
|
||||
log(Debug.WARNING, t, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logWarning(Throwable t, String msg, String module, Object... params) {
|
||||
log(Debug.WARNING, t, msg, module, params);
|
||||
}
|
||||
|
||||
public static boolean errorOn() {
|
||||
return isOn(Debug.ERROR);
|
||||
}
|
||||
|
||||
public static void logError(String msg, String module) {
|
||||
log(Debug.ERROR, null, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logError(String msg, String module, Object... params) {
|
||||
log(Debug.ERROR, null, msg, module, params);
|
||||
}
|
||||
|
||||
public static void logError(Throwable t, String module) {
|
||||
log(Debug.ERROR, t, null, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logError(Throwable t, String msg, String module) {
|
||||
log(Debug.ERROR, t, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logError(Throwable t, String msg, String module, Object... params) {
|
||||
log(Debug.ERROR, t, msg, module, params);
|
||||
}
|
||||
|
||||
public static boolean fatalOn() {
|
||||
return isOn(Debug.FATAL);
|
||||
}
|
||||
|
||||
public static void logFatal(String msg, String module) {
|
||||
log(Debug.FATAL, null, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logFatal(String msg, String module, Object... params) {
|
||||
log(Debug.FATAL, null, msg, module, params);
|
||||
}
|
||||
|
||||
public static void logFatal(Throwable t, String module) {
|
||||
log(Debug.FATAL, t, null, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logFatal(Throwable t, String msg, String module) {
|
||||
log(Debug.FATAL, t, msg, module, emptyParams);
|
||||
}
|
||||
|
||||
public static void logFatal(Throwable t, String msg, String module, Object... params) {
|
||||
log(Debug.FATAL, t, msg, module, params);
|
||||
}
|
||||
|
||||
public static void set(int level, boolean on) {
|
||||
levelOnCache[level] = on;
|
||||
}
|
||||
|
||||
public static boolean get(int level) {
|
||||
return levelOnCache[level];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.FilenameFilter;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.net.MalformedURLException;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.ofbiz.base.location.ComponentLocationResolver;
|
||||
|
||||
/**
|
||||
* File Utilities
|
||||
*
|
||||
*/
|
||||
public final class FileUtil {
|
||||
|
||||
public static final String module = FileUtil.class.getName();
|
||||
|
||||
private FileUtil () {}
|
||||
|
||||
private static class SearchTextFilesFilter implements FilenameFilter {
|
||||
String fileExtension;
|
||||
Set<String> stringsToFindInFile = new HashSet<String>();
|
||||
Set<String> stringsToFindInPath = new HashSet<String>();
|
||||
|
||||
public SearchTextFilesFilter(String fileExtension, Set<String> stringsToFindInPath, Set<String> stringsToFindInFile) {
|
||||
this.fileExtension = fileExtension;
|
||||
if (stringsToFindInPath != null) {
|
||||
this.stringsToFindInPath.addAll(stringsToFindInPath);
|
||||
}
|
||||
if (stringsToFindInFile != null) {
|
||||
this.stringsToFindInFile.addAll(stringsToFindInFile);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean accept(File dir, String name) {
|
||||
File file = new File(dir, name);
|
||||
if (file.getName().startsWith(".")) {
|
||||
return false;
|
||||
}
|
||||
if (file.isDirectory()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean hasAllPathStrings = true;
|
||||
String fullPath = dir.getPath().replace('\\', '/');
|
||||
for (String pathString: stringsToFindInPath) {
|
||||
if (fullPath.indexOf(pathString) < 0) {
|
||||
hasAllPathStrings = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasAllPathStrings && name.endsWith("." + fileExtension)) {
|
||||
if (stringsToFindInFile.size() == 0) {
|
||||
return true;
|
||||
}
|
||||
StringBuffer xmlFileBuffer = null;
|
||||
try {
|
||||
xmlFileBuffer = FileUtil.readTextFile(file, true);
|
||||
} catch (FileNotFoundException e) {
|
||||
Debug.logWarning("Error reading xml file [" + file + "] for file search: " + e.toString(), module);
|
||||
return false;
|
||||
} catch (IOException e) {
|
||||
Debug.logWarning("Error reading xml file [" + file + "] for file search: " + e.toString(), module);
|
||||
return false;
|
||||
}
|
||||
if (UtilValidate.isNotEmpty(xmlFileBuffer)) {
|
||||
boolean hasAllStrings = true;
|
||||
for (String stringToFile: stringsToFindInFile) {
|
||||
if (xmlFileBuffer.indexOf(stringToFile) < 0) {
|
||||
hasAllStrings = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return hasAllStrings;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static File getFile(String path) {
|
||||
return getFile(null, path);
|
||||
}
|
||||
|
||||
public static File getFile(File root, String path) {
|
||||
if (path.startsWith("component://")) {
|
||||
try {
|
||||
path = ComponentLocationResolver.getBaseLocation(path).toString();
|
||||
} catch (MalformedURLException e) {
|
||||
Debug.logError(e, module);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return new File(root, localizePath(path));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a file path to one that is compatible with the host operating system.
|
||||
*
|
||||
* @param path The file path to convert.
|
||||
* @return The converted file path.
|
||||
*/
|
||||
public static String localizePath(String path) {
|
||||
String fileNameSeparator = ("\\".equals(File.separator) ? "\\" + File.separator : File.separator);
|
||||
return path.replaceAll("/+|\\\\+", fileNameSeparator);
|
||||
}
|
||||
|
||||
public static void writeString(String fileName, String s) throws IOException {
|
||||
writeString(null, fileName, s);
|
||||
}
|
||||
|
||||
public static void writeString(String path, String name, String s) throws IOException {
|
||||
Writer out = getBufferedWriter(path, name);
|
||||
|
||||
try {
|
||||
out.write(s + System.getProperty("line.separator"));
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
throw e;
|
||||
} finally {
|
||||
if (out != null) {
|
||||
try {
|
||||
out.close();
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a file from a string with a specified encoding.
|
||||
*
|
||||
* @param path
|
||||
* @param name
|
||||
* @param encoding
|
||||
* @param s
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void writeString(String path, String name, String encoding, String s) throws IOException {
|
||||
String fileName = getPatchedFileName(path, name);
|
||||
if (UtilValidate.isEmpty(fileName)) {
|
||||
throw new IOException("Cannot obtain buffered writer for an empty filename!");
|
||||
}
|
||||
|
||||
try {
|
||||
FileUtils.writeStringToFile(new File(fileName), s, encoding);
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public static void writeString(String encoding, String s, File outFile) throws IOException {
|
||||
try {
|
||||
FileUtils.writeStringToFile(outFile, s, encoding);
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public static Writer getBufferedWriter(String path, String name) throws IOException {
|
||||
String fileName = getPatchedFileName(path, name);
|
||||
if (UtilValidate.isEmpty(fileName)) {
|
||||
throw new IOException("Cannot obtain buffered writer for an empty filename!");
|
||||
}
|
||||
|
||||
return new BufferedWriter(new FileWriter(fileName));
|
||||
}
|
||||
|
||||
public static OutputStream getBufferedOutputStream(String path, String name) throws IOException {
|
||||
String fileName = getPatchedFileName(path, name);
|
||||
if (UtilValidate.isEmpty(fileName)) {
|
||||
throw new IOException("Cannot obtain buffered writer for an empty filename!");
|
||||
}
|
||||
|
||||
return new BufferedOutputStream(new FileOutputStream(fileName));
|
||||
}
|
||||
|
||||
public static String getPatchedFileName(String path, String fileName) throws IOException {
|
||||
// make sure the export directory exists
|
||||
if (UtilValidate.isNotEmpty(path)) {
|
||||
path = path.replaceAll("\\\\", "/");
|
||||
File parentDir = new File(path);
|
||||
if (!parentDir.exists()) {
|
||||
if (!parentDir.mkdir()) {
|
||||
throw new IOException("Cannot create directory for path: " + path);
|
||||
}
|
||||
}
|
||||
|
||||
// build the filename with the path
|
||||
if (!path.endsWith("/")) {
|
||||
path = path + "/";
|
||||
}
|
||||
if (fileName.startsWith("/")) {
|
||||
fileName = fileName.substring(1);
|
||||
}
|
||||
fileName = path + fileName;
|
||||
}
|
||||
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public static StringBuffer readTextFile(File file, boolean newline) throws FileNotFoundException, IOException {
|
||||
if (!file.exists()) {
|
||||
throw new FileNotFoundException();
|
||||
}
|
||||
|
||||
StringBuffer buf = new StringBuffer();
|
||||
BufferedReader in = null;
|
||||
try {
|
||||
in = new BufferedReader(new FileReader(file));
|
||||
|
||||
String str;
|
||||
while ((str = in.readLine()) != null) {
|
||||
buf.append(str);
|
||||
if (newline) {
|
||||
buf.append(System.getProperty("line.separator"));
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
throw e;
|
||||
} finally {
|
||||
if (in != null) {
|
||||
try {
|
||||
in.close();
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return buf;
|
||||
}
|
||||
public static StringBuffer readTextFile(String fileName, boolean newline) throws FileNotFoundException, IOException {
|
||||
File file = new File(fileName);
|
||||
return readTextFile(file, newline);
|
||||
}
|
||||
|
||||
public static String readString(String encoding, File inFile) throws IOException {
|
||||
String readString = "";
|
||||
try {
|
||||
readString = FileUtils.readFileToString(inFile, encoding);
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
throw e;
|
||||
}
|
||||
return readString;
|
||||
}
|
||||
|
||||
public static void searchFiles(List<File> fileList, File path, FilenameFilter filter, boolean includeSubfolders) throws IOException {
|
||||
// Get filtered files in the current path
|
||||
File[] files = path.listFiles(filter);
|
||||
if (files == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Process each filtered entry
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
// recurse if the entry is a directory
|
||||
if (files[i].isDirectory() && includeSubfolders && !files[i].getName().startsWith(".")) {
|
||||
searchFiles(fileList, files[i], filter, true);
|
||||
} else {
|
||||
// add the filtered file to the list
|
||||
fileList.add(files[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List<File> findFiles(String fileExt, String basePath, String partialPath, String stringToFind) throws IOException {
|
||||
if (basePath == null) {
|
||||
basePath = System.getProperty("ofbiz.home");
|
||||
}
|
||||
|
||||
Set<String> stringsToFindInPath = new HashSet<String>();
|
||||
Set<String> stringsToFindInFile = new HashSet<String>();
|
||||
|
||||
if (partialPath != null) {
|
||||
stringsToFindInPath.add(partialPath);
|
||||
}
|
||||
if (stringToFind != null) {
|
||||
stringsToFindInFile.add(stringToFind);
|
||||
}
|
||||
|
||||
List<File> fileList = new LinkedList<File>();
|
||||
FileUtil.searchFiles(fileList, new File(basePath), new SearchTextFilesFilter(fileExt, stringsToFindInPath, stringsToFindInFile), true);
|
||||
|
||||
return fileList;
|
||||
}
|
||||
|
||||
public static List<File> findXmlFiles(String basePath, String partialPath, String rootElementName, String xsdOrDtdName) throws IOException {
|
||||
if (basePath == null) {
|
||||
basePath = System.getProperty("ofbiz.home");
|
||||
}
|
||||
|
||||
Set<String> stringsToFindInPath = new HashSet<String>();
|
||||
Set<String> stringsToFindInFile = new HashSet<String>();
|
||||
|
||||
if (partialPath != null) stringsToFindInPath.add(partialPath);
|
||||
if (rootElementName != null) stringsToFindInFile.add("<" + rootElementName + " ");
|
||||
if (xsdOrDtdName != null) stringsToFindInFile.add(xsdOrDtdName);
|
||||
|
||||
List<File> fileList = new LinkedList<File>();
|
||||
FileUtil.searchFiles(fileList, new File(basePath), new SearchTextFilesFilter("xml", stringsToFindInPath, stringsToFindInFile), true);
|
||||
return fileList;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* Search for the specified <code>searchString</code> in the given
|
||||
* {@link Reader}.
|
||||
*
|
||||
* @param reader A Reader in which the String will be searched.
|
||||
* @param searchString The String to search for
|
||||
* @return <code>TRUE</code> if the <code>searchString</code> is found;
|
||||
* <code>FALSE</code> otherwise.
|
||||
* @throws IOException
|
||||
*/
|
||||
public static boolean containsString(Reader reader, final String searchString) throws IOException {
|
||||
char[] buffer = new char[1024];
|
||||
int numCharsRead;
|
||||
int count = 0;
|
||||
while((numCharsRead = reader.read(buffer)) > 0) {
|
||||
for (int c = 0; c < numCharsRead; ++c) {
|
||||
if (buffer[c] == searchString.charAt(count)) count++;
|
||||
else count = 0;
|
||||
if (count == searchString.length()) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* Search for the specified <code>searchString</code> in the given
|
||||
* filename. If the specified file doesn't exist, <code>FALSE</code>
|
||||
* returns.
|
||||
*
|
||||
* @param fileName A full path to a file in which the String will be searched.
|
||||
* @param searchString The String to search for
|
||||
* @return <code>TRUE</code> if the <code>searchString</code> is found;
|
||||
* <code>FALSE</code> otherwise.
|
||||
* @throws IOException
|
||||
*/
|
||||
public static boolean containsString(final String fileName, final String searchString) throws IOException {
|
||||
File inFile = new File(fileName);
|
||||
if (inFile.exists()) {
|
||||
BufferedReader in = new BufferedReader(new FileReader(inFile));
|
||||
try {
|
||||
return containsString(in, searchString);
|
||||
} finally {
|
||||
if (in != null)in.close();
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* Check if the specified <code>fileName</code> exists and is a file (not a directory)
|
||||
* If the specified file doesn't exist or is a directory <code>FALSE</code> returns.
|
||||
*
|
||||
* @param fileName A full path to a file in which the String will be searched.
|
||||
* @return <code>TRUE</code> if the <code>fileName</code> exists and is a file (not a directory)
|
||||
* <code>FALSE</code> otherwise.
|
||||
*/
|
||||
public static boolean isFile(String fileName) {
|
||||
File f = new File(fileName);
|
||||
return f.isFile();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Base OFBiz Exception, provides nested exceptions, etc
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GeneralException extends Exception {
|
||||
|
||||
public static <T> T checkException(Throwable t) throws GeneralException {
|
||||
return GeneralException.<T>checkException(t.getMessage(), t);
|
||||
}
|
||||
|
||||
public static <T> T checkException(String message, Throwable t) throws GeneralException {
|
||||
if (t instanceof Error) throw (Error) t;
|
||||
if (t instanceof RuntimeException) throw (RuntimeException) t;
|
||||
if (t instanceof GeneralException) throw (GeneralException) t;
|
||||
throw (GeneralException) new GeneralException(message).initCause(t);
|
||||
}
|
||||
|
||||
List<String> messages = null;
|
||||
|
||||
/**
|
||||
* Creates new <code>GeneralException</code> without detail message.
|
||||
*/
|
||||
public GeneralException() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an <code>GeneralException</code> with the specified detail message.
|
||||
* @param msg the detail message.
|
||||
*/
|
||||
public GeneralException(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 GeneralException(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 GeneralException(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 GeneralException(String msg, List<String> messages) {
|
||||
super(msg);
|
||||
this.messages = 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 nexted exception
|
||||
*/
|
||||
public GeneralException(String msg, List<String> messages, Throwable nested) {
|
||||
super(msg, nested);
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 GeneralException(List<String> messages, Throwable nested) {
|
||||
super(nested);
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
public GeneralException(List<String> messages) {
|
||||
super();
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
/** Returns the detail message, including the message from the nested exception if there is one. */
|
||||
@Override
|
||||
public String getMessage() {
|
||||
Throwable nested = getCause();
|
||||
if (nested != null) {
|
||||
if (super.getMessage() == null) {
|
||||
return nested.getMessage();
|
||||
} else {
|
||||
return super.getMessage() + " (" + nested.getMessage() + ")";
|
||||
}
|
||||
} else {
|
||||
return super.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> getMessageList() {
|
||||
return this.messages;
|
||||
}
|
||||
|
||||
/** Returns the detail message, NOT including the message from the nested exception. */
|
||||
public String getNonNestedMessage() {
|
||||
return super.getMessage();
|
||||
}
|
||||
|
||||
/** Returns the nested exception if there is one, null if there is not. */
|
||||
public Throwable getNested() {
|
||||
Throwable nested = getCause();
|
||||
if (nested == null) {
|
||||
return this;
|
||||
}
|
||||
return nested;
|
||||
}
|
||||
|
||||
/** Prints the composite message to System.err. */
|
||||
@Override
|
||||
public void printStackTrace() {
|
||||
super.printStackTrace();
|
||||
}
|
||||
|
||||
/** Prints the composite message and the embedded stack trace to the specified stream ps. */
|
||||
@Override
|
||||
public void printStackTrace(PrintStream ps) {
|
||||
super.printStackTrace(ps);
|
||||
}
|
||||
|
||||
/** Prints the composite message and the embedded stack trace to the specified print writer pw. */
|
||||
@Override
|
||||
public void printStackTrace(PrintWriter pw) {
|
||||
super.printStackTrace(pw);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
/**
|
||||
* Base OFBiz Runtime Exception, provides nested exceptions, etc
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GeneralRuntimeException extends RuntimeException {
|
||||
|
||||
Throwable nested = null;
|
||||
|
||||
/**
|
||||
* Creates new <code>GeneralException</code> without detail message.
|
||||
*/
|
||||
public GeneralRuntimeException() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an <code>GeneralException</code> with the specified detail message.
|
||||
* @param msg the detail message.
|
||||
*/
|
||||
public GeneralRuntimeException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an <code>GeneralException</code> with a nested Exception.
|
||||
* @param nested the nested exception.
|
||||
*/
|
||||
public GeneralRuntimeException(Throwable nested) {
|
||||
super();
|
||||
this.nested = nested;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an <code>GeneralException</code> with the specified detail message and nested Exception.
|
||||
* @param msg the detail message.
|
||||
*/
|
||||
public GeneralRuntimeException(String msg, Throwable nested) {
|
||||
super(msg);
|
||||
this.nested = nested;
|
||||
}
|
||||
|
||||
/** Returns the detail message, including the message from the nested exception if there is one. */
|
||||
@Override
|
||||
public String getMessage() {
|
||||
if (nested != null)
|
||||
return super.getMessage() + " (" + nested.getMessage() + ")";
|
||||
else
|
||||
return super.getMessage();
|
||||
}
|
||||
|
||||
/** Returns the detail message, NOT including the message from the nested exception. */
|
||||
public String getNonNestedMessage() {
|
||||
return super.getMessage();
|
||||
}
|
||||
|
||||
/** Returns the nested exception if there is one, null if there is not. */
|
||||
public Throwable getNested() {
|
||||
return nested;
|
||||
}
|
||||
|
||||
/** Prints the composite message to System.err. */
|
||||
@Override
|
||||
public void printStackTrace() {
|
||||
super.printStackTrace();
|
||||
if (nested != null) nested.printStackTrace();
|
||||
}
|
||||
|
||||
/** Prints the composite message and the embedded stack trace to the specified stream ps. */
|
||||
@Override
|
||||
public void printStackTrace(PrintStream ps) {
|
||||
super.printStackTrace(ps);
|
||||
if (nested != null) nested.printStackTrace(ps);
|
||||
}
|
||||
|
||||
/** Prints the composite message and the embedded stack trace to the specified print writer pw. */
|
||||
@Override
|
||||
public void printStackTrace(PrintWriter pw) {
|
||||
super.printStackTrace(pw);
|
||||
if (nested != null) nested.printStackTrace(pw);
|
||||
}
|
||||
}
|
||||
@@ -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.base.util;
|
||||
|
||||
import groovy.lang.Binding;
|
||||
import groovy.lang.GroovyClassLoader;
|
||||
import groovy.lang.GroovyShell;
|
||||
import groovy.lang.Script;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.script.ScriptContext;
|
||||
|
||||
import org.codehaus.groovy.control.CompilationFailedException;
|
||||
import org.codehaus.groovy.control.CompilerConfiguration;
|
||||
import org.codehaus.groovy.runtime.InvokerHelper;
|
||||
import org.ofbiz.base.location.FlexibleLocation;
|
||||
import org.ofbiz.base.util.cache.UtilCache;
|
||||
|
||||
/**
|
||||
* Groovy Utilities.
|
||||
*
|
||||
*/
|
||||
public class GroovyUtil {
|
||||
|
||||
public static final String module = GroovyUtil.class.getName();
|
||||
|
||||
private static final UtilCache<String, Class<?>> parsedScripts = UtilCache.createUtilCache("script.GroovyLocationParsedCache", 0, 0, false);
|
||||
|
||||
private static final GroovyClassLoader groovyScriptClassLoader;
|
||||
static {
|
||||
GroovyClassLoader groovyClassLoader = null;
|
||||
String scriptBaseClass = UtilProperties.getPropertyValue("groovy", "scriptBaseClass");
|
||||
if (!scriptBaseClass.isEmpty()) {
|
||||
CompilerConfiguration conf = new CompilerConfiguration();
|
||||
conf.setScriptBaseClass(scriptBaseClass);
|
||||
groovyClassLoader = new GroovyClassLoader(GroovyUtil.class.getClassLoader(), conf);
|
||||
}
|
||||
groovyScriptClassLoader = groovyClassLoader;
|
||||
/*
|
||||
* With the implementation of @BaseScript annotations (introduced with Groovy 2.3.0) something was broken
|
||||
* in the CompilerConfiguration.setScriptBaseClass method and an error is thrown when our scripts are executed;
|
||||
* the workaround is to execute at startup a script containing the @BaseScript annotation.
|
||||
*/
|
||||
try {
|
||||
GroovyUtil.runScriptAtLocation("component://base/config/GroovyInit.groovy", null, null);
|
||||
} catch(Exception e) {
|
||||
Debug.logWarning("The following error occurred during the initialization of Groovy: " + e.getMessage(), module);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a Groovy condition or expression
|
||||
* @param expression The expression to evaluate
|
||||
* @param context The context to use in evaluation (re-written)
|
||||
* @see <a href="StringUtil.html#convertOperatorSubstitutions(java.lang.String)">StringUtil.convertOperatorSubstitutions(java.lang.String)</a>
|
||||
* @return Object The result of the evaluation
|
||||
* @throws CompilationFailedException
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Object eval(String expression, Map<String, Object> context) throws CompilationFailedException {
|
||||
Object o;
|
||||
if (expression == null || expression.equals("")) {
|
||||
Debug.logError("Groovy Evaluation error. Empty expression", module);
|
||||
return null;
|
||||
}
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Evaluating -- " + expression, module);
|
||||
Debug.logVerbose("Using Context -- " + context, module);
|
||||
}
|
||||
try {
|
||||
GroovyShell shell = new GroovyShell(getBinding(context, expression));
|
||||
o = shell.evaluate(StringUtil.convertOperatorSubstitutions(expression));
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Evaluated to -- " + o, module);
|
||||
}
|
||||
// read back the context info
|
||||
Binding binding = shell.getContext();
|
||||
context.putAll(binding.getVariables());
|
||||
} catch (CompilationFailedException e) {
|
||||
Debug.logError(e, "Groovy Evaluation error.", module);
|
||||
throw e;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/** Returns a <code>Binding</code> instance initialized with the
|
||||
* variables contained in <code>context</code>. If <code>context</code>
|
||||
* is <code>null</code>, an empty <code>Binding</code> is returned.
|
||||
* <p>The expression is parsed to initiate non existing variable
|
||||
* in <code>Binding</code> to null for GroovyShell evaluation.
|
||||
* <p>The <code>context Map</code> is added to the <code>Binding</code>
|
||||
* as a variable called "context" so that variables can be passed
|
||||
* back to the caller. Any variables that are created in the script
|
||||
* are lost when the script ends unless they are copied to the
|
||||
* "context" <code>Map</code>.</p>
|
||||
*
|
||||
* @param context A <code>Map</code> containing initial variables
|
||||
* @return A <code>Binding</code> instance
|
||||
*/
|
||||
public static Binding getBinding(Map<String, Object> context, String expression) {
|
||||
Map<String, Object> vars = new HashMap<String, Object>();
|
||||
if (context != null) {
|
||||
vars.putAll(context);
|
||||
if (UtilValidate.isNotEmpty(expression)) {
|
||||
//analyse expression to find variables by split non alpha, ignoring "_" to allow my_variable usage
|
||||
String [] variables = expression.split("[\\P{Alpha}&&[^_]]+");
|
||||
for (String variable: variables)
|
||||
if(!vars.containsKey(variable)) vars.put(variable, null);
|
||||
}
|
||||
vars.put("context", context);
|
||||
if (vars.get(ScriptUtil.SCRIPT_HELPER_KEY) == null) {
|
||||
ScriptContext scriptContext = ScriptUtil.createScriptContext(context);
|
||||
ScriptHelper scriptHelper = (ScriptHelper)scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY);
|
||||
if (scriptHelper != null) {
|
||||
vars.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Binding(vars);
|
||||
}
|
||||
|
||||
public static Binding getBinding(Map<String, Object> context) {
|
||||
return getBinding(context, null);
|
||||
}
|
||||
|
||||
public static Class<?> getScriptClassFromLocation(String location) throws GeneralException {
|
||||
try {
|
||||
Class<?> scriptClass = parsedScripts.get(location);
|
||||
if (scriptClass == null) {
|
||||
URL scriptUrl = FlexibleLocation.resolveLocation(location);
|
||||
if (scriptUrl == null) {
|
||||
throw new GeneralException("Script not found at location [" + location + "]");
|
||||
}
|
||||
if (groovyScriptClassLoader != null) {
|
||||
scriptClass = parseClass(scriptUrl.openStream(), location, groovyScriptClassLoader);
|
||||
} else {
|
||||
scriptClass = parseClass(scriptUrl.openStream(), location);
|
||||
}
|
||||
Class<?> scriptClassCached = parsedScripts.putIfAbsent(location, scriptClass);
|
||||
if (scriptClassCached == null) { // putIfAbsent returns null if the class is added to the cache
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Cached Groovy script at: " + location, module);
|
||||
}
|
||||
} else {
|
||||
// the newly parsed script is discarded and the one found in the cache (that has been created by a concurrent thread in the meantime) is used
|
||||
scriptClass = scriptClassCached;
|
||||
}
|
||||
}
|
||||
return scriptClass;
|
||||
} catch (Exception e) {
|
||||
throw new GeneralException("Error loading Groovy script at [" + location + "]: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Class<?> loadClass(String path) throws ClassNotFoundException {
|
||||
return new GroovyClassLoader().loadClass(path);
|
||||
}
|
||||
|
||||
public static Class<?> parseClass(InputStream in, String location) throws IOException {
|
||||
return new GroovyClassLoader().parseClass(UtilIO.readString(in), location);
|
||||
}
|
||||
public static Class<?> parseClass(InputStream in, String location, GroovyClassLoader groovyClassLoader) throws IOException {
|
||||
return groovyClassLoader.parseClass(UtilIO.readString(in), location);
|
||||
}
|
||||
|
||||
public static Class<?> parseClass(String text) {
|
||||
return new GroovyClassLoader().parseClass(text);
|
||||
}
|
||||
|
||||
public static Object runScriptAtLocation(String location, String methodName, Map<String, Object> context) throws GeneralException {
|
||||
Script script = InvokerHelper.createScript(getScriptClassFromLocation(location), getBinding(context));
|
||||
Object result = null;
|
||||
if (UtilValidate.isEmpty(methodName)) {
|
||||
result = script.run();
|
||||
} else {
|
||||
result = script.invokeMethod(methodName, new Object[] { context });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private GroovyUtil() {}
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Send HTTP GET/POST requests.
|
||||
* The main problem with current implementation is that it does not handle connections release. You must rely on the SO to release them (timeout).
|
||||
*
|
||||
*/
|
||||
public class HttpClient {
|
||||
|
||||
public static final String module = HttpClient.class.getName();
|
||||
|
||||
private int hostVerification = SSLUtil.getHostCertNormalCheck();
|
||||
private int timeout = 30000;
|
||||
private boolean debug = false;
|
||||
private boolean lineFeed = true;
|
||||
private boolean trustAny = false;
|
||||
private boolean followRedirects = true;
|
||||
private boolean keepAlive = false;
|
||||
|
||||
private String contentType = null;
|
||||
private String streamCharset = null;
|
||||
private String url = null;
|
||||
private String rawStream = null;
|
||||
private String clientCertAlias = null;
|
||||
private String basicAuthUsername = null;
|
||||
private String basicAuthPassword = null;
|
||||
|
||||
private Map<String, Object> parameters = null;
|
||||
private Map<String, String> headers = null;
|
||||
|
||||
private URL requestUrl = null;
|
||||
private URLConnection con = null;
|
||||
|
||||
/** Creates an empty HttpClient object. */
|
||||
public HttpClient() {}
|
||||
|
||||
/** Creates a new HttpClient object. */
|
||||
public HttpClient(URL url) {
|
||||
this.url = url.toExternalForm();
|
||||
}
|
||||
|
||||
/** Creates a new HttpClient object. */
|
||||
public HttpClient(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
/** Creates a new HttpClient object. */
|
||||
public HttpClient(String url, Map<String, Object> parameters) {
|
||||
this.url = url;
|
||||
this.parameters = parameters;
|
||||
}
|
||||
|
||||
/** Creates a new HttpClient object. */
|
||||
public HttpClient(URL url, Map<String, Object> parameters) {
|
||||
this.url = url.toExternalForm();
|
||||
this.parameters = parameters;
|
||||
}
|
||||
|
||||
/** Creates a new HttpClient object. */
|
||||
public HttpClient(String url, Map<String, Object> parameters, Map<String, String> headers) {
|
||||
this.url = url;
|
||||
this.parameters = parameters;
|
||||
this.headers = headers;
|
||||
}
|
||||
|
||||
/** Creates a new HttpClient object. */
|
||||
public HttpClient(URL url, Map<String, Object> parameters, Map<String, String> headers) {
|
||||
this.url = url.toExternalForm();
|
||||
this.parameters = parameters;
|
||||
this.headers = headers;
|
||||
}
|
||||
|
||||
/** When true overrides Debug.verboseOn() and forces debugging for this instance */
|
||||
public void setDebug(boolean debug) {
|
||||
this.debug = debug;
|
||||
}
|
||||
|
||||
/** Sets the timeout for waiting for the connection (default 30sec) */
|
||||
public void setTimeout(int timeout) {
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
/** Enables this request to follow redirect 3xx codes (default true) */
|
||||
public void followRedirects(boolean followRedirects) {
|
||||
this.followRedirects = followRedirects;
|
||||
}
|
||||
|
||||
/** Turns on or off line feeds in the request. (default is on) */
|
||||
public void setLineFeed(boolean lineFeed) {
|
||||
this.lineFeed = lineFeed;
|
||||
}
|
||||
|
||||
/** Set the raw stream for posts. */
|
||||
public void setRawStream(String stream) {
|
||||
this.rawStream = stream;
|
||||
}
|
||||
|
||||
/** Set the URL for this request. */
|
||||
public void setUrl(URL url) {
|
||||
this.url = url.toExternalForm();
|
||||
}
|
||||
|
||||
/** Set the URL for this request. */
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
/** Set the parameters for this request. */
|
||||
public void setParameters(Map<String, Object> parameters) {
|
||||
this.parameters = parameters;
|
||||
}
|
||||
|
||||
/** Set an individual parameter for this request. */
|
||||
public void setParameter(String name, String value) {
|
||||
if (parameters == null)
|
||||
parameters = new HashMap<String, Object>();
|
||||
parameters.put(name, value);
|
||||
}
|
||||
|
||||
/** Set the headers for this request. */
|
||||
public void setHeaders(Map<String, String> headers) {
|
||||
this.headers = headers;
|
||||
}
|
||||
|
||||
/** Set an individual header for this request. */
|
||||
public void setHeader(String name, String value) {
|
||||
if (headers == null)
|
||||
headers = new HashMap<String, String>();
|
||||
headers.put(name, value);
|
||||
}
|
||||
|
||||
/** Return a Map of headers. */
|
||||
public Map<String, String> getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
|
||||
/** Return a Map of parameters. */
|
||||
public Map<String, Object> getParameters() {
|
||||
return parameters;
|
||||
}
|
||||
|
||||
/** Return a string representing the requested URL. */
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
/** Sets the content-type */
|
||||
public void setContentType(String contentType) {
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
/** Returns the content type */
|
||||
public String getContentType() {
|
||||
return this.contentType;
|
||||
}
|
||||
|
||||
/** Sets the scream charset */
|
||||
public void setStreamCharset(String streamCharset) {
|
||||
this.streamCharset = streamCharset;
|
||||
}
|
||||
|
||||
/** Returns the stream charset */
|
||||
public String getStreamCharset() {
|
||||
return this.streamCharset;
|
||||
}
|
||||
|
||||
/** Toggle keep-alive setting */
|
||||
public void setKeepAlive(boolean keepAlive) {
|
||||
this.keepAlive = keepAlive;
|
||||
}
|
||||
|
||||
/** Return keep-alive setting */
|
||||
public boolean getKeepAlive() {
|
||||
return this.keepAlive;
|
||||
}
|
||||
|
||||
/** Sets the client certificate alias (from the keystore) to use for this SSL connection. */
|
||||
public void setClientCertificateAlias(String alias) {
|
||||
this.clientCertAlias = alias;
|
||||
}
|
||||
|
||||
/** Returns the alias of the client certificate to be used for this SSL connection. */
|
||||
public String getClientCertificateAlias() {
|
||||
return this.clientCertAlias;
|
||||
}
|
||||
|
||||
/** Sets the server hostname verification level */
|
||||
public void setHostVerificationLevel(int level) {
|
||||
this.hostVerification = level;
|
||||
}
|
||||
|
||||
/** Returns the current server hostname verification level */
|
||||
public int getHostVerificationLevel() {
|
||||
return this.hostVerification;
|
||||
}
|
||||
|
||||
/** Allow untrusted server certificates */
|
||||
public void setAllowUntrusted(boolean trustAny) {
|
||||
this.trustAny = trustAny;
|
||||
}
|
||||
|
||||
/** Do we trust any certificate */
|
||||
public boolean getAllowUntrusted() {
|
||||
return this.trustAny;
|
||||
}
|
||||
|
||||
public void setBasicAuthInfo(String basicAuthUsername, String basicAuthPassword) {
|
||||
this.basicAuthUsername = basicAuthUsername;
|
||||
this.basicAuthPassword = basicAuthPassword;
|
||||
}
|
||||
|
||||
/** Invoke HTTP request GET. */
|
||||
public String get() throws HttpClientException {
|
||||
return sendHttpRequest("get");
|
||||
}
|
||||
|
||||
/** Invoke HTTP request GET. */
|
||||
public InputStream getStream() throws HttpClientException {
|
||||
return sendHttpRequestStream("get");
|
||||
}
|
||||
|
||||
/** Invoke HTTP request POST. */
|
||||
public String post() throws HttpClientException {
|
||||
return sendHttpRequest("post");
|
||||
}
|
||||
|
||||
/** Invoke HTTP request POST and pass raw stream. */
|
||||
public String post(String stream) throws HttpClientException {
|
||||
this.rawStream = stream;
|
||||
return sendHttpRequest("post");
|
||||
}
|
||||
|
||||
/** Invoke HTTP request POST. */
|
||||
public InputStream postStream() throws HttpClientException {
|
||||
return sendHttpRequestStream("post");
|
||||
}
|
||||
|
||||
/** Returns the value of the specified named response header field. */
|
||||
public String getResponseHeader(String header) throws HttpClientException {
|
||||
if (con == null) {
|
||||
throw new HttpClientException("Connection not yet established");
|
||||
}
|
||||
return con.getHeaderField(header);
|
||||
}
|
||||
|
||||
/** Returns the key for the nth response header field. */
|
||||
public String getResponseHeaderFieldKey(int n) throws HttpClientException {
|
||||
if (con == null) {
|
||||
throw new HttpClientException("Connection not yet established");
|
||||
}
|
||||
return con.getHeaderFieldKey(n);
|
||||
}
|
||||
|
||||
/** Returns the value for the nth response header field. It returns null of there are fewer then n fields. */
|
||||
public String getResponseHeaderField(int n) throws HttpClientException {
|
||||
if (con == null) {
|
||||
throw new HttpClientException("Connection not yet established");
|
||||
}
|
||||
return con.getHeaderField(n);
|
||||
}
|
||||
|
||||
/** Returns the content of the response. */
|
||||
public Object getResponseContent() throws java.io.IOException, HttpClientException {
|
||||
if (con == null) {
|
||||
throw new HttpClientException("Connection not yet established");
|
||||
}
|
||||
return con.getContent();
|
||||
}
|
||||
|
||||
/** Returns the content-type of the response. */
|
||||
public String getResponseContentType() throws HttpClientException {
|
||||
if (con == null) {
|
||||
throw new HttpClientException("Connection not yet established");
|
||||
}
|
||||
return con.getContentType();
|
||||
}
|
||||
|
||||
/** Returns the content length of the response */
|
||||
public int getResponseContentLength() throws HttpClientException {
|
||||
if (con == null) {
|
||||
throw new HttpClientException("Connection not yet established");
|
||||
}
|
||||
return con.getContentLength();
|
||||
}
|
||||
|
||||
/** Returns the content encoding of the response. */
|
||||
public String getResponseContentEncoding() throws HttpClientException {
|
||||
if (con == null) {
|
||||
throw new HttpClientException("Connection not yet established");
|
||||
}
|
||||
return con.getContentEncoding();
|
||||
}
|
||||
|
||||
public int getResponseCode() throws HttpClientException {
|
||||
if (con == null) {
|
||||
throw new HttpClientException("Connection not yet established");
|
||||
}
|
||||
if (!(con instanceof HttpURLConnection)) {
|
||||
throw new HttpClientException("Connection is not HTTP; no response code");
|
||||
}
|
||||
|
||||
try {
|
||||
return ((HttpURLConnection) con).getResponseCode();
|
||||
} catch (IOException e) {
|
||||
throw new HttpClientException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public String sendHttpRequest(String method) throws HttpClientException {
|
||||
InputStream in = sendHttpRequestStream(method);
|
||||
if (in == null) return null;
|
||||
|
||||
StringBuilder buf = new StringBuilder();
|
||||
try {
|
||||
if (Debug.verboseOn() || debug) {
|
||||
try {
|
||||
Debug.logInfo("ContentEncoding: " + con.getContentEncoding() + "; ContentType: " +
|
||||
con.getContentType() + " or: " + URLConnection.guessContentTypeFromStream(in), module);
|
||||
} catch (IOException ioe) {
|
||||
Debug.logWarning(ioe, "Caught exception printing content debugging information", module);
|
||||
}
|
||||
}
|
||||
|
||||
String charset = null;
|
||||
String contentType = con.getContentType();
|
||||
if (contentType == null) {
|
||||
try {
|
||||
contentType = URLConnection.guessContentTypeFromStream(in);
|
||||
} catch (IOException ioe) {
|
||||
Debug.logWarning(ioe, "Problems guessing content type from steam", module);
|
||||
}
|
||||
}
|
||||
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("Content-Type: " + contentType, module);
|
||||
|
||||
if (contentType != null) {
|
||||
contentType = contentType.toUpperCase();
|
||||
int charsetEqualsLoc = contentType.indexOf("=", contentType.indexOf("CHARSET"));
|
||||
int afterSemiColon = contentType.indexOf(";", charsetEqualsLoc);
|
||||
if (charsetEqualsLoc >= 0 && afterSemiColon >= 0) {
|
||||
charset = contentType.substring(charsetEqualsLoc + 1, afterSemiColon);
|
||||
} else if (charsetEqualsLoc >= 0) {
|
||||
charset = contentType.substring(charsetEqualsLoc + 1);
|
||||
}
|
||||
|
||||
if (charset != null) charset = charset.trim().replaceAll("\"", "");
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("Getting text from HttpClient with charset: " + charset, module);
|
||||
}
|
||||
|
||||
BufferedReader post = new BufferedReader(charset == null ? new InputStreamReader(in) : new InputStreamReader(in, charset));
|
||||
String line = "";
|
||||
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("---- HttpClient Response Content ----", module);
|
||||
while ((line = post.readLine()) != null) {
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("[HttpClient] : " + line, module);
|
||||
buf.append(line);
|
||||
if (lineFeed) {
|
||||
buf.append("\n");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new HttpClientException("Error processing input stream", e);
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
private InputStream sendHttpRequestStream(String method) throws HttpClientException {
|
||||
return sendHttpRequestStream(method, false);
|
||||
}
|
||||
|
||||
private InputStream sendHttpRequestStream(String method, boolean overrideTrust) throws HttpClientException {
|
||||
// setup some SSL variables
|
||||
SSLUtil.loadJsseProperties(this.debug);
|
||||
|
||||
String arguments = null;
|
||||
InputStream in = null;
|
||||
|
||||
if (url == null) {
|
||||
throw new HttpClientException("Cannot process a null URL.");
|
||||
}
|
||||
|
||||
if (rawStream != null) {
|
||||
arguments = rawStream;
|
||||
} else if (UtilValidate.isNotEmpty(parameters)) {
|
||||
arguments = UtilHttp.urlEncodeArgs(parameters, false);
|
||||
}
|
||||
|
||||
// Append the arguments to the query string if GET.
|
||||
if (method.equalsIgnoreCase("get") && arguments != null) {
|
||||
if (url.contains("?")) {
|
||||
url = url + "&" + arguments;
|
||||
} else {
|
||||
url = url + "?" + arguments;
|
||||
}
|
||||
}
|
||||
|
||||
// Create the URL and open the connection.
|
||||
try {
|
||||
requestUrl = new URL(url);
|
||||
if (overrideTrust) {
|
||||
con = URLConnector.openUntrustedConnection(requestUrl, timeout, clientCertAlias, hostVerification);
|
||||
} else {
|
||||
con = URLConnector.openConnection(requestUrl, timeout, clientCertAlias, hostVerification);
|
||||
}
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("Connection opened to : " + requestUrl.toExternalForm(), module);
|
||||
|
||||
if ((con instanceof HttpURLConnection)) {
|
||||
((HttpURLConnection) con).setInstanceFollowRedirects(followRedirects);
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("Connection is of type HttpURLConnection, more specifically: " + con.getClass().getName(), module);
|
||||
}
|
||||
|
||||
// set the content type
|
||||
if (contentType != null) {
|
||||
con.setRequestProperty("Content-type", contentType);
|
||||
}
|
||||
|
||||
// connection settings
|
||||
con.setDoOutput(true);
|
||||
con.setUseCaches(false);
|
||||
if (keepAlive) {
|
||||
con.setRequestProperty("Connection", "Keep-Alive");
|
||||
}
|
||||
|
||||
if (method.equalsIgnoreCase("post")) {
|
||||
if (contentType == null) {
|
||||
con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
|
||||
}
|
||||
con.setDoInput(true);
|
||||
}
|
||||
|
||||
// if there is basicAuth info set the request property for it
|
||||
if (basicAuthUsername != null) {
|
||||
String basicAuthString = "Basic " + Base64.base64Encode(basicAuthUsername + ":" + (basicAuthPassword == null ? "" : basicAuthPassword));
|
||||
con.setRequestProperty("Authorization", basicAuthString);
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("Header - Authorization: " + basicAuthString, module);
|
||||
}
|
||||
|
||||
if (UtilValidate.isNotEmpty(headers)) {
|
||||
for (Map.Entry<String, String> entry: headers.entrySet()) {
|
||||
String headerName = entry.getKey();
|
||||
String headerValue = entry.getValue();
|
||||
con.setRequestProperty(headerName, headerValue);
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("Header - " + headerName + ": " + headerValue, module);
|
||||
}
|
||||
}
|
||||
|
||||
if (method.equalsIgnoreCase("post")) {
|
||||
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), this.streamCharset != null ? this.streamCharset : "UTF-8");
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("Opened output stream", module);
|
||||
|
||||
if (arguments != null) {
|
||||
out.write(arguments);
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("Wrote arguements (parameters) : " + arguments, module);
|
||||
}
|
||||
|
||||
out.flush();
|
||||
out.close();
|
||||
if (Debug.verboseOn() || debug) Debug.logVerbose("Flushed and closed buffer", module);
|
||||
}
|
||||
|
||||
if (Debug.verboseOn() || debug) {
|
||||
Map<String, List<String>> headerFields = con.getHeaderFields();
|
||||
Debug.logInfo("Header Fields : " + headerFields, module);
|
||||
}
|
||||
|
||||
in = con.getInputStream();
|
||||
} catch (IOException ioe) {
|
||||
if ((trustAny && !overrideTrust) && (ioe.getCause() instanceof CertificateException)) {
|
||||
Debug.logWarning(ioe.getCause(), module);
|
||||
return sendHttpRequestStream(method, true);
|
||||
}
|
||||
throw new HttpClientException("IO Error processing request", ioe);
|
||||
} catch (Exception e) {
|
||||
throw new HttpClientException("Error processing request", e);
|
||||
}
|
||||
|
||||
return in;
|
||||
}
|
||||
|
||||
|
||||
public static String getUrlContent(String url) throws HttpClientException {
|
||||
HttpClient client = new HttpClient(url);
|
||||
return client.get();
|
||||
}
|
||||
|
||||
public static int checkHttpRequest(String url) throws HttpClientException {
|
||||
HttpClient client = new HttpClient(url);
|
||||
client.get();
|
||||
return client.getResponseCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
/**
|
||||
* HttpClient Exception.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class HttpClientException extends GeneralException {
|
||||
|
||||
Throwable nested = null;
|
||||
|
||||
public HttpClientException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public HttpClientException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public HttpClientException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* HttpRequestFileUpload - Receive a file upload through an HttpServletRequest
|
||||
*
|
||||
*/
|
||||
public class HttpRequestFileUpload {
|
||||
|
||||
private int BUFFER_SIZE = 4096;
|
||||
private int WAIT_INTERVAL = 200; // in milliseconds
|
||||
private int MAX_WAITS = 20;
|
||||
private int waitCount = 0;
|
||||
private String savePath;
|
||||
private String filepath;
|
||||
private String filename;
|
||||
private String contentType;
|
||||
private String overrideFilename = null;
|
||||
private Map<String, String> fields;
|
||||
|
||||
public String getOverrideFilename() {
|
||||
return overrideFilename;
|
||||
}
|
||||
|
||||
public void setOverrideFilename(String ofName) {
|
||||
overrideFilename = ofName;
|
||||
}
|
||||
|
||||
public String getFilename() {
|
||||
return filename;
|
||||
}
|
||||
|
||||
public String getFilepath() {
|
||||
return filepath;
|
||||
}
|
||||
|
||||
public void setSavePath(String savePath) {
|
||||
this.savePath = savePath;
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
public String getFieldValue(String fieldName) {
|
||||
if (fields == null || fieldName == null)
|
||||
return null;
|
||||
return fields.get(fieldName);
|
||||
}
|
||||
|
||||
private void setFilename(String s) {
|
||||
if (s == null)
|
||||
return;
|
||||
|
||||
int pos = s.indexOf("filename=\"");
|
||||
|
||||
if (pos != -1) {
|
||||
filepath = s.substring(pos + 10, s.length() - 1);
|
||||
// Windows browsers include the full path on the client
|
||||
// But Linux/Unix and Mac browsers only send the filename
|
||||
// test if this is from a Windows browser
|
||||
pos = filepath.lastIndexOf("\\");
|
||||
if (pos != -1)
|
||||
filename = filepath.substring(pos + 1);
|
||||
else
|
||||
filename = filepath;
|
||||
}
|
||||
}
|
||||
|
||||
private void setContentType(String s) {
|
||||
if (s == null)
|
||||
return;
|
||||
|
||||
int pos = s.indexOf(": ");
|
||||
|
||||
if (pos != -1)
|
||||
contentType = s.substring(pos + 2, s.length());
|
||||
}
|
||||
|
||||
public void doUpload(HttpServletRequest request) throws IOException {
|
||||
ServletInputStream in = request.getInputStream();
|
||||
|
||||
/* System.out.println("Header:");
|
||||
Enumeration ee = request.getHeaderNames();
|
||||
while (ee.hasMoreElements()) {
|
||||
String ss = (String)ee.nextElement();
|
||||
System.out.println(ss + " = [" + request.getHeader(ss) + "]");
|
||||
}*/
|
||||
String reqLengthString = request.getHeader("content-length");
|
||||
|
||||
System.out.println("expect " + reqLengthString + " bytes.");
|
||||
int requestLength = 0;
|
||||
|
||||
try {
|
||||
requestLength = Integer.valueOf(reqLengthString).intValue();
|
||||
} catch (Exception e2) {
|
||||
e2.printStackTrace();
|
||||
return;
|
||||
}
|
||||
byte[] line = new byte[BUFFER_SIZE];
|
||||
|
||||
int i = -1;
|
||||
|
||||
i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength);
|
||||
requestLength -= i;
|
||||
if (i < 3)
|
||||
return;
|
||||
int boundaryLength = i - 2;
|
||||
|
||||
String boundary = new String(line, 0, boundaryLength); // -2 discards the newline character
|
||||
|
||||
System.out.println("boundary=[" + boundary + "] length is " + boundaryLength);
|
||||
fields = new HashMap<String, String>();
|
||||
|
||||
while (requestLength > 0/* i != -1*/) {
|
||||
String newLine = "";
|
||||
|
||||
if (i > -1) {
|
||||
newLine = new String(line, 0, i);
|
||||
}
|
||||
if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
|
||||
if (newLine.indexOf("filename=\"") != -1) {
|
||||
setFilename(new String(line, 0, i - 2));
|
||||
if (filename == null)
|
||||
return;
|
||||
// this is the file content
|
||||
i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength);
|
||||
requestLength -= i;
|
||||
|
||||
setContentType(new String(line, 0, i - 2));
|
||||
|
||||
// blank line
|
||||
i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength);
|
||||
requestLength -= i;
|
||||
newLine = new String(line, 0, i);
|
||||
String filenameToUse = filename;
|
||||
|
||||
if (overrideFilename != null) {
|
||||
filenameToUse = overrideFilename;
|
||||
}
|
||||
|
||||
// first line of actual file
|
||||
i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength);
|
||||
requestLength -= i;
|
||||
newLine = new String(line, 0, i);
|
||||
|
||||
byte[] lastTwoBytes = new byte[2];
|
||||
|
||||
if (i > 1) {
|
||||
lastTwoBytes[0] = line[i - 2];
|
||||
lastTwoBytes[1] = line[i - 1];
|
||||
}
|
||||
System.out.println("about to create a file:" + (savePath == null ? "" : savePath) + filenameToUse);
|
||||
// before creating the file make sure directory exists
|
||||
File savePathFile = new File(savePath);
|
||||
if (!savePathFile.exists()) {
|
||||
savePathFile.mkdirs();
|
||||
}
|
||||
FileOutputStream fos = new FileOutputStream((savePath == null ? "" : savePath) + filenameToUse);
|
||||
boolean bail = (new String(line, 0, i).startsWith(boundary));
|
||||
boolean oneByteLine = (i == 1); // handle one-byte lines
|
||||
|
||||
while ((requestLength > 0/* i != -1*/) && !bail) {
|
||||
|
||||
// write the current buffer, except the last 2 bytes;
|
||||
if (i > 1) {
|
||||
fos.write(line, 0, i - 2);
|
||||
}
|
||||
|
||||
oneByteLine = (i == 1); // we need to track on-byte lines differently
|
||||
|
||||
i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength);
|
||||
requestLength -= i;
|
||||
|
||||
// the problem is the last line of the file content
|
||||
// contains the new line character.
|
||||
|
||||
// if the line just read was the last line, we're done.
|
||||
// if not, we must write the last 2 bytes of the previous buffer
|
||||
// just assume that a one-byte line isn't the last line
|
||||
|
||||
if (requestLength < 1) {
|
||||
bail = true;
|
||||
} else if (oneByteLine) {
|
||||
fos.write(lastTwoBytes, 0, 1); // we only saved one byte
|
||||
} else {
|
||||
fos.write(lastTwoBytes, 0, 2);
|
||||
}
|
||||
|
||||
if (i > 1) {
|
||||
// save the last 2 bytes of the buffer
|
||||
lastTwoBytes[0] = line[i - 2];
|
||||
lastTwoBytes[1] = line[i - 1];
|
||||
} else {
|
||||
lastTwoBytes[0] = line[0]; // only save one byte
|
||||
}
|
||||
}
|
||||
fos.flush();
|
||||
fos.close();
|
||||
} else {
|
||||
// this is a field
|
||||
// get the field name
|
||||
int pos = newLine.indexOf("name=\"");
|
||||
String fieldName = newLine.substring(pos + 6, newLine.length() - 3);
|
||||
|
||||
// System.out.println("fieldName:" + fieldName);
|
||||
// blank line
|
||||
i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength);
|
||||
requestLength -= i;
|
||||
i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength);
|
||||
requestLength -= i;
|
||||
newLine = new String(line, 0, i);
|
||||
StringBuilder fieldValue = new StringBuilder(BUFFER_SIZE);
|
||||
|
||||
while (requestLength > 0/* i != -1*/ && !newLine.startsWith(boundary)) {
|
||||
// The last line of the field
|
||||
// contains the new line character.
|
||||
// So, we need to check if the current line is
|
||||
// the last line.
|
||||
i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength);
|
||||
requestLength -= i;
|
||||
if ((i == boundaryLength + 2 || i == boundaryLength + 4) // + 4 is eof
|
||||
&& (new String(line, 0, i).startsWith(boundary)))
|
||||
fieldValue.append(newLine.substring(0, newLine.length() - 2));
|
||||
else
|
||||
fieldValue.append(newLine);
|
||||
newLine = new String(line, 0, i);
|
||||
}
|
||||
// System.out.println("fieldValue:" + fieldValue.toString());
|
||||
fields.put(fieldName, fieldValue.toString());
|
||||
}
|
||||
}
|
||||
i = waitingReadLine(in, line, 0, BUFFER_SIZE, requestLength);
|
||||
if (i > -1) {
|
||||
requestLength -= i;
|
||||
}
|
||||
|
||||
} // end while
|
||||
}
|
||||
|
||||
// reads a line, waiting if there is nothing available and reqLen > 0
|
||||
private int waitingReadLine(ServletInputStream in, byte[] buf, int off, int len, int reqLen) throws IOException {
|
||||
int i = -1;
|
||||
|
||||
while (((i = in.readLine(buf, off, len)) == -1) && (reqLen > 0)) {
|
||||
System.out.print("waiting");
|
||||
if (waitCount > MAX_WAITS) {
|
||||
System.out.println("waited " + waitCount + " times, bailing out while still expecting " +
|
||||
reqLen + " bytes.");
|
||||
throw new IOException("waited " + waitCount + " times, bailing out while still expecting " +
|
||||
reqLen + " bytes.");
|
||||
}
|
||||
waitCount++;
|
||||
long endMS = new Date().getTime() + WAIT_INTERVAL;
|
||||
|
||||
while (endMS > (new Date().getTime())) {
|
||||
try {
|
||||
wait(WAIT_INTERVAL);
|
||||
} catch (Exception e3) {
|
||||
System.out.print(".");
|
||||
}
|
||||
}
|
||||
System.out.println((new Date().getTime() - endMS) + " ms");
|
||||
}
|
||||
return i;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.FilterWriter;
|
||||
import java.io.Writer;
|
||||
|
||||
import org.ofbiz.base.lang.SourceMonitored;
|
||||
|
||||
@SourceMonitored
|
||||
public class IndentingWriter extends FilterWriter {
|
||||
protected final StringBuilder indent = new StringBuilder();
|
||||
protected final boolean doSpace;
|
||||
protected final boolean doNewline;
|
||||
protected boolean lastWasNewline;
|
||||
|
||||
public static IndentingWriter makeIndentingWriter(Writer writer) {
|
||||
return writer instanceof IndentingWriter ? (IndentingWriter) writer : new IndentingWriter(writer);
|
||||
}
|
||||
|
||||
public IndentingWriter(Writer out, boolean doSpace, boolean doNewline) {
|
||||
super(out);
|
||||
this.doSpace = doSpace;
|
||||
this.doNewline = doNewline;
|
||||
}
|
||||
|
||||
public IndentingWriter(Writer out) {
|
||||
this(out, true, true);
|
||||
}
|
||||
|
||||
public IndentingWriter newline() throws IOException {
|
||||
lastWasNewline = true;
|
||||
if (doNewline) super.write('\n');
|
||||
return this;
|
||||
}
|
||||
|
||||
protected void checkAfterNewline() throws IOException {
|
||||
if (lastWasNewline) {
|
||||
if (doSpace) {
|
||||
if (doNewline) {
|
||||
super.write(indent.toString(), 0, indent.length());
|
||||
} else {
|
||||
super.write(' ');
|
||||
}
|
||||
}
|
||||
lastWasNewline = false;
|
||||
}
|
||||
}
|
||||
|
||||
public IndentingWriter push() {
|
||||
indent.append(' ');
|
||||
return this;
|
||||
}
|
||||
|
||||
public IndentingWriter pop() {
|
||||
indent.setLength(indent.length() - 1);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IndentingWriter space() throws IOException {
|
||||
checkAfterNewline();
|
||||
if (doSpace) super.write(' ');
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(char[] buf) throws IOException {
|
||||
write(buf, 0, buf.length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(char[] buf, int offset, int length) throws IOException {
|
||||
int i;
|
||||
for (i = offset; i < length; i++) {
|
||||
if (buf[i] == '\n') {
|
||||
checkAfterNewline();
|
||||
super.write(buf, offset, i - offset + 1);
|
||||
offset = i + 1;
|
||||
lastWasNewline = true;
|
||||
}
|
||||
}
|
||||
checkAfterNewline();
|
||||
super.write(buf, offset, i - offset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int c) throws IOException {
|
||||
checkAfterNewline();
|
||||
super.write(c);
|
||||
if (c == '\n') {
|
||||
lastWasNewline = true;
|
||||
checkAfterNewline();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(String s) throws IOException {
|
||||
write(s, 0, s.length());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(String s, int offset, int length) throws IOException {
|
||||
int i;
|
||||
for (i = offset; i < length; i++) {
|
||||
if (s.charAt(i) == '\n') {
|
||||
checkAfterNewline();
|
||||
super.write(s, offset, i - offset + 1);
|
||||
offset = i + 1;
|
||||
lastWasNewline = true;
|
||||
}
|
||||
}
|
||||
checkAfterNewline();
|
||||
super.write(s, offset, i - offset);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.util.Hashtable;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
|
||||
import org.ofbiz.base.config.GenericConfigException;
|
||||
import org.ofbiz.base.config.JNDIConfigUtil;
|
||||
import org.ofbiz.base.util.cache.UtilCache;
|
||||
|
||||
/**
|
||||
* JNDIContextFactory - central source for JNDI Contexts by helper name
|
||||
*
|
||||
*/
|
||||
public class JNDIContextFactory {
|
||||
|
||||
public static final String module = JNDIContextFactory.class.getName();
|
||||
// FIXME: InitialContext instances are not thread-safe! They should not be cached.
|
||||
private static final UtilCache<String, InitialContext> contexts = UtilCache.createUtilCache("entity.JNDIContexts", 0, 0);
|
||||
|
||||
/**
|
||||
* Return the initial context according to the entityengine.xml parameters that correspond to the given prefix
|
||||
* @return the JNDI initial context
|
||||
*/
|
||||
public static InitialContext getInitialContext(String jndiServerName) throws GenericConfigException {
|
||||
InitialContext ic = contexts.get(jndiServerName);
|
||||
|
||||
if (ic == null) {
|
||||
JNDIConfigUtil.JndiServerInfo jndiServerInfo = JNDIConfigUtil.getJndiServerInfo(jndiServerName);
|
||||
|
||||
if (jndiServerInfo == null) {
|
||||
throw new GenericConfigException("ERROR: no jndi-server definition was found with the name " + jndiServerName + " in jndiservers.xml");
|
||||
}
|
||||
|
||||
try {
|
||||
if (UtilValidate.isEmpty(jndiServerInfo.contextProviderUrl)) {
|
||||
ic = new InitialContext();
|
||||
} else {
|
||||
Hashtable<String, Object> h = new Hashtable<String, Object>();
|
||||
|
||||
h.put(Context.INITIAL_CONTEXT_FACTORY, jndiServerInfo.initialContextFactory);
|
||||
h.put(Context.PROVIDER_URL, jndiServerInfo.contextProviderUrl);
|
||||
if (UtilValidate.isNotEmpty(jndiServerInfo.urlPkgPrefixes))
|
||||
h.put(Context.URL_PKG_PREFIXES, jndiServerInfo.urlPkgPrefixes);
|
||||
|
||||
if (UtilValidate.isNotEmpty(jndiServerInfo.securityPrincipal))
|
||||
h.put(Context.SECURITY_PRINCIPAL, jndiServerInfo.securityPrincipal);
|
||||
if (UtilValidate.isNotEmpty(jndiServerInfo.securityCredentials))
|
||||
h.put(Context.SECURITY_CREDENTIALS, jndiServerInfo.securityCredentials);
|
||||
|
||||
ic = new InitialContext(h);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
String errorMsg = "Error getting JNDI initial context for server name " + jndiServerName;
|
||||
|
||||
Debug.logError(e, errorMsg, module);
|
||||
throw new GenericConfigException(errorMsg, e);
|
||||
}
|
||||
|
||||
if (ic != null) {
|
||||
ic = contexts.putIfAbsentAndGet(jndiServerName, ic);
|
||||
}
|
||||
}
|
||||
|
||||
return ic;
|
||||
}
|
||||
/**
|
||||
* Removes an entry from the JNDI cache.
|
||||
* @param jndiServerName
|
||||
*/
|
||||
public static void clearInitialContext(String jndiServerName) {
|
||||
contexts.remove(jndiServerName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintStream;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.net.URL;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.Principal;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateEncodingException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.ofbiz.base.component.ComponentConfig;
|
||||
import org.ofbiz.base.config.GenericConfigException;
|
||||
|
||||
/**
|
||||
* KeyStoreUtil - Utilities for getting KeyManagers and TrustManagers
|
||||
*
|
||||
*/
|
||||
public final class KeyStoreUtil {
|
||||
|
||||
public static final String module = KeyStoreUtil.class.getName();
|
||||
|
||||
private KeyStoreUtil () {}
|
||||
|
||||
public static void storeComponentKeyStore(String componentName, String keyStoreName, KeyStore store) throws IOException, GenericConfigException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
|
||||
ComponentConfig.KeystoreInfo ks = ComponentConfig.getKeystoreInfo(componentName, keyStoreName);
|
||||
File file = FileUtil.getFile(ks.createResourceHandler().getFullLocation());
|
||||
FileOutputStream out = new FileOutputStream(file);
|
||||
try {
|
||||
store.store(out, ks.getPassword().toCharArray());
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static KeyStore getComponentKeyStore(String componentName, String keyStoreName) throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
ComponentConfig.KeystoreInfo ks = ComponentConfig.getKeystoreInfo(componentName, keyStoreName);
|
||||
return getStore(ks.createResourceHandler().getURL(), ks.getPassword(), ks.getType());
|
||||
}
|
||||
|
||||
public static KeyStore getStore(URL url, String password) throws IOException, GeneralSecurityException {
|
||||
return getStore(url, password, "jks");
|
||||
}
|
||||
|
||||
public static KeyStore getStore(URL url, String password, String type) throws IOException, GeneralSecurityException {
|
||||
if (type == null) {
|
||||
throw new IOException("Invalid keystore type; null");
|
||||
}
|
||||
KeyStore ks = KeyStore.getInstance(type);
|
||||
InputStream in = url.openStream();
|
||||
try {
|
||||
ks.load(in, password.toCharArray());
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
return ks;
|
||||
}
|
||||
|
||||
public static KeyStore getSystemTrustStore() throws IOException, GeneralSecurityException {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
String fileName = System.getProperty("javax.net.ssl.trustStore");
|
||||
String password = System.getProperty("javax.net.ssl.trustStorePassword");
|
||||
if (password == null) {
|
||||
password = "changeit";
|
||||
}
|
||||
|
||||
KeyStore ks = KeyStore.getInstance("jks");
|
||||
File keyFile = null;
|
||||
if (fileName != null) {
|
||||
keyFile = FileUtil.getFile(fileName);
|
||||
} else {
|
||||
keyFile = FileUtil.getFile(javaHome + "/lib/security/jssecacerts");
|
||||
if (!keyFile.exists() || !keyFile.canRead()) {
|
||||
keyFile = FileUtil.getFile(javaHome + "/lib/security/cacerts");
|
||||
}
|
||||
}
|
||||
|
||||
if (keyFile.exists() && keyFile.canRead()) {
|
||||
InputStream in = new FileInputStream(keyFile);
|
||||
try {
|
||||
ks.load(in, password.toCharArray());
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
} else {
|
||||
ks.load(null, "changeit".toCharArray());
|
||||
}
|
||||
return ks;
|
||||
}
|
||||
|
||||
public static X509Certificate readCertificate(byte[] certChain) throws CertificateException {
|
||||
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(certChain);
|
||||
return (X509Certificate) cf.generateCertificate(bais);
|
||||
}
|
||||
|
||||
public static Map<String, String> getCertX500Map(java.security.cert.X509Certificate cert) {
|
||||
return getX500Map(cert.getSubjectX500Principal());
|
||||
}
|
||||
|
||||
public static Map<String, String> getCertX500Map(javax.security.cert.X509Certificate cert) {
|
||||
return getX500Map(cert.getSubjectDN());
|
||||
}
|
||||
|
||||
public static Map<String, String> getX500Map(Principal x500) {
|
||||
Map<String, String> x500Map = new HashMap<String, String>();
|
||||
|
||||
String name = x500.getName().replaceAll("\\\\,", "&com;");
|
||||
String[] x500Opts = name.split("\\,");
|
||||
for (String opt: x500Opts) {
|
||||
if (opt.indexOf("=") > -1) {
|
||||
String[] nv = opt.split("\\=", 2);
|
||||
x500Map.put(nv[0].replaceAll("&com;", ","), nv[1].replaceAll("&com;", ","));
|
||||
}
|
||||
}
|
||||
|
||||
return x500Map;
|
||||
}
|
||||
|
||||
public static void importPKCS8CertChain(KeyStore ks, String alias, byte[] keyBytes, String keyPass, byte[] certChain) throws InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
|
||||
// load the private key
|
||||
KeyFactory kf = KeyFactory.getInstance("RSA");
|
||||
PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
|
||||
PrivateKey pk = kf.generatePrivate(keysp);
|
||||
|
||||
// load the cert chain
|
||||
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(certChain);
|
||||
|
||||
Collection<? extends Certificate> certCol = cf.generateCertificates(bais);
|
||||
Certificate[] certs = new Certificate[certCol.toArray().length];
|
||||
if (certCol.size() == 1) {
|
||||
Debug.logInfo("Single certificate; no chain", module);
|
||||
bais = new ByteArrayInputStream(certChain);
|
||||
Certificate cert = cf.generateCertificate(bais);
|
||||
certs[0] = cert;
|
||||
} else {
|
||||
Debug.logInfo("Certificate chain length : " + certCol.size(), module);
|
||||
certs = certCol.toArray(new Certificate[certCol.size()]);
|
||||
}
|
||||
|
||||
ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs);
|
||||
}
|
||||
|
||||
public static String certToString(Certificate cert) throws CertificateEncodingException {
|
||||
byte[] certBuf = cert.getEncoded();
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.append("-----BEGIN CERTIFICATE-----\n");
|
||||
buf.append(new String(Base64.encodeBase64Chunked(certBuf)));
|
||||
buf.append("\n-----END CERTIFICATE-----\n");
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public static Certificate pemToCert(String certString) throws IOException, CertificateException {
|
||||
return pemToCert(new StringReader(certString));
|
||||
}
|
||||
|
||||
public static Certificate pemToCert(File certFile) throws IOException, CertificateException {
|
||||
return pemToCert(new FileInputStream(certFile));
|
||||
}
|
||||
|
||||
public static Certificate pemToCert(InputStream is) throws IOException, CertificateException {
|
||||
return pemToCert(new InputStreamReader(is));
|
||||
}
|
||||
|
||||
public static Certificate pemToCert(Reader r) throws IOException, CertificateException {
|
||||
String header = "-----BEGIN CERTIFICATE-----";
|
||||
String footer = "-----END CERTIFICATE-----";
|
||||
|
||||
BufferedReader reader = new BufferedReader(r);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintStream ps = new PrintStream(baos);
|
||||
|
||||
String line;
|
||||
|
||||
// ignore up to the header
|
||||
while ((line = reader.readLine()) != null && !line.equals(header)) {
|
||||
}
|
||||
|
||||
// no header found
|
||||
if (line == null) {
|
||||
throw new IOException("Error reading certificate, missing BEGIN boundary");
|
||||
}
|
||||
|
||||
// in between the header and footer is the actual certificate
|
||||
while ((line = reader.readLine()) != null && !line.equals(footer)) {
|
||||
line = line.replaceAll("\\s", "");
|
||||
ps.print(line);
|
||||
}
|
||||
|
||||
// no footer found
|
||||
if (line == null) {
|
||||
throw new IOException("Error reading certificate, missing END boundary");
|
||||
}
|
||||
ps.close();
|
||||
|
||||
// decode the buffer to a X509Certificate
|
||||
|
||||
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
||||
byte[] certBytes = Base64.decodeBase64(baos.toByteArray());
|
||||
return cf.generateCertificate(new ByteArrayInputStream(certBytes));
|
||||
}
|
||||
|
||||
public static String pemToPkHex(String certString) throws IOException, CertificateException {
|
||||
Certificate cert = pemToCert(certString);
|
||||
return StringUtil.toHexString(cert.getPublicKey().getEncoded());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* Contains extra information about Messages
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class MessageString implements Serializable {
|
||||
|
||||
public static final String module = MessageString.class.getName();
|
||||
|
||||
protected String message;
|
||||
protected String fieldName;
|
||||
protected String toFieldName;
|
||||
protected Throwable sourceError;
|
||||
protected Locale locale;
|
||||
protected String propertyResource;
|
||||
protected String propertyName;
|
||||
protected boolean isError = true;
|
||||
|
||||
public static List<Object> getMessagesForField(String fieldName, boolean convertToStrings, List<Object> messageStringList) {
|
||||
if (fieldName == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
Set<String> fieldSet = new TreeSet<String>();
|
||||
fieldSet.add(fieldName);
|
||||
return getMessagesForField(fieldSet, convertToStrings, messageStringList);
|
||||
}
|
||||
public static List<Object> getMessagesForField(String fieldName1, String fieldName2, String fieldName3, String fieldName4, boolean convertToStrings, List<Object> messageStringList) {
|
||||
Set<String> fieldSet = new TreeSet<String>();
|
||||
if (UtilValidate.isNotEmpty(fieldName1)) fieldSet.add(fieldName1);
|
||||
if (UtilValidate.isNotEmpty(fieldName2)) fieldSet.add(fieldName2);
|
||||
if (UtilValidate.isNotEmpty(fieldName3)) fieldSet.add(fieldName3);
|
||||
if (UtilValidate.isNotEmpty(fieldName4)) fieldSet.add(fieldName4);
|
||||
return getMessagesForField(fieldSet, convertToStrings, messageStringList);
|
||||
}
|
||||
public static List<Object> getMessagesForField(Set<String> fieldNameSet, boolean convertToStrings, List<Object> messageStringList) {
|
||||
if (messageStringList == null || UtilValidate.isEmpty(fieldNameSet)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<Object> outList = new ArrayList<Object>(messageStringList.size());
|
||||
for (Object messageStringCur: messageStringList) {
|
||||
if (messageStringCur instanceof MessageString) {
|
||||
MessageString messageString = (MessageString) messageStringCur;
|
||||
if (messageString.isForField(fieldNameSet)) {
|
||||
if (convertToStrings) {
|
||||
outList.add(messageString.toString());
|
||||
} else {
|
||||
outList.add(messageString);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// not a MessageString, don't know if it is for this field so skip it
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return outList;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param message
|
||||
* @param fieldName
|
||||
* @param locale
|
||||
* @param propertyResource
|
||||
* @param propertyName
|
||||
*/
|
||||
public MessageString(String message, String fieldName, String propertyResource, String propertyName, Locale locale, boolean isError) {
|
||||
this.message = message;
|
||||
this.fieldName = fieldName;
|
||||
this.locale = locale;
|
||||
this.propertyResource = propertyResource;
|
||||
this.propertyName = propertyName;
|
||||
this.isError = isError;
|
||||
}
|
||||
/**
|
||||
* @param message
|
||||
* @param fieldName
|
||||
*/
|
||||
public MessageString(String message, String fieldName, boolean isError) {
|
||||
this.message = message;
|
||||
this.fieldName = fieldName;
|
||||
this.isError = isError;
|
||||
}
|
||||
/**
|
||||
* @param message
|
||||
* @param fieldName
|
||||
* @param toFieldName
|
||||
* @param sourceError
|
||||
*/
|
||||
public MessageString(String message, String fieldName, String toFieldName, Throwable sourceError) {
|
||||
this.message = message;
|
||||
this.fieldName = fieldName;
|
||||
this.toFieldName = toFieldName;
|
||||
this.sourceError = sourceError;
|
||||
this.isError = true;
|
||||
}
|
||||
/**
|
||||
* @param message
|
||||
* @param sourceError
|
||||
*/
|
||||
public MessageString(String message, Throwable sourceError) {
|
||||
this.message = message;
|
||||
this.sourceError = sourceError;
|
||||
this.isError = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the fieldName.
|
||||
*/
|
||||
public String getFieldName() {
|
||||
return fieldName;
|
||||
}
|
||||
/**
|
||||
* @param fieldName The fieldName to set.
|
||||
*/
|
||||
public void setFieldName(String fieldName) {
|
||||
this.fieldName = fieldName;
|
||||
}
|
||||
public boolean isForField(Set<String> fieldNameSet) {
|
||||
if (fieldNameSet == null) {
|
||||
return true;
|
||||
}
|
||||
return fieldNameSet.contains(this.fieldName);
|
||||
}
|
||||
public boolean isForField(String fieldName) {
|
||||
if (this.fieldName == null) {
|
||||
if (fieldName == null) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return this.fieldName.equals(fieldName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the message.
|
||||
*/
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
/**
|
||||
* @param message The message to set.
|
||||
*/
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
/**
|
||||
* @return Returns the sourceError.
|
||||
*/
|
||||
public Throwable getSourceError() {
|
||||
return sourceError;
|
||||
}
|
||||
/**
|
||||
* @param sourceError The sourceError to set.
|
||||
*/
|
||||
public void setSourceError(Throwable sourceError) {
|
||||
this.sourceError = sourceError;
|
||||
}
|
||||
/**
|
||||
* @return Returns the toFieldName.
|
||||
*/
|
||||
public String getToFieldName() {
|
||||
return toFieldName;
|
||||
}
|
||||
/**
|
||||
* @param toFieldName The toFieldName to set.
|
||||
*/
|
||||
public void setToFieldName(String toFieldName) {
|
||||
this.toFieldName = toFieldName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the locale.
|
||||
*/
|
||||
public Locale getLocale() {
|
||||
return locale;
|
||||
}
|
||||
/**
|
||||
* @param locale The locale to set.
|
||||
*/
|
||||
public void setLocale(Locale locale) {
|
||||
this.locale = locale;
|
||||
}
|
||||
/**
|
||||
* @return Returns the propertyName.
|
||||
*/
|
||||
public String getPropertyName() {
|
||||
return propertyName;
|
||||
}
|
||||
/**
|
||||
* @param propertyName The propertyName to set.
|
||||
*/
|
||||
public void setPropertyName(String propertyName) {
|
||||
this.propertyName = propertyName;
|
||||
}
|
||||
/**
|
||||
* @return Returns the propertyResource.
|
||||
*/
|
||||
public String getPropertyResource() {
|
||||
return propertyResource;
|
||||
}
|
||||
/**
|
||||
* @param propertyResource The propertyResource to set.
|
||||
*/
|
||||
public void setPropertyResource(String propertyResource) {
|
||||
this.propertyResource = propertyResource;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the isError.
|
||||
*/
|
||||
public boolean isError() {
|
||||
return isError;
|
||||
}
|
||||
/**
|
||||
* @param isError The isError to set.
|
||||
*/
|
||||
public void setError(boolean isError) {
|
||||
this.isError = isError;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
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.base.util;
|
||||
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
/**
|
||||
* MultiTrustManager
|
||||
*/
|
||||
public class MultiTrustManager implements X509TrustManager {
|
||||
|
||||
public static final String module = MultiTrustManager.class.getName();
|
||||
|
||||
protected List<KeyStore> keystores;
|
||||
|
||||
public MultiTrustManager(KeyStore ks) {
|
||||
this();
|
||||
keystores.add(ks);
|
||||
}
|
||||
|
||||
public MultiTrustManager() {
|
||||
keystores = new LinkedList<KeyStore>();
|
||||
}
|
||||
|
||||
public void add(KeyStore ks) {
|
||||
if (ks != null) {
|
||||
keystores.add(ks);
|
||||
}
|
||||
}
|
||||
|
||||
public int getNumberOfKeyStores() {
|
||||
return keystores.size();
|
||||
}
|
||||
|
||||
public void checkClientTrusted(X509Certificate[] certs, String alg) throws CertificateException {
|
||||
if (isTrusted(certs)) {
|
||||
return;
|
||||
}
|
||||
if (!"true".equals(UtilProperties.getPropertyValue("certificate", "client.all-trusted", "true"))) {
|
||||
throw new CertificateException("No trusted certificate found");
|
||||
}
|
||||
}
|
||||
|
||||
public void checkServerTrusted(X509Certificate[] certs, String alg) throws CertificateException {
|
||||
if (isTrusted(certs)) {
|
||||
return;
|
||||
}
|
||||
if (!"true".equals(UtilProperties.getPropertyValue("certificate", "server.all-trusted", "true"))) {
|
||||
throw new CertificateException("No trusted certificate found");
|
||||
}
|
||||
}
|
||||
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
List<X509Certificate> issuers = new LinkedList<X509Certificate>();
|
||||
for (KeyStore store: keystores) {
|
||||
try {
|
||||
Enumeration<String> e = store.aliases();
|
||||
while (e.hasMoreElements()) {
|
||||
String alias = e.nextElement();
|
||||
Certificate[] chain = store.getCertificateChain(alias);
|
||||
if (chain != null) {
|
||||
for (Certificate cert: chain) {
|
||||
if (cert instanceof X509Certificate) {
|
||||
if (Debug.verboseOn())
|
||||
Debug.logInfo("Read certificate (chain) : " + ((X509Certificate) cert).getSubjectX500Principal().getName(), module);
|
||||
issuers.add((X509Certificate) cert);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Certificate cert = store.getCertificate(alias);
|
||||
if (cert != null && cert instanceof X509Certificate) {
|
||||
if (Debug.verboseOn())
|
||||
Debug.logInfo("Read certificate : " + ((X509Certificate) cert).getSubjectX500Principal().getName(), module);
|
||||
issuers.add((X509Certificate) cert);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (KeyStoreException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
}
|
||||
|
||||
return issuers.toArray(new X509Certificate[issuers.size()]);
|
||||
}
|
||||
|
||||
protected boolean isTrusted(X509Certificate[] cert) {
|
||||
if (cert != null) {
|
||||
X509Certificate[] issuers = this.getAcceptedIssuers();
|
||||
if (issuers != null) {
|
||||
for (X509Certificate issuer: issuers) {
|
||||
for (X509Certificate c: cert) {
|
||||
if (Debug.verboseOn())
|
||||
Debug.logInfo("--- Checking cert: " + issuer.getSubjectX500Principal() + " vs " + c.getSubjectX500Principal(), module);
|
||||
if (issuer.equals(c)) {
|
||||
if (Debug.verboseOn())
|
||||
Debug.logInfo("--- Found trusted cert: " + issuer.getSerialNumber().toString(16) + " : " + issuer.getSubjectX500Principal(), module);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectStreamClass;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
/**
|
||||
* ObjectInputStream
|
||||
*
|
||||
*/
|
||||
public class ObjectInputStream extends java.io.ObjectInputStream {
|
||||
|
||||
private ClassLoader classloader;
|
||||
|
||||
public ObjectInputStream(InputStream in, ClassLoader loader) throws IOException {
|
||||
super(in);
|
||||
this.classloader = loader;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see java.io.ObjectInputStream#resolveClass(java.io.ObjectStreamClass)
|
||||
*/
|
||||
@Override
|
||||
protected Class<?> resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException {
|
||||
return ObjectType.loadClass(classDesc.getName(), classloader);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see java.io.ObjectInputStream#resolveProxyClass(java.lang.String[])
|
||||
*/
|
||||
@Override
|
||||
protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
|
||||
Class<?>[] cinterfaces = new Class[interfaces.length];
|
||||
for (int i = 0; i < interfaces.length; i++)
|
||||
cinterfaces[i] = classloader.loadClass(interfaces[i]);
|
||||
|
||||
try {
|
||||
return Proxy.getProxyClass(classloader, cinterfaces);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new ClassNotFoundException(null, e);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,830 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.ofbiz.base.conversion.ConversionException;
|
||||
import org.ofbiz.base.conversion.Converter;
|
||||
import org.ofbiz.base.conversion.Converters;
|
||||
import org.ofbiz.base.conversion.LocalizedConverter;
|
||||
import org.ofbiz.base.lang.IsEmpty;
|
||||
import org.ofbiz.base.lang.SourceMonitored;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
/**
|
||||
* Utilities for analyzing and converting Object types in Java
|
||||
* Takes advantage of reflection
|
||||
*/
|
||||
public class ObjectType {
|
||||
|
||||
public static final String module = ObjectType.class.getName();
|
||||
|
||||
public static final Object NULL = new NullObject();
|
||||
|
||||
public static final String LANG_PACKAGE = "java.lang."; // We will test both the raw value and this + raw value
|
||||
public static final String SQL_PACKAGE = "java.sql."; // We will test both the raw value and this + raw value
|
||||
|
||||
private static final Map<String, String> classAlias = new HashMap<String, String>();
|
||||
private static final Map<String, Class<?>> primitives = new HashMap<String, Class<?>>();
|
||||
|
||||
static {
|
||||
classAlias.put("Object", "java.lang.Object");
|
||||
classAlias.put("String", "java.lang.String");
|
||||
classAlias.put("Boolean", "java.lang.Boolean");
|
||||
classAlias.put("BigDecimal", "java.math.BigDecimal");
|
||||
classAlias.put("Double", "java.lang.Double");
|
||||
classAlias.put("Float", "java.lang.Float");
|
||||
classAlias.put("Long", "java.lang.Long");
|
||||
classAlias.put("Integer", "java.lang.Integer");
|
||||
classAlias.put("Short", "java.lang.Short");
|
||||
classAlias.put("Byte", "java.lang.Byte");
|
||||
classAlias.put("Character", "java.lang.Character");
|
||||
classAlias.put("Timestamp", "java.sql.Timestamp");
|
||||
classAlias.put("Time", "java.sql.Time");
|
||||
classAlias.put("Date", "java.sql.Date");
|
||||
classAlias.put("Locale", "java.util.Locale");
|
||||
classAlias.put("Collection", "java.util.Collection");
|
||||
classAlias.put("List", "java.util.List");
|
||||
classAlias.put("Set", "java.util.Set");
|
||||
classAlias.put("Map", "java.util.Map");
|
||||
classAlias.put("HashMap", "java.util.HashMap");
|
||||
classAlias.put("TimeZone", "java.util.TimeZone");
|
||||
classAlias.put("TimeDuration", "org.ofbiz.base.util.TimeDuration");
|
||||
classAlias.put("GenericValue", "org.ofbiz.entity.GenericValue");
|
||||
classAlias.put("GenericPK", "org.ofbiz.entity.GenericPK");
|
||||
classAlias.put("GenericEntity", "org.ofbiz.entity.GenericEntity");
|
||||
primitives.put("boolean", Boolean.TYPE);
|
||||
primitives.put("short", Short.TYPE);
|
||||
primitives.put("int", Integer.TYPE);
|
||||
primitives.put("long", Long.TYPE);
|
||||
primitives.put("float", Float.TYPE);
|
||||
primitives.put("double", Double.TYPE);
|
||||
primitives.put("byte", Byte.TYPE);
|
||||
primitives.put("char", Character.TYPE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a class with the current thread's context classloader.
|
||||
* @param className The name of the class to load
|
||||
* @return The requested class
|
||||
* @throws ClassNotFoundException
|
||||
*/
|
||||
public static Class<?> loadClass(String className) throws ClassNotFoundException {
|
||||
return loadClass(className, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a class with the specified classloader.
|
||||
* @param className The name of the class to load
|
||||
* @param loader The ClassLoader to use
|
||||
* @return The requested class
|
||||
* @throws ClassNotFoundException
|
||||
*/
|
||||
public static Class<?> loadClass(String className, ClassLoader loader) throws ClassNotFoundException {
|
||||
Class<?> theClass = null;
|
||||
// if it is a primitive type, return the object from the "primitives" map
|
||||
if (primitives.containsKey(className)) {
|
||||
return primitives.get(className);
|
||||
}
|
||||
|
||||
int genericsStart = className.indexOf("<");
|
||||
if (genericsStart != -1) className = className.substring(0, genericsStart);
|
||||
|
||||
// Handle array classes. Details in http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/types.html#wp16437
|
||||
if (className.endsWith("[]")) {
|
||||
if (Character.isLowerCase(className.charAt(0)) && className.indexOf(".") < 0) {
|
||||
String prefix = className.substring(0, 1).toUpperCase();
|
||||
// long and boolean have other prefix than first letter
|
||||
if (className.startsWith("long")) {
|
||||
prefix = "J";
|
||||
} else if (className.startsWith("boolean")) {
|
||||
prefix = "Z";
|
||||
}
|
||||
className = "[" + prefix;
|
||||
} else {
|
||||
Class<?> arrayClass = loadClass(className.replace("[]", ""), loader);
|
||||
className = "[L" + arrayClass.getName().replace("[]", "") + ";";
|
||||
}
|
||||
}
|
||||
|
||||
// if className is an alias (e.g. "String") then replace it with the proper class name (e.g. "java.lang.String")
|
||||
if (classAlias.containsKey(className)) {
|
||||
className = classAlias.get(className);
|
||||
}
|
||||
|
||||
if (loader == null) loader = Thread.currentThread().getContextClassLoader();
|
||||
|
||||
theClass = Class.forName(className, true, loader);
|
||||
|
||||
return theClass;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an instance of the specified class. This uses the default
|
||||
* no-arg constructor to create the instance.
|
||||
* @param className Name of the class to instantiate
|
||||
* @return An instance of the named class
|
||||
* @throws ClassNotFoundException
|
||||
* @throws InstantiationException
|
||||
* @throws IllegalAccessException
|
||||
*/
|
||||
public static Object getInstance(String className) throws ClassNotFoundException,
|
||||
InstantiationException, IllegalAccessException {
|
||||
Class<?> c = loadClass(className);
|
||||
Object o = c.newInstance();
|
||||
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Instantiated object: " + o.toString(), module);
|
||||
return o;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a class properly implements the specified interface.
|
||||
* @param objectClass Class to test
|
||||
* @param interfaceName Name of the interface to test against
|
||||
* @return true if interfaceName is an interface of objectClass
|
||||
* @throws ClassNotFoundException
|
||||
*/
|
||||
public static boolean interfaceOf(Class<?> objectClass, String interfaceName) throws ClassNotFoundException {
|
||||
Class<?> interfaceClass = loadClass(interfaceName);
|
||||
|
||||
return interfaceOf(objectClass, interfaceClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a class properly implements the specified interface.
|
||||
* @param objectClass Class to test
|
||||
* @param interfaceObject to test against
|
||||
* @return true if interfaceObject is an interface of the objectClass
|
||||
*/
|
||||
public static boolean interfaceOf(Class<?> objectClass, Object interfaceObject) {
|
||||
Class<?> interfaceClass = interfaceObject.getClass();
|
||||
|
||||
return interfaceOf(objectClass, interfaceClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an instance of the specified class using the constructor matching the specified parameters.
|
||||
* @param className Name of the class to instantiate
|
||||
* @param parameters Parameters passed to the constructor
|
||||
* @return An instance of the className
|
||||
* @throws ClassNotFoundException
|
||||
* @throws InstantiationException
|
||||
* @throws IllegalAccessException
|
||||
*/
|
||||
public static Object getInstance(String className, Object[] parameters) throws ClassNotFoundException,
|
||||
InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
Class<?>[] sig = new Class<?>[parameters.length];
|
||||
for (int i = 0; i < sig.length; i++) {
|
||||
sig[i] = parameters[i].getClass();
|
||||
}
|
||||
Class<?> c = loadClass(className);
|
||||
Constructor<?> con = c.getConstructor(sig);
|
||||
Object o = con.newInstance(parameters);
|
||||
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Instantiated object: " + o.toString(), module);
|
||||
return o;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an object properly implements the specified interface.
|
||||
* @param obj Object to test
|
||||
* @param interfaceName Name of the interface to test against
|
||||
* @return true if interfaceName is an interface of obj
|
||||
* @throws ClassNotFoundException
|
||||
*/
|
||||
public static boolean interfaceOf(Object obj, String interfaceName) throws ClassNotFoundException {
|
||||
Class<?> interfaceClass = loadClass(interfaceName);
|
||||
|
||||
return interfaceOf(obj, interfaceClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an object properly implements the specified interface.
|
||||
* @param obj Object to test
|
||||
* @param interfaceObject to test against
|
||||
* @return true if interfaceObject is an interface of obj
|
||||
*/
|
||||
public static boolean interfaceOf(Object obj, Object interfaceObject) {
|
||||
Class<?> interfaceClass = interfaceObject.getClass();
|
||||
|
||||
return interfaceOf(obj, interfaceClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an object properly implements the specified interface.
|
||||
* @param obj Object to test
|
||||
* @param interfaceClass Class to test against
|
||||
* @return true if interfaceClass is an interface of obj
|
||||
*/
|
||||
public static boolean interfaceOf(Object obj, Class<?> interfaceClass) {
|
||||
Class<?> objectClass = obj.getClass();
|
||||
|
||||
return interfaceOf(objectClass, interfaceClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a class properly implements the specified interface.
|
||||
* @param objectClass Class to test
|
||||
* @param interfaceClass Class to test against
|
||||
* @return true if interfaceClass is an interface of objectClass
|
||||
*/
|
||||
public static boolean interfaceOf(Class<?> objectClass, Class<?> interfaceClass) {
|
||||
while (objectClass != null) {
|
||||
Class<?>[] ifaces = objectClass.getInterfaces();
|
||||
|
||||
for (Class<?> iface: ifaces) {
|
||||
if (iface == interfaceClass) return true;
|
||||
}
|
||||
objectClass = objectClass.getSuperclass();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a class is a class of or a sub-class of the parent.
|
||||
* @param objectClass Class to test
|
||||
* @param parentName Name of the parent class to test against
|
||||
* @return true if objectClass is a class of or a sub-class of the parent
|
||||
* @throws ClassNotFoundException
|
||||
*/
|
||||
public static boolean isOrSubOf(Class<?> objectClass, String parentName) throws ClassNotFoundException {
|
||||
Class<?> parentClass = loadClass(parentName);
|
||||
|
||||
return isOrSubOf(objectClass, parentClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a class is a class of or a sub-class of the parent.
|
||||
* @param objectClass Class to test
|
||||
* @param parentObject Object to test against
|
||||
* @return true if objectClass is a class of or a sub-class of the parent
|
||||
*/
|
||||
public static boolean isOrSubOf(Class<?> objectClass, Object parentObject) {
|
||||
Class<?> parentClass = parentObject.getClass();
|
||||
|
||||
return isOrSubOf(objectClass, parentClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an object is an instance of or a sub-class of the parent.
|
||||
* @param obj Object to test
|
||||
* @param parentName Name of the parent class to test against
|
||||
* @return true if obj is an instance of or a sub-class of the parent
|
||||
* @throws ClassNotFoundException
|
||||
*/
|
||||
public static boolean isOrSubOf(Object obj, String parentName) throws ClassNotFoundException {
|
||||
Class<?> parentClass = loadClass(parentName);
|
||||
|
||||
return isOrSubOf(obj, parentClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an object is an instance of or a sub-class of the parent.
|
||||
* @param obj Object to test
|
||||
* @param parentObject Object to test against
|
||||
* @return true if obj is an instance of or a sub-class of the parent
|
||||
*/
|
||||
public static boolean isOrSubOf(Object obj, Object parentObject) {
|
||||
Class<?> parentClass = parentObject.getClass();
|
||||
|
||||
return isOrSubOf(obj, parentClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an object is an instance of or a sub-class of the parent.
|
||||
* @param obj Object to test
|
||||
* @param parentClass Class to test against
|
||||
* @return true if obj is an instance of or a sub-class of the parent
|
||||
*/
|
||||
public static boolean isOrSubOf(Object obj, Class<?> parentClass) {
|
||||
Class<?> objectClass = obj.getClass();
|
||||
|
||||
return isOrSubOf(objectClass, parentClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a class is a class of or a sub-class of the parent.
|
||||
* @param objectClass Class to test
|
||||
* @param parentClass Class to test against
|
||||
* @return true if objectClass is a class of or a sub-class of the parent
|
||||
*/
|
||||
public static boolean isOrSubOf(Class<?> objectClass, Class<?> parentClass) {
|
||||
//Debug.logInfo("Checking isOrSubOf for [" + objectClass.getName() + "] and [" + objectClass.getName() + "]", module);
|
||||
while (objectClass != null) {
|
||||
if (objectClass == parentClass) return true;
|
||||
objectClass = objectClass.getSuperclass();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a class is a class of a sub-class of or properly implements an interface.
|
||||
* @param objectClass Class to test
|
||||
* @param typeObject Object to test against
|
||||
* @return true if objectClass is a class of a sub-class of, or properly implements an interface
|
||||
*/
|
||||
public static boolean instanceOf(Class<?> objectClass, Object typeObject) {
|
||||
Class<?> typeClass = typeObject.getClass();
|
||||
|
||||
return instanceOf(objectClass, typeClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a class is a class of a sub-class of or properly implements an interface.
|
||||
* @param objectClass Class to test
|
||||
* @param typeName name to test against
|
||||
* @return true if objectClass is a class or a sub-class of, or properly implements an interface
|
||||
*/
|
||||
public static boolean instanceOf(Class<?> objectClass, String typeName) {
|
||||
return instanceOf(objectClass, typeName, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an object is an instance of a sub-class of or properly implements an interface.
|
||||
* @param obj Object to test
|
||||
* @param typeObject Object to test against
|
||||
* @return true if obj is an instance of a sub-class of, or properly implements an interface
|
||||
*/
|
||||
public static boolean instanceOf(Object obj, Object typeObject) {
|
||||
Class<?> typeClass = typeObject.getClass();
|
||||
|
||||
return instanceOf(obj, typeClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an object is an instance of a sub-class of or properly implements an interface.
|
||||
* @param obj Object to test
|
||||
* @param typeName name to test against
|
||||
* @return true if obj is an instance of a sub-class of, or properly implements an interface
|
||||
*/
|
||||
public static boolean instanceOf(Object obj, String typeName) {
|
||||
return instanceOf(obj, typeName, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a class is a class of a sub-class of or properly implements an interface.
|
||||
* @param objectClass Class to test
|
||||
* @param typeName Object to test against
|
||||
* @param loader
|
||||
* @return true if objectClass is a class of a sub-class of, or properly implements an interface
|
||||
*/
|
||||
public static boolean instanceOf(Class<?> objectClass, String typeName, ClassLoader loader) {
|
||||
Class<?> infoClass = loadInfoClass(typeName, loader);
|
||||
|
||||
if (infoClass == null)
|
||||
throw new IllegalArgumentException("Illegal type found in info map (could not load class for specified type)");
|
||||
|
||||
return instanceOf(objectClass, infoClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an object is an instance of a sub-class of or properly implements an interface.
|
||||
* @param obj Object to test
|
||||
* @param typeName Object to test against
|
||||
* @param loader
|
||||
* @return true if obj is an instance of a sub-class of, or properly implements an interface
|
||||
*/
|
||||
public static boolean instanceOf(Object obj, String typeName, ClassLoader loader) {
|
||||
Class<?> infoClass = loadInfoClass(typeName, loader);
|
||||
|
||||
if (infoClass == null) {
|
||||
throw new IllegalArgumentException("Illegal type found in info map (could not load class for specified type)");
|
||||
}
|
||||
|
||||
return instanceOf(obj, infoClass);
|
||||
}
|
||||
|
||||
public static Class<?> loadInfoClass(String typeName, ClassLoader loader) {
|
||||
//Class infoClass = null;
|
||||
try {
|
||||
return loadClass(typeName, loader);
|
||||
} catch (SecurityException se1) {
|
||||
throw new IllegalArgumentException("Problems with classloader: security exception (" +
|
||||
se1.getMessage() + ")");
|
||||
} catch (ClassNotFoundException e1) {
|
||||
try {
|
||||
return loadClass(LANG_PACKAGE + typeName, loader);
|
||||
} catch (SecurityException se2) {
|
||||
throw new IllegalArgumentException("Problems with classloader: security exception (" +
|
||||
se2.getMessage() + ")");
|
||||
} catch (ClassNotFoundException e2) {
|
||||
try {
|
||||
return loadClass(SQL_PACKAGE + typeName, loader);
|
||||
} catch (SecurityException se3) {
|
||||
throw new IllegalArgumentException("Problems with classloader: security exception (" +
|
||||
se3.getMessage() + ")");
|
||||
} catch (ClassNotFoundException e3) {
|
||||
throw new IllegalArgumentException("Cannot find and load the class of type: " + typeName +
|
||||
" or of type: " + LANG_PACKAGE + typeName + " or of type: " + SQL_PACKAGE + typeName +
|
||||
": (" + e3.getMessage() + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if an object is an instance of a sub-class of or properly implements an interface.
|
||||
* @param obj Object to test
|
||||
* @param typeClass Class to test against
|
||||
* @return true if obj is an instance of a sub-class of typeClass
|
||||
*/
|
||||
public static boolean instanceOf(Object obj, Class<?> typeClass) {
|
||||
if (obj == null) return true;
|
||||
Class<?> objectClass = obj.getClass();
|
||||
return instanceOf(objectClass, typeClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a class is a class of a sub-class of or properly implements an interface.
|
||||
* @param objectClass Class to test
|
||||
* @param typeClass Class to test against
|
||||
* @return true if objectClass is a class or sub-class of, or implements typeClass
|
||||
*/
|
||||
public static boolean instanceOf(Class<?> objectClass, Class<?> typeClass) {
|
||||
if (typeClass.isInterface() && !objectClass.isInterface()) {
|
||||
return interfaceOf(objectClass, typeClass);
|
||||
} else {
|
||||
return isOrSubOf(objectClass, typeClass);
|
||||
}
|
||||
}
|
||||
|
||||
public static Object simpleTypeConvert(Object obj, String type, String format, Locale locale, boolean noTypeFail) throws GeneralException {
|
||||
return simpleTypeConvert(obj, type, format, null, locale, noTypeFail);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the passed object to the named simple type. Supported types
|
||||
* include: String, Boolean, Double, Float, Long, Integer, Date (java.sql.Date),
|
||||
* Time, Timestamp, TimeZone;
|
||||
* @param obj Object to convert
|
||||
* @param type Optional Java class name of type to convert to. A <code>null</code> or empty <code>String</code> will return the original object.
|
||||
* @param format Optional (can be null) format string for Date, Time, Timestamp
|
||||
* @param timeZone Optional (can be null) TimeZone for converting dates and times
|
||||
* @param locale Optional (can be null) Locale for formatting and parsing Double, Float, Long, Integer
|
||||
* @param noTypeFail Fail (Exception) when no type conversion is available, false will return the primary object
|
||||
* @return the converted value
|
||||
* @throws GeneralException
|
||||
*/
|
||||
@SourceMonitored
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Object simpleTypeConvert(Object obj, String type, String format, TimeZone timeZone, Locale locale, boolean noTypeFail) throws GeneralException {
|
||||
if (obj == null || UtilValidate.isEmpty(type) || "Object".equals(type) || "java.lang.Object".equals(type)) {
|
||||
return obj;
|
||||
}
|
||||
if ("PlainString".equals(type)) {
|
||||
return obj.toString();
|
||||
}
|
||||
if (obj instanceof Node) {
|
||||
Node node = (Node) obj;
|
||||
String nodeValue = node.getTextContent();
|
||||
if ("String".equals(type) || "java.lang.String".equals(type)) {
|
||||
return nodeValue;
|
||||
} else {
|
||||
return simpleTypeConvert(nodeValue, type, format, timeZone, locale, noTypeFail);
|
||||
}
|
||||
}
|
||||
int genericsStart = type.indexOf("<");
|
||||
if (genericsStart != -1) {
|
||||
type = type.substring(0, genericsStart);
|
||||
}
|
||||
Class<?> sourceClass = obj.getClass();
|
||||
Class<?> targetClass = null;
|
||||
try {
|
||||
targetClass = loadClass(type);
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new GeneralException("Conversion from " + sourceClass.getName() + " to " + type + " not currently supported", e);
|
||||
}
|
||||
if (sourceClass.equals(targetClass)) {
|
||||
return obj;
|
||||
}
|
||||
if (obj instanceof String && ((String) obj).length() == 0) {
|
||||
return null;
|
||||
}
|
||||
Converter<Object, Object> converter = null;
|
||||
try {
|
||||
converter = (Converter<Object, Object>) Converters.getConverter(sourceClass, targetClass);
|
||||
} catch (ClassNotFoundException e) {}
|
||||
if (converter != null) {
|
||||
if (converter instanceof LocalizedConverter) {
|
||||
@SuppressWarnings("rawtypes")
|
||||
LocalizedConverter<Object, Object> localizedConverter = (LocalizedConverter) converter;
|
||||
if (timeZone == null) {
|
||||
timeZone = TimeZone.getDefault();
|
||||
}
|
||||
if (locale == null) {
|
||||
locale = Locale.getDefault();
|
||||
}
|
||||
try {
|
||||
return localizedConverter.convert(obj, locale, timeZone, format);
|
||||
} catch (ConversionException e) {
|
||||
Debug.logWarning(e, "Exception thrown while converting type: ", module);
|
||||
throw new GeneralException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
try {
|
||||
return converter.convert(obj);
|
||||
} catch (ConversionException e) {
|
||||
Debug.logWarning(e, "Exception thrown while converting type: ", module);
|
||||
throw new GeneralException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
// we can pretty much always do a conversion to a String, so do that here
|
||||
if (targetClass.equals(String.class)) {
|
||||
Debug.logWarning("No special conversion available for " + obj.getClass().getName() + " to String, returning object.toString().", module);
|
||||
return obj.toString();
|
||||
}
|
||||
if (noTypeFail) {
|
||||
throw new GeneralException("Conversion from " + obj.getClass().getName() + " to " + type + " not currently supported");
|
||||
} else {
|
||||
if (Debug.infoOn()) Debug.logInfo("No type conversion available for " + obj.getClass().getName() + " to " + targetClass.getName() + ", returning original object.", module);
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object simpleTypeConvert(Object obj, String type, String format, Locale locale) throws GeneralException {
|
||||
return simpleTypeConvert(obj, type, format, locale, true);
|
||||
}
|
||||
|
||||
public static Boolean doRealCompare(Object value1, Object value2, String operator, String type, String format,
|
||||
List<Object> messages, Locale locale, ClassLoader loader, boolean value2InlineConstant) {
|
||||
boolean verboseOn = Debug.verboseOn();
|
||||
|
||||
if (verboseOn) Debug.logVerbose("Comparing value1: \"" + value1 + "\" " + operator + " value2:\"" + value2 + "\"", module);
|
||||
|
||||
try {
|
||||
if (!"PlainString".equals(type)) {
|
||||
Class<?> clz = loadClass(type, loader);
|
||||
type = clz.getName();
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
Debug.logWarning("The specified type [" + type + "] is not a valid class or a known special type, may see more errors later because of this: " + e.getMessage(), module);
|
||||
}
|
||||
|
||||
if (value1 == null) {
|
||||
// some default behavior for null values, results in a bit cleaner operation
|
||||
if ("is-null".equals(operator)) {
|
||||
return Boolean.TRUE;
|
||||
} else if ("is-not-null".equals(operator)) {
|
||||
return Boolean.FALSE;
|
||||
} else if ("is-empty".equals(operator)) {
|
||||
return Boolean.TRUE;
|
||||
} else if ("is-not-empty".equals(operator)) {
|
||||
return Boolean.FALSE;
|
||||
} else if ("contains".equals(operator)) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
int result = 0;
|
||||
|
||||
Object convertedValue2 = null;
|
||||
if (value2 != null) {
|
||||
Locale value2Locale = locale;
|
||||
if (value2InlineConstant) {
|
||||
value2Locale = UtilMisc.parseLocale("en");
|
||||
}
|
||||
try {
|
||||
convertedValue2 = simpleTypeConvert(value2, type, format, value2Locale);
|
||||
} catch (GeneralException e) {
|
||||
Debug.logError(e, module);
|
||||
messages.add("Could not convert value2 for comparison: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// have converted value 2, now before converting value 1 see if it is a Collection and we are doing a contains comparison
|
||||
if ("contains".equals(operator) && value1 instanceof Collection<?>) {
|
||||
Collection<?> col1 = (Collection<?>) value1;
|
||||
return col1.contains(convertedValue2) ? Boolean.TRUE : Boolean.FALSE;
|
||||
}
|
||||
|
||||
Object convertedValue1 = null;
|
||||
try {
|
||||
convertedValue1 = simpleTypeConvert(value1, type, format, locale);
|
||||
} catch (GeneralException e) {
|
||||
Debug.logError(e, module);
|
||||
messages.add("Could not convert value1 for comparison: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
|
||||
// handle null values...
|
||||
if (convertedValue1 == null || convertedValue2 == null) {
|
||||
if ("equals".equals(operator)) {
|
||||
return convertedValue1 == null && convertedValue2 == null ? Boolean.TRUE : Boolean.FALSE;
|
||||
} else if ("not-equals".equals(operator)) {
|
||||
return convertedValue1 == null && convertedValue2 == null ? Boolean.FALSE : Boolean.TRUE;
|
||||
} else if ("is-not-empty".equals(operator) || "is-empty".equals(operator)) {
|
||||
// do nothing, handled later...
|
||||
} else {
|
||||
if (convertedValue1 == null) {
|
||||
messages.add("Left value is null, cannot complete compare for the operator " + operator);
|
||||
return null;
|
||||
}
|
||||
if (convertedValue2 == null) {
|
||||
messages.add("Right value is null, cannot complete compare for the operator " + operator);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ("contains".equals(operator)) {
|
||||
if ("java.lang.String".equals(type) || "PlainString".equals(type)) {
|
||||
String str1 = (String) convertedValue1;
|
||||
String str2 = (String) convertedValue2;
|
||||
|
||||
return str1.indexOf(str2) < 0 ? Boolean.FALSE : Boolean.TRUE;
|
||||
} else {
|
||||
messages.add("Error in XML file: cannot do a contains compare between a String and a non-String type");
|
||||
return null;
|
||||
}
|
||||
} else if ("is-empty".equals(operator)) {
|
||||
if (convertedValue1 == null)
|
||||
return Boolean.TRUE;
|
||||
if (convertedValue1 instanceof String && ((String) convertedValue1).length() == 0)
|
||||
return Boolean.TRUE;
|
||||
if (convertedValue1 instanceof List<?> && ((List<?>) convertedValue1).size() == 0)
|
||||
return Boolean.TRUE;
|
||||
if (convertedValue1 instanceof Map<?, ?> && ((Map<?, ?>) convertedValue1).size() == 0)
|
||||
return Boolean.TRUE;
|
||||
return Boolean.FALSE;
|
||||
} else if ("is-not-empty".equals(operator)) {
|
||||
if (convertedValue1 == null)
|
||||
return Boolean.FALSE;
|
||||
if (convertedValue1 instanceof String && ((String) convertedValue1).length() == 0)
|
||||
return Boolean.FALSE;
|
||||
if (convertedValue1 instanceof List<?> && ((List<?>) convertedValue1).size() == 0)
|
||||
return Boolean.FALSE;
|
||||
if (convertedValue1 instanceof Map<?, ?> && ((Map<?, ?>) convertedValue1).size() == 0)
|
||||
return Boolean.FALSE;
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
if ("java.lang.String".equals(type) || "PlainString".equals(type)) {
|
||||
String str1 = (String) convertedValue1;
|
||||
String str2 = (String) convertedValue2;
|
||||
|
||||
if (str1.length() == 0 || str2.length() == 0) {
|
||||
if ("equals".equals(operator)) {
|
||||
return str1.length() == 0 && str2.length() == 0 ? Boolean.TRUE : Boolean.FALSE;
|
||||
} else if ("not-equals".equals(operator)) {
|
||||
return str1.length() == 0 && str2.length() == 0 ? Boolean.FALSE : Boolean.TRUE;
|
||||
} else {
|
||||
messages.add("ERROR: Could not do a compare between strings with one empty string for the operator " + operator);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
result = str1.compareTo(str2);
|
||||
} else if ("java.lang.Double".equals(type) || "java.lang.Float".equals(type) || "java.lang.Long".equals(type) || "java.lang.Integer".equals(type) || "java.math.BigDecimal".equals(type)) {
|
||||
Number tempNum = (Number) convertedValue1;
|
||||
double value1Double = tempNum.doubleValue();
|
||||
|
||||
tempNum = (Number) convertedValue2;
|
||||
double value2Double = tempNum.doubleValue();
|
||||
|
||||
if (value1Double < value2Double)
|
||||
result = -1;
|
||||
else if (value1Double > value2Double)
|
||||
result = 1;
|
||||
else
|
||||
result = 0;
|
||||
} else if ("java.sql.Date".equals(type)) {
|
||||
java.sql.Date value1Date = (java.sql.Date) convertedValue1;
|
||||
java.sql.Date value2Date = (java.sql.Date) convertedValue2;
|
||||
result = value1Date.compareTo(value2Date);
|
||||
} else if ("java.sql.Time".equals(type)) {
|
||||
java.sql.Time value1Time = (java.sql.Time) convertedValue1;
|
||||
java.sql.Time value2Time = (java.sql.Time) convertedValue2;
|
||||
result = value1Time.compareTo(value2Time);
|
||||
} else if ("java.sql.Timestamp".equals(type)) {
|
||||
java.sql.Timestamp value1Timestamp = (java.sql.Timestamp) convertedValue1;
|
||||
java.sql.Timestamp value2Timestamp = (java.sql.Timestamp) convertedValue2;
|
||||
result = value1Timestamp.compareTo(value2Timestamp);
|
||||
} else if ("java.lang.Boolean".equals(type)) {
|
||||
Boolean value1Boolean = (Boolean) convertedValue1;
|
||||
Boolean value2Boolean = (Boolean) convertedValue2;
|
||||
if ("equals".equals(operator)) {
|
||||
if ((value1Boolean.booleanValue() && value2Boolean.booleanValue()) || (!value1Boolean.booleanValue() && !value2Boolean.booleanValue()))
|
||||
result = 0;
|
||||
else
|
||||
result = 1;
|
||||
} else if ("not-equals".equals(operator)) {
|
||||
if ((!value1Boolean.booleanValue() && value2Boolean.booleanValue()) || (value1Boolean.booleanValue() && !value2Boolean.booleanValue()))
|
||||
result = 0;
|
||||
else
|
||||
result = 1;
|
||||
} else {
|
||||
messages.add("Can only compare Booleans using the operators 'equals' or 'not-equals'");
|
||||
return null;
|
||||
}
|
||||
} else if ("java.lang.Object".equals(type)) {
|
||||
if (convertedValue1.equals(convertedValue2)) {
|
||||
result = 0;
|
||||
} else {
|
||||
result = 1;
|
||||
}
|
||||
} else {
|
||||
messages.add("Type \"" + type + "\" specified for compare not supported.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (verboseOn) Debug.logVerbose("Got Compare result: " + result + ", operator: " + operator, module);
|
||||
if ("less".equals(operator)) {
|
||||
if (result >= 0)
|
||||
return Boolean.FALSE;
|
||||
} else if ("greater".equals(operator)) {
|
||||
if (result <= 0)
|
||||
return Boolean.FALSE;
|
||||
} else if ("less-equals".equals(operator)) {
|
||||
if (result > 0)
|
||||
return Boolean.FALSE;
|
||||
} else if ("greater-equals".equals(operator)) {
|
||||
if (result < 0)
|
||||
return Boolean.FALSE;
|
||||
} else if ("equals".equals(operator)) {
|
||||
if (result != 0)
|
||||
return Boolean.FALSE;
|
||||
} else if ("not-equals".equals(operator)) {
|
||||
if (result == 0)
|
||||
return Boolean.FALSE;
|
||||
} else {
|
||||
messages.add("Specified compare operator \"" + operator + "\" not known.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (verboseOn) Debug.logVerbose("Returning true", module);
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static boolean isEmpty(Object value) {
|
||||
if (value == null) return true;
|
||||
|
||||
if (value instanceof String) return ((String) value).length() == 0;
|
||||
if (value instanceof Collection) return ((Collection<? extends Object>) value).size() == 0;
|
||||
if (value instanceof Map) return ((Map<? extends Object, ? extends Object>) value).size() == 0;
|
||||
if (value instanceof CharSequence) return ((CharSequence) value).length() == 0;
|
||||
if (value instanceof IsEmpty) return ((IsEmpty) value).isEmpty();
|
||||
|
||||
// These types would flood the log
|
||||
// Number covers: BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short
|
||||
if (value instanceof Boolean) return false;
|
||||
if (value instanceof Number) return false;
|
||||
if (value instanceof Character) return false;
|
||||
if (value instanceof java.util.Date) return false;
|
||||
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("In ObjectType.isEmpty(Object value) returning false for " + value.getClass() + " Object.", module);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public static final class NullObject implements Serializable {
|
||||
public NullObject() { }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ObjectType.NullObject";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return toString().hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other instanceof NullObject) {
|
||||
// should do equality of object? don't think so, just same type
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.base.util;
|
||||
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* An observable object.
|
||||
* <p>This class is similar to <code>java.util.Observable</code> but it has some differences:
|
||||
* <ul>
|
||||
* <li>It has improved concurrency</li>
|
||||
* <li>It cannot be subclassed</li>
|
||||
* <li>The <code>notifyObservers</code> method does not clear the changed flag</li>
|
||||
* <li>Protected methods have been made public</li>
|
||||
* </ul></p>
|
||||
*
|
||||
*/
|
||||
public final class Observable {
|
||||
|
||||
private final AtomicBoolean changed = new AtomicBoolean();
|
||||
private final CopyOnWriteArrayList<Observer> observers = new CopyOnWriteArrayList<Observer>();
|
||||
|
||||
public Observable() {}
|
||||
|
||||
public Observable(Observable observable) {
|
||||
Assert.notNull("observable", observable);
|
||||
changed.set(observable.changed.get());
|
||||
observers.addAll(observable.observers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an observer to the set of observers for this object.
|
||||
*
|
||||
* @param observer the observer to be added.
|
||||
*/
|
||||
public void addObserver(Observer observer) {
|
||||
Assert.notNull("observer", observer);
|
||||
observers.addIfAbsent(observer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the changed flag.
|
||||
*/
|
||||
public void clearChanged() {
|
||||
changed.set(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an observer from the set of observers of this object.
|
||||
* Passing <code>null</code> to this method will have no effect.
|
||||
*
|
||||
* @param observer the observer to be deleted.
|
||||
*/
|
||||
public void deleteObserver(Observer observer) {
|
||||
observers.remove(observer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the observer list so that this object no longer has any observers.
|
||||
*/
|
||||
public void deleteObservers() {
|
||||
observers.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns <code>true</code> if this object has changed.
|
||||
*
|
||||
*/
|
||||
public boolean hasChanged() {
|
||||
return changed.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify all of the observers.
|
||||
* <p>Each <code>Observer</code> has its <code>update</code> method called with two
|
||||
* arguments: this observable object and <code>null</code>. In other
|
||||
* words, this method is equivalent to:
|
||||
* <blockquote><tt>
|
||||
* notifyObservers(null)</tt></blockquote></p>
|
||||
*
|
||||
*/
|
||||
public void notifyObservers() {
|
||||
notifyObservers(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify all of the observers.
|
||||
* <p>Each observer has its <code>update</code> method called with two
|
||||
* arguments: this observable object and the <code>arg</code> argument.</p>
|
||||
*
|
||||
*/
|
||||
public void notifyObservers(Object arg) {
|
||||
for (Observer observer : observers) {
|
||||
observer.update(this, arg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the changed flag to <code>true</code>.
|
||||
*/
|
||||
public void setChanged() {
|
||||
changed.set(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
/**
|
||||
* An <code>Observable</code> observer.
|
||||
*
|
||||
*/
|
||||
public interface Observer {
|
||||
/**
|
||||
* Called when <code>Observable.notifyObservers</code> is invoked.
|
||||
*
|
||||
* @param observable
|
||||
* @param arg
|
||||
*/
|
||||
void update(Observable observable, Object arg);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import org.apache.oro.text.regex.MalformedPatternException;
|
||||
import org.apache.oro.text.regex.Pattern;
|
||||
import org.apache.oro.text.regex.Perl5Compiler;
|
||||
import org.ofbiz.base.util.cache.UtilCache;
|
||||
|
||||
/**
|
||||
* A RegEx compiled pattern factory.
|
||||
*
|
||||
*/
|
||||
public class PatternFactory {
|
||||
|
||||
public static final String module = PatternFactory.class.getName();
|
||||
private static final UtilCache<String, Pattern> compiledPerl5Patterns = UtilCache.createUtilCache("regularExpression.compiledPerl5Patterns", false);
|
||||
|
||||
/**
|
||||
* Compiles and caches a Perl5 regexp pattern for the given string pattern.
|
||||
* This would be of no benefits (and may bloat memory usage) if stringPattern is never the same.
|
||||
* @param stringPattern a Perl5 pattern string
|
||||
* @param caseSensitive case sensitive true/false
|
||||
* @return a <code>Pattern</code> instance for the given string pattern
|
||||
* @throws MalformedPatternException
|
||||
*/
|
||||
|
||||
public static Pattern createOrGetPerl5CompiledPattern(String stringPattern, boolean caseSensitive) throws MalformedPatternException {
|
||||
Pattern pattern = compiledPerl5Patterns.get(stringPattern);
|
||||
if (pattern == null) {
|
||||
Perl5Compiler compiler = new Perl5Compiler();
|
||||
if (caseSensitive) {
|
||||
pattern = compiler.compile(stringPattern, Perl5Compiler.READ_ONLY_MASK); // READ_ONLY_MASK guarantees immutability
|
||||
} else {
|
||||
pattern = compiler.compile(stringPattern, Perl5Compiler.CASE_INSENSITIVE_MASK | Perl5Compiler.READ_ONLY_MASK);
|
||||
}
|
||||
pattern = compiledPerl5Patterns.putIfAbsentAndGet(stringPattern, pattern);
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Compiled and cached the pattern: '" + stringPattern, module);
|
||||
}
|
||||
}
|
||||
return pattern;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.UnknownHostException;
|
||||
import java.rmi.server.RMISocketFactory;
|
||||
|
||||
/**
|
||||
* A <code>RMISocketFactory</code> implementation that creates <code>ServerSocket</code>s bound
|
||||
* on a specified network interface.
|
||||
*/
|
||||
public class RMIExtendedSocketFactory extends RMISocketFactory {
|
||||
|
||||
/**
|
||||
* The network interface to bind the <code>ServerSocket</code> to. If null than bind to all interfaces.
|
||||
*/
|
||||
private InetAddress hostInetAddress;
|
||||
|
||||
/**
|
||||
* Default constructor. Bind the server sockets on all interfaces.
|
||||
*/
|
||||
public RMIExtendedSocketFactory() {
|
||||
// leave hostInetAddress null
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new <code>RMIExtendedSocketFactory</code> which will create <code>ServerSocket</code>s
|
||||
* bound on the specified network interface.
|
||||
*
|
||||
* @param inetAddress The <code>InetAddress</code> of the network interface.
|
||||
*/
|
||||
public RMIExtendedSocketFactory( InetAddress inetAddress ) {
|
||||
this.hostInetAddress = inetAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new <code>RMIExtendedSocketFactory</code> which will create <code>ServerSocket</code>s
|
||||
* bound on the specified network interface.
|
||||
*
|
||||
* @param hostIpAddress The IP address of the interface to bind the server sockets to.
|
||||
* @throws UnknownHostException If an invalid IP address is provided.
|
||||
*/
|
||||
public RMIExtendedSocketFactory( String hostIpAddress ) throws UnknownHostException {
|
||||
|
||||
// check if host length is at least equal to "0.0.0.0"
|
||||
if ( hostIpAddress != null && hostIpAddress.length() >= 7 ) {
|
||||
String[] octets = hostIpAddress.split( "\\." );
|
||||
|
||||
if ( octets == null || octets.length != 4 ) {
|
||||
throw new UnknownHostException( "Invalid IP address: " + hostIpAddress );
|
||||
}
|
||||
|
||||
byte[] ipAddr = new byte[4];
|
||||
for ( int i = 0; i < octets.length; i++ ) {
|
||||
try {
|
||||
ipAddr[i] = ( byte ) Integer.parseInt( octets[i] );
|
||||
} catch ( NumberFormatException nfEx ) {
|
||||
throw new UnknownHostException( "Invalid IP address: " + hostIpAddress );
|
||||
}
|
||||
}
|
||||
|
||||
hostInetAddress = InetAddress.getByAddress( ipAddr );
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerSocket createServerSocket(int port) throws IOException {
|
||||
if ( hostInetAddress != null ) {
|
||||
return new ServerSocket( port, 0, hostInetAddress );
|
||||
} else {
|
||||
return new ServerSocket( port );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Socket createSocket(String host, int port) throws IOException {
|
||||
|
||||
return new Socket( host, port );
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.lang.ref.PhantomReference;
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
import java.lang.ref.SoftReference;
|
||||
import java.lang.ref.WeakReference;
|
||||
|
||||
public final class ReferenceCleaner {
|
||||
public static final String module = ReferenceCleaner.class.getName();
|
||||
|
||||
private static final class CleanerThread extends Thread {
|
||||
private boolean keepRunning = true;
|
||||
|
||||
protected CleanerThread() {
|
||||
setDaemon(true);
|
||||
setName("ReferenceCleaner");
|
||||
}
|
||||
|
||||
protected void stopRunning() {
|
||||
keepRunning = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while (keepRunning) {
|
||||
try {
|
||||
((Removable) QUEUE.remove()).remove();
|
||||
} catch (Throwable t) {
|
||||
// ignore
|
||||
}
|
||||
if (interrupted()) {
|
||||
stopRunning();
|
||||
cleanerThread = new CleanerThread();
|
||||
cleanerThread.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private static CleanerThread cleanerThread = new CleanerThread();
|
||||
|
||||
static {
|
||||
cleanerThread.start();
|
||||
}
|
||||
|
||||
private ReferenceCleaner() {
|
||||
}
|
||||
|
||||
private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue<Object>();
|
||||
|
||||
public interface Removable {
|
||||
void remove() throws Exception;
|
||||
}
|
||||
|
||||
public abstract static class Soft<V> extends SoftReference<V> implements Removable {
|
||||
public Soft(V value) {
|
||||
super(value, QUEUE);
|
||||
}
|
||||
}
|
||||
|
||||
public abstract static class Phantom<V> extends PhantomReference<V> implements Removable {
|
||||
public Phantom(V value) {
|
||||
super(value, QUEUE);
|
||||
}
|
||||
}
|
||||
|
||||
public abstract static class Weak<V> extends WeakReference<V> implements Removable {
|
||||
public Weak(V value) {
|
||||
super(value, QUEUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.Principal;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.KeyManager;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLPeerUnverifiedException;
|
||||
import javax.net.ssl.SSLServerSocketFactory;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509KeyManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
import org.ofbiz.base.component.ComponentConfig;
|
||||
import org.ofbiz.base.config.GenericConfigException;
|
||||
|
||||
/**
|
||||
* KeyStoreUtil - Utilities for setting up SSL connections with specific client certificates
|
||||
*
|
||||
*/
|
||||
public final class SSLUtil {
|
||||
|
||||
public static final String module = SSLUtil.class.getName();
|
||||
|
||||
private static final int HOSTCERT_NO_CHECK = 0;
|
||||
private static final int HOSTCERT_MIN_CHECK = 1;
|
||||
private static final int HOSTCERT_NORMAL_CHECK = 2;
|
||||
|
||||
private static boolean loadedProps = false;
|
||||
|
||||
private SSLUtil () {}
|
||||
|
||||
static {
|
||||
SSLUtil.loadJsseProperties();
|
||||
}
|
||||
|
||||
private static class TrustAnyManager implements X509TrustManager {
|
||||
|
||||
public void checkClientTrusted(X509Certificate[] certs, String string) throws CertificateException {
|
||||
Debug.logImportant("Trusting (un-trusted) client certificate chain:", module);
|
||||
for (X509Certificate cert: certs) {
|
||||
Debug.logImportant("---- " + cert.getSubjectX500Principal().getName() + " valid: " + cert.getNotAfter(), module);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void checkServerTrusted(X509Certificate[] certs, String string) throws CertificateException {
|
||||
Debug.logImportant("Trusting (un-trusted) server certificate chain:", module);
|
||||
for (X509Certificate cert: certs) {
|
||||
Debug.logImportant("---- " + cert.getSubjectX500Principal().getName() + " valid: " + cert.getNotAfter(), module);
|
||||
}
|
||||
}
|
||||
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return new X509Certificate[0];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static int getHostCertNoCheck() {
|
||||
return HOSTCERT_NO_CHECK;
|
||||
}
|
||||
|
||||
public static int getHostCertMinCheck() {
|
||||
return HOSTCERT_MIN_CHECK;
|
||||
}
|
||||
|
||||
public static int getHostCertNormalCheck() {
|
||||
return HOSTCERT_NORMAL_CHECK;
|
||||
}
|
||||
|
||||
public static boolean isClientTrusted(X509Certificate[] chain, String authType) {
|
||||
TrustManager[] mgrs = new TrustManager[0];
|
||||
try {
|
||||
mgrs = SSLUtil.getTrustManagers();
|
||||
} catch (IOException e) {
|
||||
Debug.logError(e, module);
|
||||
} catch (GeneralSecurityException e) {
|
||||
Debug.logError(e, module);
|
||||
} catch (GenericConfigException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
|
||||
if (mgrs != null) {
|
||||
for (TrustManager mgr: mgrs) {
|
||||
if (mgr instanceof X509TrustManager) {
|
||||
try {
|
||||
((X509TrustManager) mgr).checkClientTrusted(chain, authType);
|
||||
return true;
|
||||
} catch (CertificateException e) {
|
||||
// do nothing; just loop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static KeyManager[] getKeyManagers(String alias) throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
List<KeyManager> keyMgrs = new LinkedList<KeyManager>();
|
||||
for (ComponentConfig.KeystoreInfo ksi: ComponentConfig.getAllKeystoreInfos()) {
|
||||
if (ksi.isCertStore()) {
|
||||
KeyStore ks = ksi.getKeyStore();
|
||||
if (ks != null) {
|
||||
List<KeyManager> newKeyManagers = Arrays.asList(getKeyManagers(ks, ksi.getPassword(), alias));
|
||||
keyMgrs.addAll(newKeyManagers);
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Loaded another cert store, adding [" + (newKeyManagers == null ? "0" : newKeyManagers.size()) + "] KeyManagers for alias [" + alias + "] and keystore: " + ksi.createResourceHandler().getFullLocation(), module);
|
||||
} else {
|
||||
throw new IOException("Unable to load keystore: " + ksi.createResourceHandler().getFullLocation());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return keyMgrs.toArray(new KeyManager[keyMgrs.size()]);
|
||||
}
|
||||
|
||||
public static KeyManager[] getKeyManagers() throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
return getKeyManagers(null);
|
||||
}
|
||||
|
||||
public static TrustManager[] getTrustManagers() throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
MultiTrustManager tm = new MultiTrustManager();
|
||||
tm.add(KeyStoreUtil.getSystemTrustStore());
|
||||
if (tm.getNumberOfKeyStores() < 1) {
|
||||
Debug.logWarning("System truststore not found!", module);
|
||||
}
|
||||
|
||||
for (ComponentConfig.KeystoreInfo ksi: ComponentConfig.getAllKeystoreInfos()) {
|
||||
if (ksi.isTrustStore()) {
|
||||
KeyStore ks = ksi.getKeyStore();
|
||||
if (ks != null) {
|
||||
tm.add(ks);
|
||||
} else {
|
||||
throw new IOException("Unable to load keystore: " + ksi.createResourceHandler().getFullLocation());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new TrustManager[] { tm };
|
||||
}
|
||||
|
||||
public static TrustManager[] getTrustAnyManagers() {
|
||||
return new TrustManager[] { new TrustAnyManager() };
|
||||
}
|
||||
|
||||
public static KeyManager[] getKeyManagers(KeyStore ks, String password, String alias) throws GeneralSecurityException {
|
||||
KeyManagerFactory factory = KeyManagerFactory.getInstance("SunX509");
|
||||
factory.init(ks, password.toCharArray());
|
||||
KeyManager[] keyManagers = factory.getKeyManagers();
|
||||
if (alias != null) {
|
||||
for (int i = 0; i < keyManagers.length; i++) {
|
||||
if (keyManagers[i] instanceof X509KeyManager) {
|
||||
keyManagers[i] = new AliasKeyManager((X509KeyManager)keyManagers[i], alias);
|
||||
}
|
||||
}
|
||||
}
|
||||
return keyManagers;
|
||||
}
|
||||
|
||||
public static TrustManager[] getTrustManagers(KeyStore ks) throws GeneralSecurityException {
|
||||
return new TrustManager[] { new MultiTrustManager(ks) };
|
||||
}
|
||||
|
||||
public static SSLSocketFactory getSSLSocketFactory(KeyStore ks, String password, String alias) throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
return getSSLContext(ks, password, alias, false).getSocketFactory();
|
||||
}
|
||||
|
||||
public static SSLContext getSSLContext(KeyStore ks, String password, String alias, boolean trustAny) throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
KeyManager[] km = SSLUtil.getKeyManagers(ks, password, alias);
|
||||
TrustManager[] tm;
|
||||
if (trustAny) {
|
||||
tm = SSLUtil.getTrustAnyManagers();
|
||||
} else {
|
||||
tm = SSLUtil.getTrustManagers();
|
||||
}
|
||||
|
||||
SSLContext context = SSLContext.getInstance("SSL");
|
||||
context.init(km, tm, new SecureRandom());
|
||||
return context;
|
||||
}
|
||||
|
||||
public static SSLSocketFactory getSSLSocketFactory(String alias, boolean trustAny) throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
return getSSLContext(alias, trustAny).getSocketFactory();
|
||||
}
|
||||
|
||||
public static SSLContext getSSLContext(String alias, boolean trustAny) throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
KeyManager[] km = SSLUtil.getKeyManagers(alias);
|
||||
TrustManager[] tm;
|
||||
if (trustAny) {
|
||||
tm = SSLUtil.getTrustAnyManagers();
|
||||
} else {
|
||||
tm = SSLUtil.getTrustManagers();
|
||||
}
|
||||
|
||||
SSLContext context = SSLContext.getInstance("SSL");
|
||||
context.init(km, tm, new SecureRandom());
|
||||
return context;
|
||||
}
|
||||
|
||||
public static SSLSocketFactory getSSLSocketFactory(String alias) throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
return getSSLSocketFactory(alias, false);
|
||||
}
|
||||
|
||||
public static SSLSocketFactory getSSLSocketFactory() throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
return getSSLSocketFactory(null);
|
||||
}
|
||||
|
||||
public static SSLServerSocketFactory getSSLServerSocketFactory(KeyStore ks, String password, String alias) throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
return getSSLContext(ks, password, alias, false).getServerSocketFactory();
|
||||
}
|
||||
|
||||
public static SSLServerSocketFactory getSSLServerSocketFactory(String alias) throws IOException, GeneralSecurityException, GenericConfigException {
|
||||
return getSSLContext(alias, false).getServerSocketFactory();
|
||||
}
|
||||
|
||||
public static HostnameVerifier getHostnameVerifier(int level) {
|
||||
switch (level) {
|
||||
case HOSTCERT_MIN_CHECK:
|
||||
return new HostnameVerifier() {
|
||||
public boolean verify(String hostname, SSLSession session) {
|
||||
javax.security.cert.X509Certificate[] peerCerts;
|
||||
try {
|
||||
peerCerts = session.getPeerCertificateChain();
|
||||
} catch (SSLPeerUnverifiedException e) {
|
||||
// cert not verified
|
||||
Debug.logWarning(e.getMessage(), module);
|
||||
return false;
|
||||
}
|
||||
for (javax.security.cert.X509Certificate peerCert: peerCerts) {
|
||||
Principal x500s = peerCert.getSubjectDN();
|
||||
Map<String, String> subjectMap = KeyStoreUtil.getX500Map(x500s);
|
||||
|
||||
if (Debug.infoOn())
|
||||
Debug.logInfo(peerCert.getSerialNumber().toString(16) + " :: " + subjectMap.get("CN"), module);
|
||||
|
||||
try {
|
||||
peerCert.checkValidity();
|
||||
} catch (Exception e) {
|
||||
// certificate not valid
|
||||
Debug.logWarning("Certificate is not valid!", module);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
case HOSTCERT_NO_CHECK:
|
||||
return new HostnameVerifier() {
|
||||
public boolean verify(String hostname, SSLSession session) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void loadJsseProperties() {
|
||||
loadJsseProperties(false);
|
||||
}
|
||||
|
||||
public static synchronized void loadJsseProperties(boolean debug) {
|
||||
if (!loadedProps) {
|
||||
String protocol = UtilProperties.getPropertyValue("jsse", "java.protocol.handler.pkgs", "NONE");
|
||||
String proxyHost = UtilProperties.getPropertyValue("jsse", "https.proxyHost", "NONE");
|
||||
String proxyPort = UtilProperties.getPropertyValue("jsse", "https.proxyPort", "NONE");
|
||||
String cypher = UtilProperties.getPropertyValue("jsse", "https.cipherSuites", "NONE");
|
||||
if (protocol != null && !protocol.equals("NONE")) {
|
||||
System.setProperty("java.protocol.handler.pkgs", protocol);
|
||||
}
|
||||
if (proxyHost != null && !proxyHost.equals("NONE")) {
|
||||
System.setProperty("https.proxyHost", proxyHost);
|
||||
}
|
||||
if (proxyPort != null && !proxyPort.equals("NONE")) {
|
||||
System.setProperty("https.proxyPort", proxyPort);
|
||||
}
|
||||
if (cypher != null && !cypher.equals("NONE")) {
|
||||
System.setProperty("https.cipherSuites", cypher);
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
System.setProperty("javax.net.debug","ssl:handshake");
|
||||
}
|
||||
loadedProps = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.script.ScriptException;
|
||||
|
||||
/**
|
||||
* A script helper object. The OFBiz scripting framework will include an instance of this class in the script's bindings.
|
||||
* <p>The scripting language will determine how the helper is used. Most languages will access it as a variable:<br />
|
||||
* <code>partyValue = ofbiz.findOne("Party");</code><br />
|
||||
* while other languages might access it as a native method or function:<br />
|
||||
* <code>partyValue = findOne("Party");</code></p>
|
||||
*/
|
||||
public interface ScriptHelper {
|
||||
|
||||
/**
|
||||
* Extracts service IN parameters from <code>inputMap</code> and returns them in a new <code>Map</code>.
|
||||
*
|
||||
* @param serviceName
|
||||
* @param inputMap
|
||||
* @return The matching service parameters
|
||||
* @throws ScriptException
|
||||
*/
|
||||
Map<String, ? extends Object> createServiceMap(String serviceName, Map<String, ? extends Object> inputMap) throws ScriptException;
|
||||
|
||||
/**
|
||||
* Sets the event/service status to error status.
|
||||
*
|
||||
* @param message
|
||||
*/
|
||||
void error(String message);
|
||||
|
||||
/**
|
||||
* Evaluates a <code>String</code> and returns the result.
|
||||
*
|
||||
* @param original
|
||||
* @return
|
||||
*/
|
||||
String evalString(String original);
|
||||
|
||||
/**
|
||||
* Sets the event/service status to failure status.
|
||||
*
|
||||
* @param message
|
||||
*/
|
||||
void failure(String message);
|
||||
|
||||
/**
|
||||
* Returns a <code>List</code> of <code>GenericValue</code>s.
|
||||
* @param entityName
|
||||
* @param fields
|
||||
* @return
|
||||
* @throws ScriptException
|
||||
*/
|
||||
List<Map<String, Object>> findList(String entityName, Map<String, ? extends Object> fields) throws ScriptException;
|
||||
|
||||
/**
|
||||
* Finds a <code>GenericValue</code> by primary key. The helper will construct a primary key from existing variables.
|
||||
* @param entityName
|
||||
* @return
|
||||
* @throws ScriptException
|
||||
*/
|
||||
Map<String, Object> findOne(String entityName) throws ScriptException;
|
||||
|
||||
/**
|
||||
* Finds a <code>GenericValue</code> by primary key. The helper will construct a primary key from existing variables
|
||||
* and/or <code>fields</code>.
|
||||
* @param entityName
|
||||
* @param fields
|
||||
* @param args
|
||||
* @return
|
||||
* @throws ScriptException
|
||||
*/
|
||||
Map<String, Object> findOne(String entityName, Map<String, ? extends Object> fields, Map<String, ? extends Object> args) throws ScriptException;
|
||||
|
||||
/**
|
||||
* Logs an error message.
|
||||
*
|
||||
* @param message
|
||||
*/
|
||||
void logError(String message);
|
||||
|
||||
/**
|
||||
* Logs an info message.
|
||||
*
|
||||
* @param message
|
||||
*/
|
||||
void logInfo(String message);
|
||||
|
||||
/**
|
||||
* Logs a warning message.
|
||||
*
|
||||
* @param message
|
||||
*/
|
||||
void logWarning(String message);
|
||||
|
||||
/**
|
||||
* Creates a new, empty <code>GenericValue</code>.
|
||||
* @param entityName
|
||||
* @return
|
||||
* @throws ScriptException
|
||||
*/
|
||||
Map<String, Object> makeValue(String entityName) throws ScriptException;
|
||||
|
||||
/**
|
||||
* Creates a new, empty <code>GenericValue</code>.
|
||||
*
|
||||
* @param entityName
|
||||
* @param fields
|
||||
* @return
|
||||
* @throws ScriptException
|
||||
*/
|
||||
Map<String, Object> makeValue(String entityName, Map<String, Object> fields) throws ScriptException;
|
||||
|
||||
/**
|
||||
* Runs a service synchronously.
|
||||
*
|
||||
* @param serviceName
|
||||
* @param inputMap
|
||||
* @return
|
||||
* @throws ScriptException
|
||||
*/
|
||||
Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap) throws ScriptException;
|
||||
|
||||
/**
|
||||
* Runs a service synchronously.
|
||||
*
|
||||
* @param serviceName
|
||||
* @param inputMap
|
||||
* @param args
|
||||
* @return
|
||||
* @throws ScriptException
|
||||
*/
|
||||
Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap, Map<String, ? extends Object> args) throws ScriptException;
|
||||
|
||||
/**
|
||||
* Sets the event/service status to success status.
|
||||
*/
|
||||
void success();
|
||||
|
||||
/**
|
||||
* Sets the event/service status to success status.
|
||||
*
|
||||
* @param message
|
||||
*/
|
||||
void success(String message);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import javax.script.ScriptContext;
|
||||
|
||||
import org.ofbiz.base.lang.Factory;
|
||||
|
||||
/**
|
||||
* A <code>ScriptHelper</code> factory.
|
||||
*/
|
||||
public interface ScriptHelperFactory extends Factory<ScriptHelper, ScriptContext> {
|
||||
|
||||
ScriptHelper getInstance(ScriptContext context);
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
/*******************************************************************************
|
||||
* 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.base.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URL;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.ServiceLoader;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.script.Bindings;
|
||||
import javax.script.Compilable;
|
||||
import javax.script.CompiledScript;
|
||||
import javax.script.Invocable;
|
||||
import javax.script.ScriptContext;
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptEngineFactory;
|
||||
import javax.script.ScriptEngineManager;
|
||||
import javax.script.ScriptException;
|
||||
import javax.script.SimpleBindings;
|
||||
import javax.script.SimpleScriptContext;
|
||||
|
||||
import org.codehaus.groovy.runtime.InvokerHelper;
|
||||
import org.ofbiz.base.location.FlexibleLocation;
|
||||
import org.ofbiz.base.util.cache.UtilCache;
|
||||
|
||||
/**
|
||||
* Scripting utility methods. This is a facade class that is used to connect OFBiz to JSR-223 scripting engines.
|
||||
* <p><b>Important:</b> To avoid a lot of <code>Map</code> copying, all methods that accept a context
|
||||
* <code>Map</code> argument will pass that <code>Map</code> directly to the scripting engine. Any variables that
|
||||
* are declared or modified in the script will affect the original <code>Map</code>. Client code that wishes to preserve
|
||||
* the state of the <code>Map</code> argument should pass a copy of the <code>Map</code>.</p>
|
||||
*
|
||||
*/
|
||||
public final class ScriptUtil {
|
||||
|
||||
public static final String module = ScriptUtil.class.getName();
|
||||
/** The screen widget context map bindings key. */
|
||||
public static final String WIDGET_CONTEXT_KEY = "widget";
|
||||
/** The service/servlet/request parameters map bindings key. */
|
||||
public static final String PARAMETERS_KEY = "parameters";
|
||||
/** The result map bindings key. */
|
||||
public static final String RESULT_KEY = "result";
|
||||
/** The <code>ScriptHelper</code> key. */
|
||||
public static final String SCRIPT_HELPER_KEY = "ofbiz";
|
||||
private static final UtilCache<String, CompiledScript> parsedScripts = UtilCache.createUtilCache("script.ParsedScripts", 0, 0, false);
|
||||
private static final Object[] EMPTY_ARGS = {};
|
||||
private static ScriptHelperFactory helperFactory = null;
|
||||
/** A set of script names - derived from the JSR-223 scripting engines. */
|
||||
public static final Set<String> SCRIPT_NAMES;
|
||||
|
||||
static {
|
||||
Set<String> writableScriptNames = new HashSet<String>();
|
||||
ScriptEngineManager manager = new ScriptEngineManager();
|
||||
List<ScriptEngineFactory> engines = manager.getEngineFactories();
|
||||
if (engines.isEmpty()) {
|
||||
Debug.logInfo("No scripting engines were found.", module);
|
||||
} else {
|
||||
Debug.logInfo("The following " + engines.size() + " scripting engines were found:", module);
|
||||
for (ScriptEngineFactory engine : engines) {
|
||||
Debug.logInfo("Engine name: " + engine.getEngineName(), module);
|
||||
Debug.logInfo(" Version: " + engine.getEngineVersion(), module);
|
||||
Debug.logInfo(" Language: " + engine.getLanguageName(), module);
|
||||
List<String> extensions = engine.getExtensions();
|
||||
if (extensions.size() > 0) {
|
||||
Debug.logInfo(" Engine supports the following extensions:", module);
|
||||
for (String e : extensions) {
|
||||
Debug.logInfo(" " + e, module);
|
||||
}
|
||||
}
|
||||
List<String> shortNames = engine.getNames();
|
||||
if (shortNames.size() > 0) {
|
||||
Debug.logInfo(" Engine has the following short names:", module);
|
||||
for (String name : engine.getNames()) {
|
||||
writableScriptNames.add(name);
|
||||
Debug.logInfo(" " + name, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SCRIPT_NAMES = Collections.unmodifiableSet(writableScriptNames);
|
||||
Iterator<ScriptHelperFactory> iter = ServiceLoader.load(ScriptHelperFactory.class).iterator();
|
||||
if (iter.hasNext()) {
|
||||
helperFactory = iter.next();
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("ScriptHelper factory set to " + helperFactory.getClass().getName(), module);
|
||||
}
|
||||
} else {
|
||||
Debug.logWarning("ScriptHelper factory not found", module);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a compiled script.
|
||||
*
|
||||
* @param filePath Script path and file name.
|
||||
* @return The compiled script, or <code>null</code> if the script engine does not support compilation.
|
||||
* @throws IllegalArgumentException
|
||||
* @throws ScriptException
|
||||
* @throws IOException
|
||||
*/
|
||||
public static CompiledScript compileScriptFile(String filePath) throws ScriptException, IOException {
|
||||
Assert.notNull("filePath", filePath);
|
||||
CompiledScript script = parsedScripts.get(filePath);
|
||||
if (script == null) {
|
||||
ScriptEngineManager manager = new ScriptEngineManager();
|
||||
ScriptEngine engine = manager.getEngineByExtension(getFileExtension(filePath));
|
||||
if (engine == null) {
|
||||
throw new IllegalArgumentException("The script type is not supported for location: " + filePath);
|
||||
}
|
||||
try {
|
||||
Compilable compilableEngine = (Compilable) engine;
|
||||
URL scriptUrl = FlexibleLocation.resolveLocation(filePath);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(scriptUrl.openStream()));
|
||||
script = compilableEngine.compile(reader);
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Compiled script " + filePath + " using engine " + engine.getClass().getName(), module);
|
||||
}
|
||||
} catch (ClassCastException e) {
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Script engine " + engine.getClass().getName() + " does not implement Compilable", module);
|
||||
}
|
||||
}
|
||||
if (script != null) {
|
||||
parsedScripts.putIfAbsent(filePath, script);
|
||||
}
|
||||
}
|
||||
return script;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a compiled script.
|
||||
*
|
||||
* @param language
|
||||
* @param script
|
||||
* @return The compiled script, or <code>null</code> if the script engine does not support compilation.
|
||||
* @throws IllegalArgumentException
|
||||
* @throws ScriptException
|
||||
*/
|
||||
public static CompiledScript compileScriptString(String language, String script) throws ScriptException {
|
||||
Assert.notNull("language", language, "script", script);
|
||||
String cacheKey = language.concat("://").concat(script);
|
||||
CompiledScript compiledScript = parsedScripts.get(cacheKey);
|
||||
if (compiledScript == null) {
|
||||
ScriptEngineManager manager = new ScriptEngineManager();
|
||||
ScriptEngine engine = manager.getEngineByName(language);
|
||||
if (engine == null) {
|
||||
throw new IllegalArgumentException("The script type is not supported for language: " + language);
|
||||
}
|
||||
try {
|
||||
Compilable compilableEngine = (Compilable) engine;
|
||||
compiledScript = compilableEngine.compile(script);
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Compiled script [" + script + "] using engine " + engine.getClass().getName(), module);
|
||||
}
|
||||
} catch (ClassCastException e) {
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Script engine " + engine.getClass().getName() + " does not implement Compilable", module);
|
||||
}
|
||||
}
|
||||
if (compiledScript != null) {
|
||||
parsedScripts.putIfAbsent(cacheKey, compiledScript);
|
||||
}
|
||||
}
|
||||
return compiledScript;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a <code>ScriptContext</code> that contains the members of <code>context</code>.
|
||||
* <p>If a <code>CompiledScript</code> instance is to be shared by multiple threads, then
|
||||
* each thread must create its own <code>ScriptContext</code> and pass it to the
|
||||
* <code>CompiledScript</code> eval method.</p>
|
||||
*
|
||||
* @param context
|
||||
* @return
|
||||
*/
|
||||
public static ScriptContext createScriptContext(Map<String, Object> context) {
|
||||
Assert.notNull("context", context);
|
||||
Map<String, Object> localContext = new HashMap<String, Object>(context);
|
||||
localContext.put(WIDGET_CONTEXT_KEY, context);
|
||||
localContext.put("context", context);
|
||||
ScriptContext scriptContext = new SimpleScriptContext();
|
||||
ScriptHelper helper = createScriptHelper(scriptContext);
|
||||
if (helper != null) {
|
||||
localContext.put(SCRIPT_HELPER_KEY, helper);
|
||||
}
|
||||
Bindings bindings = new SimpleBindings(localContext);
|
||||
scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
|
||||
return scriptContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a <code>ScriptContext</code> that contains the members of <code>context</code>.
|
||||
* <p>If a <code>CompiledScript</code> instance is to be shared by multiple threads, then
|
||||
* each thread must create its own <code>ScriptContext</code> and pass it to the
|
||||
* <code>CompiledScript</code> eval method.</p>
|
||||
*
|
||||
* @param context
|
||||
* @param protectedKeys
|
||||
* @return
|
||||
*/
|
||||
public static ScriptContext createScriptContext(Map<String, Object> context, Set<String> protectedKeys) {
|
||||
Assert.notNull("context", context, "protectedKeys", protectedKeys);
|
||||
Map<String, Object> localContext = new HashMap<String, Object>(context);
|
||||
localContext.put(WIDGET_CONTEXT_KEY, context);
|
||||
localContext.put("context", context);
|
||||
ScriptContext scriptContext = new SimpleScriptContext();
|
||||
Bindings bindings = new ProtectedBindings(localContext, Collections.unmodifiableSet(protectedKeys));
|
||||
scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
|
||||
ScriptHelper helper = createScriptHelper(scriptContext);
|
||||
if (helper != null) {
|
||||
localContext.put(SCRIPT_HELPER_KEY, helper);
|
||||
}
|
||||
return scriptContext;
|
||||
}
|
||||
|
||||
public static ScriptHelper createScriptHelper(ScriptContext context) {
|
||||
if (helperFactory != null) {
|
||||
return helperFactory.getInstance(context);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a script <code>String</code> and returns the result.
|
||||
*
|
||||
* @param language
|
||||
* @param script
|
||||
* @param scriptClass
|
||||
* @param context
|
||||
* @return The script result.
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Object evaluate(String language, String script, Class<?> scriptClass, Map<String, Object> context) throws Exception {
|
||||
Assert.notNull("context", context);
|
||||
if (scriptClass != null) {
|
||||
return InvokerHelper.createScript(scriptClass, GroovyUtil.getBinding(context)).run();
|
||||
}
|
||||
try {
|
||||
CompiledScript compiledScript = compileScriptString(language, script);
|
||||
if (compiledScript != null) {
|
||||
return executeScript(compiledScript, null, createScriptContext(context), null);
|
||||
}
|
||||
ScriptEngineManager manager = new ScriptEngineManager();
|
||||
ScriptEngine engine = manager.getEngineByName(language);
|
||||
if (engine == null) {
|
||||
throw new IllegalArgumentException("The script type is not supported for language: " + language);
|
||||
}
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Begin processing script [" + script + "] using engine " + engine.getClass().getName(), module);
|
||||
}
|
||||
ScriptContext scriptContext = createScriptContext(context);
|
||||
return engine.eval(script, scriptContext);
|
||||
} catch (Exception e) {
|
||||
String errMsg = "Error running " + language + " script [" + script + "]: " + e.toString();
|
||||
Debug.logWarning(e, errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a compiled script and returns the result.
|
||||
*
|
||||
* @param script Compiled script.
|
||||
* @param functionName Optional function or method to invoke.
|
||||
* @param scriptContext Script execution context.
|
||||
* @return The script result.
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
|
||||
Assert.notNull("script", script, "scriptContext", scriptContext);
|
||||
Object result = script.eval(scriptContext);
|
||||
if (UtilValidate.isNotEmpty(functionName)) {
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Invoking function/method " + functionName, module);
|
||||
}
|
||||
ScriptEngine engine = script.getEngine();
|
||||
try {
|
||||
Invocable invocableEngine = (Invocable) engine;
|
||||
result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
|
||||
} catch (ClassCastException e) {
|
||||
throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the script at the specified location and returns the result.
|
||||
*
|
||||
* @param filePath Script path and file name.
|
||||
* @param functionName Optional function or method to invoke.
|
||||
* @param context Script execution context.
|
||||
* @return The script result.
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static Object executeScript(String filePath, String functionName, Map<String, Object> context) {
|
||||
return executeScript(filePath, functionName, context, new Object[] { context });
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the script at the specified location and returns the result.
|
||||
*
|
||||
* @param filePath Script path and file name.
|
||||
* @param functionName Optional function or method to invoke.
|
||||
* @param context Script execution context.
|
||||
* @param args Function/method arguments.
|
||||
* @return The script result.
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static Object executeScript(String filePath, String functionName, Map<String, Object> context, Object[] args) {
|
||||
try {
|
||||
// Enabled to run Groovy data preparation scripts using GroovyUtil rather than the generic JSR223 that doesn't support debug mode
|
||||
// and does not return a stack trace with line number on error
|
||||
if (filePath.endsWith(".groovy")) {
|
||||
return GroovyUtil.runScriptAtLocation(filePath, functionName, context);
|
||||
}
|
||||
return executeScript(filePath, functionName, createScriptContext(context), args);
|
||||
} catch (Exception e) {
|
||||
String errMsg = "Error running script at location [" + filePath + "]: " + e.toString();
|
||||
Debug.logWarning(e, errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the script at the specified location and returns the result.
|
||||
*
|
||||
* @param filePath Script path and file name.
|
||||
* @param functionName Optional function or method to invoke.
|
||||
* @param scriptContext Script execution context.
|
||||
* @param args Function/method arguments.
|
||||
* @return The script result.
|
||||
* @throws ScriptException
|
||||
* @throws NoSuchMethodException
|
||||
* @throws IOException
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
public static Object executeScript(String filePath, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException, IOException {
|
||||
Assert.notNull("filePath", filePath, "scriptContext", scriptContext);
|
||||
scriptContext.setAttribute(ScriptEngine.FILENAME, filePath, ScriptContext.ENGINE_SCOPE);
|
||||
if (functionName == null) {
|
||||
// The Rhino script engine will not work when invoking a function on a compiled script.
|
||||
// The test for null can be removed when the engine is fixed.
|
||||
CompiledScript script = compileScriptFile(filePath);
|
||||
if (script != null) {
|
||||
return executeScript(script, functionName, scriptContext, args);
|
||||
}
|
||||
}
|
||||
String fileExtension = getFileExtension(filePath);
|
||||
ScriptEngineManager manager = new ScriptEngineManager();
|
||||
ScriptEngine engine = manager.getEngineByExtension(fileExtension);
|
||||
if (engine == null) {
|
||||
throw new IllegalArgumentException("The script type is not supported for location: " + filePath);
|
||||
}
|
||||
if (Debug.verboseOn()) {
|
||||
Debug.logVerbose("Begin processing script [" + filePath + "] using engine " + engine.getClass().getName(), module);
|
||||
}
|
||||
engine.setContext(scriptContext);
|
||||
URL scriptUrl = FlexibleLocation.resolveLocation(filePath);
|
||||
FileReader reader = new FileReader(new File(scriptUrl.getFile()));
|
||||
Object result = engine.eval(reader);
|
||||
if (UtilValidate.isNotEmpty(functionName)) {
|
||||
try {
|
||||
Invocable invocableEngine = (Invocable) engine;
|
||||
result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
|
||||
} catch (ClassCastException e) {
|
||||
throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String getFileExtension(String filePath) {
|
||||
int pos = filePath.lastIndexOf(".");
|
||||
if (pos == -1) {
|
||||
throw new IllegalArgumentException("Extension missing in script file name: " + filePath);
|
||||
}
|
||||
return filePath.substring(pos + 1);
|
||||
}
|
||||
|
||||
public static Class<?> parseScript(String language, String script) {
|
||||
Class<?> scriptClass = null;
|
||||
if ("groovy".equals(language)) {
|
||||
scriptClass = GroovyUtil.parseClass(script);
|
||||
}
|
||||
return scriptClass;
|
||||
}
|
||||
|
||||
private ScriptUtil() {}
|
||||
|
||||
private static final class ProtectedBindings implements Bindings {
|
||||
private final Map<String, Object> bindings;
|
||||
private final Set<String> protectedKeys;
|
||||
private ProtectedBindings(Map<String, Object> bindings, Set<String> protectedKeys) {
|
||||
this.bindings = bindings;
|
||||
this.protectedKeys = protectedKeys;
|
||||
}
|
||||
public void clear() {
|
||||
for (String key : bindings.keySet()) {
|
||||
if (!protectedKeys.contains(key)) {
|
||||
bindings.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
public boolean containsKey(Object key) {
|
||||
return bindings.containsKey(key);
|
||||
}
|
||||
public boolean containsValue(Object value) {
|
||||
return bindings.containsValue(value);
|
||||
}
|
||||
public Set<java.util.Map.Entry<String, Object>> entrySet() {
|
||||
return bindings.entrySet();
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return bindings.equals(o);
|
||||
}
|
||||
public Object get(Object key) {
|
||||
return bindings.get(key);
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return bindings.hashCode();
|
||||
}
|
||||
public boolean isEmpty() {
|
||||
return bindings.isEmpty();
|
||||
}
|
||||
public Set<String> keySet() {
|
||||
return bindings.keySet();
|
||||
}
|
||||
public Object put(String key, Object value) {
|
||||
Assert.notNull("key", key);
|
||||
if (protectedKeys.contains(key)) {
|
||||
UnsupportedOperationException e = new UnsupportedOperationException("Variable " + key + " is read-only");
|
||||
Debug.logWarning(e, module);
|
||||
throw e;
|
||||
}
|
||||
return bindings.put(key, value);
|
||||
}
|
||||
public void putAll(Map<? extends String, ? extends Object> map) {
|
||||
for (Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) {
|
||||
Assert.notNull("key", entry.getKey());
|
||||
if (!protectedKeys.contains(entry.getKey())) {
|
||||
bindings.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
public Object remove(Object key) {
|
||||
if (protectedKeys.contains(key)) {
|
||||
UnsupportedOperationException e = new UnsupportedOperationException("Variable " + key + " is read-only");
|
||||
Debug.logWarning(e, module);
|
||||
throw e;
|
||||
}
|
||||
return bindings.remove(key);
|
||||
}
|
||||
public int size() {
|
||||
return bindings.size();
|
||||
}
|
||||
public Collection<Object> values() {
|
||||
return bindings.values();
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user