From 067df90ae1b4e8265f1a1e4ae18c74fb3e95ff2f Mon Sep 17 00:00:00 2001 From: Jacques Le Roux Date: Mon, 10 Aug 2015 16:33:23 +0000 Subject: [PATCH] After r1695126, I found that most of the Java files have svn:eol-style=native. So only 116 Java files were missing svn:eol-style=native. I guess those have been added by committers who are not using the OFBiz svn config file on their machines. So rather than removing svn:eol-style=native, this commits add the property to the files which miss it. Here 116+89=205 files have their svn:eol-style property changed to native. git-svn-id: https://svn.apache.org/repos/asf/ofbiz/trunk@1695129 13f79535-47bb-0310-9956-ffa450edef68 --- .../authorizedotnet/AIMRespPositions.java | 106 +- .../authorizedotnet/CPRespPositions.java | 106 +- .../securepay/SecurePayPaymentServices.java | 1018 +- .../securepay/SecurePayServiceTest.java | 518 +- .../ftl/RenderContentAndSubContent.java | 280 +- .../webapp/ftl/RenderContentTransform.java | 322 +- .../marketing/MarketingServices.java | 232 +- .../requirement/RequirementServices.java | 664 +- .../product/inventory/InventoryWorker.java | 294 +- .../ofbiz/base/concurrent/ExecutionPool.java | 310 +- .../base/config/CoberturaInstrumenter.java | 188 +- .../JustLoadComponentsContainer.java | 116 +- .../conversion/GenericSingletonToList.java | 68 +- .../conversion/GenericSingletonToSet.java | 68 +- .../ofbiz/base/conversion/JSONConverters.java | 180 +- .../ofbiz/base/conversion/NetConverters.java | 274 +- .../base/conversion/test/DateTimeTests.java | 150 +- .../ofbiz/base/conversion/test/MiscTests.java | 206 +- .../base/src/org/ofbiz/base/lang/IsEmpty.java | 46 +- .../base/src/org/ofbiz/base/lang/JSON.java | 272 +- .../src/org/ofbiz/base/lang/LockedBy.java | 74 +- .../org/ofbiz/base/lang/SourceMonitored.java | 58 +- .../base/lang/test/ComparableRangeTests.java | 256 +- .../ofbiz/base/test/GenericTestCaseBase.java | 778 +- .../org/ofbiz/base/util/IndentingWriter.java | 264 +- .../base/util/RMIExtendedSocketFactory.java | 208 +- .../org/ofbiz/base/util/ReferenceCleaner.java | 178 +- .../base/src/org/ofbiz/base/util/UtilIO.java | 636 +- .../base/util/cache/test/UtilCacheTests.java | 872 +- .../base/util/collections/GenericMap.java | 506 +- .../collections/GenericMapCollection.java | 242 +- .../util/collections/GenericMapEntry.java | 120 +- .../util/collections/GenericMapEntrySet.java | 94 +- .../util/collections/GenericMapKeySet.java | 64 +- .../base/util/collections/GenericMapSet.java | 100 +- .../util/collections/GenericMapValues.java | 158 +- .../util/collections/IteratorWrapper.java | 150 +- .../base/util/collections/MapContext.java | 674 +- .../util/collections/ReadOnlyMapEntry.java | 122 +- .../test/FlexibleMapAccessorTests.java | 376 +- .../util/collections/test/GenericMapTest.java | 342 +- .../test/FlexibleStringExpanderTests.java | 680 +- .../base/util/test/IndentingWriterTests.java | 146 +- .../ofbiz/base/util/test/ObjectTypeTests.java | 976 +- .../base/util/test/ReferenceCleanerTests.java | 152 +- .../ofbiz/base/util/test/StringUtilTests.java | 654 +- .../org/ofbiz/base/util/test/UtilIOTests.java | 242 +- .../ofbiz/base/util/test/UtilMiscTests.java | 82 +- .../ofbiz/base/util/test/UtilObjectTests.java | 680 +- .../common/JsLanguageFileMappingCreator.java | 412 +- .../ofbiz/common/JsLanguageFilesMapping.java | 1404 +-- .../common/authentication/AuthHelper.java | 258 +- .../AuthenticationComparator.java | 152 +- .../authentication/api/Authenticator.java | 194 +- .../api/AuthenticatorException.java | 204 +- .../example/TestFailAuthenticator.java | 276 +- .../example/TestPassAuthenticator.java | 114 +- .../ofbiz/entity/util/EntityClassLoader.java | 424 +- .../minilang/method/callops/CallScript.java | 298 +- .../method/ifops/test/IfRegexpTest.java | 174 +- .../ofbiz/base/start/CommonsDaemonStart.java | 94 +- .../org/ofbiz/base/start/Instrumenter.java | 58 +- .../ofbiz/base/start/InstrumenterWorker.java | 384 +- .../base/start/InstrumentingClassLoader.java | 264 +- .../base/start/NativeLibClassLoader.java | 160 +- .../ofbiz/testtools/TestListContainer.java | 252 +- .../widget/artifact/ArtifactInfoContext.java | 286 +- .../widget/artifact/ArtifactInfoGatherer.java | 1210 +-- .../content/ContentWorkerInterface.java | 96 +- .../content/DataResourceWorkerInterface.java | 74 +- .../widget/content/WidgetContentWorker.java | 84 +- .../content/WidgetDataResourceWorker.java | 84 +- .../widget/model/AbstractModelAction.java | 1902 ++-- .../widget/model/AbstractModelCondition.java | 1654 ++-- .../widget/model/CommonWidgetModels.java | 1294 +-- .../src/org/ofbiz/widget/model/FieldInfo.java | 368 +- .../org/ofbiz/widget/model/FormFactory.java | 268 +- .../org/ofbiz/widget/model/GridFactory.java | 268 +- .../org/ofbiz/widget/model/HtmlWidget.java | 622 +- .../widget/model/IterateSectionWidget.java | 774 +- .../org/ofbiz/widget/model/MenuFactory.java | 220 +- .../org/ofbiz/widget/model/ModelAction.java | 72 +- .../widget/model/ModelActionVisitor.java | 118 +- .../ofbiz/widget/model/ModelCondition.java | 56 +- .../widget/model/ModelConditionFactory.java | 74 +- .../widget/model/ModelConditionVisitor.java | 138 +- .../ofbiz/widget/model/ModelFieldVisitor.java | 202 +- .../src/org/ofbiz/widget/model/ModelForm.java | 3640 +++---- .../ofbiz/widget/model/ModelFormAction.java | 544 +- .../ofbiz/widget/model/ModelFormField.java | 8538 ++++++++--------- .../widget/model/ModelFormFieldBuilder.java | 1938 ++-- .../src/org/ofbiz/widget/model/ModelGrid.java | 200 +- .../src/org/ofbiz/widget/model/ModelMenu.java | 1068 +-- .../ofbiz/widget/model/ModelMenuAction.java | 464 +- .../widget/model/ModelMenuCondition.java | 136 +- .../org/ofbiz/widget/model/ModelMenuItem.java | 1338 +-- .../org/ofbiz/widget/model/ModelScreen.java | 388 +- .../widget/model/ModelScreenCondition.java | 192 +- .../ofbiz/widget/model/ModelScreenWidget.java | 4092 ++++---- .../ofbiz/widget/model/ModelSingleForm.java | 198 +- .../src/org/ofbiz/widget/model/ModelTree.java | 2270 ++--- .../ofbiz/widget/model/ModelTreeAction.java | 920 +- .../widget/model/ModelTreeCondition.java | 78 +- .../org/ofbiz/widget/model/ModelWidget.java | 308 +- .../widget/model/ModelWidgetCondition.java | 1300 +-- .../widget/model/ModelWidgetVisitor.java | 184 +- .../org/ofbiz/widget/model/ScreenFactory.java | 426 +- .../org/ofbiz/widget/model/TreeFactory.java | 152 +- .../model/XmlAbstractWidgetVisitor.java | 330 +- .../widget/model/XmlWidgetActionVisitor.java | 420 +- .../model/XmlWidgetConditionVisitor.java | 356 +- .../widget/model/XmlWidgetFieldVisitor.java | 1004 +- .../ofbiz/widget/model/XmlWidgetVisitor.java | 1332 +-- .../ofbiz/widget/portal/PortalPageWorker.java | 354 +- .../portal/PortalPageWorkerInterface.java | 66 +- .../widget/portal/WidgetPortalPageWorker.java | 84 +- .../ofbiz/widget/renderer/FormRenderer.java | 2480 ++--- .../widget/renderer/FormStringRenderer.java | 200 +- .../widget/renderer/MenuStringRenderer.java | 82 +- .../widget/renderer/MenuWrapTransform.java | 402 +- .../org/ofbiz/widget/renderer/Paginator.java | 474 +- .../renderer/ScreenRenderException.java | 96 +- .../ofbiz/widget/renderer/ScreenRenderer.java | 646 +- .../widget/renderer/ScreenStringRenderer.java | 134 +- .../widget/renderer/TreeStringRenderer.java | 76 +- .../ofbiz/widget/renderer/UtilHelpText.java | 174 +- .../widget/renderer/fo/FoFormRenderer.java | 864 +- .../widget/renderer/fo/FoScreenRenderer.java | 390 +- .../renderer/fo/ScreenFopViewHandler.java | 372 +- .../renderer/html/HtmlFormRenderer.java | 5670 +++++------ .../widget/renderer/html/HtmlFormWrapper.java | 400 +- .../renderer/html/HtmlMenuRenderer.java | 1184 +-- .../renderer/html/HtmlMenuRendererImage.java | 160 +- .../widget/renderer/html/HtmlMenuWrapper.java | 504 +- .../renderer/html/HtmlMenuWrapperImage.java | 160 +- .../renderer/html/HtmlScreenRenderer.java | 1896 ++-- .../renderer/html/HtmlTreeRenderer.java | 684 +- .../renderer/html/HtmlWidgetRenderer.java | 198 +- .../renderer/macro/MacroFormRenderer.java | 6442 ++++++------- .../renderer/macro/MacroMenuRenderer.java | 736 +- .../renderer/macro/MacroScreenRenderer.java | 2104 ++-- .../macro/MacroScreenViewHandler.java | 346 +- .../renderer/macro/MacroTreeRenderer.java | 740 +- .../renderer/text/TextFormRenderer.java | 614 +- .../renderer/text/TextScreenRenderer.java | 306 +- .../widget/renderer/xml/XmlFormRenderer.java | 696 +- .../src/org/ofbiz/ebaystore/EbayAccount.java | 220 +- .../ebaystore/EbayBestOfferAutoPref.java | 406 +- .../src/org/ofbiz/ebaystore/EbayEvents.java | 2368 ++--- .../src/org/ofbiz/ebaystore/EbayFeedback.java | 780 +- .../src/org/ofbiz/ebaystore/EbayStore.java | 5894 ++++++------ .../ebaystore/EbayStoreAutoPrefEvents.java | 222 +- .../ebaystore/EbayStoreAutoPreferences.java | 2716 +++--- .../ebaystore/EbayStoreCategoryFacade.java | 690 +- .../ebaystore/EbayStoreCustomerService.java | 340 +- .../org/ofbiz/ebaystore/EbayStoreHelper.java | 1472 +-- .../ebaystore/EbayStoreInventoryServices.java | 812 +- .../org/ofbiz/ebaystore/EbayStoreOptions.java | 528 +- .../org/ofbiz/ebaystore/EbayStoreOrder.java | 1146 +-- .../ofbiz/ebaystore/EbayStoreSiteFacade.java | 476 +- .../ofbiz/pos/component/PromoStatusBar.java | 162 +- .../org/ofbiz/pos/screen/ClientProfile.java | 714 +- 162 files changed, 55392 insertions(+), 55392 deletions(-) diff --git a/applications/accounting/src/org/ofbiz/accounting/thirdparty/authorizedotnet/AIMRespPositions.java b/applications/accounting/src/org/ofbiz/accounting/thirdparty/authorizedotnet/AIMRespPositions.java index ac1d28c7ba..75c6f28ea6 100644 --- a/applications/accounting/src/org/ofbiz/accounting/thirdparty/authorizedotnet/AIMRespPositions.java +++ b/applications/accounting/src/org/ofbiz/accounting/thirdparty/authorizedotnet/AIMRespPositions.java @@ -1,53 +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.accounting.thirdparty.authorizedotnet; - -import java.util.LinkedHashMap; -import java.util.Map; - -public class AIMRespPositions extends AuthorizeResponse.RespPositions { - - // AIM v3.1 response positions - private static Map positions = new LinkedHashMap(); - static { - positions.put(AuthorizeResponse.RESPONSE_CODE, 1); - positions.put(AuthorizeResponse.REASON_CODE, 3); - positions.put(AuthorizeResponse.REASON_TEXT, 4); - positions.put(AuthorizeResponse.AUTHORIZATION_CODE, 5); - positions.put(AuthorizeResponse.AVS_RESULT_CODE, 6); - positions.put(AuthorizeResponse.CVV_RESULT_CODE, 39); - positions.put(AuthorizeResponse.TRANSACTION_ID, 7); - positions.put(AuthorizeResponse.AMOUNT, 10); - } - - @Override - public int getPosition(String name) { - if (positions.containsKey(name)) { - return positions.get(name); - } else { - return -1; - } - } - - @Override - public String getApprovalString() { - return "1"; - } -} +/******************************************************************************* + * 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.accounting.thirdparty.authorizedotnet; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class AIMRespPositions extends AuthorizeResponse.RespPositions { + + // AIM v3.1 response positions + private static Map positions = new LinkedHashMap(); + static { + positions.put(AuthorizeResponse.RESPONSE_CODE, 1); + positions.put(AuthorizeResponse.REASON_CODE, 3); + positions.put(AuthorizeResponse.REASON_TEXT, 4); + positions.put(AuthorizeResponse.AUTHORIZATION_CODE, 5); + positions.put(AuthorizeResponse.AVS_RESULT_CODE, 6); + positions.put(AuthorizeResponse.CVV_RESULT_CODE, 39); + positions.put(AuthorizeResponse.TRANSACTION_ID, 7); + positions.put(AuthorizeResponse.AMOUNT, 10); + } + + @Override + public int getPosition(String name) { + if (positions.containsKey(name)) { + return positions.get(name); + } else { + return -1; + } + } + + @Override + public String getApprovalString() { + return "1"; + } +} diff --git a/applications/accounting/src/org/ofbiz/accounting/thirdparty/authorizedotnet/CPRespPositions.java b/applications/accounting/src/org/ofbiz/accounting/thirdparty/authorizedotnet/CPRespPositions.java index 48e6cfd4ec..3f143ce2c4 100644 --- a/applications/accounting/src/org/ofbiz/accounting/thirdparty/authorizedotnet/CPRespPositions.java +++ b/applications/accounting/src/org/ofbiz/accounting/thirdparty/authorizedotnet/CPRespPositions.java @@ -1,53 +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.accounting.thirdparty.authorizedotnet; - -import java.util.LinkedHashMap; -import java.util.Map; - -public class CPRespPositions extends AuthorizeResponse.RespPositions { - - // Card-Present v1.0 response positions - private static Map positions = new LinkedHashMap(); - static { - positions.put(AuthorizeResponse.RESPONSE_CODE, 2); - positions.put(AuthorizeResponse.REASON_CODE, 3); - positions.put(AuthorizeResponse.REASON_TEXT, 4); - positions.put(AuthorizeResponse.AUTHORIZATION_CODE, 5); - positions.put(AuthorizeResponse.AVS_RESULT_CODE, 6); - positions.put(AuthorizeResponse.CVV_RESULT_CODE, 7); - positions.put(AuthorizeResponse.TRANSACTION_ID, 8); - positions.put(AuthorizeResponse.AMOUNT, 25); - } - - @Override - public int getPosition(String name) { - if (positions.containsKey(name)) { - return positions.get(name); - } else { - return -1; - } - } - - @Override - public String getApprovalString() { - return "1"; - } -} +/******************************************************************************* + * 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.accounting.thirdparty.authorizedotnet; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class CPRespPositions extends AuthorizeResponse.RespPositions { + + // Card-Present v1.0 response positions + private static Map positions = new LinkedHashMap(); + static { + positions.put(AuthorizeResponse.RESPONSE_CODE, 2); + positions.put(AuthorizeResponse.REASON_CODE, 3); + positions.put(AuthorizeResponse.REASON_TEXT, 4); + positions.put(AuthorizeResponse.AUTHORIZATION_CODE, 5); + positions.put(AuthorizeResponse.AVS_RESULT_CODE, 6); + positions.put(AuthorizeResponse.CVV_RESULT_CODE, 7); + positions.put(AuthorizeResponse.TRANSACTION_ID, 8); + positions.put(AuthorizeResponse.AMOUNT, 25); + } + + @Override + public int getPosition(String name) { + if (positions.containsKey(name)) { + return positions.get(name); + } else { + return -1; + } + } + + @Override + public String getApprovalString() { + return "1"; + } +} diff --git a/applications/accounting/src/org/ofbiz/accounting/thirdparty/securepay/SecurePayPaymentServices.java b/applications/accounting/src/org/ofbiz/accounting/thirdparty/securepay/SecurePayPaymentServices.java index f2d153ecec..93be9124f0 100644 --- a/applications/accounting/src/org/ofbiz/accounting/thirdparty/securepay/SecurePayPaymentServices.java +++ b/applications/accounting/src/org/ofbiz/accounting/thirdparty/securepay/SecurePayPaymentServices.java @@ -1,510 +1,510 @@ -/******************************************************************************* - * 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.accounting.thirdparty.securepay; - -import java.math.BigDecimal; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; - -import org.ofbiz.accounting.payment.PaymentGatewayServices; -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilProperties; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.entity.Delegator; -import org.ofbiz.entity.GenericEntityException; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.entity.util.EntityQuery; -import org.ofbiz.entity.util.EntityUtilProperties; -import org.ofbiz.service.DispatchContext; -import org.ofbiz.service.ServiceUtil; - -import securepay.jxa.api.Payment; -import securepay.jxa.api.Txn; - -public class SecurePayPaymentServices { - - public static final String module = SecurePayPaymentServices.class.getName(); - public final static String resource = "AccountingUiLabels"; - - public static Map doAuth(DispatchContext dctx, Map context) { - Locale locale = (Locale) context.get("locale"); - Delegator delegator = dctx.getDelegator(); - String orderId = (String) context.get("orderId"); - BigDecimal processAmount = (BigDecimal) context.get("processAmount"); - // generate the request/properties - Properties props = buildScProperties(context, delegator); - if (props == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingSecurityPayNotProperlyConfigurated", locale)); - } - - String merchantId = props.getProperty("merchantID"); - String serverURL = props.getProperty("serverurl"); - String processtimeout = props.getProperty("processtimeout"); - String pwd = props.getProperty("pwd"); - String enableamountround = props.getProperty("enableamountround"); - String currency = (String) context.get("currency"); - BigDecimal multiplyAmount = new BigDecimal(100); - BigDecimal newAmount = null; - int amont; - - if (enableamountround.equals("Y")) { - newAmount = new BigDecimal(processAmount.setScale(0, BigDecimal.ROUND_HALF_UP)+".00"); - } else { - newAmount = processAmount; - } - - if (currency.equals("JPY")) { - amont = newAmount.intValue(); - } else { - amont = newAmount.multiply(multiplyAmount).intValue(); - } - - GenericValue creditCard = (GenericValue) context.get("creditCard"); - String expiryDate = (String) creditCard.get("expireDate"); - String cardSecurityCode = (String) context.get("cardSecurityCode"); - Payment payment = new Payment(); - payment.setServerURL(serverURL); - payment.setProcessTimeout(Integer.valueOf(processtimeout)); - payment.setMerchantId(merchantId); - - Txn txn = payment.addTxn(10, orderId); - txn.setTxnSource(8); - txn.setAmount(Integer.toString(amont)); - if (UtilValidate.isNotEmpty(currency)) { - txn.setCurrencyCode(currency); - } else { - txn.setCurrencyCode("AUD"); - } - - txn.setCardNumber((String) creditCard.get("cardNumber")); - txn.setExpiryDate(expiryDate.substring(0, 3) + expiryDate.substring(5)); - if (UtilValidate.isNotEmpty(cardSecurityCode)) { - txn.setCVV(cardSecurityCode); - } - // Send payment to SecurePay for processing - boolean processed = payment.process(pwd); - - Map result = ServiceUtil.returnSuccess(); - if (UtilValidate.isEmpty(processed)) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingSecurityPayPaymentWasNotSent", locale)); - } else { - if (payment.getCount() == 1) { - Txn resp = payment.getTxn(0); - boolean approved = resp.getApproved(); - if (approved == false){ - result.put("authResult", new Boolean(false)); - result.put("authRefNum", "N/A"); - result.put("processAmount", BigDecimal.ZERO); - } else { - result.put("authRefNum", resp.getTxnId()); - result.put("authResult", new Boolean(true)); - result.put("processAmount", processAmount); - } - result.put("authCode", resp.getResponseCode()); - result.put("authMessage", resp.getResponseText()); - } - } - return result; - } - - public static Map ccReAuth(DispatchContext dctx, Map context) { - return ServiceUtil.returnSuccess(); - } - - public static Map doCapture(DispatchContext dctx, Map context) { - Locale locale = (Locale) context.get("locale"); - Delegator delegator = dctx.getDelegator(); - GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); - GenericValue authTransaction = (GenericValue) context.get("authTrans"); - if (authTransaction == null) { - authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference); - } - if (authTransaction == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingPaymentTransactionAuthorizationNotFoundCannotCapture", locale)); - } - - Properties props = buildScProperties(context, delegator); - if (props == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingSecurityPayNotProperlyConfigurated", locale)); - } - - String merchantId = props.getProperty("merchantID"); - String serverURL = props.getProperty("serverurl"); - String processtimeout = props.getProperty("processtimeout"); - String pwd = props.getProperty("pwd"); - String enableamountround = props.getProperty("enableamountround"); - String currency = authTransaction.getString("currencyUomId"); - BigDecimal captureAmount = (BigDecimal) context.get("captureAmount"); - BigDecimal multiplyAmount = new BigDecimal(100); - BigDecimal newAmount = null; - int amont; - - if (enableamountround.equals("Y")) { - newAmount = new BigDecimal(captureAmount.setScale(0, BigDecimal.ROUND_HALF_UP)+".00"); - } else { - newAmount = captureAmount; - } - - if (currency.equals("JPY")) { - amont = newAmount.intValue(); - } else { - amont = newAmount.multiply(multiplyAmount).intValue(); - } - - Payment payment = new Payment(); - payment.setServerURL(serverURL); - payment.setProcessTimeout(Integer.valueOf(processtimeout)); - payment.setMerchantId(merchantId); - Txn txn = payment.addTxn(11, (String) orderPaymentPreference.get("orderId")); - txn.setTxnSource(8); - txn.setAmount(Integer.toString(amont)); - txn.setPreauthId(authTransaction.getString("referenceNum")); - - // Send payment to SecurePay for processing - boolean processed = payment.process(pwd); - - Map result = ServiceUtil.returnSuccess(); - if (UtilValidate.isEmpty(processed)) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingSecurityPayPaymentWasNotSent", locale)); - } else { - if (payment.getCount() == 1){ - Txn resp = payment.getTxn(0); - boolean approved = resp.getApproved(); - if (approved == false){ - result.put("captureResult", false); - result.put("captureRefNum", authTransaction.getString("referenceNum")); - result.put("captureAmount", BigDecimal.ZERO); - } else { - result.put("captureResult", true); - result.put("captureAmount", captureAmount); - result.put("captureRefNum", resp.getTxnId()); - } - result.put("captureFlag", "C"); - result.put("captureCode", resp.getResponseCode()); - result.put("captureMessage", resp.getResponseText()); - } - } - return result; - } - - public static Map doVoid(DispatchContext dctx, Map context) { - Locale locale = (Locale) context.get("locale"); - Delegator delegator = dctx.getDelegator(); - GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); - GenericValue authTransaction = (GenericValue) context.get("authTrans"); - if (authTransaction == null) { - authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference); - } - if (authTransaction == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingPaymentTransactionAuthorizationNotFoundCannotRelease", locale)); - } - - Properties props = buildScProperties(context, delegator); - if (props == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingSecurityPayNotProperlyConfigurated", locale)); - } - - String merchantId = props.getProperty("merchantID"); - String serverURL = props.getProperty("serverurl"); - String processtimeout = props.getProperty("processtimeout"); - String pwd = props.getProperty("pwd"); - String enableamountround = props.getProperty("enableamountround"); - String currency = authTransaction.getString("currencyUomId"); - BigDecimal releaseAmount = (BigDecimal) context.get("releaseAmount"); - BigDecimal multiplyAmount = new BigDecimal(100); - BigDecimal newAmount = null; - int amont; - - if (enableamountround.equals("Y")) { - newAmount = new BigDecimal(releaseAmount.setScale(0, BigDecimal.ROUND_HALF_UP)+".00"); - } else { - newAmount = releaseAmount; - } - - if (currency.equals("JPY")) { - amont = newAmount.intValue(); - } else { - amont = newAmount.multiply(multiplyAmount).intValue(); - } - - Payment payment = new Payment(); - payment.setServerURL(serverURL); - payment.setProcessTimeout(Integer.valueOf(processtimeout)); - payment.setMerchantId(merchantId); - Txn txn = payment.addTxn(6, (String) orderPaymentPreference.get("orderId")); - txn.setTxnSource(8); - txn.setAmount(Integer.toString(amont)); - txn.setTxnId(authTransaction.getString("referenceNum")); - - // Send payment to SecurePay for processing - boolean processed = payment.process(pwd); - - Map result = ServiceUtil.returnSuccess(); - if (UtilValidate.isEmpty(processed)) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingSecurityPayPaymentWasNotSent", locale)); - } else { - if (payment.getCount() == 1){ - Txn resp = payment.getTxn(0); - boolean approved = resp.getApproved(); - if (approved == false){ - result.put("releaseResult", false); - result.put("releaseRefNum", authTransaction.getString("referenceNum")); - result.put("releaseAmount", BigDecimal.ZERO); - } else { - result.put("releaseResult", true); - result.put("releaseAmount", releaseAmount); - result.put("releaseRefNum", resp.getTxnId()); - } - result.put("releaseFlag", "U"); - result.put("releaseCode", resp.getResponseCode()); - result.put("releaseMessage", resp.getResponseText()); - } - } - return result; - } - - public static Map doRefund(DispatchContext dctx, Map context) { - Locale locale = (Locale) context.get("locale"); - Delegator delegator = dctx.getDelegator(); - GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); - GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference); - if (authTransaction == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingPaymentTransactionAuthorizationNotFoundCannotRefund", locale)); - } - - String referenceNum = null; - try { - GenericValue paymentGatewayResponse = EntityQuery.use(delegator).from("PaymentGatewayResponse") - .where("orderPaymentPreferenceId", authTransaction.get("orderPaymentPreferenceId"), - "paymentServiceTypeEnumId", "PRDS_PAY_CAPTURE") - .queryFirst(); - referenceNum = paymentGatewayResponse != null ? paymentGatewayResponse.get("referenceNum") : authTransaction.getString("referenceNum"); - } catch (GenericEntityException e) { - e.printStackTrace(); - } - - Properties props = buildScProperties(context, delegator); - if (props == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingSecurityPayNotProperlyConfigurated", locale)); - } - - String merchantId = props.getProperty("merchantID"); - String serverURL = props.getProperty("serverurl"); - String processtimeout = props.getProperty("processtimeout"); - String pwd = props.getProperty("pwd"); - String enableamountround = props.getProperty("enableamountround"); - String currency = authTransaction.getString("currencyUomId"); - BigDecimal refundAmount = (BigDecimal) context.get("refundAmount"); - BigDecimal multiplyAmount = new BigDecimal(100); - BigDecimal newAmount = null; - - if (enableamountround.equals("Y")) { - newAmount = new BigDecimal(refundAmount.setScale(0, BigDecimal.ROUND_HALF_UP)+".00"); - } else { - newAmount = refundAmount; - } - - int amont; - if (currency.equals("JPY")) { - amont = newAmount.intValue(); - } else { - amont = newAmount.multiply(multiplyAmount).intValue(); - } - - Payment payment = new Payment(); - payment.setServerURL(serverURL); - payment.setProcessTimeout(Integer.valueOf(processtimeout)); - payment.setMerchantId(merchantId); - Txn txn = payment.addTxn(4, (String) orderPaymentPreference.get("orderId")); - txn.setTxnSource(8); - txn.setAmount(Integer.toString(amont)); - txn.setTxnId(referenceNum); - - // Send payment to SecurePay for processing - boolean processed = payment.process(pwd); - - Map result = ServiceUtil.returnSuccess(); - if (UtilValidate.isEmpty(processed)) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingSecurityPayPaymentWasNotSent", locale)); - } else { - if (payment.getCount() == 1){ - Txn resp = payment.getTxn(0); - boolean approved = resp.getApproved(); - if (approved == false){ - result.put("refundResult", false); - result.put("refundRefNum", authTransaction.getString("referenceNum")); - result.put("refundAmount", BigDecimal.ZERO); - } else { - result.put("refundResult", true); - result.put("refundAmount", refundAmount); - result.put("refundRefNum", resp.getTxnId()); - } - result.put("refundCode", resp.getResponseCode()); - result.put("refundMessage", resp.getResponseText()); - result.put("refundFlag", "R"); - } - } - return result; - } - - public static Map doCredit(DispatchContext dctx, Map context) { - Locale locale = (Locale) context.get("locale"); - Delegator delegator = dctx.getDelegator(); - // generate the request/properties - Properties props = buildScProperties(context, delegator); - if (props == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingSecurityPayNotProperlyConfigurated", locale)); - } - - String merchantId = props.getProperty("merchantID"); - String serverURL = props.getProperty("serverurl"); - String processtimeout = props.getProperty("processtimeout"); - String pwd = props.getProperty("pwd"); - String enableamountround = props.getProperty("enableamountround"); - String referenceCode = (String) context.get("referenceCode"); - String currency = (String) context.get("currency"); - String cardSecurityCode = (String) context.get("cardSecurityCode"); - BigDecimal creditAmount = (BigDecimal) context.get("creditAmount"); - BigDecimal multiplyAmount = new BigDecimal(100); - BigDecimal newAmount = null; - int amont; - - if (enableamountround.equals("Y")) { - newAmount = new BigDecimal(creditAmount.setScale(0, BigDecimal.ROUND_HALF_UP)+".00"); - } else { - newAmount = creditAmount; - } - - if (currency.equals("JPY")) { - amont = newAmount.intValue(); - } else { - amont = newAmount.multiply(multiplyAmount).intValue(); - } - - GenericValue creditCard = (GenericValue) context.get("creditCard"); - Payment payment = new Payment(); - payment.setServerURL(serverURL); - payment.setProcessTimeout(Integer.valueOf(processtimeout)); - payment.setMerchantId(merchantId); - - Txn txn = payment.addTxn(0, referenceCode); - txn.setTxnSource(8); - txn.setAmount(Integer.toString(amont)); - txn.setCardNumber((String) creditCard.get("cardNumber")); - String expiryDate = (String) creditCard.get("expireDate"); - txn.setExpiryDate(expiryDate.substring(0, 3) + expiryDate.substring(5)); - if (UtilValidate.isNotEmpty(cardSecurityCode)) { - txn.setCVV(cardSecurityCode); - } - - // Send payment to SecurePay for processing - boolean processed = payment.process(pwd); - - Map result = ServiceUtil.returnSuccess(); - if (UtilValidate.isEmpty(processed)) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, - "AccountingSecurityPayPaymentWasNotSent", locale)); - } else { - if (payment.getCount() == 1) { - Txn resp = payment.getTxn(0); - boolean approved = resp.getApproved(); - if (approved == false){ - result.put("creditResult", false); - result.put("creditRefNum", "N/A"); - result.put("creditAmount", BigDecimal.ZERO); - } else { - result.put("creditResult", true); - result.put("creditAmount", creditAmount); - result.put("creditRefNum", resp.getTxnId()); - } - result.put("creditCode", resp.getResponseCode()); - result.put("creditMessage", resp.getResponseText()); - } - } - return result; - } - - private static Properties buildScProperties(Map context, Delegator delegator) { - String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId"); - String configString = (String) context.get("paymentConfig"); - if (configString == null) { - configString = "payment.properties"; - } - - String merchantId = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "merchantId", configString, "payment.securepay.merchantID", null); - String pwd = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "pwd", configString, "payment.securepay.pwd", null); - String serverURL = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "serverURL", configString, "payment.securepay.serverurl", null); - String processTimeout = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "processTimeout", configString, "payment.securepay.processtimeout", null); - String enableAmountRound = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableAmountRound", configString, "payment.securepay.enableamountround", null); - - Properties props = new Properties(); - props.put("merchantID", merchantId); - props.put("pwd", pwd); - props.put("serverurl", serverURL); - props.put("processtimeout", processTimeout); - props.put("enableamountround", enableAmountRound); - return props; - } - - private static String getPaymentGatewayConfigValue(Delegator delegator, String paymentGatewayConfigId, String paymentGatewayConfigParameterName,String resource, String parameterName) { - String returnValue = ""; - if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) { - try { - GenericValue securePay = EntityQuery.use(delegator).from("PaymentGatewaySecurePay").where("paymentGatewayConfigId", paymentGatewayConfigId).queryOne(); - if (UtilValidate.isNotEmpty(securePay)) { - Object securePayField = securePay.get(paymentGatewayConfigParameterName); - if (securePayField != null) { - returnValue = securePayField.toString().trim(); - } - } - } catch (GenericEntityException e) { - Debug.logError(e, module); - } - } else { - String value = EntityUtilProperties.getPropertyValue(resource, parameterName, delegator); - if (value != null) { - returnValue = value.trim(); - } - } - return returnValue; - } - - private static String getPaymentGatewayConfigValue(Delegator delegator, String paymentGatewayConfigId, String paymentGatewayConfigParameterName,String resource, String parameterName, String defaultValue) { - String returnValue = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, paymentGatewayConfigParameterName, resource, parameterName); - if (UtilValidate.isEmpty(returnValue)) { - returnValue = defaultValue; - } - return returnValue; - } +/******************************************************************************* + * 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.accounting.thirdparty.securepay; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; + +import org.ofbiz.accounting.payment.PaymentGatewayServices; +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilProperties; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.Delegator; +import org.ofbiz.entity.GenericEntityException; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.entity.util.EntityQuery; +import org.ofbiz.entity.util.EntityUtilProperties; +import org.ofbiz.service.DispatchContext; +import org.ofbiz.service.ServiceUtil; + +import securepay.jxa.api.Payment; +import securepay.jxa.api.Txn; + +public class SecurePayPaymentServices { + + public static final String module = SecurePayPaymentServices.class.getName(); + public final static String resource = "AccountingUiLabels"; + + public static Map doAuth(DispatchContext dctx, Map context) { + Locale locale = (Locale) context.get("locale"); + Delegator delegator = dctx.getDelegator(); + String orderId = (String) context.get("orderId"); + BigDecimal processAmount = (BigDecimal) context.get("processAmount"); + // generate the request/properties + Properties props = buildScProperties(context, delegator); + if (props == null) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingSecurityPayNotProperlyConfigurated", locale)); + } + + String merchantId = props.getProperty("merchantID"); + String serverURL = props.getProperty("serverurl"); + String processtimeout = props.getProperty("processtimeout"); + String pwd = props.getProperty("pwd"); + String enableamountround = props.getProperty("enableamountround"); + String currency = (String) context.get("currency"); + BigDecimal multiplyAmount = new BigDecimal(100); + BigDecimal newAmount = null; + int amont; + + if (enableamountround.equals("Y")) { + newAmount = new BigDecimal(processAmount.setScale(0, BigDecimal.ROUND_HALF_UP)+".00"); + } else { + newAmount = processAmount; + } + + if (currency.equals("JPY")) { + amont = newAmount.intValue(); + } else { + amont = newAmount.multiply(multiplyAmount).intValue(); + } + + GenericValue creditCard = (GenericValue) context.get("creditCard"); + String expiryDate = (String) creditCard.get("expireDate"); + String cardSecurityCode = (String) context.get("cardSecurityCode"); + Payment payment = new Payment(); + payment.setServerURL(serverURL); + payment.setProcessTimeout(Integer.valueOf(processtimeout)); + payment.setMerchantId(merchantId); + + Txn txn = payment.addTxn(10, orderId); + txn.setTxnSource(8); + txn.setAmount(Integer.toString(amont)); + if (UtilValidate.isNotEmpty(currency)) { + txn.setCurrencyCode(currency); + } else { + txn.setCurrencyCode("AUD"); + } + + txn.setCardNumber((String) creditCard.get("cardNumber")); + txn.setExpiryDate(expiryDate.substring(0, 3) + expiryDate.substring(5)); + if (UtilValidate.isNotEmpty(cardSecurityCode)) { + txn.setCVV(cardSecurityCode); + } + // Send payment to SecurePay for processing + boolean processed = payment.process(pwd); + + Map result = ServiceUtil.returnSuccess(); + if (UtilValidate.isEmpty(processed)) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingSecurityPayPaymentWasNotSent", locale)); + } else { + if (payment.getCount() == 1) { + Txn resp = payment.getTxn(0); + boolean approved = resp.getApproved(); + if (approved == false){ + result.put("authResult", new Boolean(false)); + result.put("authRefNum", "N/A"); + result.put("processAmount", BigDecimal.ZERO); + } else { + result.put("authRefNum", resp.getTxnId()); + result.put("authResult", new Boolean(true)); + result.put("processAmount", processAmount); + } + result.put("authCode", resp.getResponseCode()); + result.put("authMessage", resp.getResponseText()); + } + } + return result; + } + + public static Map ccReAuth(DispatchContext dctx, Map context) { + return ServiceUtil.returnSuccess(); + } + + public static Map doCapture(DispatchContext dctx, Map context) { + Locale locale = (Locale) context.get("locale"); + Delegator delegator = dctx.getDelegator(); + GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); + GenericValue authTransaction = (GenericValue) context.get("authTrans"); + if (authTransaction == null) { + authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference); + } + if (authTransaction == null) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingPaymentTransactionAuthorizationNotFoundCannotCapture", locale)); + } + + Properties props = buildScProperties(context, delegator); + if (props == null) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingSecurityPayNotProperlyConfigurated", locale)); + } + + String merchantId = props.getProperty("merchantID"); + String serverURL = props.getProperty("serverurl"); + String processtimeout = props.getProperty("processtimeout"); + String pwd = props.getProperty("pwd"); + String enableamountround = props.getProperty("enableamountround"); + String currency = authTransaction.getString("currencyUomId"); + BigDecimal captureAmount = (BigDecimal) context.get("captureAmount"); + BigDecimal multiplyAmount = new BigDecimal(100); + BigDecimal newAmount = null; + int amont; + + if (enableamountround.equals("Y")) { + newAmount = new BigDecimal(captureAmount.setScale(0, BigDecimal.ROUND_HALF_UP)+".00"); + } else { + newAmount = captureAmount; + } + + if (currency.equals("JPY")) { + amont = newAmount.intValue(); + } else { + amont = newAmount.multiply(multiplyAmount).intValue(); + } + + Payment payment = new Payment(); + payment.setServerURL(serverURL); + payment.setProcessTimeout(Integer.valueOf(processtimeout)); + payment.setMerchantId(merchantId); + Txn txn = payment.addTxn(11, (String) orderPaymentPreference.get("orderId")); + txn.setTxnSource(8); + txn.setAmount(Integer.toString(amont)); + txn.setPreauthId(authTransaction.getString("referenceNum")); + + // Send payment to SecurePay for processing + boolean processed = payment.process(pwd); + + Map result = ServiceUtil.returnSuccess(); + if (UtilValidate.isEmpty(processed)) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingSecurityPayPaymentWasNotSent", locale)); + } else { + if (payment.getCount() == 1){ + Txn resp = payment.getTxn(0); + boolean approved = resp.getApproved(); + if (approved == false){ + result.put("captureResult", false); + result.put("captureRefNum", authTransaction.getString("referenceNum")); + result.put("captureAmount", BigDecimal.ZERO); + } else { + result.put("captureResult", true); + result.put("captureAmount", captureAmount); + result.put("captureRefNum", resp.getTxnId()); + } + result.put("captureFlag", "C"); + result.put("captureCode", resp.getResponseCode()); + result.put("captureMessage", resp.getResponseText()); + } + } + return result; + } + + public static Map doVoid(DispatchContext dctx, Map context) { + Locale locale = (Locale) context.get("locale"); + Delegator delegator = dctx.getDelegator(); + GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); + GenericValue authTransaction = (GenericValue) context.get("authTrans"); + if (authTransaction == null) { + authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference); + } + if (authTransaction == null) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingPaymentTransactionAuthorizationNotFoundCannotRelease", locale)); + } + + Properties props = buildScProperties(context, delegator); + if (props == null) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingSecurityPayNotProperlyConfigurated", locale)); + } + + String merchantId = props.getProperty("merchantID"); + String serverURL = props.getProperty("serverurl"); + String processtimeout = props.getProperty("processtimeout"); + String pwd = props.getProperty("pwd"); + String enableamountround = props.getProperty("enableamountround"); + String currency = authTransaction.getString("currencyUomId"); + BigDecimal releaseAmount = (BigDecimal) context.get("releaseAmount"); + BigDecimal multiplyAmount = new BigDecimal(100); + BigDecimal newAmount = null; + int amont; + + if (enableamountround.equals("Y")) { + newAmount = new BigDecimal(releaseAmount.setScale(0, BigDecimal.ROUND_HALF_UP)+".00"); + } else { + newAmount = releaseAmount; + } + + if (currency.equals("JPY")) { + amont = newAmount.intValue(); + } else { + amont = newAmount.multiply(multiplyAmount).intValue(); + } + + Payment payment = new Payment(); + payment.setServerURL(serverURL); + payment.setProcessTimeout(Integer.valueOf(processtimeout)); + payment.setMerchantId(merchantId); + Txn txn = payment.addTxn(6, (String) orderPaymentPreference.get("orderId")); + txn.setTxnSource(8); + txn.setAmount(Integer.toString(amont)); + txn.setTxnId(authTransaction.getString("referenceNum")); + + // Send payment to SecurePay for processing + boolean processed = payment.process(pwd); + + Map result = ServiceUtil.returnSuccess(); + if (UtilValidate.isEmpty(processed)) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingSecurityPayPaymentWasNotSent", locale)); + } else { + if (payment.getCount() == 1){ + Txn resp = payment.getTxn(0); + boolean approved = resp.getApproved(); + if (approved == false){ + result.put("releaseResult", false); + result.put("releaseRefNum", authTransaction.getString("referenceNum")); + result.put("releaseAmount", BigDecimal.ZERO); + } else { + result.put("releaseResult", true); + result.put("releaseAmount", releaseAmount); + result.put("releaseRefNum", resp.getTxnId()); + } + result.put("releaseFlag", "U"); + result.put("releaseCode", resp.getResponseCode()); + result.put("releaseMessage", resp.getResponseText()); + } + } + return result; + } + + public static Map doRefund(DispatchContext dctx, Map context) { + Locale locale = (Locale) context.get("locale"); + Delegator delegator = dctx.getDelegator(); + GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); + GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference); + if (authTransaction == null) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingPaymentTransactionAuthorizationNotFoundCannotRefund", locale)); + } + + String referenceNum = null; + try { + GenericValue paymentGatewayResponse = EntityQuery.use(delegator).from("PaymentGatewayResponse") + .where("orderPaymentPreferenceId", authTransaction.get("orderPaymentPreferenceId"), + "paymentServiceTypeEnumId", "PRDS_PAY_CAPTURE") + .queryFirst(); + referenceNum = paymentGatewayResponse != null ? paymentGatewayResponse.get("referenceNum") : authTransaction.getString("referenceNum"); + } catch (GenericEntityException e) { + e.printStackTrace(); + } + + Properties props = buildScProperties(context, delegator); + if (props == null) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingSecurityPayNotProperlyConfigurated", locale)); + } + + String merchantId = props.getProperty("merchantID"); + String serverURL = props.getProperty("serverurl"); + String processtimeout = props.getProperty("processtimeout"); + String pwd = props.getProperty("pwd"); + String enableamountround = props.getProperty("enableamountround"); + String currency = authTransaction.getString("currencyUomId"); + BigDecimal refundAmount = (BigDecimal) context.get("refundAmount"); + BigDecimal multiplyAmount = new BigDecimal(100); + BigDecimal newAmount = null; + + if (enableamountround.equals("Y")) { + newAmount = new BigDecimal(refundAmount.setScale(0, BigDecimal.ROUND_HALF_UP)+".00"); + } else { + newAmount = refundAmount; + } + + int amont; + if (currency.equals("JPY")) { + amont = newAmount.intValue(); + } else { + amont = newAmount.multiply(multiplyAmount).intValue(); + } + + Payment payment = new Payment(); + payment.setServerURL(serverURL); + payment.setProcessTimeout(Integer.valueOf(processtimeout)); + payment.setMerchantId(merchantId); + Txn txn = payment.addTxn(4, (String) orderPaymentPreference.get("orderId")); + txn.setTxnSource(8); + txn.setAmount(Integer.toString(amont)); + txn.setTxnId(referenceNum); + + // Send payment to SecurePay for processing + boolean processed = payment.process(pwd); + + Map result = ServiceUtil.returnSuccess(); + if (UtilValidate.isEmpty(processed)) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingSecurityPayPaymentWasNotSent", locale)); + } else { + if (payment.getCount() == 1){ + Txn resp = payment.getTxn(0); + boolean approved = resp.getApproved(); + if (approved == false){ + result.put("refundResult", false); + result.put("refundRefNum", authTransaction.getString("referenceNum")); + result.put("refundAmount", BigDecimal.ZERO); + } else { + result.put("refundResult", true); + result.put("refundAmount", refundAmount); + result.put("refundRefNum", resp.getTxnId()); + } + result.put("refundCode", resp.getResponseCode()); + result.put("refundMessage", resp.getResponseText()); + result.put("refundFlag", "R"); + } + } + return result; + } + + public static Map doCredit(DispatchContext dctx, Map context) { + Locale locale = (Locale) context.get("locale"); + Delegator delegator = dctx.getDelegator(); + // generate the request/properties + Properties props = buildScProperties(context, delegator); + if (props == null) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingSecurityPayNotProperlyConfigurated", locale)); + } + + String merchantId = props.getProperty("merchantID"); + String serverURL = props.getProperty("serverurl"); + String processtimeout = props.getProperty("processtimeout"); + String pwd = props.getProperty("pwd"); + String enableamountround = props.getProperty("enableamountround"); + String referenceCode = (String) context.get("referenceCode"); + String currency = (String) context.get("currency"); + String cardSecurityCode = (String) context.get("cardSecurityCode"); + BigDecimal creditAmount = (BigDecimal) context.get("creditAmount"); + BigDecimal multiplyAmount = new BigDecimal(100); + BigDecimal newAmount = null; + int amont; + + if (enableamountround.equals("Y")) { + newAmount = new BigDecimal(creditAmount.setScale(0, BigDecimal.ROUND_HALF_UP)+".00"); + } else { + newAmount = creditAmount; + } + + if (currency.equals("JPY")) { + amont = newAmount.intValue(); + } else { + amont = newAmount.multiply(multiplyAmount).intValue(); + } + + GenericValue creditCard = (GenericValue) context.get("creditCard"); + Payment payment = new Payment(); + payment.setServerURL(serverURL); + payment.setProcessTimeout(Integer.valueOf(processtimeout)); + payment.setMerchantId(merchantId); + + Txn txn = payment.addTxn(0, referenceCode); + txn.setTxnSource(8); + txn.setAmount(Integer.toString(amont)); + txn.setCardNumber((String) creditCard.get("cardNumber")); + String expiryDate = (String) creditCard.get("expireDate"); + txn.setExpiryDate(expiryDate.substring(0, 3) + expiryDate.substring(5)); + if (UtilValidate.isNotEmpty(cardSecurityCode)) { + txn.setCVV(cardSecurityCode); + } + + // Send payment to SecurePay for processing + boolean processed = payment.process(pwd); + + Map result = ServiceUtil.returnSuccess(); + if (UtilValidate.isEmpty(processed)) { + return ServiceUtil.returnError(UtilProperties.getMessage(resource, + "AccountingSecurityPayPaymentWasNotSent", locale)); + } else { + if (payment.getCount() == 1) { + Txn resp = payment.getTxn(0); + boolean approved = resp.getApproved(); + if (approved == false){ + result.put("creditResult", false); + result.put("creditRefNum", "N/A"); + result.put("creditAmount", BigDecimal.ZERO); + } else { + result.put("creditResult", true); + result.put("creditAmount", creditAmount); + result.put("creditRefNum", resp.getTxnId()); + } + result.put("creditCode", resp.getResponseCode()); + result.put("creditMessage", resp.getResponseText()); + } + } + return result; + } + + private static Properties buildScProperties(Map context, Delegator delegator) { + String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId"); + String configString = (String) context.get("paymentConfig"); + if (configString == null) { + configString = "payment.properties"; + } + + String merchantId = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "merchantId", configString, "payment.securepay.merchantID", null); + String pwd = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "pwd", configString, "payment.securepay.pwd", null); + String serverURL = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "serverURL", configString, "payment.securepay.serverurl", null); + String processTimeout = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "processTimeout", configString, "payment.securepay.processtimeout", null); + String enableAmountRound = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableAmountRound", configString, "payment.securepay.enableamountround", null); + + Properties props = new Properties(); + props.put("merchantID", merchantId); + props.put("pwd", pwd); + props.put("serverurl", serverURL); + props.put("processtimeout", processTimeout); + props.put("enableamountround", enableAmountRound); + return props; + } + + private static String getPaymentGatewayConfigValue(Delegator delegator, String paymentGatewayConfigId, String paymentGatewayConfigParameterName,String resource, String parameterName) { + String returnValue = ""; + if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) { + try { + GenericValue securePay = EntityQuery.use(delegator).from("PaymentGatewaySecurePay").where("paymentGatewayConfigId", paymentGatewayConfigId).queryOne(); + if (UtilValidate.isNotEmpty(securePay)) { + Object securePayField = securePay.get(paymentGatewayConfigParameterName); + if (securePayField != null) { + returnValue = securePayField.toString().trim(); + } + } + } catch (GenericEntityException e) { + Debug.logError(e, module); + } + } else { + String value = EntityUtilProperties.getPropertyValue(resource, parameterName, delegator); + if (value != null) { + returnValue = value.trim(); + } + } + return returnValue; + } + + private static String getPaymentGatewayConfigValue(Delegator delegator, String paymentGatewayConfigId, String paymentGatewayConfigParameterName,String resource, String parameterName, String defaultValue) { + String returnValue = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, paymentGatewayConfigParameterName, resource, parameterName); + if (UtilValidate.isEmpty(returnValue)) { + returnValue = defaultValue; + } + return returnValue; + } } \ No newline at end of file diff --git a/applications/accounting/src/org/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java b/applications/accounting/src/org/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java index da13a2b41e..c438fa7e23 100644 --- a/applications/accounting/src/org/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java +++ b/applications/accounting/src/org/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java @@ -1,259 +1,259 @@ -/******************************************************************************* - * 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.accounting.thirdparty.securepay; - -import java.math.BigDecimal; -import java.util.List; -import java.util.Map; - -import junit.framework.TestCase; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.service.GenericServiceException; -import org.ofbiz.service.ModelService; -import org.ofbiz.service.testtools.OFBizTestCase; - -public class SecurePayServiceTest extends OFBizTestCase{ - - public SecurePayServiceTest(String name) { - super(name); - } - - public static final String module = SecurePayServiceTest.class.getName(); - - // test data - protected GenericValue emailAddr = null; - protected String orderId = null; - protected GenericValue creditCard = null; - protected GenericValue billingAddress = null; - protected GenericValue shippingAddress = null; - protected BigDecimal creditAmount = null; - protected String configFile = null; - protected GenericValue orderPaymentPreference = null; - protected List orderItems = null; - protected Map orderItemMap = null; - protected GenericValue billToParty = null; - protected String paymentGatewayConfigId = null; - protected BigDecimal refundAmount = null; - protected GenericValue paymentGatewayResponse = null; - protected String releaseRefNum = null; - - @Override - protected void setUp() throws Exception { - // populate test data - configFile = "paymentTest.properties"; - creditAmount = new BigDecimal("234.51"); - emailAddr = delegator.makeValue("ContactMech", UtilMisc.toMap( - "infoString","test@hansbakker.com")); - orderId = "Demo1002"; - creditCard = delegator.makeValue("CreditCard", UtilMisc.toMap( - "cardType","CCT_VISA", - "expireDate","10/2011", // mm/yyyy, gets converted to mm/yy - "cardNumber","4444333322221111")); - billingAddress = delegator.makeValue("PostalAddress", UtilMisc.toMap( - "toName","The customer Name", - "address1","The customer billingAddress1", - "address2","The customer billingAddress2", - "city","The customer city", - "stateProvinceGeoId", "NLD")); - shippingAddress = delegator.makeValue("PostalAddress", UtilMisc.toMap( - "toName","The customer Name", - "address1","The customer shippingStreet1", - "address2","The customer shippingStreet2", - "city","The customer city", - "stateProvinceGeoId", "NLD", - "postalCode","12345")); - orderItemMap = UtilMisc.toMap( - "orderId", "Demo1002", - "orderItemSeqId", "00001", - "orderItemTypeId", "PRODUCT_ORDER_ITEM", - "productId", "GZ-1000", - "prodCatalogId", "DemoCatalog", - "quantity" , new BigDecimal("2.000000"), - "unitPrice", new BigDecimal("59.00"), - "statusId" ,"ITEM_COMPLETED" - ); - orderItems = UtilMisc.toList(orderItemMap); - billToParty = delegator.makeValue("Party" , UtilMisc.toMap("partyId", "DemoCustomer")); - paymentGatewayConfigId = "SECUREPAY_CONFIG"; - refundAmount = new BigDecimal("100.08"); - orderPaymentPreference = delegator.makeValue("OrderPaymentPreference", UtilMisc.toMap( - "orderPaymentPreferenceId", "testOrder1000_01", - "orderId", "Demo1002", - "paymentMethodTypeId", "CREDIT_CARD", - "maxAmount", new BigDecimal("200.00"), - "statusId", "PAYMENT_AUTHORIZED")); - - GenericValue checkOrderPaymentPreference = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderPaymentPreferenceId", "testOrder1000_01").queryOne(); - if (UtilValidate.isEmpty(checkOrderPaymentPreference)) { - orderPaymentPreference.create(); - } - } - - public void testAuth() throws Exception{ - Debug.logInfo("=====[testAuth] starting....", module); - try { - Map serviceInput = UtilMisc.toMap( - "paymentConfig", configFile, - "billToParty", billToParty, - "billToEmail", emailAddr, - "orderPaymentPreference", orderPaymentPreference, - "orderItems", orderItems, - "creditCard", creditCard, - "billingAddress", billingAddress, - "shippingAddress", shippingAddress, - "orderId", orderId, - "currency", "AUD" - ); - serviceInput.put("processAmount", new BigDecimal("100.08")); - - // run the service - Map result = dispatcher.runSync("ofbScAuthorize",serviceInput); - - // verify the results - String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); - Debug.logInfo("[testCCAuth] responseMessage: " + responseMessage, module); - TestCase.assertEquals("Service result is success", ModelService.RESPOND_SUCCESS, responseMessage); - - if (((Boolean) result.get("authResult")).equals(new Boolean(false))) { // returnCode ok? - Debug.logInfo("[testAuth] Error Messages from SecurePay: " + result.get("internalRespMsgs"), module); - TestCase.fail("Returned messages:" + result.get("internalRespMsgs")); - } else { - Debug.logInfo("[testAuth] Result from SecurePay: " + result, module); - String authRefNum = (String) result.get("authRefNum"); - BigDecimal processAmount = (BigDecimal) result.get("processAmount"); - paymentGatewayResponse = delegator.makeValue("PaymentGatewayResponse" , UtilMisc.toMap( - "paymentGatewayResponseId", "testOrder1000_01", - "orderPaymentPreferenceId", "testOrder1000_01", - "amount" , processAmount, - "referenceNum", authRefNum, - "paymentMethodTypeId", "CREDIT_CARD", - "paymentServiceTypeEnumId", "PRDS_PAY_AUTH", - "currencyUomId", "AUD" - )); - GenericValue checkPaymentGatewayResponse = EntityQuery.use(delegator).from("PaymentGatewayResponse").where("paymentGatewayResponseId", "testOrder1000_01").queryOne(); - if (UtilValidate.isEmpty(checkPaymentGatewayResponse)) { - paymentGatewayResponse.create(); - } - } - } catch (GenericServiceException ex) { - TestCase.fail(ex.getMessage()); - } - } - - public void testdoCapture() throws Exception { - Debug.logInfo("=====[testdoCapture] starting....", module); - GenericValue paymentGatewayResponse = EntityQuery.use(delegator).from("PaymentGatewayResponse").where("paymentGatewayResponseId", "testOrder1000_01").queryOne(); - try { - Map serviceInput = UtilMisc.toMap( - "paymentConfig", configFile, - "orderPaymentPreference", orderPaymentPreference, - "authTrans", paymentGatewayResponse - ); - serviceInput.put("captureAmount", refundAmount); - - // run the service - Map result = dispatcher.runSync("ofbScCapture",serviceInput); - - // verify the results - String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); - Debug.logInfo("[testdoCapture] responseMessage: " + responseMessage, module); - TestCase.assertEquals("Service result is success", ModelService.RESPOND_SUCCESS, responseMessage); - - if (((Boolean) result.get("captureResult")).equals(new Boolean(false))) { // returnCode ok? - Debug.logInfo("[testdoCapture] Error Messages from SecurePay: " + result.get("internalRespMsgs"), module); - TestCase.fail("Returned messages:" + result.get("internalRespMsgs")); - } else { - String captureRefNum = (String) result.get("captureRefNum"); - GenericValue checkPaymentGatewayResponse = EntityQuery.use(delegator).from("PaymentGatewayResponse").where("paymentGatewayResponseId", "testOrder1000_01").queryOne(); - checkPaymentGatewayResponse.set("referenceNum", captureRefNum); - checkPaymentGatewayResponse.store(); - Debug.logInfo("[testdoCapture] Result from SecurePay: " + result, module); - } - - } catch (GenericServiceException ex) { - TestCase.fail(ex.getMessage()); - } - } - - public void testdoRefund() throws Exception { - Debug.logInfo("=====[testdoRefund] starting....", module); - try { - Map serviceInput = UtilMisc.toMap( - "paymentConfig", configFile, - "orderPaymentPreference", orderPaymentPreference - ); - serviceInput.put("refundAmount", refundAmount); - // run the service - Map result = dispatcher.runSync("ofbScRefund", serviceInput); - - // verify the results - String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); - Debug.logInfo("[testdoRefund] responseMessage: " + responseMessage, module); - TestCase.assertEquals("Service result is success", ModelService.RESPOND_SUCCESS, responseMessage); - - if (((Boolean) result.get("refundResult")).equals(new Boolean(false))) { // returnCode ok? - Debug.logInfo("[testdoRefund] Error Messages from SecurePay: " + result.get("internalRespMsgs"), module); - TestCase.fail("Returned messages:" + result.get("internalRespMsgs")); - } else { - Debug.logInfo("[testdoRefund] Result from SecurePay: " + result, module); - } - - } catch (GenericServiceException ex) { - TestCase.fail(ex.getMessage()); - } - } - - public void testdoCredit() throws Exception{ - Debug.logInfo("=====[testdoCredit] starting....", module); - try { - Map serviceInput = UtilMisc.toMap( - "paymentConfig", configFile, - "billToParty", billToParty, - "billToEmail", emailAddr, - "orderItems", orderItems, - "creditCard", creditCard, - "billingAddress", billingAddress, - "referenceCode", orderId, - "currency", "AUD" - ); - serviceInput.put("creditAmount", creditAmount); - // run the service - Map result = dispatcher.runSync("ofbScCCCredit",serviceInput); - // verify the results - String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); - Debug.logInfo("[testdoCredit] responseMessage: " + responseMessage, module); - TestCase.assertEquals("Service result is success", ModelService.RESPOND_SUCCESS, responseMessage); - - if (((Boolean) result.get("creditResult")).equals(new Boolean(false))) { // returnCode ok? - Debug.logInfo("[testdoCredit] Error Messages from SecurePay: " + result.get("internalRespMsgs"), module); - TestCase.fail("Returned messages:" + result.get("internalRespMsgs")); - } else { - Debug.logInfo("[testdoCredit] Result from SecurePay: " + result, module); - } - - } catch (GenericServiceException ex) { - TestCase.fail(ex.getMessage()); - } - } -} +/******************************************************************************* + * 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.accounting.thirdparty.securepay; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.service.GenericServiceException; +import org.ofbiz.service.ModelService; +import org.ofbiz.service.testtools.OFBizTestCase; + +public class SecurePayServiceTest extends OFBizTestCase{ + + public SecurePayServiceTest(String name) { + super(name); + } + + public static final String module = SecurePayServiceTest.class.getName(); + + // test data + protected GenericValue emailAddr = null; + protected String orderId = null; + protected GenericValue creditCard = null; + protected GenericValue billingAddress = null; + protected GenericValue shippingAddress = null; + protected BigDecimal creditAmount = null; + protected String configFile = null; + protected GenericValue orderPaymentPreference = null; + protected List orderItems = null; + protected Map orderItemMap = null; + protected GenericValue billToParty = null; + protected String paymentGatewayConfigId = null; + protected BigDecimal refundAmount = null; + protected GenericValue paymentGatewayResponse = null; + protected String releaseRefNum = null; + + @Override + protected void setUp() throws Exception { + // populate test data + configFile = "paymentTest.properties"; + creditAmount = new BigDecimal("234.51"); + emailAddr = delegator.makeValue("ContactMech", UtilMisc.toMap( + "infoString","test@hansbakker.com")); + orderId = "Demo1002"; + creditCard = delegator.makeValue("CreditCard", UtilMisc.toMap( + "cardType","CCT_VISA", + "expireDate","10/2011", // mm/yyyy, gets converted to mm/yy + "cardNumber","4444333322221111")); + billingAddress = delegator.makeValue("PostalAddress", UtilMisc.toMap( + "toName","The customer Name", + "address1","The customer billingAddress1", + "address2","The customer billingAddress2", + "city","The customer city", + "stateProvinceGeoId", "NLD")); + shippingAddress = delegator.makeValue("PostalAddress", UtilMisc.toMap( + "toName","The customer Name", + "address1","The customer shippingStreet1", + "address2","The customer shippingStreet2", + "city","The customer city", + "stateProvinceGeoId", "NLD", + "postalCode","12345")); + orderItemMap = UtilMisc.toMap( + "orderId", "Demo1002", + "orderItemSeqId", "00001", + "orderItemTypeId", "PRODUCT_ORDER_ITEM", + "productId", "GZ-1000", + "prodCatalogId", "DemoCatalog", + "quantity" , new BigDecimal("2.000000"), + "unitPrice", new BigDecimal("59.00"), + "statusId" ,"ITEM_COMPLETED" + ); + orderItems = UtilMisc.toList(orderItemMap); + billToParty = delegator.makeValue("Party" , UtilMisc.toMap("partyId", "DemoCustomer")); + paymentGatewayConfigId = "SECUREPAY_CONFIG"; + refundAmount = new BigDecimal("100.08"); + orderPaymentPreference = delegator.makeValue("OrderPaymentPreference", UtilMisc.toMap( + "orderPaymentPreferenceId", "testOrder1000_01", + "orderId", "Demo1002", + "paymentMethodTypeId", "CREDIT_CARD", + "maxAmount", new BigDecimal("200.00"), + "statusId", "PAYMENT_AUTHORIZED")); + + GenericValue checkOrderPaymentPreference = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderPaymentPreferenceId", "testOrder1000_01").queryOne(); + if (UtilValidate.isEmpty(checkOrderPaymentPreference)) { + orderPaymentPreference.create(); + } + } + + public void testAuth() throws Exception{ + Debug.logInfo("=====[testAuth] starting....", module); + try { + Map serviceInput = UtilMisc.toMap( + "paymentConfig", configFile, + "billToParty", billToParty, + "billToEmail", emailAddr, + "orderPaymentPreference", orderPaymentPreference, + "orderItems", orderItems, + "creditCard", creditCard, + "billingAddress", billingAddress, + "shippingAddress", shippingAddress, + "orderId", orderId, + "currency", "AUD" + ); + serviceInput.put("processAmount", new BigDecimal("100.08")); + + // run the service + Map result = dispatcher.runSync("ofbScAuthorize",serviceInput); + + // verify the results + String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); + Debug.logInfo("[testCCAuth] responseMessage: " + responseMessage, module); + TestCase.assertEquals("Service result is success", ModelService.RESPOND_SUCCESS, responseMessage); + + if (((Boolean) result.get("authResult")).equals(new Boolean(false))) { // returnCode ok? + Debug.logInfo("[testAuth] Error Messages from SecurePay: " + result.get("internalRespMsgs"), module); + TestCase.fail("Returned messages:" + result.get("internalRespMsgs")); + } else { + Debug.logInfo("[testAuth] Result from SecurePay: " + result, module); + String authRefNum = (String) result.get("authRefNum"); + BigDecimal processAmount = (BigDecimal) result.get("processAmount"); + paymentGatewayResponse = delegator.makeValue("PaymentGatewayResponse" , UtilMisc.toMap( + "paymentGatewayResponseId", "testOrder1000_01", + "orderPaymentPreferenceId", "testOrder1000_01", + "amount" , processAmount, + "referenceNum", authRefNum, + "paymentMethodTypeId", "CREDIT_CARD", + "paymentServiceTypeEnumId", "PRDS_PAY_AUTH", + "currencyUomId", "AUD" + )); + GenericValue checkPaymentGatewayResponse = EntityQuery.use(delegator).from("PaymentGatewayResponse").where("paymentGatewayResponseId", "testOrder1000_01").queryOne(); + if (UtilValidate.isEmpty(checkPaymentGatewayResponse)) { + paymentGatewayResponse.create(); + } + } + } catch (GenericServiceException ex) { + TestCase.fail(ex.getMessage()); + } + } + + public void testdoCapture() throws Exception { + Debug.logInfo("=====[testdoCapture] starting....", module); + GenericValue paymentGatewayResponse = EntityQuery.use(delegator).from("PaymentGatewayResponse").where("paymentGatewayResponseId", "testOrder1000_01").queryOne(); + try { + Map serviceInput = UtilMisc.toMap( + "paymentConfig", configFile, + "orderPaymentPreference", orderPaymentPreference, + "authTrans", paymentGatewayResponse + ); + serviceInput.put("captureAmount", refundAmount); + + // run the service + Map result = dispatcher.runSync("ofbScCapture",serviceInput); + + // verify the results + String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); + Debug.logInfo("[testdoCapture] responseMessage: " + responseMessage, module); + TestCase.assertEquals("Service result is success", ModelService.RESPOND_SUCCESS, responseMessage); + + if (((Boolean) result.get("captureResult")).equals(new Boolean(false))) { // returnCode ok? + Debug.logInfo("[testdoCapture] Error Messages from SecurePay: " + result.get("internalRespMsgs"), module); + TestCase.fail("Returned messages:" + result.get("internalRespMsgs")); + } else { + String captureRefNum = (String) result.get("captureRefNum"); + GenericValue checkPaymentGatewayResponse = EntityQuery.use(delegator).from("PaymentGatewayResponse").where("paymentGatewayResponseId", "testOrder1000_01").queryOne(); + checkPaymentGatewayResponse.set("referenceNum", captureRefNum); + checkPaymentGatewayResponse.store(); + Debug.logInfo("[testdoCapture] Result from SecurePay: " + result, module); + } + + } catch (GenericServiceException ex) { + TestCase.fail(ex.getMessage()); + } + } + + public void testdoRefund() throws Exception { + Debug.logInfo("=====[testdoRefund] starting....", module); + try { + Map serviceInput = UtilMisc.toMap( + "paymentConfig", configFile, + "orderPaymentPreference", orderPaymentPreference + ); + serviceInput.put("refundAmount", refundAmount); + // run the service + Map result = dispatcher.runSync("ofbScRefund", serviceInput); + + // verify the results + String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); + Debug.logInfo("[testdoRefund] responseMessage: " + responseMessage, module); + TestCase.assertEquals("Service result is success", ModelService.RESPOND_SUCCESS, responseMessage); + + if (((Boolean) result.get("refundResult")).equals(new Boolean(false))) { // returnCode ok? + Debug.logInfo("[testdoRefund] Error Messages from SecurePay: " + result.get("internalRespMsgs"), module); + TestCase.fail("Returned messages:" + result.get("internalRespMsgs")); + } else { + Debug.logInfo("[testdoRefund] Result from SecurePay: " + result, module); + } + + } catch (GenericServiceException ex) { + TestCase.fail(ex.getMessage()); + } + } + + public void testdoCredit() throws Exception{ + Debug.logInfo("=====[testdoCredit] starting....", module); + try { + Map serviceInput = UtilMisc.toMap( + "paymentConfig", configFile, + "billToParty", billToParty, + "billToEmail", emailAddr, + "orderItems", orderItems, + "creditCard", creditCard, + "billingAddress", billingAddress, + "referenceCode", orderId, + "currency", "AUD" + ); + serviceInput.put("creditAmount", creditAmount); + // run the service + Map result = dispatcher.runSync("ofbScCCCredit",serviceInput); + // verify the results + String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); + Debug.logInfo("[testdoCredit] responseMessage: " + responseMessage, module); + TestCase.assertEquals("Service result is success", ModelService.RESPOND_SUCCESS, responseMessage); + + if (((Boolean) result.get("creditResult")).equals(new Boolean(false))) { // returnCode ok? + Debug.logInfo("[testdoCredit] Error Messages from SecurePay: " + result.get("internalRespMsgs"), module); + TestCase.fail("Returned messages:" + result.get("internalRespMsgs")); + } else { + Debug.logInfo("[testdoCredit] Result from SecurePay: " + result, module); + } + + } catch (GenericServiceException ex) { + TestCase.fail(ex.getMessage()); + } + } +} diff --git a/applications/content/src/org/ofbiz/content/webapp/ftl/RenderContentAndSubContent.java b/applications/content/src/org/ofbiz/content/webapp/ftl/RenderContentAndSubContent.java index e533892ef1..574d58cfc7 100644 --- a/applications/content/src/org/ofbiz/content/webapp/ftl/RenderContentAndSubContent.java +++ b/applications/content/src/org/ofbiz/content/webapp/ftl/RenderContentAndSubContent.java @@ -1,140 +1,140 @@ -/******************************************************************************* - * 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.content.webapp.ftl; - -import java.io.IOException; -import java.io.Writer; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.GeneralException; -import org.ofbiz.base.util.UtilHttp; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.base.util.collections.MapStack; -import org.ofbiz.base.util.template.FreeMarkerWorker; -import org.ofbiz.content.content.ContentWorker; -import org.ofbiz.entity.Delegator; -import org.ofbiz.service.LocalDispatcher; - -import freemarker.core.Environment; -import freemarker.template.TemplateTransformModel; - -/** - * RenderContentAndSubContent - Freemarker Transform for Content rendering - * This transform cannot be called recursively (at this time). - */ -public class RenderContentAndSubContent implements TemplateTransformModel { - - public static final String module = RenderContentAndSubContent.class.getName(); -// public static final String [] upSaveKeyNames = {"globalNodeTrail"}; -// public static final String [] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; - - @SuppressWarnings("unchecked") - public Writer getWriter(final Writer out, Map args) { - final Environment env = Environment.getCurrentEnvironment(); - final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env); - final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env); - final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env); - // final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env); - final Map envMap = FreeMarkerWorker.createEnvironmentMap(env); - final MapStack templateRoot = MapStack.create(); - ((MapStack)templateRoot).push(envMap); - if (Debug.verboseOn()) Debug.logVerbose("in RenderContentAndSubContent, contentId(0):" + templateRoot.get("contentId"), module); - FreeMarkerWorker.getSiteParameters(request, templateRoot); - // final Map savedValuesUp = new HashMap(); - // FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp); - FreeMarkerWorker.overrideWithArgs(templateRoot, args); - - // final Map savedValues = new HashMap(); - - return new Writer(out) { - - @Override - public void write(char cbuf[], int off, int len) { - } - - @Override - public void flush() throws IOException { - out.flush(); - } - - @Override - public void close() throws IOException { - renderSubContent(); - //if (Debug.verboseOn()) Debug.logVerbose("in Render(2), globalNodeTrail ." + getWrapped(env, "globalNodeTrail") , module); - } - - public void renderSubContent() throws IOException { - String mimeTypeId = (String) templateRoot.get("mimeTypeId"); - Object localeObject = templateRoot.get("locale"); - Locale locale = null; - if (localeObject == null) { - locale = UtilHttp.getLocale(request); - } else { - locale = UtilMisc.ensureLocale(localeObject); - } - - if (Debug.verboseOn()) Debug.logVerbose("in RenderContentAndSubContent, contentId(2):" + templateRoot.get("contentId"), module); - if (Debug.verboseOn()) Debug.logVerbose("in RenderContentAndSubContent, subContentId(2):" + templateRoot.get("subContentId"), module); - //if (thisView != null) { - try { - String contentId = (String)templateRoot.get("contentId"); - String mapKey = (String)templateRoot.get("mapKey"); - String contentAssocTypeId = (String)templateRoot.get("contentAssocTypeId"); - if (UtilValidate.isNotEmpty(mapKey) || UtilValidate.isNotEmpty(contentAssocTypeId)) { - String txt = ContentWorker.renderSubContentAsText(dispatcher, delegator, contentId, mapKey, templateRoot, locale, mimeTypeId, true); - //String txt = ContentWorker.renderSubContentAsTextCache(delegator, thisContentId, thisMapKey, null, templateRoot, locale, mimeTypeId, null, fromDate); -// if ("true".equals(xmlEscape)) { -// txt = UtilFormatOut.encodeXmlValue(txt); -// } - - out.write(txt); - -// if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, after renderContentAsTextCache:", module); -// List assocList = null; -// if (UtilValidate.isNotEmpty(contentAssocTypeId)) { -// assocList = UtilMisc.toList(contentAssocTypeId); -// } -// GenericValue content = ContentWorker.getSubContent(delegator, contentId, mapKey, null, null, assocList, null); -// if (content != null) { -// contentId = content.getString("contentId"); -// } else { -// contentId = null; -// } - } else if (contentId != null) { - ContentWorker.renderContentAsText(dispatcher, delegator, contentId, out, templateRoot, locale, mimeTypeId, null, null, true); -// ((MapStack)templateRoot).pop(); - } - //FreeMarkerWorker.reloadValues(templateRoot, savedValues, env); - //FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env); - - } catch (GeneralException e) { - String errMsg = "Error rendering thisContentId:" + (String)templateRoot.get("contentId") + " msg:" + e.toString(); - Debug.logError(e, errMsg, module); - // just log a message and don't return anything: throw new IOException(); - } - } - - }; - } -} +/******************************************************************************* + * 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.content.webapp.ftl; + +import java.io.IOException; +import java.io.Writer; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.GeneralException; +import org.ofbiz.base.util.UtilHttp; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.base.util.collections.MapStack; +import org.ofbiz.base.util.template.FreeMarkerWorker; +import org.ofbiz.content.content.ContentWorker; +import org.ofbiz.entity.Delegator; +import org.ofbiz.service.LocalDispatcher; + +import freemarker.core.Environment; +import freemarker.template.TemplateTransformModel; + +/** + * RenderContentAndSubContent - Freemarker Transform for Content rendering + * This transform cannot be called recursively (at this time). + */ +public class RenderContentAndSubContent implements TemplateTransformModel { + + public static final String module = RenderContentAndSubContent.class.getName(); +// public static final String [] upSaveKeyNames = {"globalNodeTrail"}; +// public static final String [] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; + + @SuppressWarnings("unchecked") + public Writer getWriter(final Writer out, Map args) { + final Environment env = Environment.getCurrentEnvironment(); + final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env); + final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env); + final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env); + // final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env); + final Map envMap = FreeMarkerWorker.createEnvironmentMap(env); + final MapStack templateRoot = MapStack.create(); + ((MapStack)templateRoot).push(envMap); + if (Debug.verboseOn()) Debug.logVerbose("in RenderContentAndSubContent, contentId(0):" + templateRoot.get("contentId"), module); + FreeMarkerWorker.getSiteParameters(request, templateRoot); + // final Map savedValuesUp = new HashMap(); + // FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp); + FreeMarkerWorker.overrideWithArgs(templateRoot, args); + + // final Map savedValues = new HashMap(); + + return new Writer(out) { + + @Override + public void write(char cbuf[], int off, int len) { + } + + @Override + public void flush() throws IOException { + out.flush(); + } + + @Override + public void close() throws IOException { + renderSubContent(); + //if (Debug.verboseOn()) Debug.logVerbose("in Render(2), globalNodeTrail ." + getWrapped(env, "globalNodeTrail") , module); + } + + public void renderSubContent() throws IOException { + String mimeTypeId = (String) templateRoot.get("mimeTypeId"); + Object localeObject = templateRoot.get("locale"); + Locale locale = null; + if (localeObject == null) { + locale = UtilHttp.getLocale(request); + } else { + locale = UtilMisc.ensureLocale(localeObject); + } + + if (Debug.verboseOn()) Debug.logVerbose("in RenderContentAndSubContent, contentId(2):" + templateRoot.get("contentId"), module); + if (Debug.verboseOn()) Debug.logVerbose("in RenderContentAndSubContent, subContentId(2):" + templateRoot.get("subContentId"), module); + //if (thisView != null) { + try { + String contentId = (String)templateRoot.get("contentId"); + String mapKey = (String)templateRoot.get("mapKey"); + String contentAssocTypeId = (String)templateRoot.get("contentAssocTypeId"); + if (UtilValidate.isNotEmpty(mapKey) || UtilValidate.isNotEmpty(contentAssocTypeId)) { + String txt = ContentWorker.renderSubContentAsText(dispatcher, delegator, contentId, mapKey, templateRoot, locale, mimeTypeId, true); + //String txt = ContentWorker.renderSubContentAsTextCache(delegator, thisContentId, thisMapKey, null, templateRoot, locale, mimeTypeId, null, fromDate); +// if ("true".equals(xmlEscape)) { +// txt = UtilFormatOut.encodeXmlValue(txt); +// } + + out.write(txt); + +// if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, after renderContentAsTextCache:", module); +// List assocList = null; +// if (UtilValidate.isNotEmpty(contentAssocTypeId)) { +// assocList = UtilMisc.toList(contentAssocTypeId); +// } +// GenericValue content = ContentWorker.getSubContent(delegator, contentId, mapKey, null, null, assocList, null); +// if (content != null) { +// contentId = content.getString("contentId"); +// } else { +// contentId = null; +// } + } else if (contentId != null) { + ContentWorker.renderContentAsText(dispatcher, delegator, contentId, out, templateRoot, locale, mimeTypeId, null, null, true); +// ((MapStack)templateRoot).pop(); + } + //FreeMarkerWorker.reloadValues(templateRoot, savedValues, env); + //FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env); + + } catch (GeneralException e) { + String errMsg = "Error rendering thisContentId:" + (String)templateRoot.get("contentId") + " msg:" + e.toString(); + Debug.logError(e, errMsg, module); + // just log a message and don't return anything: throw new IOException(); + } + } + + }; + } +} diff --git a/applications/content/src/org/ofbiz/content/webapp/ftl/RenderContentTransform.java b/applications/content/src/org/ofbiz/content/webapp/ftl/RenderContentTransform.java index 85f373fb95..f7c83efe66 100644 --- a/applications/content/src/org/ofbiz/content/webapp/ftl/RenderContentTransform.java +++ b/applications/content/src/org/ofbiz/content/webapp/ftl/RenderContentTransform.java @@ -1,161 +1,161 @@ -/******************************************************************************* - * 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.content.webapp.ftl; - -import java.io.IOException; -import java.io.Writer; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.GeneralException; -import org.ofbiz.base.util.UtilFormatOut; -import org.ofbiz.base.util.UtilHttp; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilProperties; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.base.util.collections.MapStack; -import org.ofbiz.base.util.template.FreeMarkerWorker; -import org.ofbiz.content.content.ContentWorker; -import org.ofbiz.entity.Delegator; -import org.ofbiz.service.LocalDispatcher; -import org.ofbiz.webapp.control.RequestHandler; - -import freemarker.core.Environment; -import freemarker.template.TemplateTransformModel; - -/** - * RenderContentAsText - Freemarker Transform for Content rendering - * This transform cannot be called recursively (at this time). - */ -public class RenderContentTransform implements TemplateTransformModel { - - public static final String module = RenderContentTransform.class.getName(); - - @SuppressWarnings("unchecked") - public Writer getWriter(final Writer out, Map args) { - final Environment env = Environment.getCurrentEnvironment(); - final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env); - final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env); - final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env); - final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env); - - final Map templateRoot = MapStack.create(FreeMarkerWorker.createEnvironmentMap(env)); - ((MapStack)templateRoot).push(args); - final String xmlEscape = (String)templateRoot.get("xmlEscape"); - final String thisContentId = (String)templateRoot.get("contentId"); - - return new Writer(out) { - - @Override - public void write(char cbuf[], int off, int len) { - } - - @Override - public void flush() throws IOException { - out.flush(); - } - - @Override - public void close() throws IOException { - renderSubContent(); - } - - public void renderSubContent() throws IOException { - String mimeTypeId = (String) templateRoot.get("mimeTypeId"); - Object localeObject = templateRoot.get("locale"); - Locale locale = null; - if (localeObject == null) { - locale = UtilHttp.getLocale(request); - } else { - locale = UtilMisc.ensureLocale(localeObject); - } - - String editRequestName = (String)templateRoot.get("editRequestName"); - - if (UtilValidate.isNotEmpty(editRequestName)) { - String editStyle = getEditStyle(); - openEditWrap(out, editStyle); - } - - try { - String txt = null; - - String mapKey = (String)templateRoot.get("mapKey"); - if (UtilValidate.isEmpty(mapKey)) { - txt = ContentWorker.renderContentAsText(dispatcher, delegator, thisContentId, templateRoot, locale, mimeTypeId, true); - } else { - txt = ContentWorker.renderSubContentAsText(dispatcher, delegator, thisContentId, mapKey, templateRoot, locale, mimeTypeId, true); - } - if ("true".equals(xmlEscape)) { - txt = UtilFormatOut.encodeXmlValue(txt); - } - - out.write(txt); - - } catch (GeneralException e) { - String errMsg = "Error rendering thisContentId:" + thisContentId + " msg:" + e.toString(); - Debug.logError(e, errMsg, module); - // just log a message and don't return anything: throw new IOException(); - } - if (UtilValidate.isNotEmpty(editRequestName)) { - closeEditWrap(out, editRequestName); - } - - } - - public void openEditWrap(Writer out, String editStyle) throws IOException { - String divStr = "
"; - out.write(divStr); - } - - public void closeEditWrap(Writer out, String editRequestName) throws IOException { - // StringBuilder sb = new StringBuilder(); - String fullRequest = editRequestName; - String delim = "?"; - if (UtilValidate.isNotEmpty(thisContentId)) { - fullRequest += delim + "contentId=" + thisContentId; - delim = "&"; - } - - out.write("Edit"); - out.write("
"); - } - - public String getEditStyle() { - String editStyle = (String)templateRoot.get("editStyle"); - if (UtilValidate.isEmpty(editStyle)) { - editStyle = UtilProperties.getPropertyValue("content", "defaultEditStyle"); - } - if (UtilValidate.isEmpty(editStyle)) { - editStyle = "buttontext"; - } - return editStyle; - } - }; - } -} +/******************************************************************************* + * 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.content.webapp.ftl; + +import java.io.IOException; +import java.io.Writer; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.GeneralException; +import org.ofbiz.base.util.UtilFormatOut; +import org.ofbiz.base.util.UtilHttp; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilProperties; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.base.util.collections.MapStack; +import org.ofbiz.base.util.template.FreeMarkerWorker; +import org.ofbiz.content.content.ContentWorker; +import org.ofbiz.entity.Delegator; +import org.ofbiz.service.LocalDispatcher; +import org.ofbiz.webapp.control.RequestHandler; + +import freemarker.core.Environment; +import freemarker.template.TemplateTransformModel; + +/** + * RenderContentAsText - Freemarker Transform for Content rendering + * This transform cannot be called recursively (at this time). + */ +public class RenderContentTransform implements TemplateTransformModel { + + public static final String module = RenderContentTransform.class.getName(); + + @SuppressWarnings("unchecked") + public Writer getWriter(final Writer out, Map args) { + final Environment env = Environment.getCurrentEnvironment(); + final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env); + final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env); + final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env); + final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env); + + final Map templateRoot = MapStack.create(FreeMarkerWorker.createEnvironmentMap(env)); + ((MapStack)templateRoot).push(args); + final String xmlEscape = (String)templateRoot.get("xmlEscape"); + final String thisContentId = (String)templateRoot.get("contentId"); + + return new Writer(out) { + + @Override + public void write(char cbuf[], int off, int len) { + } + + @Override + public void flush() throws IOException { + out.flush(); + } + + @Override + public void close() throws IOException { + renderSubContent(); + } + + public void renderSubContent() throws IOException { + String mimeTypeId = (String) templateRoot.get("mimeTypeId"); + Object localeObject = templateRoot.get("locale"); + Locale locale = null; + if (localeObject == null) { + locale = UtilHttp.getLocale(request); + } else { + locale = UtilMisc.ensureLocale(localeObject); + } + + String editRequestName = (String)templateRoot.get("editRequestName"); + + if (UtilValidate.isNotEmpty(editRequestName)) { + String editStyle = getEditStyle(); + openEditWrap(out, editStyle); + } + + try { + String txt = null; + + String mapKey = (String)templateRoot.get("mapKey"); + if (UtilValidate.isEmpty(mapKey)) { + txt = ContentWorker.renderContentAsText(dispatcher, delegator, thisContentId, templateRoot, locale, mimeTypeId, true); + } else { + txt = ContentWorker.renderSubContentAsText(dispatcher, delegator, thisContentId, mapKey, templateRoot, locale, mimeTypeId, true); + } + if ("true".equals(xmlEscape)) { + txt = UtilFormatOut.encodeXmlValue(txt); + } + + out.write(txt); + + } catch (GeneralException e) { + String errMsg = "Error rendering thisContentId:" + thisContentId + " msg:" + e.toString(); + Debug.logError(e, errMsg, module); + // just log a message and don't return anything: throw new IOException(); + } + if (UtilValidate.isNotEmpty(editRequestName)) { + closeEditWrap(out, editRequestName); + } + + } + + public void openEditWrap(Writer out, String editStyle) throws IOException { + String divStr = "
"; + out.write(divStr); + } + + public void closeEditWrap(Writer out, String editRequestName) throws IOException { + // StringBuilder sb = new StringBuilder(); + String fullRequest = editRequestName; + String delim = "?"; + if (UtilValidate.isNotEmpty(thisContentId)) { + fullRequest += delim + "contentId=" + thisContentId; + delim = "&"; + } + + out.write("Edit"); + out.write("
"); + } + + public String getEditStyle() { + String editStyle = (String)templateRoot.get("editStyle"); + if (UtilValidate.isEmpty(editStyle)) { + editStyle = UtilProperties.getPropertyValue("content", "defaultEditStyle"); + } + if (UtilValidate.isEmpty(editStyle)) { + editStyle = "buttontext"; + } + return editStyle; + } + }; + } +} diff --git a/applications/marketing/src/org/ofbiz/marketing/marketing/MarketingServices.java b/applications/marketing/src/org/ofbiz/marketing/marketing/MarketingServices.java index abaa1c48e4..984e5c9535 100644 --- a/applications/marketing/src/org/ofbiz/marketing/marketing/MarketingServices.java +++ b/applications/marketing/src/org/ofbiz/marketing/marketing/MarketingServices.java @@ -1,116 +1,116 @@ -/******************************************************************************* - * 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.marketing.marketing; - -import java.sql.Timestamp; -import java.util.Locale; -import java.util.Map; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.UtilDateTime; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilProperties; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.entity.Delegator; -import org.ofbiz.entity.GenericEntityException; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.entity.util.EntityQuery; -import org.ofbiz.service.DispatchContext; -import org.ofbiz.service.GenericServiceException; -import org.ofbiz.service.LocalDispatcher; -import org.ofbiz.service.ServiceUtil; - -/** - * MarketingServices contains static service methods for Marketing Campaigns and Contact Lists. - * See the documentation in marketing/servicedef/services.xml and use the service reference in - * webtools. Comments in this file are implemntation notes and technical details. - */ -public class MarketingServices { - - public static final String module = MarketingServices.class.getName(); - public static final String resourceMarketing = "MarketingUiLabels"; - public static final String resourceOrder = "OrderUiLabels"; - - public static Map signUpForContactList(DispatchContext dctx, Map context) { - LocalDispatcher dispatcher = dctx.getDispatcher(); - Delegator delegator = dctx.getDelegator(); - Locale locale = (Locale) context.get("locale"); - - Timestamp fromDate = UtilDateTime.nowTimestamp(); - String contactListId = (String) context.get("contactListId"); - String email = (String) context.get("email"); - String partyId = (String) context.get("partyId"); - - if (!UtilValidate.isEmail(email)) { - String error = UtilProperties.getMessage(resourceMarketing, "MarketingCampaignInvalidEmailInput", locale); - return ServiceUtil.returnError(error); - } - - try { - // locate the contact list - GenericValue contactList = EntityQuery.use(delegator).from("ContactList").where("contactListId", contactListId).queryOne(); - if (contactList == null) { - String error = UtilProperties.getMessage(resourceMarketing, "MarketingContactListNotFound", UtilMisc.toMap("contactListId", contactListId), locale); - return ServiceUtil.returnError(error); - } - - // perform actions as the system user - GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").cache().queryOne(); - - // associate the email with anonymous user TODO: do we need a custom contact mech purpose type, say MARKETING_EMAIL? - if (partyId == null) { - // Check existing email - GenericValue contact = EntityQuery.use(delegator).from("PartyContactDetailByPurpose") - .where("infoString", email, - "contactMechTypeId", "EMAIL_ADDRESS", - "contactMechPurposeTypeId", "PRIMARY_EMAIL") - .orderBy("-fromDate") - .filterByDate("fromDate", "thruDate", "purposeFromDate", "purposeThruDate") - .queryFirst(); - if (contact != null) { - partyId = contact.getString("partyId"); - } else { - partyId = "_NA_"; - } - } - Map input = UtilMisc.toMap("userLogin", userLogin, "emailAddress", email, "partyId", partyId, "fromDate", fromDate, "contactMechPurposeTypeId", "OTHER_EMAIL"); - Map serviceResults = dispatcher.runSync("createPartyEmailAddress", input); - if (ServiceUtil.isError(serviceResults)) { - throw new GenericServiceException(ServiceUtil.getErrorMessage(serviceResults)); - } - String contactMechId = (String) serviceResults.get("contactMechId"); - // create a new association at this fromDate to the anonymous party with status accepted - input = UtilMisc.toMap("userLogin", userLogin, "contactListId", contactList.get("contactListId"), - "partyId", partyId, "fromDate", fromDate, "statusId", "CLPT_PENDING", "preferredContactMechId", contactMechId, "baseLocation", context.get("baseLocation")); - serviceResults = dispatcher.runSync("createContactListParty", input); - if (ServiceUtil.isError(serviceResults)) { - throw new GenericServiceException(ServiceUtil.getErrorMessage(serviceResults)); - } - } catch (GenericEntityException e) { - String error = UtilProperties.getMessage(resourceOrder, "checkhelper.problems_reading_database", locale); - Debug.logInfo(e, error + e.getMessage(), module); - return ServiceUtil.returnError(error); - } catch (GenericServiceException e) { - String error = UtilProperties.getMessage(resourceMarketing, "MarketingServiceError", locale); - Debug.logInfo(e, error + e.getMessage(), module); - return ServiceUtil.returnError(error); - } - return ServiceUtil.returnSuccess(); - } -} +/******************************************************************************* + * 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.marketing.marketing; + +import java.sql.Timestamp; +import java.util.Locale; +import java.util.Map; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.UtilDateTime; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilProperties; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.Delegator; +import org.ofbiz.entity.GenericEntityException; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.entity.util.EntityQuery; +import org.ofbiz.service.DispatchContext; +import org.ofbiz.service.GenericServiceException; +import org.ofbiz.service.LocalDispatcher; +import org.ofbiz.service.ServiceUtil; + +/** + * MarketingServices contains static service methods for Marketing Campaigns and Contact Lists. + * See the documentation in marketing/servicedef/services.xml and use the service reference in + * webtools. Comments in this file are implemntation notes and technical details. + */ +public class MarketingServices { + + public static final String module = MarketingServices.class.getName(); + public static final String resourceMarketing = "MarketingUiLabels"; + public static final String resourceOrder = "OrderUiLabels"; + + public static Map signUpForContactList(DispatchContext dctx, Map context) { + LocalDispatcher dispatcher = dctx.getDispatcher(); + Delegator delegator = dctx.getDelegator(); + Locale locale = (Locale) context.get("locale"); + + Timestamp fromDate = UtilDateTime.nowTimestamp(); + String contactListId = (String) context.get("contactListId"); + String email = (String) context.get("email"); + String partyId = (String) context.get("partyId"); + + if (!UtilValidate.isEmail(email)) { + String error = UtilProperties.getMessage(resourceMarketing, "MarketingCampaignInvalidEmailInput", locale); + return ServiceUtil.returnError(error); + } + + try { + // locate the contact list + GenericValue contactList = EntityQuery.use(delegator).from("ContactList").where("contactListId", contactListId).queryOne(); + if (contactList == null) { + String error = UtilProperties.getMessage(resourceMarketing, "MarketingContactListNotFound", UtilMisc.toMap("contactListId", contactListId), locale); + return ServiceUtil.returnError(error); + } + + // perform actions as the system user + GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").cache().queryOne(); + + // associate the email with anonymous user TODO: do we need a custom contact mech purpose type, say MARKETING_EMAIL? + if (partyId == null) { + // Check existing email + GenericValue contact = EntityQuery.use(delegator).from("PartyContactDetailByPurpose") + .where("infoString", email, + "contactMechTypeId", "EMAIL_ADDRESS", + "contactMechPurposeTypeId", "PRIMARY_EMAIL") + .orderBy("-fromDate") + .filterByDate("fromDate", "thruDate", "purposeFromDate", "purposeThruDate") + .queryFirst(); + if (contact != null) { + partyId = contact.getString("partyId"); + } else { + partyId = "_NA_"; + } + } + Map input = UtilMisc.toMap("userLogin", userLogin, "emailAddress", email, "partyId", partyId, "fromDate", fromDate, "contactMechPurposeTypeId", "OTHER_EMAIL"); + Map serviceResults = dispatcher.runSync("createPartyEmailAddress", input); + if (ServiceUtil.isError(serviceResults)) { + throw new GenericServiceException(ServiceUtil.getErrorMessage(serviceResults)); + } + String contactMechId = (String) serviceResults.get("contactMechId"); + // create a new association at this fromDate to the anonymous party with status accepted + input = UtilMisc.toMap("userLogin", userLogin, "contactListId", contactList.get("contactListId"), + "partyId", partyId, "fromDate", fromDate, "statusId", "CLPT_PENDING", "preferredContactMechId", contactMechId, "baseLocation", context.get("baseLocation")); + serviceResults = dispatcher.runSync("createContactListParty", input); + if (ServiceUtil.isError(serviceResults)) { + throw new GenericServiceException(ServiceUtil.getErrorMessage(serviceResults)); + } + } catch (GenericEntityException e) { + String error = UtilProperties.getMessage(resourceOrder, "checkhelper.problems_reading_database", locale); + Debug.logInfo(e, error + e.getMessage(), module); + return ServiceUtil.returnError(error); + } catch (GenericServiceException e) { + String error = UtilProperties.getMessage(resourceMarketing, "MarketingServiceError", locale); + Debug.logInfo(e, error + e.getMessage(), module); + return ServiceUtil.returnError(error); + } + return ServiceUtil.returnSuccess(); + } +} diff --git a/applications/order/src/org/ofbiz/order/requirement/RequirementServices.java b/applications/order/src/org/ofbiz/order/requirement/RequirementServices.java index 851e81a6b5..2a98e466b5 100644 --- a/applications/order/src/org/ofbiz/order/requirement/RequirementServices.java +++ b/applications/order/src/org/ofbiz/order/requirement/RequirementServices.java @@ -1,332 +1,332 @@ -/* - * 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.order.requirement; - -import java.util.*; -import java.math.BigDecimal; -import java.sql.Timestamp; - -import org.ofbiz.base.util.*; -import org.ofbiz.entity.condition.*; -import org.ofbiz.entity.Delegator; -import org.ofbiz.entity.GenericEntityException; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.entity.util.EntityQuery; -import org.ofbiz.entity.util.EntityUtil; -import org.ofbiz.service.DispatchContext; -import org.ofbiz.service.GenericServiceException; -import org.ofbiz.service.LocalDispatcher; -import org.ofbiz.service.ServiceUtil; - -/** - * Requirement Services - */ - -public class RequirementServices { - - public static final String module = RequirementServices.class.getName(); - public static final String resource_error = "OrderErrorUiLabels"; - - public static Map getRequirementsForSupplier(DispatchContext ctx, Map context) { - Delegator delegator = ctx.getDelegator(); - LocalDispatcher dispatcher = ctx.getDispatcher(); - Locale locale = (Locale) context.get("locale"); - - EntityCondition requirementConditions = (EntityCondition) context.get("requirementConditions"); - String partyId = (String) context.get("partyId"); - String unassignedRequirements = (String) context.get("unassignedRequirements"); - List statusIds = UtilGenerics.checkList(context.get("statusIds")); - //TODO currencyUomId still not used - //String currencyUomId = (String) context.get("currencyUomId"); - try { - List conditions = UtilMisc.toList( - EntityCondition.makeCondition("requirementTypeId", EntityOperator.EQUALS, "PRODUCT_REQUIREMENT"), - EntityUtil.getFilterByDateExpr() - ); - if (UtilValidate.isNotEmpty(statusIds)) { - conditions.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, statusIds)); - } else { - conditions.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "REQ_APPROVED")); - } - if (requirementConditions != null) conditions.add(requirementConditions); - - // we're either getting the requirements for a given supplier, unassigned requirements, or requirements for all suppliers - if (UtilValidate.isNotEmpty(partyId)) { - conditions.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId)); - conditions.add(EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SUPPLIER")); - } else if (UtilValidate.isNotEmpty(unassignedRequirements)) { - conditions.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, null)); - } else { - conditions.add(EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SUPPLIER")); - } - - List requirementAndRoles = EntityQuery.use(delegator).from("RequirementAndRole") - .where(conditions) - .orderBy("partyId", "requirementId") - .queryList(); - - // maps to cache the associated suppliers and products data, so we don't do redundant DB and service requests - Map suppliers = new HashMap(); - Map gids = new HashMap(); - Map> inventories = new HashMap>(); - Map productsSold = new HashMap(); - - // to count quantity, running total, and distinct products in list - BigDecimal quantity = BigDecimal.ZERO; - BigDecimal amountTotal = BigDecimal.ZERO; - Set products = new HashSet(); - - // time period to count products ordered from, six months ago and the 1st of that month - Timestamp timePeriodStart = UtilDateTime.getMonthStart(UtilDateTime.nowTimestamp(), 0, -6); - - // join in fields with extra data about the suppliers and products - List> requirements = new LinkedList>(); - for (GenericValue requirement : requirementAndRoles) { - Map union = new HashMap(); - String productId = requirement.getString("productId"); - partyId = requirement.getString("partyId"); - String facilityId = requirement.getString("facilityId"); - BigDecimal requiredQuantity = requirement.getBigDecimal("quantity"); - - // get an available supplier product, preferably the one with the smallest minimum quantity to order, followed by price - String supplierKey = partyId + "^" + productId; - GenericValue supplierProduct = suppliers.get(supplierKey); - if (supplierProduct == null) { - // TODO: it is possible to restrict to quantity > minimumOrderQuantity, but then the entire requirement must be skipped - supplierProduct = EntityQuery.use(delegator).from("SupplierProduct") - .where("partyId", partyId, "productId", productId) - .orderBy("minimumOrderQuantity", "lastPrice") - .filterByDate("availableFromDate", "availableThruDate") - .queryFirst(); - suppliers.put(supplierKey, supplierProduct); - } - - // add our supplier product and cost of this line to the data - if (supplierProduct != null) { - union.putAll(supplierProduct.getAllFields()); - BigDecimal lastPrice = supplierProduct.getBigDecimal("lastPrice"); - amountTotal = amountTotal.add(lastPrice.multiply(requiredQuantity)); - } - - // for good identification, get the UPCA type (UPC code) - GenericValue gid = gids.get(productId); - if (gid == null) { - gid = EntityQuery.use(delegator).from("GoodIdentification").where("goodIdentificationTypeId", "UPCA", "productId", requirement.get("productId")).queryOne(); - gids.put(productId, gid); - } - if (gid != null) union.put("idValue", gid.get("idValue")); - - // the ATP and QOH quantities - if (UtilValidate.isNotEmpty(facilityId)) { - String inventoryKey = facilityId + "^" + productId; - Map inventory = inventories.get(inventoryKey); - if (inventory == null) { - inventory = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId", facilityId)); - if (ServiceUtil.isError(inventory)) { - return inventory; - } - inventories.put(inventoryKey, inventory); - } - if (inventory != null) { - union.put("qoh", inventory.get("quantityOnHandTotal")); - union.put("atp", inventory.get("availableToPromiseTotal")); - } - } - - // how many of the products were sold (note this is for a fixed time period across all product stores) - BigDecimal sold = productsSold.get(productId); - if (sold == null) { - EntityCondition prodConditions = EntityCondition.makeCondition(UtilMisc.toList( - EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), - EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER"), - EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_IN, UtilMisc.toList("ORDER_REJECTED", "ORDER_CANCELLED")), - EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_IN, UtilMisc.toList("ITEM_REJECTED", "ITEM_CANCELLED")), - EntityCondition.makeCondition("orderDate", EntityOperator.GREATER_THAN_EQUAL_TO, timePeriodStart) - ), EntityOperator.AND); - GenericValue count = EntityQuery.use(delegator).select("quantityOrdered").from("OrderItemQuantityReportGroupByProduct").where(prodConditions).queryFirst(); - if (count != null) { - sold = count.getBigDecimal("quantityOrdered"); - if (sold != null) productsSold.put(productId, sold); - } - } - if (sold != null) { - union.put("qtySold", sold); - } - - // keep a running total of distinct products and quantity to order - if (requirement.getBigDecimal("quantity") == null) requirement.put("quantity", BigDecimal.ONE); // default quantity = 1 - quantity = quantity.add(requiredQuantity); - products.add(productId); - - // add all the requirement fields last, to overwrite any conflicting fields - union.putAll(requirement.getAllFields()); - requirements.add(union); - } - - Map results = ServiceUtil.returnSuccess(); - results.put("requirementsForSupplier", requirements); - results.put("distinctProductCount", Integer.valueOf(products.size())); - results.put("quantityTotal", quantity); - results.put("amountTotal", amountTotal); - return results; - } catch (GenericServiceException e) { - Debug.logError(e, module); - return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderServiceExceptionSeeLogs", locale)); - } catch (GenericEntityException e) { - Debug.logError(e, module); - return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderEntityExceptionSeeLogs", locale)); - } - } - - // note that this service is designed to work only when a sales order status changes from CREATED -> APPROVED because HOLD -> APPROVED is too complex - public static Map createAutoRequirementsForOrder(DispatchContext ctx, Map context) { - Delegator delegator = ctx.getDelegator(); - LocalDispatcher dispatcher = ctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); - - String orderId = (String) context.get("orderId"); - try { - GenericValue order = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne(); - GenericValue productStore = order.getRelatedOne("ProductStore", true); - if (productStore == null) { - Debug.logInfo("ProductStore for order ID " + orderId + " not found, requirements not created", module); - return ServiceUtil.returnSuccess(); - } - String facilityId = productStore.getString("inventoryFacilityId"); - List orderItems = order.getRelated("OrderItem", null, null, false); - for (GenericValue item : orderItems) { - GenericValue product = item.getRelatedOne("Product", false); - if (product == null) continue; - if ((!"PRODRQM_AUTO".equals(product.get("requirementMethodEnumId")) && - !"PRODRQM_AUTO".equals(productStore.get("requirementMethodEnumId"))) || - (product.get("requirementMethodEnumId") == null && - !"PRODRQM_AUTO".equals(productStore.get("requirementMethodEnumId")))) continue; - BigDecimal quantity = item.getBigDecimal("quantity"); - BigDecimal cancelQuantity = item.getBigDecimal("cancelQuantity"); - BigDecimal required = quantity.subtract(cancelQuantity == null ? BigDecimal.ZERO : cancelQuantity); - if (required.compareTo(BigDecimal.ZERO) <= 0) continue; - - Map input = UtilMisc.toMap("userLogin", userLogin, "facilityId", facilityId, "productId", product.get("productId"), "quantity", required, "requirementTypeId", "PRODUCT_REQUIREMENT"); - Map results = dispatcher.runSync("createRequirement", input); - if (ServiceUtil.isError(results)) return results; - String requirementId = (String) results.get("requirementId"); - - input = UtilMisc.toMap("userLogin", userLogin, "orderId", order.get("orderId"), "orderItemSeqId", item.get("orderItemSeqId"), "requirementId", requirementId, "quantity", required); - results = dispatcher.runSync("createOrderRequirementCommitment", input); - if (ServiceUtil.isError(results)) return results; - } - } catch (GenericEntityException e) { - Debug.logError(e, module); - } catch (GenericServiceException e) { - Debug.logError(e, module); - } - return ServiceUtil.returnSuccess(); - } - - // note that this service is designed to work only when a sales order status changes from CREATED -> APPROVED because HOLD -> APPROVED is too complex - public static Map createATPRequirementsForOrder(DispatchContext ctx, Map context) { - Delegator delegator = ctx.getDelegator(); - LocalDispatcher dispatcher = ctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); - - /* - * The strategy in this service is to begin making requirements when the product falls below the - * ProductFacility.minimumStock. Because the minimumStock is an upper bound, the quantity to be required - * is either that required to bring the ATP back up to the minimumStock level or the amount ordered, - * whichever is less. - * - * If there is a way to support reorderQuantity without losing the order item -> requirement association data, - * then this service should be updated. - * - * The result is that this service generates many small requirements when stock levels are low for a product, - * which is perfectly fine since the system is capable of creating POs in bulk from aggregate requirements. - * The only concern would be a UI to manage numerous requirements with ease, preferrably by aggregating - * on productId. - */ - String orderId = (String) context.get("orderId"); - try { - GenericValue order = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne(); - GenericValue productStore = order.getRelatedOne("ProductStore", true); - if (productStore == null) { - Debug.logInfo("ProductStore for order ID " + orderId + " not found, ATP requirements not created", module); - return ServiceUtil.returnSuccess(); - } - String facilityId = productStore.getString("inventoryFacilityId"); - List orderItems = order.getRelated("OrderItem", null, null, false); - for (GenericValue item : orderItems) { - GenericValue product = item.getRelatedOne("Product", false); - if (product == null) continue; - - if (!("PRODRQM_ATP".equals(product.get("requirementMethodEnumId")) || - ("PRODRQM_ATP".equals(productStore.get("requirementMethodEnumId")) && product.get("requirementMethodEnumId") == null))) continue; - - BigDecimal quantity = item.getBigDecimal("quantity"); - BigDecimal cancelQuantity = item.getBigDecimal("cancelQuantity"); - BigDecimal ordered = quantity.subtract(cancelQuantity == null ? BigDecimal.ZERO : cancelQuantity); - if (ordered.compareTo(BigDecimal.ZERO) <= 0) continue; - - // get the minimum stock for this facility (if not configured assume a minimum of zero, ie create requirements when it goes into backorder) - GenericValue productFacility = EntityQuery.use(delegator).from("ProductFacility").where("facilityId", facilityId, "productId", product.get("productId")).queryOne(); - BigDecimal minimumStock = BigDecimal.ZERO; - if (productFacility != null && productFacility.get("minimumStock") != null) { - minimumStock = productFacility.getBigDecimal("minimumStock"); - } - - // get the facility ATP for product, which should be updated for this item's reservation - Map results = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("userLogin", userLogin, "productId", product.get("productId"), "facilityId", facilityId)); - if (ServiceUtil.isError(results)) return results; - BigDecimal atp = ((BigDecimal) results.get("availableToPromiseTotal")); // safe since this is a required OUT param - - // count all current requirements for this product - BigDecimal pendingRequirements = BigDecimal.ZERO; - EntityConditionList ecl = EntityCondition.makeCondition(UtilMisc.toList( - EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), - EntityCondition.makeCondition("productId", EntityOperator.EQUALS, product.get("productId")), - EntityCondition.makeCondition("requirementTypeId", EntityOperator.EQUALS, "PRODUCT_REQUIREMENT"), - EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "REQ_ORDERED"), - EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "REQ_REJECTED")), - EntityOperator.AND); - List requirements = EntityQuery.use(delegator).from("Requirement").where(ecl).queryList(); - for (GenericValue requirement : requirements) { - pendingRequirements = pendingRequirements.add(requirement.get("quantity") == null ? BigDecimal.ZERO : requirement.getBigDecimal("quantity")); - } - - // the minimum stock is an upper bound, therefore we either require up to the minimum stock or the input required quantity, whichever is less - BigDecimal shortfall = minimumStock.subtract(atp).subtract(pendingRequirements); - BigDecimal required = ordered.compareTo(shortfall) < 0 ? ordered : shortfall; - if (required.compareTo(BigDecimal.ZERO) <= 0) continue; - - Map input = UtilMisc.toMap("userLogin", userLogin, "facilityId", facilityId, "productId", product.get("productId"), "quantity", required, "requirementTypeId", "PRODUCT_REQUIREMENT"); - results = dispatcher.runSync("createRequirement", input); - if (ServiceUtil.isError(results)) return results; - String requirementId = (String) results.get("requirementId"); - - input = UtilMisc.toMap("userLogin", userLogin, "orderId", order.get("orderId"), "orderItemSeqId", item.get("orderItemSeqId"), "requirementId", requirementId, "quantity", required); - results = dispatcher.runSync("createOrderRequirementCommitment", input); - if (ServiceUtil.isError(results)) return results; - } - } catch (GenericEntityException e) { - Debug.logError(e, module); - } catch (GenericServiceException e) { - Debug.logError(e, module); - } - return ServiceUtil.returnSuccess(); - } -} - +/* + * 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.order.requirement; + +import java.util.*; +import java.math.BigDecimal; +import java.sql.Timestamp; + +import org.ofbiz.base.util.*; +import org.ofbiz.entity.condition.*; +import org.ofbiz.entity.Delegator; +import org.ofbiz.entity.GenericEntityException; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.entity.util.EntityQuery; +import org.ofbiz.entity.util.EntityUtil; +import org.ofbiz.service.DispatchContext; +import org.ofbiz.service.GenericServiceException; +import org.ofbiz.service.LocalDispatcher; +import org.ofbiz.service.ServiceUtil; + +/** + * Requirement Services + */ + +public class RequirementServices { + + public static final String module = RequirementServices.class.getName(); + public static final String resource_error = "OrderErrorUiLabels"; + + public static Map getRequirementsForSupplier(DispatchContext ctx, Map context) { + Delegator delegator = ctx.getDelegator(); + LocalDispatcher dispatcher = ctx.getDispatcher(); + Locale locale = (Locale) context.get("locale"); + + EntityCondition requirementConditions = (EntityCondition) context.get("requirementConditions"); + String partyId = (String) context.get("partyId"); + String unassignedRequirements = (String) context.get("unassignedRequirements"); + List statusIds = UtilGenerics.checkList(context.get("statusIds")); + //TODO currencyUomId still not used + //String currencyUomId = (String) context.get("currencyUomId"); + try { + List conditions = UtilMisc.toList( + EntityCondition.makeCondition("requirementTypeId", EntityOperator.EQUALS, "PRODUCT_REQUIREMENT"), + EntityUtil.getFilterByDateExpr() + ); + if (UtilValidate.isNotEmpty(statusIds)) { + conditions.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, statusIds)); + } else { + conditions.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "REQ_APPROVED")); + } + if (requirementConditions != null) conditions.add(requirementConditions); + + // we're either getting the requirements for a given supplier, unassigned requirements, or requirements for all suppliers + if (UtilValidate.isNotEmpty(partyId)) { + conditions.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId)); + conditions.add(EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SUPPLIER")); + } else if (UtilValidate.isNotEmpty(unassignedRequirements)) { + conditions.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, null)); + } else { + conditions.add(EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SUPPLIER")); + } + + List requirementAndRoles = EntityQuery.use(delegator).from("RequirementAndRole") + .where(conditions) + .orderBy("partyId", "requirementId") + .queryList(); + + // maps to cache the associated suppliers and products data, so we don't do redundant DB and service requests + Map suppliers = new HashMap(); + Map gids = new HashMap(); + Map> inventories = new HashMap>(); + Map productsSold = new HashMap(); + + // to count quantity, running total, and distinct products in list + BigDecimal quantity = BigDecimal.ZERO; + BigDecimal amountTotal = BigDecimal.ZERO; + Set products = new HashSet(); + + // time period to count products ordered from, six months ago and the 1st of that month + Timestamp timePeriodStart = UtilDateTime.getMonthStart(UtilDateTime.nowTimestamp(), 0, -6); + + // join in fields with extra data about the suppliers and products + List> requirements = new LinkedList>(); + for (GenericValue requirement : requirementAndRoles) { + Map union = new HashMap(); + String productId = requirement.getString("productId"); + partyId = requirement.getString("partyId"); + String facilityId = requirement.getString("facilityId"); + BigDecimal requiredQuantity = requirement.getBigDecimal("quantity"); + + // get an available supplier product, preferably the one with the smallest minimum quantity to order, followed by price + String supplierKey = partyId + "^" + productId; + GenericValue supplierProduct = suppliers.get(supplierKey); + if (supplierProduct == null) { + // TODO: it is possible to restrict to quantity > minimumOrderQuantity, but then the entire requirement must be skipped + supplierProduct = EntityQuery.use(delegator).from("SupplierProduct") + .where("partyId", partyId, "productId", productId) + .orderBy("minimumOrderQuantity", "lastPrice") + .filterByDate("availableFromDate", "availableThruDate") + .queryFirst(); + suppliers.put(supplierKey, supplierProduct); + } + + // add our supplier product and cost of this line to the data + if (supplierProduct != null) { + union.putAll(supplierProduct.getAllFields()); + BigDecimal lastPrice = supplierProduct.getBigDecimal("lastPrice"); + amountTotal = amountTotal.add(lastPrice.multiply(requiredQuantity)); + } + + // for good identification, get the UPCA type (UPC code) + GenericValue gid = gids.get(productId); + if (gid == null) { + gid = EntityQuery.use(delegator).from("GoodIdentification").where("goodIdentificationTypeId", "UPCA", "productId", requirement.get("productId")).queryOne(); + gids.put(productId, gid); + } + if (gid != null) union.put("idValue", gid.get("idValue")); + + // the ATP and QOH quantities + if (UtilValidate.isNotEmpty(facilityId)) { + String inventoryKey = facilityId + "^" + productId; + Map inventory = inventories.get(inventoryKey); + if (inventory == null) { + inventory = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId", facilityId)); + if (ServiceUtil.isError(inventory)) { + return inventory; + } + inventories.put(inventoryKey, inventory); + } + if (inventory != null) { + union.put("qoh", inventory.get("quantityOnHandTotal")); + union.put("atp", inventory.get("availableToPromiseTotal")); + } + } + + // how many of the products were sold (note this is for a fixed time period across all product stores) + BigDecimal sold = productsSold.get(productId); + if (sold == null) { + EntityCondition prodConditions = EntityCondition.makeCondition(UtilMisc.toList( + EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), + EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER"), + EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_IN, UtilMisc.toList("ORDER_REJECTED", "ORDER_CANCELLED")), + EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_IN, UtilMisc.toList("ITEM_REJECTED", "ITEM_CANCELLED")), + EntityCondition.makeCondition("orderDate", EntityOperator.GREATER_THAN_EQUAL_TO, timePeriodStart) + ), EntityOperator.AND); + GenericValue count = EntityQuery.use(delegator).select("quantityOrdered").from("OrderItemQuantityReportGroupByProduct").where(prodConditions).queryFirst(); + if (count != null) { + sold = count.getBigDecimal("quantityOrdered"); + if (sold != null) productsSold.put(productId, sold); + } + } + if (sold != null) { + union.put("qtySold", sold); + } + + // keep a running total of distinct products and quantity to order + if (requirement.getBigDecimal("quantity") == null) requirement.put("quantity", BigDecimal.ONE); // default quantity = 1 + quantity = quantity.add(requiredQuantity); + products.add(productId); + + // add all the requirement fields last, to overwrite any conflicting fields + union.putAll(requirement.getAllFields()); + requirements.add(union); + } + + Map results = ServiceUtil.returnSuccess(); + results.put("requirementsForSupplier", requirements); + results.put("distinctProductCount", Integer.valueOf(products.size())); + results.put("quantityTotal", quantity); + results.put("amountTotal", amountTotal); + return results; + } catch (GenericServiceException e) { + Debug.logError(e, module); + return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderServiceExceptionSeeLogs", locale)); + } catch (GenericEntityException e) { + Debug.logError(e, module); + return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderEntityExceptionSeeLogs", locale)); + } + } + + // note that this service is designed to work only when a sales order status changes from CREATED -> APPROVED because HOLD -> APPROVED is too complex + public static Map createAutoRequirementsForOrder(DispatchContext ctx, Map context) { + Delegator delegator = ctx.getDelegator(); + LocalDispatcher dispatcher = ctx.getDispatcher(); + GenericValue userLogin = (GenericValue) context.get("userLogin"); + + String orderId = (String) context.get("orderId"); + try { + GenericValue order = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne(); + GenericValue productStore = order.getRelatedOne("ProductStore", true); + if (productStore == null) { + Debug.logInfo("ProductStore for order ID " + orderId + " not found, requirements not created", module); + return ServiceUtil.returnSuccess(); + } + String facilityId = productStore.getString("inventoryFacilityId"); + List orderItems = order.getRelated("OrderItem", null, null, false); + for (GenericValue item : orderItems) { + GenericValue product = item.getRelatedOne("Product", false); + if (product == null) continue; + if ((!"PRODRQM_AUTO".equals(product.get("requirementMethodEnumId")) && + !"PRODRQM_AUTO".equals(productStore.get("requirementMethodEnumId"))) || + (product.get("requirementMethodEnumId") == null && + !"PRODRQM_AUTO".equals(productStore.get("requirementMethodEnumId")))) continue; + BigDecimal quantity = item.getBigDecimal("quantity"); + BigDecimal cancelQuantity = item.getBigDecimal("cancelQuantity"); + BigDecimal required = quantity.subtract(cancelQuantity == null ? BigDecimal.ZERO : cancelQuantity); + if (required.compareTo(BigDecimal.ZERO) <= 0) continue; + + Map input = UtilMisc.toMap("userLogin", userLogin, "facilityId", facilityId, "productId", product.get("productId"), "quantity", required, "requirementTypeId", "PRODUCT_REQUIREMENT"); + Map results = dispatcher.runSync("createRequirement", input); + if (ServiceUtil.isError(results)) return results; + String requirementId = (String) results.get("requirementId"); + + input = UtilMisc.toMap("userLogin", userLogin, "orderId", order.get("orderId"), "orderItemSeqId", item.get("orderItemSeqId"), "requirementId", requirementId, "quantity", required); + results = dispatcher.runSync("createOrderRequirementCommitment", input); + if (ServiceUtil.isError(results)) return results; + } + } catch (GenericEntityException e) { + Debug.logError(e, module); + } catch (GenericServiceException e) { + Debug.logError(e, module); + } + return ServiceUtil.returnSuccess(); + } + + // note that this service is designed to work only when a sales order status changes from CREATED -> APPROVED because HOLD -> APPROVED is too complex + public static Map createATPRequirementsForOrder(DispatchContext ctx, Map context) { + Delegator delegator = ctx.getDelegator(); + LocalDispatcher dispatcher = ctx.getDispatcher(); + GenericValue userLogin = (GenericValue) context.get("userLogin"); + + /* + * The strategy in this service is to begin making requirements when the product falls below the + * ProductFacility.minimumStock. Because the minimumStock is an upper bound, the quantity to be required + * is either that required to bring the ATP back up to the minimumStock level or the amount ordered, + * whichever is less. + * + * If there is a way to support reorderQuantity without losing the order item -> requirement association data, + * then this service should be updated. + * + * The result is that this service generates many small requirements when stock levels are low for a product, + * which is perfectly fine since the system is capable of creating POs in bulk from aggregate requirements. + * The only concern would be a UI to manage numerous requirements with ease, preferrably by aggregating + * on productId. + */ + String orderId = (String) context.get("orderId"); + try { + GenericValue order = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne(); + GenericValue productStore = order.getRelatedOne("ProductStore", true); + if (productStore == null) { + Debug.logInfo("ProductStore for order ID " + orderId + " not found, ATP requirements not created", module); + return ServiceUtil.returnSuccess(); + } + String facilityId = productStore.getString("inventoryFacilityId"); + List orderItems = order.getRelated("OrderItem", null, null, false); + for (GenericValue item : orderItems) { + GenericValue product = item.getRelatedOne("Product", false); + if (product == null) continue; + + if (!("PRODRQM_ATP".equals(product.get("requirementMethodEnumId")) || + ("PRODRQM_ATP".equals(productStore.get("requirementMethodEnumId")) && product.get("requirementMethodEnumId") == null))) continue; + + BigDecimal quantity = item.getBigDecimal("quantity"); + BigDecimal cancelQuantity = item.getBigDecimal("cancelQuantity"); + BigDecimal ordered = quantity.subtract(cancelQuantity == null ? BigDecimal.ZERO : cancelQuantity); + if (ordered.compareTo(BigDecimal.ZERO) <= 0) continue; + + // get the minimum stock for this facility (if not configured assume a minimum of zero, ie create requirements when it goes into backorder) + GenericValue productFacility = EntityQuery.use(delegator).from("ProductFacility").where("facilityId", facilityId, "productId", product.get("productId")).queryOne(); + BigDecimal minimumStock = BigDecimal.ZERO; + if (productFacility != null && productFacility.get("minimumStock") != null) { + minimumStock = productFacility.getBigDecimal("minimumStock"); + } + + // get the facility ATP for product, which should be updated for this item's reservation + Map results = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("userLogin", userLogin, "productId", product.get("productId"), "facilityId", facilityId)); + if (ServiceUtil.isError(results)) return results; + BigDecimal atp = ((BigDecimal) results.get("availableToPromiseTotal")); // safe since this is a required OUT param + + // count all current requirements for this product + BigDecimal pendingRequirements = BigDecimal.ZERO; + EntityConditionList ecl = EntityCondition.makeCondition(UtilMisc.toList( + EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), + EntityCondition.makeCondition("productId", EntityOperator.EQUALS, product.get("productId")), + EntityCondition.makeCondition("requirementTypeId", EntityOperator.EQUALS, "PRODUCT_REQUIREMENT"), + EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "REQ_ORDERED"), + EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "REQ_REJECTED")), + EntityOperator.AND); + List requirements = EntityQuery.use(delegator).from("Requirement").where(ecl).queryList(); + for (GenericValue requirement : requirements) { + pendingRequirements = pendingRequirements.add(requirement.get("quantity") == null ? BigDecimal.ZERO : requirement.getBigDecimal("quantity")); + } + + // the minimum stock is an upper bound, therefore we either require up to the minimum stock or the input required quantity, whichever is less + BigDecimal shortfall = minimumStock.subtract(atp).subtract(pendingRequirements); + BigDecimal required = ordered.compareTo(shortfall) < 0 ? ordered : shortfall; + if (required.compareTo(BigDecimal.ZERO) <= 0) continue; + + Map input = UtilMisc.toMap("userLogin", userLogin, "facilityId", facilityId, "productId", product.get("productId"), "quantity", required, "requirementTypeId", "PRODUCT_REQUIREMENT"); + results = dispatcher.runSync("createRequirement", input); + if (ServiceUtil.isError(results)) return results; + String requirementId = (String) results.get("requirementId"); + + input = UtilMisc.toMap("userLogin", userLogin, "orderId", order.get("orderId"), "orderItemSeqId", item.get("orderItemSeqId"), "requirementId", requirementId, "quantity", required); + results = dispatcher.runSync("createOrderRequirementCommitment", input); + if (ServiceUtil.isError(results)) return results; + } + } catch (GenericEntityException e) { + Debug.logError(e, module); + } catch (GenericServiceException e) { + Debug.logError(e, module); + } + return ServiceUtil.returnSuccess(); + } +} + diff --git a/applications/product/src/org/ofbiz/product/inventory/InventoryWorker.java b/applications/product/src/org/ofbiz/product/inventory/InventoryWorker.java index 3bc85f2ce5..25488385b8 100644 --- a/applications/product/src/org/ofbiz/product/inventory/InventoryWorker.java +++ b/applications/product/src/org/ofbiz/product/inventory/InventoryWorker.java @@ -1,147 +1,147 @@ -/* - * 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.product.inventory; - -import java.math.BigDecimal; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.entity.Delegator; -import org.ofbiz.entity.GenericEntityException; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.entity.condition.EntityCondition; -import org.ofbiz.entity.condition.EntityConditionList; -import org.ofbiz.entity.condition.EntityOperator; -import org.ofbiz.entity.util.EntityQuery; - -public class InventoryWorker { - - public final static String module = InventoryWorker.class.getName(); - - /** - * Finds all outstanding Purchase orders for a productId. The orders and the items cannot be completed, cancelled, or rejected - * @param productId the product id - * @param delegator the delegator - * @return returns all outstanding Purchase orders for a productId - */ - public static List getOutstandingPurchaseOrders(String productId, Delegator delegator) { - try { - List purchaseOrderConditions = UtilMisc.toList(EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_COMPLETED"), - EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED"), - EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"), - EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_COMPLETED"), - EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"), - EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED")); - purchaseOrderConditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "PURCHASE_ORDER")); - purchaseOrderConditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId)); - List purchaseOrders = EntityQuery.use(delegator).from("OrderHeaderAndItems") - .where(EntityCondition.makeCondition(purchaseOrderConditions, EntityOperator.AND)) - .orderBy("estimatedDeliveryDate DESC", "orderDate") - .queryList(); - return purchaseOrders; - } catch (GenericEntityException ex) { - Debug.logError("Unable to find outstanding purchase orders for product [" + productId + "] due to " + ex.getMessage() + " - returning null", module); - return null; - } - } - - /** - * Finds the net outstanding ordered quantity for a productId, netting quantity on outstanding purchase orders against cancelQuantity - * @param productId the product id - * @param delegator the delegator - * @return returns the net outstanding ordered quantity for a productId - */ - public static BigDecimal getOutstandingPurchasedQuantity(String productId, Delegator delegator) { - BigDecimal qty = BigDecimal.ZERO; - List purchaseOrders = getOutstandingPurchaseOrders(productId, delegator); - if (UtilValidate.isEmpty(purchaseOrders)) { - return qty; - } else { - for (GenericValue nextOrder: purchaseOrders) { - if (nextOrder.get("quantity") != null) { - BigDecimal itemQuantity = nextOrder.getBigDecimal("quantity"); - BigDecimal cancelQuantity = BigDecimal.ZERO; - if (nextOrder.get("cancelQuantity") != null) { - cancelQuantity = nextOrder.getBigDecimal("cancelQuantity"); - } - itemQuantity = itemQuantity.subtract(cancelQuantity); - if (itemQuantity.compareTo(BigDecimal.ZERO) >= 0) { - qty = qty.add(itemQuantity); - } - } - } - } - - return qty; - } - - /** - * Gets the quanitty of each product in the order that is outstanding across all orders of the given input type. - * Uses the OrderItemQuantityReportGroupByProduct view entity. - * - * @param productIds Collection of disticnt productIds in an order. Use OrderReadHelper.getOrderProductIds() - * @param orderTypeId Either "SALES_ORDER" or "PURCHASE_ORDER" - * @param delegator The delegator to use - * @return Map of productIds to quantities outstanding. - */ - public static Map getOutstandingProductQuantities(Collection productIds, String orderTypeId, Delegator delegator) { - Set fieldsToSelect = UtilMisc.toSet("productId", "quantityOpen"); - List condList = UtilMisc.toList( - EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, orderTypeId), - EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_COMPLETED"), - EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"), - EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED") - ); - if (productIds.size() > 0) { - condList.add(EntityCondition.makeCondition("productId", EntityOperator.IN, productIds)); - } - condList.add(EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_EQUAL, "ITEM_COMPLETED")); - condList.add(EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED")); - condList.add(EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED")); - EntityConditionList conditions = EntityCondition.makeCondition(condList, EntityOperator.AND); - - Map results = new HashMap(); - try { - List orderedProducts = EntityQuery.use(delegator).select(fieldsToSelect).from("OrderItemQuantityReportGroupByProduct").where(conditions).queryList(); - for (GenericValue value: orderedProducts) { - results.put(value.getString("productId"), value.getBigDecimal("quantityOpen")); - } - } catch (GenericEntityException e) { - Debug.logError(e, module); - } - return results; - } - - /** As above, but for sales orders */ - public static Map getOutstandingProductQuantitiesForSalesOrders(Collection productIds, Delegator delegator) { - return getOutstandingProductQuantities(productIds, "SALES_ORDER", delegator); - } - - /** As above, but for purchase orders */ - public static Map getOutstandingProductQuantitiesForPurchaseOrders(Collection productIds, Delegator delegator) { - return getOutstandingProductQuantities(productIds, "PURCHASE_ORDER", delegator); - } -} +/* + * 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.product.inventory; + +import java.math.BigDecimal; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.Delegator; +import org.ofbiz.entity.GenericEntityException; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.entity.condition.EntityCondition; +import org.ofbiz.entity.condition.EntityConditionList; +import org.ofbiz.entity.condition.EntityOperator; +import org.ofbiz.entity.util.EntityQuery; + +public class InventoryWorker { + + public final static String module = InventoryWorker.class.getName(); + + /** + * Finds all outstanding Purchase orders for a productId. The orders and the items cannot be completed, cancelled, or rejected + * @param productId the product id + * @param delegator the delegator + * @return returns all outstanding Purchase orders for a productId + */ + public static List getOutstandingPurchaseOrders(String productId, Delegator delegator) { + try { + List purchaseOrderConditions = UtilMisc.toList(EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_COMPLETED"), + EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED"), + EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"), + EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_COMPLETED"), + EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"), + EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED")); + purchaseOrderConditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "PURCHASE_ORDER")); + purchaseOrderConditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId)); + List purchaseOrders = EntityQuery.use(delegator).from("OrderHeaderAndItems") + .where(EntityCondition.makeCondition(purchaseOrderConditions, EntityOperator.AND)) + .orderBy("estimatedDeliveryDate DESC", "orderDate") + .queryList(); + return purchaseOrders; + } catch (GenericEntityException ex) { + Debug.logError("Unable to find outstanding purchase orders for product [" + productId + "] due to " + ex.getMessage() + " - returning null", module); + return null; + } + } + + /** + * Finds the net outstanding ordered quantity for a productId, netting quantity on outstanding purchase orders against cancelQuantity + * @param productId the product id + * @param delegator the delegator + * @return returns the net outstanding ordered quantity for a productId + */ + public static BigDecimal getOutstandingPurchasedQuantity(String productId, Delegator delegator) { + BigDecimal qty = BigDecimal.ZERO; + List purchaseOrders = getOutstandingPurchaseOrders(productId, delegator); + if (UtilValidate.isEmpty(purchaseOrders)) { + return qty; + } else { + for (GenericValue nextOrder: purchaseOrders) { + if (nextOrder.get("quantity") != null) { + BigDecimal itemQuantity = nextOrder.getBigDecimal("quantity"); + BigDecimal cancelQuantity = BigDecimal.ZERO; + if (nextOrder.get("cancelQuantity") != null) { + cancelQuantity = nextOrder.getBigDecimal("cancelQuantity"); + } + itemQuantity = itemQuantity.subtract(cancelQuantity); + if (itemQuantity.compareTo(BigDecimal.ZERO) >= 0) { + qty = qty.add(itemQuantity); + } + } + } + } + + return qty; + } + + /** + * Gets the quanitty of each product in the order that is outstanding across all orders of the given input type. + * Uses the OrderItemQuantityReportGroupByProduct view entity. + * + * @param productIds Collection of disticnt productIds in an order. Use OrderReadHelper.getOrderProductIds() + * @param orderTypeId Either "SALES_ORDER" or "PURCHASE_ORDER" + * @param delegator The delegator to use + * @return Map of productIds to quantities outstanding. + */ + public static Map getOutstandingProductQuantities(Collection productIds, String orderTypeId, Delegator delegator) { + Set fieldsToSelect = UtilMisc.toSet("productId", "quantityOpen"); + List condList = UtilMisc.toList( + EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, orderTypeId), + EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_COMPLETED"), + EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"), + EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED") + ); + if (productIds.size() > 0) { + condList.add(EntityCondition.makeCondition("productId", EntityOperator.IN, productIds)); + } + condList.add(EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_EQUAL, "ITEM_COMPLETED")); + condList.add(EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED")); + condList.add(EntityCondition.makeCondition("orderItemStatusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED")); + EntityConditionList conditions = EntityCondition.makeCondition(condList, EntityOperator.AND); + + Map results = new HashMap(); + try { + List orderedProducts = EntityQuery.use(delegator).select(fieldsToSelect).from("OrderItemQuantityReportGroupByProduct").where(conditions).queryList(); + for (GenericValue value: orderedProducts) { + results.put(value.getString("productId"), value.getBigDecimal("quantityOpen")); + } + } catch (GenericEntityException e) { + Debug.logError(e, module); + } + return results; + } + + /** As above, but for sales orders */ + public static Map getOutstandingProductQuantitiesForSalesOrders(Collection productIds, Delegator delegator) { + return getOutstandingProductQuantities(productIds, "SALES_ORDER", delegator); + } + + /** As above, but for purchase orders */ + public static Map getOutstandingProductQuantitiesForPurchaseOrders(Collection productIds, Delegator delegator) { + return getOutstandingProductQuantities(productIds, "PURCHASE_ORDER", delegator); + } +} diff --git a/framework/base/src/org/ofbiz/base/concurrent/ExecutionPool.java b/framework/base/src/org/ofbiz/base/concurrent/ExecutionPool.java index fa224776fc..04359a7e3c 100644 --- a/framework/base/src/org/ofbiz/base/concurrent/ExecutionPool.java +++ b/framework/base/src/org/ofbiz/base/concurrent/ExecutionPool.java @@ -1,155 +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(), 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 List getAllFutures(Collection> futureList) { - List result = new LinkedList(); - for (Future 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 delayQueue = new DelayQueue(); - - 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; - } - } - -} +/******************************************************************************* + * 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(), 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 List getAllFutures(Collection> futureList) { + List result = new LinkedList(); + for (Future 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 delayQueue = new DelayQueue(); + + 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; + } + } + +} diff --git a/framework/base/src/org/ofbiz/base/config/CoberturaInstrumenter.java b/framework/base/src/org/ofbiz/base/config/CoberturaInstrumenter.java index df48e057c0..f44357cef1 100644 --- a/framework/base/src/org/ofbiz/base/config/CoberturaInstrumenter.java +++ b/framework/base/src/org/ofbiz/base/config/CoberturaInstrumenter.java @@ -1,94 +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.config; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.Collections; - -import net.sourceforge.cobertura.coveragedata.CoverageDataFileHandler; -import net.sourceforge.cobertura.coveragedata.ProjectData; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.ofbiz.base.start.Instrumenter; - -public final class CoberturaInstrumenter implements Instrumenter { - private static final Constructor INSTRUMENTER_CONSTRUCTOR; - private static final Method IS_INSTRUMENTED_METHOD; - static { - try { - Class clz = CoberturaInstrumenter.class.getClassLoader().loadClass("net.sourceforge.cobertura.instrument.ClassInstrumenter"); - INSTRUMENTER_CONSTRUCTOR = clz.getConstructor(ProjectData.class, ClassVisitor.class, Collection.class, Collection.class); - INSTRUMENTER_CONSTRUCTOR.setAccessible(true); - IS_INSTRUMENTED_METHOD = clz.getDeclaredMethod("isInstrumented"); - IS_INSTRUMENTED_METHOD.setAccessible(true); - } catch (Throwable t) { - throw (InternalError) new InternalError(t.getMessage()).initCause(t); - } - } - - protected File dataFile; - protected ProjectData projectData; - protected boolean forInstrumenting; - - public File getDefaultFile() throws IOException { - return CoverageDataFileHandler.getDefaultDataFile(); - } - - public void open(File dataFile, boolean forInstrumenting) throws IOException { - System.setProperty("net.sourceforge.cobertura.datafile", dataFile.toString()); - this.forInstrumenting = forInstrumenting; - this.dataFile = dataFile; - if (forInstrumenting) { - if (dataFile.exists()) { - projectData = CoverageDataFileHandler.loadCoverageData(dataFile); - } else { - projectData = new ProjectData(); - } - } - } - - public void close() throws IOException { - if (forInstrumenting) { - CoverageDataFileHandler.saveCoverageData(projectData, dataFile); - } - } - - public byte[] instrumentClass(byte[] bytes) throws IOException { - if (forInstrumenting) { - ClassReader cr = new ClassReader(bytes); - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS/* | ClassWriter.COMPUTE_FRAMES*/); - try { - ClassVisitor ci = (ClassVisitor) INSTRUMENTER_CONSTRUCTOR.newInstance(projectData, cw, Collections.EMPTY_LIST, Collections.EMPTY_LIST); - cr.accept(ci, 0); - if (((Boolean) IS_INSTRUMENTED_METHOD.invoke(ci)).booleanValue()) { - return cw.toByteArray(); - } - } catch (Throwable t) { - throw (IOException) new IOException(t.getMessage()).initCause(t); - } - } - return bytes; - } -} +/******************************************************************************* + * 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.File; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Collections; + +import net.sourceforge.cobertura.coveragedata.CoverageDataFileHandler; +import net.sourceforge.cobertura.coveragedata.ProjectData; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.ofbiz.base.start.Instrumenter; + +public final class CoberturaInstrumenter implements Instrumenter { + private static final Constructor INSTRUMENTER_CONSTRUCTOR; + private static final Method IS_INSTRUMENTED_METHOD; + static { + try { + Class clz = CoberturaInstrumenter.class.getClassLoader().loadClass("net.sourceforge.cobertura.instrument.ClassInstrumenter"); + INSTRUMENTER_CONSTRUCTOR = clz.getConstructor(ProjectData.class, ClassVisitor.class, Collection.class, Collection.class); + INSTRUMENTER_CONSTRUCTOR.setAccessible(true); + IS_INSTRUMENTED_METHOD = clz.getDeclaredMethod("isInstrumented"); + IS_INSTRUMENTED_METHOD.setAccessible(true); + } catch (Throwable t) { + throw (InternalError) new InternalError(t.getMessage()).initCause(t); + } + } + + protected File dataFile; + protected ProjectData projectData; + protected boolean forInstrumenting; + + public File getDefaultFile() throws IOException { + return CoverageDataFileHandler.getDefaultDataFile(); + } + + public void open(File dataFile, boolean forInstrumenting) throws IOException { + System.setProperty("net.sourceforge.cobertura.datafile", dataFile.toString()); + this.forInstrumenting = forInstrumenting; + this.dataFile = dataFile; + if (forInstrumenting) { + if (dataFile.exists()) { + projectData = CoverageDataFileHandler.loadCoverageData(dataFile); + } else { + projectData = new ProjectData(); + } + } + } + + public void close() throws IOException { + if (forInstrumenting) { + CoverageDataFileHandler.saveCoverageData(projectData, dataFile); + } + } + + public byte[] instrumentClass(byte[] bytes) throws IOException { + if (forInstrumenting) { + ClassReader cr = new ClassReader(bytes); + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS/* | ClassWriter.COMPUTE_FRAMES*/); + try { + ClassVisitor ci = (ClassVisitor) INSTRUMENTER_CONSTRUCTOR.newInstance(projectData, cw, Collections.EMPTY_LIST, Collections.EMPTY_LIST); + cr.accept(ci, 0); + if (((Boolean) IS_INSTRUMENTED_METHOD.invoke(ci)).booleanValue()) { + return cw.toByteArray(); + } + } catch (Throwable t) { + throw (IOException) new IOException(t.getMessage()).initCause(t); + } + } + return bytes; + } +} diff --git a/framework/base/src/org/ofbiz/base/container/JustLoadComponentsContainer.java b/framework/base/src/org/ofbiz/base/container/JustLoadComponentsContainer.java index 796f21dec1..fa80c284fb 100644 --- a/framework/base/src/org/ofbiz/base/container/JustLoadComponentsContainer.java +++ b/framework/base/src/org/ofbiz/base/container/JustLoadComponentsContainer.java @@ -1,58 +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; - } -} +/******************************************************************************* + * 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; + } +} diff --git a/framework/base/src/org/ofbiz/base/conversion/GenericSingletonToList.java b/framework/base/src/org/ofbiz/base/conversion/GenericSingletonToList.java index c2bc7780d8..349a8b6464 100644 --- a/framework/base/src/org/ofbiz/base/conversion/GenericSingletonToList.java +++ b/framework/base/src/org/ofbiz/base/conversion/GenericSingletonToList.java @@ -1,34 +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 extends AbstractConverter> { - public GenericSingletonToList(Class sourceClass) { - super(sourceClass, List.class); - } - - public List convert(T obj) throws ConversionException { - List tempList = new LinkedList(); - tempList.add(obj); - return tempList; - } -} +/******************************************************************************* + * 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 extends AbstractConverter> { + public GenericSingletonToList(Class sourceClass) { + super(sourceClass, List.class); + } + + public List convert(T obj) throws ConversionException { + List tempList = new LinkedList(); + tempList.add(obj); + return tempList; + } +} diff --git a/framework/base/src/org/ofbiz/base/conversion/GenericSingletonToSet.java b/framework/base/src/org/ofbiz/base/conversion/GenericSingletonToSet.java index 34216f0dcf..a5ad343815 100644 --- a/framework/base/src/org/ofbiz/base/conversion/GenericSingletonToSet.java +++ b/framework/base/src/org/ofbiz/base/conversion/GenericSingletonToSet.java @@ -1,34 +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 extends AbstractConverter> { - public GenericSingletonToSet(Class sourceClass) { - super(sourceClass, Set.class); - } - - public Set convert(T obj) throws ConversionException { - Set tempSet = new HashSet(); - tempSet.add(obj); - return tempSet; - } -} +/******************************************************************************* + * 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 extends AbstractConverter> { + public GenericSingletonToSet(Class sourceClass) { + super(sourceClass, Set.class); + } + + public Set convert(T obj) throws ConversionException { + Set tempSet = new HashSet(); + tempSet.add(obj); + return tempSet; + } +} diff --git a/framework/base/src/org/ofbiz/base/conversion/JSONConverters.java b/framework/base/src/org/ofbiz/base/conversion/JSONConverters.java index 718a54ab99..28cebc07b2 100644 --- a/framework/base/src/org/ofbiz/base/conversion/JSONConverters.java +++ b/framework/base/src/org/ofbiz/base/conversion/JSONConverters.java @@ -1,90 +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> { - public JSONToList() { - super(JSON.class, List.class); - } - - public List convert(JSON obj) throws ConversionException { - try { - return UtilGenerics.>cast(obj.toObject(List.class)); - } catch (IOException e) { - throw new ConversionException(e); - } - } - } - - public static class JSONToMap extends AbstractConverter> { - public JSONToMap() { - super(JSON.class, Map.class); - } - - public Map convert(JSON obj) throws ConversionException { - try { - return UtilGenerics.>cast(obj.toObject(Map.class)); - } catch (IOException e) { - throw new ConversionException(e); - } - } - } - - public static class ListToJSON extends AbstractConverter, JSON> { - public ListToJSON() { - super(List.class, JSON.class); - } - - public JSON convert(List obj) throws ConversionException { - try { - return JSON.from(obj); - } catch (IOException e) { - throw new ConversionException(e); - } - } - } - - public static class MapToJSON extends AbstractConverter, JSON> { - public MapToJSON() { - super(Map.class, JSON.class); - } - - public JSON convert(Map obj) throws ConversionException { - try { - return JSON.from(obj); - } catch (IOException e) { - throw new ConversionException(e); - } - } - } - - public void loadConverters() { - Converters.loadContainedConverters(JSONConverters.class); - } -} +/******************************************************************************* + * 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> { + public JSONToList() { + super(JSON.class, List.class); + } + + public List convert(JSON obj) throws ConversionException { + try { + return UtilGenerics.>cast(obj.toObject(List.class)); + } catch (IOException e) { + throw new ConversionException(e); + } + } + } + + public static class JSONToMap extends AbstractConverter> { + public JSONToMap() { + super(JSON.class, Map.class); + } + + public Map convert(JSON obj) throws ConversionException { + try { + return UtilGenerics.>cast(obj.toObject(Map.class)); + } catch (IOException e) { + throw new ConversionException(e); + } + } + } + + public static class ListToJSON extends AbstractConverter, JSON> { + public ListToJSON() { + super(List.class, JSON.class); + } + + public JSON convert(List obj) throws ConversionException { + try { + return JSON.from(obj); + } catch (IOException e) { + throw new ConversionException(e); + } + } + } + + public static class MapToJSON extends AbstractConverter, JSON> { + public MapToJSON() { + super(Map.class, JSON.class); + } + + public JSON convert(Map obj) throws ConversionException { + try { + return JSON.from(obj); + } catch (IOException e) { + throw new ConversionException(e); + } + } + } + + public void loadConverters() { + Converters.loadContainedConverters(JSONConverters.class); + } +} diff --git a/framework/base/src/org/ofbiz/base/conversion/NetConverters.java b/framework/base/src/org/ofbiz/base/conversion/NetConverters.java index d97d800194..07816185d2 100644 --- a/framework/base/src/org/ofbiz/base/conversion/NetConverters.java +++ b/framework/base/src/org/ofbiz/base/conversion/NetConverters.java @@ -1,137 +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 { - 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 { - 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 { - 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 { - public URIToString() { - super(URI.class, String.class); - } - - public String convert(URI obj) throws ConversionException { - return obj.toString(); - } - } - - public static class StringToURL extends AbstractConverter { - 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 { - public URLToString() { - super(URL.class, String.class); - } - - public String convert(URL obj) throws ConversionException { - return obj.toString(); - } - } - - public static class URIToURL extends AbstractConverter { - 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 { - 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); - } -} +/******************************************************************************* + * 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 { + 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 { + 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 { + 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 { + public URIToString() { + super(URI.class, String.class); + } + + public String convert(URI obj) throws ConversionException { + return obj.toString(); + } + } + + public static class StringToURL extends AbstractConverter { + 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 { + public URLToString() { + super(URL.class, String.class); + } + + public String convert(URL obj) throws ConversionException { + return obj.toString(); + } + } + + public static class URIToURL extends AbstractConverter { + 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 { + 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); + } +} diff --git a/framework/base/src/org/ofbiz/base/conversion/test/DateTimeTests.java b/framework/base/src/org/ofbiz/base/conversion/test/DateTimeTests.java index ef10d4402f..0e6e2b7611 100644 --- a/framework/base/src/org/ofbiz/base/conversion/test/DateTimeTests.java +++ b/framework/base/src/org/ofbiz/base/conversion/test/DateTimeTests.java @@ -1,75 +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 void assertConversion(String label, Converter 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); - } -} +/******************************************************************************* + * 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 void assertConversion(String label, Converter 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); + } +} diff --git a/framework/base/src/org/ofbiz/base/conversion/test/MiscTests.java b/framework/base/src/org/ofbiz/base/conversion/test/MiscTests.java index 9cd129b1bc..407088b366 100644 --- a/framework/base/src/org/ofbiz/base/conversion/test/MiscTests.java +++ b/framework/base/src/org/ofbiz/base/conversion/test/MiscTests.java @@ -1,103 +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 void assertPassThru(Object wanted, Class sourceClass) throws Exception { - assertPassThru(wanted, sourceClass, sourceClass); - } - - public static void assertPassThru(Object wanted, Class sourceClass, Class targetClass) throws Exception { - Converter converter = Converters.getConverter(sourceClass, targetClass); - Object result = converter.convert(UtilGenerics.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 baseList = UtilMisc.toList("a", "1", "b", "2", "c", "3"); - ArrayList arrayList = new ArrayList(); - arrayList.addAll(baseList); - List fastList = new LinkedList(); - fastList.addAll(baseList); - Map baseMap = UtilMisc.toMap("a", "1", "b", "2", "c", "3"); - HashMap hashMap = new HashMap(); - hashMap.putAll(baseMap); - Map fastMap = new HashMap(); - 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); - } -} +/******************************************************************************* + * 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 void assertPassThru(Object wanted, Class sourceClass) throws Exception { + assertPassThru(wanted, sourceClass, sourceClass); + } + + public static void assertPassThru(Object wanted, Class sourceClass, Class targetClass) throws Exception { + Converter converter = Converters.getConverter(sourceClass, targetClass); + Object result = converter.convert(UtilGenerics.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 baseList = UtilMisc.toList("a", "1", "b", "2", "c", "3"); + ArrayList arrayList = new ArrayList(); + arrayList.addAll(baseList); + List fastList = new LinkedList(); + fastList.addAll(baseList); + Map baseMap = UtilMisc.toMap("a", "1", "b", "2", "c", "3"); + HashMap hashMap = new HashMap(); + hashMap.putAll(baseMap); + Map fastMap = new HashMap(); + 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); + } +} diff --git a/framework/base/src/org/ofbiz/base/lang/IsEmpty.java b/framework/base/src/org/ofbiz/base/lang/IsEmpty.java index caaacc5694..fdee6b9eec 100644 --- a/framework/base/src/org/ofbiz/base/lang/IsEmpty.java +++ b/framework/base/src/org/ofbiz/base/lang/IsEmpty.java @@ -1,23 +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(); -} +/* + * 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(); +} diff --git a/framework/base/src/org/ofbiz/base/lang/JSON.java b/framework/base/src/org/ofbiz/base/lang/JSON.java index 16a0143481..350ab6415a 100644 --- a/framework/base/src/org/ofbiz/base/lang/JSON.java +++ b/framework/base/src/org/ofbiz/base/lang/JSON.java @@ -1,136 +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 JSON instance from an InputStream. - * The method assumes the character set is UTF-8. - * - * @param inStream - * @return a JSON 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 JSON instance from an unknown data type. - * - * @param object - * @return a JSON 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 JSON instance from a Reader. - * - * @param reader - * @return a JSON 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 JSON instance from a String. - * - * @param jsonString - * @return a JSON 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 JSON object to the specified type. - * - * @param targetClass - * @return an object of the specified type - * @throws IOException - */ - public T toObject(Class 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; - } -} +/******************************************************************************* + * 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 JSON instance from an InputStream. + * The method assumes the character set is UTF-8. + * + * @param inStream + * @return a JSON 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 JSON instance from an unknown data type. + * + * @param object + * @return a JSON 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 JSON instance from a Reader. + * + * @param reader + * @return a JSON 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 JSON instance from a String. + * + * @param jsonString + * @return a JSON 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 JSON object to the specified type. + * + * @param targetClass + * @return an object of the specified type + * @throws IOException + */ + public T toObject(Class 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; + } +} diff --git a/framework/base/src/org/ofbiz/base/lang/LockedBy.java b/framework/base/src/org/ofbiz/base/lang/LockedBy.java index 1f1e490419..ed15d81c6d 100644 --- a/framework/base/src/org/ofbiz/base/lang/LockedBy.java +++ b/framework/base/src/org/ofbiz/base/lang/LockedBy.java @@ -1,37 +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 this. - */ -@Documented -@Retention(RetentionPolicy.SOURCE) -@Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD}) -public @interface LockedBy { - String value(); -} +/* + * 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 this. + */ +@Documented +@Retention(RetentionPolicy.SOURCE) +@Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD}) +public @interface LockedBy { + String value(); +} diff --git a/framework/base/src/org/ofbiz/base/lang/SourceMonitored.java b/framework/base/src/org/ofbiz/base/lang/SourceMonitored.java index 17192ce47e..ea1fffd3b4 100644 --- a/framework/base/src/org/ofbiz/base/lang/SourceMonitored.java +++ b/framework/base/src/org/ofbiz/base/lang/SourceMonitored.java @@ -1,29 +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 { -} +/******************************************************************************* + * 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 { +} diff --git a/framework/base/src/org/ofbiz/base/lang/test/ComparableRangeTests.java b/framework/base/src/org/ofbiz/base/lang/test/ComparableRangeTests.java index be680fb9b1..46ce339737 100644 --- a/framework/base/src/org/ofbiz/base/lang/test/ComparableRangeTests.java +++ b/framework/base/src/org/ofbiz/base/lang/test/ComparableRangeTests.java @@ -1,128 +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 , R extends Comparable> void comparableRangeConstructorTest(L left, R right) { - new ComparableRange(left, left); - new ComparableRange(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 , B extends Comparable> void comparableRangeTest(String label, B bad, T a, T b, T c, T d) { - comparableRangeConstructorTest(bad, a); - assertTrue(label + ":a-isPoint", new ComparableRange(a, a).isPoint()); - assertTrue(label + ":b-isPoint", new ComparableRange(b, b).isPoint()); - assertTrue(label + ":c-isPoint", new ComparableRange(c, c).isPoint()); - ComparableRange first = new ComparableRange(a, b); - ComparableRange second = new ComparableRange(c, d); - ComparableRange all = new ComparableRange(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(a, b)); - assertEquals(label + ":a-b.compareTo(new a-b)", 0, first.compareTo(new ComparableRange(a, b))); - assertEquals(label + ":a-b equals b-a", first, new ComparableRange(b, a)); - assertEquals(label + ":a-b.compareTo(new b-a)", 0, first.compareTo(new ComparableRange(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.>cast(first).compareTo(ComparableRangeTests.class); - } catch (ClassCastException e) { - caught = e; - } finally { - assertNotNull(label + " compareTo CCE", caught); - } - assertNotEquals(label + ":a-a != a-b", new ComparableRange(a, a), first); - assertThat(label + ":a-a.compareTo(a-b) < 0", 0, greaterThan(new ComparableRange(a, a).compareTo(first))); - assertNotEquals(label + ":a-a != c-d", new ComparableRange(a, a), second); - assertThat(label + ":a-a.compareTo(c-d) < 0", 0, greaterThan(new ComparableRange(a, a).compareTo(second))); - assertNotEquals(label + ":a-a != a-d", new ComparableRange(a, a), all); - assertThat(label + ":a-a.compareTo(a-d) < 0", 0, greaterThan(new ComparableRange(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(b, c))); - assertTrue(label + ":b-c overlaps c-d", new ComparableRange(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(b, c))); - assertTrue(label + ":b-c overlaps a-d", new ComparableRange(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(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); - } -} +/******************************************************************************* + * 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 , R extends Comparable> void comparableRangeConstructorTest(L left, R right) { + new ComparableRange(left, left); + new ComparableRange(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 , B extends Comparable> void comparableRangeTest(String label, B bad, T a, T b, T c, T d) { + comparableRangeConstructorTest(bad, a); + assertTrue(label + ":a-isPoint", new ComparableRange(a, a).isPoint()); + assertTrue(label + ":b-isPoint", new ComparableRange(b, b).isPoint()); + assertTrue(label + ":c-isPoint", new ComparableRange(c, c).isPoint()); + ComparableRange first = new ComparableRange(a, b); + ComparableRange second = new ComparableRange(c, d); + ComparableRange all = new ComparableRange(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(a, b)); + assertEquals(label + ":a-b.compareTo(new a-b)", 0, first.compareTo(new ComparableRange(a, b))); + assertEquals(label + ":a-b equals b-a", first, new ComparableRange(b, a)); + assertEquals(label + ":a-b.compareTo(new b-a)", 0, first.compareTo(new ComparableRange(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.>cast(first).compareTo(ComparableRangeTests.class); + } catch (ClassCastException e) { + caught = e; + } finally { + assertNotNull(label + " compareTo CCE", caught); + } + assertNotEquals(label + ":a-a != a-b", new ComparableRange(a, a), first); + assertThat(label + ":a-a.compareTo(a-b) < 0", 0, greaterThan(new ComparableRange(a, a).compareTo(first))); + assertNotEquals(label + ":a-a != c-d", new ComparableRange(a, a), second); + assertThat(label + ":a-a.compareTo(c-d) < 0", 0, greaterThan(new ComparableRange(a, a).compareTo(second))); + assertNotEquals(label + ":a-a != a-d", new ComparableRange(a, a), all); + assertThat(label + ":a-a.compareTo(a-d) < 0", 0, greaterThan(new ComparableRange(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(b, c))); + assertTrue(label + ":b-c overlaps c-d", new ComparableRange(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(b, c))); + assertTrue(label + ":b-c overlaps a-d", new ComparableRange(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(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); + } +} diff --git a/framework/base/src/org/ofbiz/base/test/GenericTestCaseBase.java b/framework/base/src/org/ofbiz/base/test/GenericTestCaseBase.java index af70abfda6..4905798f13 100644 --- a/framework/base/src/org/ofbiz/base/test/GenericTestCaseBase.java +++ b/framework/base/src/org/ofbiz/base/test/GenericTestCaseBase.java @@ -1,389 +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 dummy = new LinkedList(); - 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 void assertFuture(String label, Future future, V wanted, boolean interruptable, Class 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 void assertNotEquals(Object wanted, Object got) { - assertNotEquals(null, wanted, got); - } - - public static 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 void assertEquals(List wanted, Object got) { - assertEquals(null, wanted, got); - } - - public static void assertEquals(String msg, List 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 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 void assertEquals(Collection wanted, Object got) { - assertEquals(null, wanted, got); - } - - public static void assertEquals(String msg, Collection 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 list = new ArrayList(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 void assertEquals(Set wanted, Object got) { - assertEquals(null, wanted, got); - } - - public static void assertEquals(String msg, Set 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 wantedSet = new HashSet(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 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 void assertEqualsArrayList(String msg, Object wanted, List got) { - Iterator 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 void assertEqualsListArray(String msg, List wanted, Object got) { - Iterator 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 > void assertEqualsIterable(String label, List wanted, I got) { - assertEqualsIterable(label, wanted, 0, got, 0); - } - - public static > void assertEqualsIterable(String label, List wanted, int wantedExtra, I got, int gotExtra) { - Iterator wantedIt = wanted.iterator(); - Iterator 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 > void assertEqualsIterable(String label, List wanted, List wantedExtra, I got, List gotExtra) { - assertEqualsIterable(label, wanted, wantedExtra, false, got, gotExtra, false); - } - - public static > void assertEqualsIterable(String label, List wanted, List wantedExtra, boolean removeWanted, I got, List gotExtra, boolean removeGot) { - Iterator wantedIt = wanted.iterator(); - Iterator 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 void assertEquals(Map wanted, Object got) { - assertEquals(null, wanted, got); - } - - public static void assertEquals(String msg, Map 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 leftKeys = new LinkedHashSet(wanted.keySet()); - HashSet rightKeys = new HashSet(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 List list(T value) { - ArrayList list = new ArrayList(1); - list.add(value); - return list; - } - - public static List list(T... list) { - return new ArrayList(Arrays.asList(list)); - } - - public static Set set(T value) { - HashSet set = new HashSet(1); - set.add(value); - return set; - } - - public static Set set(T... list) { - return new HashSet(Arrays.asList(list)); - } - - public static Set set(Iterable iterable) { - return set(iterable.iterator()); - } - - public static Set set(Iterator it) { - HashSet set = new HashSet(); - while (it.hasNext()) { - T item = it.next(); - set.add(item); - } - return set; - } - - @SuppressWarnings("unchecked") - public static Map map(Object... list) { - assertEquals("list has even number of elements", 0, list.length % 2); - Map map = new LinkedHashMap(); - for (int i = 0; i < list.length; i += 2) { - map.put((K) list[i], (V) list[i + 1]); - } - return map; - } -} +/******************************************************************************* + * 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 dummy = new LinkedList(); + 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 void assertFuture(String label, Future future, V wanted, boolean interruptable, Class 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 void assertNotEquals(Object wanted, Object got) { + assertNotEquals(null, wanted, got); + } + + public static 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 void assertEquals(List wanted, Object got) { + assertEquals(null, wanted, got); + } + + public static void assertEquals(String msg, List 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 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 void assertEquals(Collection wanted, Object got) { + assertEquals(null, wanted, got); + } + + public static void assertEquals(String msg, Collection 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 list = new ArrayList(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 void assertEquals(Set wanted, Object got) { + assertEquals(null, wanted, got); + } + + public static void assertEquals(String msg, Set 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 wantedSet = new HashSet(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 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 void assertEqualsArrayList(String msg, Object wanted, List got) { + Iterator 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 void assertEqualsListArray(String msg, List wanted, Object got) { + Iterator 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 > void assertEqualsIterable(String label, List wanted, I got) { + assertEqualsIterable(label, wanted, 0, got, 0); + } + + public static > void assertEqualsIterable(String label, List wanted, int wantedExtra, I got, int gotExtra) { + Iterator wantedIt = wanted.iterator(); + Iterator 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 > void assertEqualsIterable(String label, List wanted, List wantedExtra, I got, List gotExtra) { + assertEqualsIterable(label, wanted, wantedExtra, false, got, gotExtra, false); + } + + public static > void assertEqualsIterable(String label, List wanted, List wantedExtra, boolean removeWanted, I got, List gotExtra, boolean removeGot) { + Iterator wantedIt = wanted.iterator(); + Iterator 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 void assertEquals(Map wanted, Object got) { + assertEquals(null, wanted, got); + } + + public static void assertEquals(String msg, Map 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 leftKeys = new LinkedHashSet(wanted.keySet()); + HashSet rightKeys = new HashSet(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 List list(T value) { + ArrayList list = new ArrayList(1); + list.add(value); + return list; + } + + public static List list(T... list) { + return new ArrayList(Arrays.asList(list)); + } + + public static Set set(T value) { + HashSet set = new HashSet(1); + set.add(value); + return set; + } + + public static Set set(T... list) { + return new HashSet(Arrays.asList(list)); + } + + public static Set set(Iterable iterable) { + return set(iterable.iterator()); + } + + public static Set set(Iterator it) { + HashSet set = new HashSet(); + while (it.hasNext()) { + T item = it.next(); + set.add(item); + } + return set; + } + + @SuppressWarnings("unchecked") + public static Map map(Object... list) { + assertEquals("list has even number of elements", 0, list.length % 2); + Map map = new LinkedHashMap(); + for (int i = 0; i < list.length; i += 2) { + map.put((K) list[i], (V) list[i + 1]); + } + return map; + } +} diff --git a/framework/base/src/org/ofbiz/base/util/IndentingWriter.java b/framework/base/src/org/ofbiz/base/util/IndentingWriter.java index 5e74bbc1e8..b389d7b645 100644 --- a/framework/base/src/org/ofbiz/base/util/IndentingWriter.java +++ b/framework/base/src/org/ofbiz/base/util/IndentingWriter.java @@ -1,132 +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); - } -} +/******************************************************************************* + * 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); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/RMIExtendedSocketFactory.java b/framework/base/src/org/ofbiz/base/util/RMIExtendedSocketFactory.java index cea76080dd..39d0c5740d 100644 --- a/framework/base/src/org/ofbiz/base/util/RMIExtendedSocketFactory.java +++ b/framework/base/src/org/ofbiz/base/util/RMIExtendedSocketFactory.java @@ -1,104 +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 RMISocketFactory implementation that creates ServerSockets bound - * on a specified network interface. - */ -public class RMIExtendedSocketFactory extends RMISocketFactory { - - /** - * The network interface to bind the ServerSocket 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 RMIExtendedSocketFactory which will create ServerSockets - * bound on the specified network interface. - * - * @param inetAddress The InetAddress of the network interface. - */ - public RMIExtendedSocketFactory( InetAddress inetAddress ) { - this.hostInetAddress = inetAddress; - } - - /** - * Creates a new RMIExtendedSocketFactory which will create ServerSockets - * 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 ); - } - -} +/******************************************************************************* + * 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 RMISocketFactory implementation that creates ServerSockets bound + * on a specified network interface. + */ +public class RMIExtendedSocketFactory extends RMISocketFactory { + + /** + * The network interface to bind the ServerSocket 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 RMIExtendedSocketFactory which will create ServerSockets + * bound on the specified network interface. + * + * @param inetAddress The InetAddress of the network interface. + */ + public RMIExtendedSocketFactory( InetAddress inetAddress ) { + this.hostInetAddress = inetAddress; + } + + /** + * Creates a new RMIExtendedSocketFactory which will create ServerSockets + * 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 ); + } + +} diff --git a/framework/base/src/org/ofbiz/base/util/ReferenceCleaner.java b/framework/base/src/org/ofbiz/base/util/ReferenceCleaner.java index 7657d7c881..b9102c8b8c 100644 --- a/framework/base/src/org/ofbiz/base/util/ReferenceCleaner.java +++ b/framework/base/src/org/ofbiz/base/util/ReferenceCleaner.java @@ -1,89 +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 QUEUE = new ReferenceQueue(); - - public interface Removable { - void remove() throws Exception; - } - - public abstract static class Soft extends SoftReference implements Removable { - public Soft(V value) { - super(value, QUEUE); - } - } - - public abstract static class Phantom extends PhantomReference implements Removable { - public Phantom(V value) { - super(value, QUEUE); - } - } - - public abstract static class Weak extends WeakReference implements Removable { - public Weak(V value) { - super(value, QUEUE); - } - } -} +/******************************************************************************* + * 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 QUEUE = new ReferenceQueue(); + + public interface Removable { + void remove() throws Exception; + } + + public abstract static class Soft extends SoftReference implements Removable { + public Soft(V value) { + super(value, QUEUE); + } + } + + public abstract static class Phantom extends PhantomReference implements Removable { + public Phantom(V value) { + super(value, QUEUE); + } + } + + public abstract static class Weak extends WeakReference implements Removable { + public Weak(V value) { + super(value, QUEUE); + } + } +} diff --git a/framework/base/src/org/ofbiz/base/util/UtilIO.java b/framework/base/src/org/ofbiz/base/util/UtilIO.java index d679d74e92..ecbfee64d9 100644 --- a/framework/base/src/org/ofbiz/base/util/UtilIO.java +++ b/framework/base/src/org/ofbiz/base/util/UtilIO.java @@ -1,318 +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.BufferedInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.Writer; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; - -import org.apache.commons.io.IOUtils; - -public final class UtilIO { - public static final Charset UTF8 = Charset.forName("UTF-8"); - public static final String module = UtilIO.class.getName(); - - /** Copy an InputStream to an OutputStream, optionally closing either - * the input or the output. - * - * @param in the InputStream to copy from - * @param closeIn whether to close the input when the copy is done - * @param out the OutputStream to copy to - * @param closeOut whether to close the output when the copy is done - * @throws IOException if an error occurs - */ - public static void copy(InputStream in, boolean closeIn, OutputStream out, boolean closeOut) throws IOException { - try { - try { - IOUtils.copy(in, out); - } finally { - if (closeIn) IOUtils.closeQuietly(in); - } - } finally { - if (closeOut) IOUtils.closeQuietly(out); - } - } - - /** Copy a Reader to a Writer, optionally closing either the input or - * the output. - * - * @param reader the Reader to copy from - * @param closeIn whether to close the input when the copy is done - * @param writer the Writer to copy to - * @param closeOut whether to close the output when the copy is done - * @throws IOException if an error occurs - */ - public static void copy(Reader reader, boolean closeIn, Writer writer, boolean closeOut) throws IOException { - try { - try { - IOUtils.copy(reader, writer); - } finally { - if (closeIn) IOUtils.closeQuietly(reader); - } - } finally { - if (closeOut) IOUtils.closeQuietly(writer); - } - } - - /** Copy a Reader to an Appendable, optionally closing the input. - * - * @param reader the Reader to copy from - * @param closeIn whether to close the input when the copy is done - * @param out the Appendable to copy to - * @throws IOException if an error occurs - */ - public static void copy(Reader reader, boolean closeIn, Appendable out) throws IOException { - try { - CharBuffer buffer = CharBuffer.allocate(4096); - while (reader.read(buffer) > 0) { - buffer.flip(); - buffer.rewind(); - out.append(buffer); - } - } finally { - if (closeIn) IOUtils.closeQuietly(reader); - } - } - - /** Convert a byte array to a string; consistently uses \n line endings - * in java. This uses a default {@link Charset UTF-8} charset. - * - * @param bytes the array of bytes to convert - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes) throws IOException { - return readString(bytes, 0, bytes.length, UTF8); - } - - /** Convert a byte array to a string; consistently uses \n line endings - * in java. The conversion is limited to the specified offset/length - * pair, and uses a default {@link Charset UTF-8} charset. - * - * @param bytes the array of bytes to convert - * @param offset the start of the conversion - * @param length how many bytes to convert - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes, int offset, int length) throws IOException { - return readString(bytes, offset, length, UTF8); - } - - /** Convert a byte array to a string; consistently uses \n line endings - * in java. The conversion is limited to the specified offset/length - * pair, and uses the requested charset to decode the bytes. - * - * @param bytes the array of bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes, String charset) throws IOException { - return readString(bytes, 0, bytes.length, Charset.forName(charset)); - } - - /** Convert a byte array to a string; consistently uses \n line - * endings in java. The conversion is limited to the specified - * offset/length pair, and uses the requested charset to decode the - * bytes. - * - * @param bytes the array of bytes to convert - * @param offset the start of the conversion - * @param length how many bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes, int offset, int length, String charset) throws IOException { - return readString(bytes, 0, bytes.length, Charset.forName(charset)); - } - - /** Convert a byte array to a string, consistently uses \n line - * endings in java. The specified {@link Charset charset} is used - * to decode the bytes. - * @param bytes the array of bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes, Charset charset) throws IOException { - return readString(bytes, 0, bytes.length, charset); - } - - /** Convert a byte array to a string, consistently uses \n line - * endings in java. The conversion is limited to the specified - * offset/length pair, and uses the requested {@link Charset - * charset} to decode the bytes. - * - * @param bytes the array of bytes to convert - * @param offset the start of the conversion - * @param length how many bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes, int offset, int length, Charset charset) throws IOException { - ByteBuffer buf = ByteBuffer.allocate(length); - buf.put(bytes, offset, length); - buf.flip(); - return filterLineEndings(new StringBuilder(charset.decode(buf).toString())).toString(); - } - - /** Convert an {@link InputStream} to a string; consistently uses \n line endings - * in java. This uses a default {@link Charset UTF-8} charset. - * - * @param stream the stream of bytes to convert - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(InputStream stream) throws IOException { - return readString(stream, UTF8); - } - - /** Convert an {@link InputStream} to a string; consistently uses \n line endings - * in java. This uses a default {@link Charset UTF-8} charset. - * - * @param stream the stream of bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(InputStream stream, String charset) throws IOException { - return readString(stream, Charset.forName(charset)); - } - - /** Convert an {@link InputStream} to a string; consistently uses \n line endings - * in java. This uses a default {@link Charset UTF-8} charset. - * - * @param stream the stream of bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(InputStream stream, Charset charset) throws IOException { - return readString(new InputStreamReader(new BufferedInputStream(stream), charset)); - } - - /** Convert an {@link Reader} to a string; consistently uses \n line endings - * in java. - * - * @param reader the stream of characters convert - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(Reader reader) throws IOException { - try { - StringBuilder sb = new StringBuilder(); - char[] buf = new char[4096]; - int r; - while ((r = reader.read(buf, 0, 4096)) > 0) { - sb.append(buf, 0, r); - } - return filterLineEndings(sb).toString(); - } finally { - try { - reader.close(); - } catch (IOException e) { - Debug.logError(e, "Error closing after reading text: " + e.toString(), module); - } - } - } - - private static StringBuilder filterLineEndings(StringBuilder sb) { - String nl = System.getProperty("line.separator"); - if (!nl.equals("\n")) { - int r = 0; - while (r < sb.length()) { - int i = sb.indexOf(nl, r); - if (i == -1) { - break; - } - sb.replace(i, i + nl.length(), "\n"); - r = i + 1; - } - } - return sb; - } - - /** Convert a \n string to a platform encoding. This uses a default - * {@link Charset UTF-8} charset. - * - * @param file where to write the converted bytes to - * @param value the value to write - */ - public static void writeString(File file, String value) throws IOException { - writeString(new FileOutputStream(file), UTF8, value); - } - - /** Convert a \n string to a platform encoding. This uses a default - * {@link Charset UTF-8} charset. - * - * @param out where to write the converted bytes to - * @param value the value to write - */ - public static void writeString(OutputStream out, String value) throws IOException { - writeString(out, UTF8, value); - } - - /** Convert a \n string to a platform encoding. This uses the - * specified charset to extract the raw bytes. - * - * @param out where to write the converted bytes to - * @param charset the charset to use to convert the raw bytes - * @param value the value to write - */ - public static void writeString(OutputStream out, String charset, String value) throws IOException { - writeString(out, Charset.forName(charset), value); - } - - /** Convert a \n string to a platform encoding. This uses the - * specified charset to extract the raw bytes. - * - * @param out where to write the converted bytes to - * @param charset the charset to use to convert the raw bytes - * @param value the value to write - */ - public static void writeString(OutputStream out, Charset charset, String value) throws IOException { - Writer writer = new OutputStreamWriter(out, charset); - String nl = System.getProperty("line.separator"); - int r = 0; - while (r < value.length()) { - int i = value.indexOf("\n", r); - if (i == -1) { - break; - } - writer.write(value.substring(r, i)); - writer.write(nl); - r = i + 1; - } - writer.write(value.substring(r)); - writer.close(); - } -} +/******************************************************************************* + * 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.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; + +import org.apache.commons.io.IOUtils; + +public final class UtilIO { + public static final Charset UTF8 = Charset.forName("UTF-8"); + public static final String module = UtilIO.class.getName(); + + /** Copy an InputStream to an OutputStream, optionally closing either + * the input or the output. + * + * @param in the InputStream to copy from + * @param closeIn whether to close the input when the copy is done + * @param out the OutputStream to copy to + * @param closeOut whether to close the output when the copy is done + * @throws IOException if an error occurs + */ + public static void copy(InputStream in, boolean closeIn, OutputStream out, boolean closeOut) throws IOException { + try { + try { + IOUtils.copy(in, out); + } finally { + if (closeIn) IOUtils.closeQuietly(in); + } + } finally { + if (closeOut) IOUtils.closeQuietly(out); + } + } + + /** Copy a Reader to a Writer, optionally closing either the input or + * the output. + * + * @param reader the Reader to copy from + * @param closeIn whether to close the input when the copy is done + * @param writer the Writer to copy to + * @param closeOut whether to close the output when the copy is done + * @throws IOException if an error occurs + */ + public static void copy(Reader reader, boolean closeIn, Writer writer, boolean closeOut) throws IOException { + try { + try { + IOUtils.copy(reader, writer); + } finally { + if (closeIn) IOUtils.closeQuietly(reader); + } + } finally { + if (closeOut) IOUtils.closeQuietly(writer); + } + } + + /** Copy a Reader to an Appendable, optionally closing the input. + * + * @param reader the Reader to copy from + * @param closeIn whether to close the input when the copy is done + * @param out the Appendable to copy to + * @throws IOException if an error occurs + */ + public static void copy(Reader reader, boolean closeIn, Appendable out) throws IOException { + try { + CharBuffer buffer = CharBuffer.allocate(4096); + while (reader.read(buffer) > 0) { + buffer.flip(); + buffer.rewind(); + out.append(buffer); + } + } finally { + if (closeIn) IOUtils.closeQuietly(reader); + } + } + + /** Convert a byte array to a string; consistently uses \n line endings + * in java. This uses a default {@link Charset UTF-8} charset. + * + * @param bytes the array of bytes to convert + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes) throws IOException { + return readString(bytes, 0, bytes.length, UTF8); + } + + /** Convert a byte array to a string; consistently uses \n line endings + * in java. The conversion is limited to the specified offset/length + * pair, and uses a default {@link Charset UTF-8} charset. + * + * @param bytes the array of bytes to convert + * @param offset the start of the conversion + * @param length how many bytes to convert + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes, int offset, int length) throws IOException { + return readString(bytes, offset, length, UTF8); + } + + /** Convert a byte array to a string; consistently uses \n line endings + * in java. The conversion is limited to the specified offset/length + * pair, and uses the requested charset to decode the bytes. + * + * @param bytes the array of bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes, String charset) throws IOException { + return readString(bytes, 0, bytes.length, Charset.forName(charset)); + } + + /** Convert a byte array to a string; consistently uses \n line + * endings in java. The conversion is limited to the specified + * offset/length pair, and uses the requested charset to decode the + * bytes. + * + * @param bytes the array of bytes to convert + * @param offset the start of the conversion + * @param length how many bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes, int offset, int length, String charset) throws IOException { + return readString(bytes, 0, bytes.length, Charset.forName(charset)); + } + + /** Convert a byte array to a string, consistently uses \n line + * endings in java. The specified {@link Charset charset} is used + * to decode the bytes. + * @param bytes the array of bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes, Charset charset) throws IOException { + return readString(bytes, 0, bytes.length, charset); + } + + /** Convert a byte array to a string, consistently uses \n line + * endings in java. The conversion is limited to the specified + * offset/length pair, and uses the requested {@link Charset + * charset} to decode the bytes. + * + * @param bytes the array of bytes to convert + * @param offset the start of the conversion + * @param length how many bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes, int offset, int length, Charset charset) throws IOException { + ByteBuffer buf = ByteBuffer.allocate(length); + buf.put(bytes, offset, length); + buf.flip(); + return filterLineEndings(new StringBuilder(charset.decode(buf).toString())).toString(); + } + + /** Convert an {@link InputStream} to a string; consistently uses \n line endings + * in java. This uses a default {@link Charset UTF-8} charset. + * + * @param stream the stream of bytes to convert + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(InputStream stream) throws IOException { + return readString(stream, UTF8); + } + + /** Convert an {@link InputStream} to a string; consistently uses \n line endings + * in java. This uses a default {@link Charset UTF-8} charset. + * + * @param stream the stream of bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(InputStream stream, String charset) throws IOException { + return readString(stream, Charset.forName(charset)); + } + + /** Convert an {@link InputStream} to a string; consistently uses \n line endings + * in java. This uses a default {@link Charset UTF-8} charset. + * + * @param stream the stream of bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(InputStream stream, Charset charset) throws IOException { + return readString(new InputStreamReader(new BufferedInputStream(stream), charset)); + } + + /** Convert an {@link Reader} to a string; consistently uses \n line endings + * in java. + * + * @param reader the stream of characters convert + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(Reader reader) throws IOException { + try { + StringBuilder sb = new StringBuilder(); + char[] buf = new char[4096]; + int r; + while ((r = reader.read(buf, 0, 4096)) > 0) { + sb.append(buf, 0, r); + } + return filterLineEndings(sb).toString(); + } finally { + try { + reader.close(); + } catch (IOException e) { + Debug.logError(e, "Error closing after reading text: " + e.toString(), module); + } + } + } + + private static StringBuilder filterLineEndings(StringBuilder sb) { + String nl = System.getProperty("line.separator"); + if (!nl.equals("\n")) { + int r = 0; + while (r < sb.length()) { + int i = sb.indexOf(nl, r); + if (i == -1) { + break; + } + sb.replace(i, i + nl.length(), "\n"); + r = i + 1; + } + } + return sb; + } + + /** Convert a \n string to a platform encoding. This uses a default + * {@link Charset UTF-8} charset. + * + * @param file where to write the converted bytes to + * @param value the value to write + */ + public static void writeString(File file, String value) throws IOException { + writeString(new FileOutputStream(file), UTF8, value); + } + + /** Convert a \n string to a platform encoding. This uses a default + * {@link Charset UTF-8} charset. + * + * @param out where to write the converted bytes to + * @param value the value to write + */ + public static void writeString(OutputStream out, String value) throws IOException { + writeString(out, UTF8, value); + } + + /** Convert a \n string to a platform encoding. This uses the + * specified charset to extract the raw bytes. + * + * @param out where to write the converted bytes to + * @param charset the charset to use to convert the raw bytes + * @param value the value to write + */ + public static void writeString(OutputStream out, String charset, String value) throws IOException { + writeString(out, Charset.forName(charset), value); + } + + /** Convert a \n string to a platform encoding. This uses the + * specified charset to extract the raw bytes. + * + * @param out where to write the converted bytes to + * @param charset the charset to use to convert the raw bytes + * @param value the value to write + */ + public static void writeString(OutputStream out, Charset charset, String value) throws IOException { + Writer writer = new OutputStreamWriter(out, charset); + String nl = System.getProperty("line.separator"); + int r = 0; + while (r < value.length()) { + int i = value.indexOf("\n", r); + if (i == -1) { + break; + } + writer.write(value.substring(r, i)); + writer.write(nl); + r = i + 1; + } + writer.write(value.substring(r)); + writer.close(); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/cache/test/UtilCacheTests.java b/framework/base/src/org/ofbiz/base/util/cache/test/UtilCacheTests.java index 10b892ddc2..0cc8268064 100644 --- a/framework/base/src/org/ofbiz/base/util/cache/test/UtilCacheTests.java +++ b/framework/base/src/org/ofbiz/base/util/cache/test/UtilCacheTests.java @@ -1,436 +1,436 @@ -/******************************************************************************* - * 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.cache.test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.greaterThan; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.ofbiz.base.test.GenericTestCaseBase; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilObject; -import org.ofbiz.base.util.cache.CacheListener; -import org.ofbiz.base.util.cache.UtilCache; - -@SuppressWarnings("serial") -public class UtilCacheTests extends GenericTestCaseBase implements Serializable { - public static final String module = UtilCacheTests.class.getName(); - - protected static abstract class Change { - protected int count = 1; - } - - protected static final class Removal extends Change { - protected final V oldValue; - - protected Removal(V oldValue) { - this.oldValue = oldValue; - } - - @Override - public int hashCode() { - return UtilObject.doHashCode(oldValue); - } - - @Override - public boolean equals(Object o) { - if (o instanceof Removal) { - Removal other = (Removal) o; - return UtilObject.equalsHelper(oldValue, other.oldValue); - } - return false; - } - } - - protected static final class Addition extends Change { - protected final V newValue; - - protected Addition(V newValue) { - this.newValue = newValue; - } - - @Override - public int hashCode() { - return UtilObject.doHashCode(newValue); - } - - @Override - public boolean equals(Object o) { - if (o instanceof Addition) { - Addition other = (Addition) o; - return UtilObject.equalsHelper(newValue, other.newValue); - } - return false; - } - } - - protected static final class Update extends Change { - protected final V newValue; - protected final V oldValue; - - protected Update(V newValue, V oldValue) { - this.newValue = newValue; - this.oldValue = oldValue; - } - - @Override - public int hashCode() { - return UtilObject.doHashCode(newValue) ^ UtilObject.doHashCode(oldValue); - } - - @Override - public boolean equals(Object o) { - if (o instanceof Update) { - Update other = (Update) o; - if (!UtilObject.equalsHelper(newValue, other.newValue)) { - return false; - } - return UtilObject.equalsHelper(oldValue, other.oldValue); - } - return false; - } - } - - protected static class Listener implements CacheListener { - protected Map>> changeMap = new HashMap>>(); - - private void add(K key, Change change) { - Set> changeSet = changeMap.get(key); - if (changeSet == null) { - changeSet = new HashSet>(); - changeMap.put(key, changeSet); - } - for (Change checkChange: changeSet) { - if (checkChange.equals(change)) { - checkChange.count++; - return; - } - } - changeSet.add(change); - } - - public synchronized void noteKeyRemoval(UtilCache cache, K key, V oldValue) { - add(key, new Removal(oldValue)); - } - - public synchronized void noteKeyAddition(UtilCache cache, K key, V newValue) { - add(key, new Addition(newValue)); - } - - public synchronized void noteKeyUpdate(UtilCache cache, K key, V newValue, V oldValue) { - add(key, new Update(newValue, oldValue)); - } - - @Override - public boolean equals(Object o) { - Listener other = (Listener) o; - return changeMap.equals(other.changeMap); - } - } - - private static Listener createListener(UtilCache cache) { - Listener listener = new Listener(); - cache.addListener(listener); - return listener; - } - - public UtilCacheTests(String name) { - super(name); - } - - private UtilCache createUtilCache(int sizeLimit, int maxInMemory, long ttl, boolean useSoftReference, boolean useFileSystemStore) { - return UtilCache.createUtilCache(getClass().getName() + "." + getName(), sizeLimit, maxInMemory, ttl, useSoftReference, useFileSystemStore); - } - - private static void assertUtilCacheSettings(UtilCache cache, Integer sizeLimit, Integer maxInMemory, Long expireTime, Boolean useSoftReference, Boolean useFileSystemStore) { - if (sizeLimit != null) { - assertEquals(cache.getName() + ":sizeLimit", sizeLimit.intValue(), cache.getSizeLimit()); - } - if (maxInMemory != null) { - assertEquals(cache.getName() + ":maxInMemory", maxInMemory.intValue(), cache.getMaxInMemory()); - } - if (expireTime != null) { - assertEquals(cache.getName() + ":expireTime", expireTime.longValue(), cache.getExpireTime()); - } - if (useSoftReference != null) { - assertEquals(cache.getName() + ":useSoftReference", useSoftReference.booleanValue(), cache.getUseSoftReference()); - } - if (useFileSystemStore != null) { - assertEquals(cache.getName() + ":useFileSystemStore", useFileSystemStore.booleanValue(), cache.getUseFileSystemStore()); - } - assertEquals("initial empty", true, cache.isEmpty()); - assertEquals("empty keys", Collections.emptySet(), cache.getCacheLineKeys()); - assertEquals("empty values", Collections.emptyList(), cache.values()); - assertSame("find cache", cache, UtilCache.findCache(cache.getName())); - assertNotSame("new cache", cache, UtilCache.createUtilCache()); - } - - public void testCreateUtilCache() { - String name = getClass().getName() + "." + getName(); - assertUtilCacheSettings(UtilCache.createUtilCache(), null, null, null, null, null); - assertUtilCacheSettings(UtilCache.createUtilCache(name), null, null, null, null, null); - assertUtilCacheSettings(UtilCache.createUtilCache(name, false), null, null, null, Boolean.FALSE, null); - assertUtilCacheSettings(UtilCache.createUtilCache(name, true), null, null, null, Boolean.TRUE, null); - assertUtilCacheSettings(UtilCache.createUtilCache(5, 15000), 5, null, 15000L, null, null); - assertUtilCacheSettings(UtilCache.createUtilCache(name, 6, 16000), 6, null, 16000L, null, null); - assertUtilCacheSettings(UtilCache.createUtilCache(name, 7, 17000, false), 7, null, 17000L, Boolean.FALSE, null); - assertUtilCacheSettings(UtilCache.createUtilCache(name, 8, 18000, true), 8, null, 18000L, Boolean.TRUE, null); - assertUtilCacheSettings(UtilCache.createUtilCache(name, 9, 5, 19000, false, false), 9, 5, 19000L, Boolean.FALSE, null); - assertUtilCacheSettings(UtilCache.createUtilCache(name, 10, 6, 20000, false, true), 10, 6, 20000L, Boolean.FALSE, null); - assertUtilCacheSettings(UtilCache.createUtilCache(name, 11, 7, 21000, false, false, "a", "b"), 11, 7, 21000L, Boolean.FALSE, Boolean.FALSE); - assertUtilCacheSettings(UtilCache.createUtilCache(name, 12, 8, 22000, false, true, "c", "d"), 12, 8, 22000L, Boolean.FALSE, Boolean.TRUE); - } - - public static void assertKey(String label, UtilCache cache, K key, V value, V other, int size, Map map) { - assertNull(label + ":get-empty", cache.get(key)); - assertFalse(label + ":containsKey-empty", cache.containsKey(key)); - V oldValue = cache.put(key, other); - assertTrue(label + ":containsKey-class", cache.containsKey(key)); - assertEquals(label + ":get-class", other, cache.get(key)); - assertNull(label + ":oldValue-class", oldValue); - assertEquals(label + ":size-class", size, cache.size()); - oldValue = cache.put(key, value); - assertTrue(label + ":containsKey-value", cache.containsKey(key)); - assertEquals(label + ":get-value", value, cache.get(key)); - assertEquals(label + ":oldValue-value", other, oldValue); - assertEquals(label + ":size-value", size, cache.size()); - map.put(key, value); - assertEquals(label + ":map-keys", map.keySet(), cache.getCacheLineKeys()); - assertEquals(label + ":map-values", map.values(), cache.values()); - } - - private static void assertHasSingleKey(UtilCache cache, K key, V value) { - assertFalse("is-empty", cache.isEmpty()); - assertEquals("size", 1, cache.size()); - assertTrue("found", cache.containsKey(key)); - assertTrue("validKey", UtilCache.validKey(cache.getName(), key)); - assertFalse("validKey", UtilCache.validKey(":::" + cache.getName(), key)); - assertEquals("get", value, cache.get(key)); - assertEquals("keys", new HashSet(UtilMisc.toList(key)), cache.getCacheLineKeys()); - assertEquals("values", UtilMisc.toList(value), cache.values()); - } - - private static void assertNoSingleKey(UtilCache cache, K key) { - assertFalse("not-found", cache.containsKey(key)); - assertFalse("validKey", UtilCache.validKey(cache.getName(), key)); - assertNull("no-get", cache.get(key)); - assertNull("remove", cache.remove(key)); - assertTrue("is-empty", cache.isEmpty()); - assertEquals("size", 0, cache.size()); - assertEquals("keys", Collections.emptySet(), cache.getCacheLineKeys()); - assertEquals("values", Collections.emptyList(), cache.values()); - } - - private static void basicTest(UtilCache cache) throws Exception { - Listener gotListener = createListener(cache); - Listener wantedListener = new Listener(); - for (int i = 0; i < 2; i++) { - assertTrue("UtilCacheTable.keySet", UtilCache.getUtilCacheTableKeySet().contains(cache.getName())); - assertSame("UtilCache.findCache", cache, UtilCache.findCache(cache.getName())); - assertSame("UtilCache.getOrCreateUtilCache", cache, UtilCache.getOrCreateUtilCache(cache.getName(), cache.getSizeLimit(), cache.getMaxInMemory(), cache.getExpireTime(), cache.getUseSoftReference(), cache.getUseFileSystemStore())); - - assertNoSingleKey(cache, "one"); - long origByteSize = cache.getSizeInBytes(); - - wantedListener.noteKeyAddition(cache, null, "null"); - assertNull("put", cache.put(null, "null")); - assertHasSingleKey(cache, null, "null"); - long nullByteSize = cache.getSizeInBytes(); - assertThat(nullByteSize, greaterThan(origByteSize)); - - wantedListener.noteKeyRemoval(cache, null, "null"); - assertEquals("remove", "null", cache.remove(null)); - assertNoSingleKey(cache, null); - - wantedListener.noteKeyAddition(cache, "one", "uno"); - assertNull("put", cache.put("one", "uno")); - assertHasSingleKey(cache, "one", "uno"); - long unoByteSize = cache.getSizeInBytes(); - assertThat(unoByteSize, greaterThan(origByteSize)); - - wantedListener.noteKeyUpdate(cache, "one", "single", "uno"); - assertEquals("replace", "uno", cache.put("one", "single")); - assertHasSingleKey(cache, "one", "single"); - long singleByteSize = cache.getSizeInBytes(); - assertThat(singleByteSize, greaterThan(origByteSize)); - assertThat(singleByteSize, greaterThan(unoByteSize)); - - wantedListener.noteKeyRemoval(cache, "one", "single"); - assertEquals("remove", "single", cache.remove("one")); - assertNoSingleKey(cache, "one"); - assertEquals("byteSize", origByteSize, cache.getSizeInBytes()); - - wantedListener.noteKeyAddition(cache, "one", "uno"); - assertNull("put", cache.put("one", "uno")); - assertHasSingleKey(cache, "one", "uno"); - - wantedListener.noteKeyUpdate(cache, "one", "only", "uno"); - assertEquals("replace", "uno", cache.put("one", "only")); - assertHasSingleKey(cache, "one", "only"); - - wantedListener.noteKeyRemoval(cache, "one", "only"); - cache.erase(); - assertNoSingleKey(cache, "one"); - assertEquals("byteSize", origByteSize, cache.getSizeInBytes()); - - cache.setExpireTime(100); - wantedListener.noteKeyAddition(cache, "one", "uno"); - assertNull("put", cache.put("one", "uno")); - assertHasSingleKey(cache, "one", "uno"); - - wantedListener.noteKeyRemoval(cache, "one", "uno"); - Thread.sleep(200); - assertNoSingleKey(cache, "one"); - } - - assertEquals("get-miss", 10, cache.getMissCountNotFound()); - assertEquals("get-miss-total", 10, cache.getMissCountTotal()); - assertEquals("get-hit", 12, cache.getHitCount()); - assertEquals("remove-hit", 6, cache.getRemoveHitCount()); - assertEquals("remove-miss", 10, cache.getRemoveMissCount()); - cache.removeListener(gotListener); - assertEquals("listener", wantedListener, gotListener); - UtilCache.clearCache(cache.getName()); - UtilCache.clearCache(":::" + cache.getName()); - } - - public void testBasicDisk() throws Exception { - UtilCache cache = createUtilCache(5, 0, 0, false, true); - basicTest(cache); - } - - public void testSimple() throws Exception { - UtilCache cache = createUtilCache(5, 0, 0, false, false); - basicTest(cache); - } - - public void testPutIfAbsent() throws Exception { - UtilCache cache = createUtilCache(5, 5, 2000, false, false); - Listener gotListener = createListener(cache); - Listener wantedListener = new Listener(); - wantedListener.noteKeyAddition(cache, "two", "dos"); - assertNull("putIfAbsent", cache.putIfAbsent("two", "dos")); - assertHasSingleKey(cache, "two", "dos"); - assertEquals("putIfAbsent", "dos", cache.putIfAbsent("two", "double")); - assertHasSingleKey(cache, "two", "dos"); - cache.removeListener(gotListener); - assertEquals("listener", wantedListener, gotListener); - } - - public void testPutIfAbsentAndGet() throws Exception { - UtilCache cache = createUtilCache(5, 5, 2000, false, false); - Listener gotListener = createListener(cache); - Listener wantedListener = new Listener(); - wantedListener.noteKeyAddition(cache, "key", "value"); - wantedListener.noteKeyAddition(cache, "anotherKey", "anotherValue"); - assertNull("no-get", cache.get("key")); - assertEquals("putIfAbsentAndGet", "value", cache.putIfAbsentAndGet("key", "value")); - assertHasSingleKey(cache, "key", "value"); - assertEquals("putIfAbsentAndGet", "value", cache.putIfAbsentAndGet("key", "newValue")); - assertHasSingleKey(cache, "key", "value"); - String anotherValueAddedToCache = new String("anotherValue"); - String anotherValueNotAddedToCache = new String("anotherValue"); - assertEquals(anotherValueAddedToCache, anotherValueNotAddedToCache); - assertNotSame(anotherValueAddedToCache, anotherValueNotAddedToCache); - String cachedValue = cache.putIfAbsentAndGet("anotherKey", anotherValueAddedToCache); - assertSame(cachedValue, anotherValueAddedToCache); - cachedValue = cache.putIfAbsentAndGet("anotherKey", anotherValueNotAddedToCache); - assertNotSame(cachedValue, anotherValueNotAddedToCache); - assertSame(cachedValue, anotherValueAddedToCache); - cache.removeListener(gotListener); - assertEquals("listener", wantedListener, gotListener); - } - - public void testChangeMemSize() throws Exception { - int size = 5; - long ttl = 2000; - UtilCache cache = createUtilCache(size, size, ttl, false, false); - Map map = new HashMap(); - for (int i = 0; i < size; i++) { - String s = Integer.toString(i); - assertKey(s, cache, s, new String(s), new String(":" + s), i + 1, map); - } - cache.setMaxInMemory(2); - assertEquals("cache.size", 2, cache.size()); - map.keySet().retainAll(cache.getCacheLineKeys()); - assertEquals("map-keys", map.keySet(), cache.getCacheLineKeys()); - assertEquals("map-values", map.values(), cache.values()); - cache.setMaxInMemory(0); - assertEquals("map-keys", map.keySet(), cache.getCacheLineKeys()); - assertEquals("map-values", map.values(), cache.values()); - for (int i = size * 2; i < size * 3; i++) { - String s = Integer.toString(i); - assertKey(s, cache, s, new String(s), new String(":" + s), i - size * 2 + 3, map); - } - cache.setMaxInMemory(0); - assertEquals("map-keys", map.keySet(), cache.getCacheLineKeys()); - assertEquals("map-values", map.values(), cache.values()); - cache.setMaxInMemory(size); - for (int i = 0; i < size * 2; i++) { - map.remove(Integer.toString(i)); - } - // Can't compare the contents of these collections, as setting LRU after not - // having one, means the items that get evicted are essentially random. - assertEquals("map-keys", map.keySet().size(), cache.getCacheLineKeys().size()); - assertEquals("map-values", map.values().size(), cache.values().size()); - } - - private void expireTest(UtilCache cache, int size, long ttl) throws Exception { - Map map = new HashMap(); - for (int i = 0; i < size; i++) { - String s = Integer.toString(i); - assertKey(s, cache, s, new String(s), new String(":" + s), i + 1, map); - } - Thread.sleep(ttl + 500); - map.clear(); - for (int i = 0; i < size; i++) { - String s = Integer.toString(i); - assertNull("no-key(" + s + ")", cache.get(s)); - } - assertEquals("map-keys", map.keySet(), cache.getCacheLineKeys()); - assertEquals("map-values", map.values(), cache.values()); - for (int i = 0; i < size; i++) { - String s = Integer.toString(i); - assertKey(s, cache, s, new String(s), new String(":" + s), i + 1, map); - } - assertEquals("map-keys", map.keySet(), cache.getCacheLineKeys()); - assertEquals("map-values", map.values(), cache.values()); - } - - public void testExpire() throws Exception { - UtilCache cache = createUtilCache(5, 5, 2000, false, false); - expireTest(cache, 5, 2000); - long start = System.currentTimeMillis(); - useAllMemory(); - long end = System.currentTimeMillis(); - long ttl = end - start + 1000; - cache = createUtilCache(1, 1, ttl, true, false); - expireTest(cache, 1, ttl); - assertFalse("not empty", cache.isEmpty()); - useAllMemory(); - assertNull("not-key(0)", cache.get("0")); - assertTrue("empty", cache.isEmpty()); - } -} +/******************************************************************************* + * 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.cache.test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.ofbiz.base.test.GenericTestCaseBase; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilObject; +import org.ofbiz.base.util.cache.CacheListener; +import org.ofbiz.base.util.cache.UtilCache; + +@SuppressWarnings("serial") +public class UtilCacheTests extends GenericTestCaseBase implements Serializable { + public static final String module = UtilCacheTests.class.getName(); + + protected static abstract class Change { + protected int count = 1; + } + + protected static final class Removal extends Change { + protected final V oldValue; + + protected Removal(V oldValue) { + this.oldValue = oldValue; + } + + @Override + public int hashCode() { + return UtilObject.doHashCode(oldValue); + } + + @Override + public boolean equals(Object o) { + if (o instanceof Removal) { + Removal other = (Removal) o; + return UtilObject.equalsHelper(oldValue, other.oldValue); + } + return false; + } + } + + protected static final class Addition extends Change { + protected final V newValue; + + protected Addition(V newValue) { + this.newValue = newValue; + } + + @Override + public int hashCode() { + return UtilObject.doHashCode(newValue); + } + + @Override + public boolean equals(Object o) { + if (o instanceof Addition) { + Addition other = (Addition) o; + return UtilObject.equalsHelper(newValue, other.newValue); + } + return false; + } + } + + protected static final class Update extends Change { + protected final V newValue; + protected final V oldValue; + + protected Update(V newValue, V oldValue) { + this.newValue = newValue; + this.oldValue = oldValue; + } + + @Override + public int hashCode() { + return UtilObject.doHashCode(newValue) ^ UtilObject.doHashCode(oldValue); + } + + @Override + public boolean equals(Object o) { + if (o instanceof Update) { + Update other = (Update) o; + if (!UtilObject.equalsHelper(newValue, other.newValue)) { + return false; + } + return UtilObject.equalsHelper(oldValue, other.oldValue); + } + return false; + } + } + + protected static class Listener implements CacheListener { + protected Map>> changeMap = new HashMap>>(); + + private void add(K key, Change change) { + Set> changeSet = changeMap.get(key); + if (changeSet == null) { + changeSet = new HashSet>(); + changeMap.put(key, changeSet); + } + for (Change checkChange: changeSet) { + if (checkChange.equals(change)) { + checkChange.count++; + return; + } + } + changeSet.add(change); + } + + public synchronized void noteKeyRemoval(UtilCache cache, K key, V oldValue) { + add(key, new Removal(oldValue)); + } + + public synchronized void noteKeyAddition(UtilCache cache, K key, V newValue) { + add(key, new Addition(newValue)); + } + + public synchronized void noteKeyUpdate(UtilCache cache, K key, V newValue, V oldValue) { + add(key, new Update(newValue, oldValue)); + } + + @Override + public boolean equals(Object o) { + Listener other = (Listener) o; + return changeMap.equals(other.changeMap); + } + } + + private static Listener createListener(UtilCache cache) { + Listener listener = new Listener(); + cache.addListener(listener); + return listener; + } + + public UtilCacheTests(String name) { + super(name); + } + + private UtilCache createUtilCache(int sizeLimit, int maxInMemory, long ttl, boolean useSoftReference, boolean useFileSystemStore) { + return UtilCache.createUtilCache(getClass().getName() + "." + getName(), sizeLimit, maxInMemory, ttl, useSoftReference, useFileSystemStore); + } + + private static void assertUtilCacheSettings(UtilCache cache, Integer sizeLimit, Integer maxInMemory, Long expireTime, Boolean useSoftReference, Boolean useFileSystemStore) { + if (sizeLimit != null) { + assertEquals(cache.getName() + ":sizeLimit", sizeLimit.intValue(), cache.getSizeLimit()); + } + if (maxInMemory != null) { + assertEquals(cache.getName() + ":maxInMemory", maxInMemory.intValue(), cache.getMaxInMemory()); + } + if (expireTime != null) { + assertEquals(cache.getName() + ":expireTime", expireTime.longValue(), cache.getExpireTime()); + } + if (useSoftReference != null) { + assertEquals(cache.getName() + ":useSoftReference", useSoftReference.booleanValue(), cache.getUseSoftReference()); + } + if (useFileSystemStore != null) { + assertEquals(cache.getName() + ":useFileSystemStore", useFileSystemStore.booleanValue(), cache.getUseFileSystemStore()); + } + assertEquals("initial empty", true, cache.isEmpty()); + assertEquals("empty keys", Collections.emptySet(), cache.getCacheLineKeys()); + assertEquals("empty values", Collections.emptyList(), cache.values()); + assertSame("find cache", cache, UtilCache.findCache(cache.getName())); + assertNotSame("new cache", cache, UtilCache.createUtilCache()); + } + + public void testCreateUtilCache() { + String name = getClass().getName() + "." + getName(); + assertUtilCacheSettings(UtilCache.createUtilCache(), null, null, null, null, null); + assertUtilCacheSettings(UtilCache.createUtilCache(name), null, null, null, null, null); + assertUtilCacheSettings(UtilCache.createUtilCache(name, false), null, null, null, Boolean.FALSE, null); + assertUtilCacheSettings(UtilCache.createUtilCache(name, true), null, null, null, Boolean.TRUE, null); + assertUtilCacheSettings(UtilCache.createUtilCache(5, 15000), 5, null, 15000L, null, null); + assertUtilCacheSettings(UtilCache.createUtilCache(name, 6, 16000), 6, null, 16000L, null, null); + assertUtilCacheSettings(UtilCache.createUtilCache(name, 7, 17000, false), 7, null, 17000L, Boolean.FALSE, null); + assertUtilCacheSettings(UtilCache.createUtilCache(name, 8, 18000, true), 8, null, 18000L, Boolean.TRUE, null); + assertUtilCacheSettings(UtilCache.createUtilCache(name, 9, 5, 19000, false, false), 9, 5, 19000L, Boolean.FALSE, null); + assertUtilCacheSettings(UtilCache.createUtilCache(name, 10, 6, 20000, false, true), 10, 6, 20000L, Boolean.FALSE, null); + assertUtilCacheSettings(UtilCache.createUtilCache(name, 11, 7, 21000, false, false, "a", "b"), 11, 7, 21000L, Boolean.FALSE, Boolean.FALSE); + assertUtilCacheSettings(UtilCache.createUtilCache(name, 12, 8, 22000, false, true, "c", "d"), 12, 8, 22000L, Boolean.FALSE, Boolean.TRUE); + } + + public static void assertKey(String label, UtilCache cache, K key, V value, V other, int size, Map map) { + assertNull(label + ":get-empty", cache.get(key)); + assertFalse(label + ":containsKey-empty", cache.containsKey(key)); + V oldValue = cache.put(key, other); + assertTrue(label + ":containsKey-class", cache.containsKey(key)); + assertEquals(label + ":get-class", other, cache.get(key)); + assertNull(label + ":oldValue-class", oldValue); + assertEquals(label + ":size-class", size, cache.size()); + oldValue = cache.put(key, value); + assertTrue(label + ":containsKey-value", cache.containsKey(key)); + assertEquals(label + ":get-value", value, cache.get(key)); + assertEquals(label + ":oldValue-value", other, oldValue); + assertEquals(label + ":size-value", size, cache.size()); + map.put(key, value); + assertEquals(label + ":map-keys", map.keySet(), cache.getCacheLineKeys()); + assertEquals(label + ":map-values", map.values(), cache.values()); + } + + private static void assertHasSingleKey(UtilCache cache, K key, V value) { + assertFalse("is-empty", cache.isEmpty()); + assertEquals("size", 1, cache.size()); + assertTrue("found", cache.containsKey(key)); + assertTrue("validKey", UtilCache.validKey(cache.getName(), key)); + assertFalse("validKey", UtilCache.validKey(":::" + cache.getName(), key)); + assertEquals("get", value, cache.get(key)); + assertEquals("keys", new HashSet(UtilMisc.toList(key)), cache.getCacheLineKeys()); + assertEquals("values", UtilMisc.toList(value), cache.values()); + } + + private static void assertNoSingleKey(UtilCache cache, K key) { + assertFalse("not-found", cache.containsKey(key)); + assertFalse("validKey", UtilCache.validKey(cache.getName(), key)); + assertNull("no-get", cache.get(key)); + assertNull("remove", cache.remove(key)); + assertTrue("is-empty", cache.isEmpty()); + assertEquals("size", 0, cache.size()); + assertEquals("keys", Collections.emptySet(), cache.getCacheLineKeys()); + assertEquals("values", Collections.emptyList(), cache.values()); + } + + private static void basicTest(UtilCache cache) throws Exception { + Listener gotListener = createListener(cache); + Listener wantedListener = new Listener(); + for (int i = 0; i < 2; i++) { + assertTrue("UtilCacheTable.keySet", UtilCache.getUtilCacheTableKeySet().contains(cache.getName())); + assertSame("UtilCache.findCache", cache, UtilCache.findCache(cache.getName())); + assertSame("UtilCache.getOrCreateUtilCache", cache, UtilCache.getOrCreateUtilCache(cache.getName(), cache.getSizeLimit(), cache.getMaxInMemory(), cache.getExpireTime(), cache.getUseSoftReference(), cache.getUseFileSystemStore())); + + assertNoSingleKey(cache, "one"); + long origByteSize = cache.getSizeInBytes(); + + wantedListener.noteKeyAddition(cache, null, "null"); + assertNull("put", cache.put(null, "null")); + assertHasSingleKey(cache, null, "null"); + long nullByteSize = cache.getSizeInBytes(); + assertThat(nullByteSize, greaterThan(origByteSize)); + + wantedListener.noteKeyRemoval(cache, null, "null"); + assertEquals("remove", "null", cache.remove(null)); + assertNoSingleKey(cache, null); + + wantedListener.noteKeyAddition(cache, "one", "uno"); + assertNull("put", cache.put("one", "uno")); + assertHasSingleKey(cache, "one", "uno"); + long unoByteSize = cache.getSizeInBytes(); + assertThat(unoByteSize, greaterThan(origByteSize)); + + wantedListener.noteKeyUpdate(cache, "one", "single", "uno"); + assertEquals("replace", "uno", cache.put("one", "single")); + assertHasSingleKey(cache, "one", "single"); + long singleByteSize = cache.getSizeInBytes(); + assertThat(singleByteSize, greaterThan(origByteSize)); + assertThat(singleByteSize, greaterThan(unoByteSize)); + + wantedListener.noteKeyRemoval(cache, "one", "single"); + assertEquals("remove", "single", cache.remove("one")); + assertNoSingleKey(cache, "one"); + assertEquals("byteSize", origByteSize, cache.getSizeInBytes()); + + wantedListener.noteKeyAddition(cache, "one", "uno"); + assertNull("put", cache.put("one", "uno")); + assertHasSingleKey(cache, "one", "uno"); + + wantedListener.noteKeyUpdate(cache, "one", "only", "uno"); + assertEquals("replace", "uno", cache.put("one", "only")); + assertHasSingleKey(cache, "one", "only"); + + wantedListener.noteKeyRemoval(cache, "one", "only"); + cache.erase(); + assertNoSingleKey(cache, "one"); + assertEquals("byteSize", origByteSize, cache.getSizeInBytes()); + + cache.setExpireTime(100); + wantedListener.noteKeyAddition(cache, "one", "uno"); + assertNull("put", cache.put("one", "uno")); + assertHasSingleKey(cache, "one", "uno"); + + wantedListener.noteKeyRemoval(cache, "one", "uno"); + Thread.sleep(200); + assertNoSingleKey(cache, "one"); + } + + assertEquals("get-miss", 10, cache.getMissCountNotFound()); + assertEquals("get-miss-total", 10, cache.getMissCountTotal()); + assertEquals("get-hit", 12, cache.getHitCount()); + assertEquals("remove-hit", 6, cache.getRemoveHitCount()); + assertEquals("remove-miss", 10, cache.getRemoveMissCount()); + cache.removeListener(gotListener); + assertEquals("listener", wantedListener, gotListener); + UtilCache.clearCache(cache.getName()); + UtilCache.clearCache(":::" + cache.getName()); + } + + public void testBasicDisk() throws Exception { + UtilCache cache = createUtilCache(5, 0, 0, false, true); + basicTest(cache); + } + + public void testSimple() throws Exception { + UtilCache cache = createUtilCache(5, 0, 0, false, false); + basicTest(cache); + } + + public void testPutIfAbsent() throws Exception { + UtilCache cache = createUtilCache(5, 5, 2000, false, false); + Listener gotListener = createListener(cache); + Listener wantedListener = new Listener(); + wantedListener.noteKeyAddition(cache, "two", "dos"); + assertNull("putIfAbsent", cache.putIfAbsent("two", "dos")); + assertHasSingleKey(cache, "two", "dos"); + assertEquals("putIfAbsent", "dos", cache.putIfAbsent("two", "double")); + assertHasSingleKey(cache, "two", "dos"); + cache.removeListener(gotListener); + assertEquals("listener", wantedListener, gotListener); + } + + public void testPutIfAbsentAndGet() throws Exception { + UtilCache cache = createUtilCache(5, 5, 2000, false, false); + Listener gotListener = createListener(cache); + Listener wantedListener = new Listener(); + wantedListener.noteKeyAddition(cache, "key", "value"); + wantedListener.noteKeyAddition(cache, "anotherKey", "anotherValue"); + assertNull("no-get", cache.get("key")); + assertEquals("putIfAbsentAndGet", "value", cache.putIfAbsentAndGet("key", "value")); + assertHasSingleKey(cache, "key", "value"); + assertEquals("putIfAbsentAndGet", "value", cache.putIfAbsentAndGet("key", "newValue")); + assertHasSingleKey(cache, "key", "value"); + String anotherValueAddedToCache = new String("anotherValue"); + String anotherValueNotAddedToCache = new String("anotherValue"); + assertEquals(anotherValueAddedToCache, anotherValueNotAddedToCache); + assertNotSame(anotherValueAddedToCache, anotherValueNotAddedToCache); + String cachedValue = cache.putIfAbsentAndGet("anotherKey", anotherValueAddedToCache); + assertSame(cachedValue, anotherValueAddedToCache); + cachedValue = cache.putIfAbsentAndGet("anotherKey", anotherValueNotAddedToCache); + assertNotSame(cachedValue, anotherValueNotAddedToCache); + assertSame(cachedValue, anotherValueAddedToCache); + cache.removeListener(gotListener); + assertEquals("listener", wantedListener, gotListener); + } + + public void testChangeMemSize() throws Exception { + int size = 5; + long ttl = 2000; + UtilCache cache = createUtilCache(size, size, ttl, false, false); + Map map = new HashMap(); + for (int i = 0; i < size; i++) { + String s = Integer.toString(i); + assertKey(s, cache, s, new String(s), new String(":" + s), i + 1, map); + } + cache.setMaxInMemory(2); + assertEquals("cache.size", 2, cache.size()); + map.keySet().retainAll(cache.getCacheLineKeys()); + assertEquals("map-keys", map.keySet(), cache.getCacheLineKeys()); + assertEquals("map-values", map.values(), cache.values()); + cache.setMaxInMemory(0); + assertEquals("map-keys", map.keySet(), cache.getCacheLineKeys()); + assertEquals("map-values", map.values(), cache.values()); + for (int i = size * 2; i < size * 3; i++) { + String s = Integer.toString(i); + assertKey(s, cache, s, new String(s), new String(":" + s), i - size * 2 + 3, map); + } + cache.setMaxInMemory(0); + assertEquals("map-keys", map.keySet(), cache.getCacheLineKeys()); + assertEquals("map-values", map.values(), cache.values()); + cache.setMaxInMemory(size); + for (int i = 0; i < size * 2; i++) { + map.remove(Integer.toString(i)); + } + // Can't compare the contents of these collections, as setting LRU after not + // having one, means the items that get evicted are essentially random. + assertEquals("map-keys", map.keySet().size(), cache.getCacheLineKeys().size()); + assertEquals("map-values", map.values().size(), cache.values().size()); + } + + private void expireTest(UtilCache cache, int size, long ttl) throws Exception { + Map map = new HashMap(); + for (int i = 0; i < size; i++) { + String s = Integer.toString(i); + assertKey(s, cache, s, new String(s), new String(":" + s), i + 1, map); + } + Thread.sleep(ttl + 500); + map.clear(); + for (int i = 0; i < size; i++) { + String s = Integer.toString(i); + assertNull("no-key(" + s + ")", cache.get(s)); + } + assertEquals("map-keys", map.keySet(), cache.getCacheLineKeys()); + assertEquals("map-values", map.values(), cache.values()); + for (int i = 0; i < size; i++) { + String s = Integer.toString(i); + assertKey(s, cache, s, new String(s), new String(":" + s), i + 1, map); + } + assertEquals("map-keys", map.keySet(), cache.getCacheLineKeys()); + assertEquals("map-values", map.values(), cache.values()); + } + + public void testExpire() throws Exception { + UtilCache cache = createUtilCache(5, 5, 2000, false, false); + expireTest(cache, 5, 2000); + long start = System.currentTimeMillis(); + useAllMemory(); + long end = System.currentTimeMillis(); + long ttl = end - start + 1000; + cache = createUtilCache(1, 1, ttl, true, false); + expireTest(cache, 1, ttl); + assertFalse("not empty", cache.isEmpty()); + useAllMemory(); + assertNull("not-key(0)", cache.get("0")); + assertTrue("empty", cache.isEmpty()); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/collections/GenericMap.java b/framework/base/src/org/ofbiz/base/util/collections/GenericMap.java index 02433d737b..4bc98f5981 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/GenericMap.java +++ b/framework/base/src/org/ofbiz/base/util/collections/GenericMap.java @@ -1,253 +1,253 @@ -/*******n*********************************************************************** - * 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.collections; - -import java.io.Serializable; -import java.util.ConcurrentModificationException; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; - -import org.ofbiz.base.lang.Appender; -import org.ofbiz.base.util.UtilGenerics; -import org.ofbiz.base.util.UtilObject; - -@SuppressWarnings("serial") -public abstract class GenericMap implements Appender, Map, Serializable { - private static final AtomicReferenceFieldUpdater, Set> keySetUpdater = UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Set.class, "keySet")); - private static final AtomicReferenceFieldUpdater, Set> entrySetUpdater = UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Set.class, "entrySet")); - private static final AtomicReferenceFieldUpdater, Collection> valuesUpdater = UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Collection.class, "values")); - private static final AtomicIntegerFieldUpdater> modCountUpdater = UtilGenerics.cast(AtomicIntegerFieldUpdater.newUpdater(GenericMap.class, "modCount")); - - private volatile Set keySet; - private volatile Set> entrySet; - private volatile Collection values; - private volatile int modCount; - - public int getModCount() { - return modCount; - } - - protected void incrementModCount() { - modCountUpdater.getAndIncrement(this); - } - - public final void clear() { - if (isEmpty()) return; - incrementModCount(); - clearInternal(); - } - - protected abstract void clearInternal(); - - public boolean containsValue(Object value) { - return values().contains(value); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof Map)) return false; - if (this == o) return true; - Map map = (Map) o; - if (size() != map.size()) return false; - if (o instanceof GenericMap) return equalsGenericMap((GenericMap) o); - return equalsMap(map); - } - - protected boolean equalsGenericMap(GenericMap map) { - Iterator> it = iterator(false); - while (it.hasNext()) { - Map.Entry entry = it.next(); - K key = entry.getKey(); - V value = entry.getValue(); - if (value != null) { - if (!value.equals(map.get(key, false))) return false; - } else { - Object otherValue = map.get(key, false); - if (otherValue != null) return false; - if (!map.containsKey(key)) return false; - } - } - return true; - } - - protected boolean equalsMap(Map map) { - Iterator> it = iterator(false); - while (it.hasNext()) { - Map.Entry entry = it.next(); - K key = entry.getKey(); - V value = entry.getValue(); - if (value != null) { - if (!value.equals(map.get(key))) return false; - } else { - Object otherValue = map.get(key); - if (otherValue != null) return false; - if (!map.containsKey(key)) return false; - } - } - return true; - } - - public final V get(Object key) { - return get(key, true); - } - - protected abstract V get(Object key, boolean noteAccess); - - protected abstract class GenericMapIterator extends IteratorWrapper> { - private final int currentModCount = getModCount(); - - protected GenericMapIterator(boolean noteAccess) { - super(iterator(noteAccess)); - } - - protected boolean isValid(Map.Entry src) { - if (currentModCount != getModCount()) throw new ConcurrentModificationException(); - return true; - } - } - - public final Set> entrySet() { - if (entrySet == null) { - entrySetUpdater.compareAndSet(this, null, new GenericMapEntrySet>(this) { - @Override - protected boolean contains(Object key, Object value) { - return UtilObject.equalsHelper(get(key, false), value); - } - - @Override - public Iterator> iterator(boolean noteAccess) { - return new GenericMapIterator>(noteAccess) { - @Override - protected void noteRemoval(Map.Entry dest, Map.Entry src) { - // No need to note the remove, the wrapped iterator does that for us - // evictionPolicy.remove(evictionDeque, dest); - // if (diskStore != null) diskStore.remove(dest); - } - - @Override - protected Map.Entry convert(Map.Entry src) { - return src; - } - }; - } - }); - } - return entrySet; - } - - protected abstract Iterator> iterator(boolean noteAccess); - - public final Set keySet() { - if (keySet == null) { - keySetUpdater.compareAndSet(this, null, new GenericMapKeySet>(this) { - public boolean contains(Object key) { - return containsKey(key); - } - - @Override - public Iterator iterator(boolean noteAccess) { - return new GenericMapIterator(noteAccess) { - @Override - protected void noteRemoval(K dest, Map.Entry src) { - // No need to note the remove, the wrapped iterator does that for us - // evictionPolicy.remove(evictionDeque, dest); - // if (diskStore != null) diskStore.remove(dest); - } - - @Override - protected K convert(Map.Entry src) { - return src.getKey(); - } - }; - } - }); - } - return keySet; - } - - public final Collection values() { - if (values == null) { - valuesUpdater.compareAndSet(this, null, new GenericMapValues>(this) { - @Override - public Iterator iterator(boolean noteAccess) { - return new GenericMapIterator(noteAccess) { - @Override - protected void noteRemoval(V dest, Map.Entry src) { - // No need to note the remove, the wrapped iterator does that for us - // evictionPolicy.remove(evictionDeque, src.getKey()); - // if (diskStore != null) diskStore.remove(src.getKey()); - } - - @Override - protected V convert(Map.Entry src) { - return src.getValue(); - } - }; - } - }); - } - return values; - } - - public final V remove(Object key) { - return removeInternal(key, true); - } - - protected abstract V removeInternal(Object key, boolean incrementModCount); - - public final void putAll(Map map) { - putAllInternal(map); - } - - private void putAllInternal(Map map) { - if (map.isEmpty()) return; - incrementModCount(); - Iterator> it; - if (map instanceof GenericMap) { - GenericMap otherMap = UtilGenerics.cast(map); - it = otherMap.iterator(false); - } else { - it = map.entrySet().iterator(); - } - putAllIterator(it); - } - - protected abstract void putAllIterator(Iterator> it); - - @Override - public String toString() { - return appendTo(new StringBuilder()).toString(); - } - - public StringBuilder appendTo(StringBuilder sb) { - sb.append("{"); - Iterator> it = iterator(false); - while (it.hasNext()) { - Map.Entry entry = it.next(); - sb.append(entry.getKey()).append("=").append(entry.getValue()); - if (it.hasNext()) sb.append(","); - } - return sb.append("}"); - } -} - +/*******n*********************************************************************** + * 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.collections; + +import java.io.Serializable; +import java.util.ConcurrentModificationException; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; + +import org.ofbiz.base.lang.Appender; +import org.ofbiz.base.util.UtilGenerics; +import org.ofbiz.base.util.UtilObject; + +@SuppressWarnings("serial") +public abstract class GenericMap implements Appender, Map, Serializable { + private static final AtomicReferenceFieldUpdater, Set> keySetUpdater = UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Set.class, "keySet")); + private static final AtomicReferenceFieldUpdater, Set> entrySetUpdater = UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Set.class, "entrySet")); + private static final AtomicReferenceFieldUpdater, Collection> valuesUpdater = UtilGenerics.cast(AtomicReferenceFieldUpdater.newUpdater(GenericMap.class, Collection.class, "values")); + private static final AtomicIntegerFieldUpdater> modCountUpdater = UtilGenerics.cast(AtomicIntegerFieldUpdater.newUpdater(GenericMap.class, "modCount")); + + private volatile Set keySet; + private volatile Set> entrySet; + private volatile Collection values; + private volatile int modCount; + + public int getModCount() { + return modCount; + } + + protected void incrementModCount() { + modCountUpdater.getAndIncrement(this); + } + + public final void clear() { + if (isEmpty()) return; + incrementModCount(); + clearInternal(); + } + + protected abstract void clearInternal(); + + public boolean containsValue(Object value) { + return values().contains(value); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map)) return false; + if (this == o) return true; + Map map = (Map) o; + if (size() != map.size()) return false; + if (o instanceof GenericMap) return equalsGenericMap((GenericMap) o); + return equalsMap(map); + } + + protected boolean equalsGenericMap(GenericMap map) { + Iterator> it = iterator(false); + while (it.hasNext()) { + Map.Entry entry = it.next(); + K key = entry.getKey(); + V value = entry.getValue(); + if (value != null) { + if (!value.equals(map.get(key, false))) return false; + } else { + Object otherValue = map.get(key, false); + if (otherValue != null) return false; + if (!map.containsKey(key)) return false; + } + } + return true; + } + + protected boolean equalsMap(Map map) { + Iterator> it = iterator(false); + while (it.hasNext()) { + Map.Entry entry = it.next(); + K key = entry.getKey(); + V value = entry.getValue(); + if (value != null) { + if (!value.equals(map.get(key))) return false; + } else { + Object otherValue = map.get(key); + if (otherValue != null) return false; + if (!map.containsKey(key)) return false; + } + } + return true; + } + + public final V get(Object key) { + return get(key, true); + } + + protected abstract V get(Object key, boolean noteAccess); + + protected abstract class GenericMapIterator extends IteratorWrapper> { + private final int currentModCount = getModCount(); + + protected GenericMapIterator(boolean noteAccess) { + super(iterator(noteAccess)); + } + + protected boolean isValid(Map.Entry src) { + if (currentModCount != getModCount()) throw new ConcurrentModificationException(); + return true; + } + } + + public final Set> entrySet() { + if (entrySet == null) { + entrySetUpdater.compareAndSet(this, null, new GenericMapEntrySet>(this) { + @Override + protected boolean contains(Object key, Object value) { + return UtilObject.equalsHelper(get(key, false), value); + } + + @Override + public Iterator> iterator(boolean noteAccess) { + return new GenericMapIterator>(noteAccess) { + @Override + protected void noteRemoval(Map.Entry dest, Map.Entry src) { + // No need to note the remove, the wrapped iterator does that for us + // evictionPolicy.remove(evictionDeque, dest); + // if (diskStore != null) diskStore.remove(dest); + } + + @Override + protected Map.Entry convert(Map.Entry src) { + return src; + } + }; + } + }); + } + return entrySet; + } + + protected abstract Iterator> iterator(boolean noteAccess); + + public final Set keySet() { + if (keySet == null) { + keySetUpdater.compareAndSet(this, null, new GenericMapKeySet>(this) { + public boolean contains(Object key) { + return containsKey(key); + } + + @Override + public Iterator iterator(boolean noteAccess) { + return new GenericMapIterator(noteAccess) { + @Override + protected void noteRemoval(K dest, Map.Entry src) { + // No need to note the remove, the wrapped iterator does that for us + // evictionPolicy.remove(evictionDeque, dest); + // if (diskStore != null) diskStore.remove(dest); + } + + @Override + protected K convert(Map.Entry src) { + return src.getKey(); + } + }; + } + }); + } + return keySet; + } + + public final Collection values() { + if (values == null) { + valuesUpdater.compareAndSet(this, null, new GenericMapValues>(this) { + @Override + public Iterator iterator(boolean noteAccess) { + return new GenericMapIterator(noteAccess) { + @Override + protected void noteRemoval(V dest, Map.Entry src) { + // No need to note the remove, the wrapped iterator does that for us + // evictionPolicy.remove(evictionDeque, src.getKey()); + // if (diskStore != null) diskStore.remove(src.getKey()); + } + + @Override + protected V convert(Map.Entry src) { + return src.getValue(); + } + }; + } + }); + } + return values; + } + + public final V remove(Object key) { + return removeInternal(key, true); + } + + protected abstract V removeInternal(Object key, boolean incrementModCount); + + public final void putAll(Map map) { + putAllInternal(map); + } + + private void putAllInternal(Map map) { + if (map.isEmpty()) return; + incrementModCount(); + Iterator> it; + if (map instanceof GenericMap) { + GenericMap otherMap = UtilGenerics.cast(map); + it = otherMap.iterator(false); + } else { + it = map.entrySet().iterator(); + } + putAllIterator(it); + } + + protected abstract void putAllIterator(Iterator> it); + + @Override + public String toString() { + return appendTo(new StringBuilder()).toString(); + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append("{"); + Iterator> it = iterator(false); + while (it.hasNext()) { + Map.Entry entry = it.next(); + sb.append(entry.getKey()).append("=").append(entry.getValue()); + if (it.hasNext()) sb.append(","); + } + return sb.append("}"); + } +} + diff --git a/framework/base/src/org/ofbiz/base/util/collections/GenericMapCollection.java b/framework/base/src/org/ofbiz/base/util/collections/GenericMapCollection.java index e1e9882844..ffaf865fcd 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/GenericMapCollection.java +++ b/framework/base/src/org/ofbiz/base/util/collections/GenericMapCollection.java @@ -1,121 +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.collections; - -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -public abstract class GenericMapCollection, I> implements Collection { - protected final M source; - - public GenericMapCollection(M source) { - this.source = source; - } - - public boolean add(I item) { - throw new UnsupportedOperationException(); - } - - public boolean addAll(Collection collection) { - throw new UnsupportedOperationException(); - } - - public void clear() { - source.clear(); - } - - public boolean containsAll(Collection collection) { - for (Object item: collection) { - if (!contains(item)) return false; - } - return true; - } - - public boolean isEmpty() { - return source.isEmpty(); - } - - public final Iterator iterator() { - return iterator(true); - } - - protected abstract Iterator iterator(boolean noteAccess); - - public boolean removeAll(Collection collection) { - int count = 0; - for (Object item: collection) { - if (remove(item)) count++; - } - return count > 0; - } - - public boolean retainAll(Collection collection) { - int count = 0; - Iterator it = iterator(false); - while (it.hasNext()) { - I item = it.next(); - if (!collection.contains(item)) { - it.remove(); - count++; - } - } - return count > 0; - } - - public int size() { - return source.size(); - } - - public Object[] toArray() { - List list = new LinkedList(); - Iterator it = iterator(false); - while (it.hasNext()) { - list.add(it.next()); - } - return list.toArray(); - } - - public T[] toArray(T[] array) { - List list = new LinkedList(); - Iterator it = iterator(false); - while (it.hasNext()) { - list.add(it.next()); - } - return list.toArray(array); - } - - @Override - public String toString() { - return appendTo(new StringBuilder()).toString(); - } - - public StringBuilder appendTo(StringBuilder sb) { - sb.append("["); - Iterator it = iterator(false); - while (it.hasNext()) { - sb.append(it.next()); - if (it.hasNext()) sb.append(", "); - } - return sb.append("]"); - } -} - +/******************************************************************************* + * 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.collections; + +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public abstract class GenericMapCollection, I> implements Collection { + protected final M source; + + public GenericMapCollection(M source) { + this.source = source; + } + + public boolean add(I item) { + throw new UnsupportedOperationException(); + } + + public boolean addAll(Collection collection) { + throw new UnsupportedOperationException(); + } + + public void clear() { + source.clear(); + } + + public boolean containsAll(Collection collection) { + for (Object item: collection) { + if (!contains(item)) return false; + } + return true; + } + + public boolean isEmpty() { + return source.isEmpty(); + } + + public final Iterator iterator() { + return iterator(true); + } + + protected abstract Iterator iterator(boolean noteAccess); + + public boolean removeAll(Collection collection) { + int count = 0; + for (Object item: collection) { + if (remove(item)) count++; + } + return count > 0; + } + + public boolean retainAll(Collection collection) { + int count = 0; + Iterator it = iterator(false); + while (it.hasNext()) { + I item = it.next(); + if (!collection.contains(item)) { + it.remove(); + count++; + } + } + return count > 0; + } + + public int size() { + return source.size(); + } + + public Object[] toArray() { + List list = new LinkedList(); + Iterator it = iterator(false); + while (it.hasNext()) { + list.add(it.next()); + } + return list.toArray(); + } + + public T[] toArray(T[] array) { + List list = new LinkedList(); + Iterator it = iterator(false); + while (it.hasNext()) { + list.add(it.next()); + } + return list.toArray(array); + } + + @Override + public String toString() { + return appendTo(new StringBuilder()).toString(); + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append("["); + Iterator it = iterator(false); + while (it.hasNext()) { + sb.append(it.next()); + if (it.hasNext()) sb.append(", "); + } + return sb.append("]"); + } +} + diff --git a/framework/base/src/org/ofbiz/base/util/collections/GenericMapEntry.java b/framework/base/src/org/ofbiz/base/util/collections/GenericMapEntry.java index 34329d233f..41da9e4dab 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/GenericMapEntry.java +++ b/framework/base/src/org/ofbiz/base/util/collections/GenericMapEntry.java @@ -1,60 +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.collections; - -import java.util.Map; - -import org.ofbiz.base.util.UtilObject; - -public class GenericMapEntry implements Map.Entry { - protected final GenericMap map; - protected final K key; - protected final boolean noteAccess; - - public GenericMapEntry(GenericMap map, K key, boolean noteAccess) { - this.map = map; - this.key = key; - this.noteAccess = noteAccess; - } - - public K getKey() { - return key; - } - - public V getValue() { - return map.get(key, noteAccess); - } - - public V setValue(V value) { - return map.put(key, value); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof Map.Entry)) return false; - if (this == o) return true; - Map.Entry other = (Map.Entry) o; - return UtilObject.equalsHelper(getKey(), other.getKey()) && UtilObject.equalsHelper(getValue(), other.getValue()); - } - - @Override - public int hashCode() { - return UtilObject.doHashCode(getKey()) ^ UtilObject.doHashCode(getValue()); - } -} +/******************************************************************************* + * 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.collections; + +import java.util.Map; + +import org.ofbiz.base.util.UtilObject; + +public class GenericMapEntry implements Map.Entry { + protected final GenericMap map; + protected final K key; + protected final boolean noteAccess; + + public GenericMapEntry(GenericMap map, K key, boolean noteAccess) { + this.map = map; + this.key = key; + this.noteAccess = noteAccess; + } + + public K getKey() { + return key; + } + + public V getValue() { + return map.get(key, noteAccess); + } + + public V setValue(V value) { + return map.put(key, value); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry)) return false; + if (this == o) return true; + Map.Entry other = (Map.Entry) o; + return UtilObject.equalsHelper(getKey(), other.getKey()) && UtilObject.equalsHelper(getValue(), other.getValue()); + } + + @Override + public int hashCode() { + return UtilObject.doHashCode(getKey()) ^ UtilObject.doHashCode(getValue()); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/collections/GenericMapEntrySet.java b/framework/base/src/org/ofbiz/base/util/collections/GenericMapEntrySet.java index 4efe513941..a3e58f8d18 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/GenericMapEntrySet.java +++ b/framework/base/src/org/ofbiz/base/util/collections/GenericMapEntrySet.java @@ -1,47 +1,47 @@ -/******************************************************************************* - * 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.collections; - -import java.util.Map; - -public abstract class GenericMapEntrySet> extends GenericMapSet> { - public GenericMapEntrySet(M source) { - super(source); - } - - public boolean contains(Object item) { - if (item == null) return false; - if (!(item instanceof Map.Entry)) return false; - Map.Entry other = (Map.Entry) item; - return contains(other.getKey(), other.getValue()); - } - - protected abstract boolean contains(Object key, Object value); - - public boolean remove(Object item) { - if (item == null) return false; - if (!(item instanceof Map.Entry)) return false; - Map.Entry other = (Map.Entry) item; - Object key = other.getKey(); - if (!source.containsKey(key)) return false; - source.remove(key); - return true; - } -} - +/******************************************************************************* + * 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.collections; + +import java.util.Map; + +public abstract class GenericMapEntrySet> extends GenericMapSet> { + public GenericMapEntrySet(M source) { + super(source); + } + + public boolean contains(Object item) { + if (item == null) return false; + if (!(item instanceof Map.Entry)) return false; + Map.Entry other = (Map.Entry) item; + return contains(other.getKey(), other.getValue()); + } + + protected abstract boolean contains(Object key, Object value); + + public boolean remove(Object item) { + if (item == null) return false; + if (!(item instanceof Map.Entry)) return false; + Map.Entry other = (Map.Entry) item; + Object key = other.getKey(); + if (!source.containsKey(key)) return false; + source.remove(key); + return true; + } +} + diff --git a/framework/base/src/org/ofbiz/base/util/collections/GenericMapKeySet.java b/framework/base/src/org/ofbiz/base/util/collections/GenericMapKeySet.java index 08c438711a..68588c6329 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/GenericMapKeySet.java +++ b/framework/base/src/org/ofbiz/base/util/collections/GenericMapKeySet.java @@ -1,32 +1,32 @@ -/******************************************************************************* - * 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.collections; - -import java.util.Map; - -public abstract class GenericMapKeySet> extends GenericMapSet { - public GenericMapKeySet(M source) { - super(source); - } - - public boolean remove(Object item) { - return source.remove(item) != null; - } -} - +/******************************************************************************* + * 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.collections; + +import java.util.Map; + +public abstract class GenericMapKeySet> extends GenericMapSet { + public GenericMapKeySet(M source) { + super(source); + } + + public boolean remove(Object item) { + return source.remove(item) != null; + } +} + diff --git a/framework/base/src/org/ofbiz/base/util/collections/GenericMapSet.java b/framework/base/src/org/ofbiz/base/util/collections/GenericMapSet.java index ba195646fa..dbd6aaee14 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/GenericMapSet.java +++ b/framework/base/src/org/ofbiz/base/util/collections/GenericMapSet.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * 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.collections; - -import java.util.Map; -import java.util.Set; - -public abstract class GenericMapSet, I> extends GenericMapCollection implements Set { - public GenericMapSet(M source) { - super(source); - } - - @Override - public final boolean equals(Object o) { - if (!(o instanceof Set)) return false; - Set other = (Set) o; - if (source.size() != other.size()) return false; - for (I item: this) { - if (!other.contains(item)) return false; - } - return true; - } - - @Override - public final int hashCode() { - int h = 0; - for (I item: this) { - if (item == null) continue; - h += item.hashCode(); - } - return h; - } -} - +/******************************************************************************* + * 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.collections; + +import java.util.Map; +import java.util.Set; + +public abstract class GenericMapSet, I> extends GenericMapCollection implements Set { + public GenericMapSet(M source) { + super(source); + } + + @Override + public final boolean equals(Object o) { + if (!(o instanceof Set)) return false; + Set other = (Set) o; + if (source.size() != other.size()) return false; + for (I item: this) { + if (!other.contains(item)) return false; + } + return true; + } + + @Override + public final int hashCode() { + int h = 0; + for (I item: this) { + if (item == null) continue; + h += item.hashCode(); + } + return h; + } +} + diff --git a/framework/base/src/org/ofbiz/base/util/collections/GenericMapValues.java b/framework/base/src/org/ofbiz/base/util/collections/GenericMapValues.java index b9a8b60ed3..1d8e73fefc 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/GenericMapValues.java +++ b/framework/base/src/org/ofbiz/base/util/collections/GenericMapValues.java @@ -1,79 +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.util.collections; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.ofbiz.base.util.UtilObject; - -public abstract class GenericMapValues> extends GenericMapCollection { - public GenericMapValues(M source) { - super(source); - } - - public boolean contains(Object item) { - Iterator it = iterator(false); - while (it.hasNext()) { - if (UtilObject.equalsHelper(item, it.next())) return true; - } - return false; - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof Collection)) return false; - if (o instanceof List || o instanceof Set) return false; - Collection other = (Collection) o; - if (source.size() != other.size()) return false; - Iterator it = iterator(false); - while (it.hasNext()) { - V item = it.next(); - if (!other.contains(item)) return false; - } - return true; - } - - @Override - public int hashCode() { - int h = 0; - Iterator it = iterator(false); - while (it.hasNext()) { - V item = it.next(); - if (item == null) continue; - h += item.hashCode(); - } - return h; - } - - public boolean remove(Object item) { - Iterator it = iterator(false); - while (it.hasNext()) { - if (UtilObject.equalsHelper(item, it.next())) { - it.remove(); - return true; - } - } - return false; - } -} - +/******************************************************************************* + * 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.collections; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.ofbiz.base.util.UtilObject; + +public abstract class GenericMapValues> extends GenericMapCollection { + public GenericMapValues(M source) { + super(source); + } + + public boolean contains(Object item) { + Iterator it = iterator(false); + while (it.hasNext()) { + if (UtilObject.equalsHelper(item, it.next())) return true; + } + return false; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Collection)) return false; + if (o instanceof List || o instanceof Set) return false; + Collection other = (Collection) o; + if (source.size() != other.size()) return false; + Iterator it = iterator(false); + while (it.hasNext()) { + V item = it.next(); + if (!other.contains(item)) return false; + } + return true; + } + + @Override + public int hashCode() { + int h = 0; + Iterator it = iterator(false); + while (it.hasNext()) { + V item = it.next(); + if (item == null) continue; + h += item.hashCode(); + } + return h; + } + + public boolean remove(Object item) { + Iterator it = iterator(false); + while (it.hasNext()) { + if (UtilObject.equalsHelper(item, it.next())) { + it.remove(); + return true; + } + } + return false; + } +} + diff --git a/framework/base/src/org/ofbiz/base/util/collections/IteratorWrapper.java b/framework/base/src/org/ofbiz/base/util/collections/IteratorWrapper.java index 0fa5ce9e5a..d91a477226 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/IteratorWrapper.java +++ b/framework/base/src/org/ofbiz/base/util/collections/IteratorWrapper.java @@ -1,75 +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.util.collections; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -public abstract class IteratorWrapper implements Iterator { - private final Iterator it; - private boolean nextCalled; - private DEST lastDest; - private SRC lastSrc; - - protected IteratorWrapper(Iterator it) { - this.it = it; - } - - public boolean hasNext() { - if (nextCalled) return true; - if (!it.hasNext()) return false; - do { - lastSrc = it.next(); - DEST nextDest = convert(lastSrc); - if (isValid(lastSrc, nextDest)) { - nextCalled = true; - lastDest = nextDest; - return true; - } - } while (it.hasNext()); - return false; - } - - public DEST next() { - if (!nextCalled) { - if (!hasNext()) throw new NoSuchElementException(); - } - nextCalled = false; - return lastDest; - } - - public void remove() { - if (lastSrc != null) { - noteRemoval(lastDest, lastSrc); - it.remove(); - lastDest = null; - lastSrc = null; - } else { - throw new IllegalStateException(); - } - } - - protected boolean isValid(SRC src, DEST dest) { - return true; - } - - protected abstract void noteRemoval(DEST dest, SRC src); - protected abstract DEST convert(SRC src); -} - +/******************************************************************************* + * 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.collections; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +public abstract class IteratorWrapper implements Iterator { + private final Iterator it; + private boolean nextCalled; + private DEST lastDest; + private SRC lastSrc; + + protected IteratorWrapper(Iterator it) { + this.it = it; + } + + public boolean hasNext() { + if (nextCalled) return true; + if (!it.hasNext()) return false; + do { + lastSrc = it.next(); + DEST nextDest = convert(lastSrc); + if (isValid(lastSrc, nextDest)) { + nextCalled = true; + lastDest = nextDest; + return true; + } + } while (it.hasNext()); + return false; + } + + public DEST next() { + if (!nextCalled) { + if (!hasNext()) throw new NoSuchElementException(); + } + nextCalled = false; + return lastDest; + } + + public void remove() { + if (lastSrc != null) { + noteRemoval(lastDest, lastSrc); + it.remove(); + lastDest = null; + lastSrc = null; + } else { + throw new IllegalStateException(); + } + } + + protected boolean isValid(SRC src, DEST dest) { + return true; + } + + protected abstract void noteRemoval(DEST dest, SRC src); + protected abstract DEST convert(SRC src); +} + diff --git a/framework/base/src/org/ofbiz/base/util/collections/MapContext.java b/framework/base/src/org/ofbiz/base/util/collections/MapContext.java index c715c2e3ab..14269af06f 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/MapContext.java +++ b/framework/base/src/org/ofbiz/base/util/collections/MapContext.java @@ -1,337 +1,337 @@ -/******************************************************************************* - * 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.collections; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.ofbiz.base.util.UtilGenerics; - - -/** - * Map Stack - * - */ -public class MapContext implements Map, LocalizedMap { - - public static final String module = MapContext.class.getName(); - - public static final MapContext getMapContext() { - return new MapContext(); - } - - public static MapContext createMapContext() { - MapContext newValue = MapContext.getMapContext(); - // initialize with a single entry - newValue.push(); - return newValue; - } - - @SuppressWarnings("unchecked") - public static MapContext createMapContext(Map baseMap) { - MapContext newValue = MapContext.getMapContext(); - if (baseMap instanceof MapContext) { - newValue.stackList.addAll(((MapContext) baseMap).stackList); - } else { - newValue.stackList.add(0, baseMap); - } - return newValue; - } - - /** Does a shallow copy of the internal stack of the passed MapContext; enables simultaneous stacks that share common parent Maps */ - public static MapContext createMapContext(MapContext source) { - MapContext newValue = MapContext.getMapContext(); - newValue.stackList.addAll(source.stackList); - return newValue; - } - - protected MapContext() { - super(); - } - - protected List> stackList = new LinkedList>(); - - public void reset() { - stackList = new LinkedList>(); - } - - /** Puts a new Map on the top of the stack */ - public void push() { - Map newMap = new HashMap(); - this.stackList.add(0,newMap); - } - - /** Puts an existing Map on the top of the stack (top meaning will override lower layers on the stack) */ - public void push(Map existingMap) { - if (existingMap == null) { - throw new IllegalArgumentException("Error: cannot push null existing Map onto a MapContext"); - } - this.stackList.add(0, existingMap); - } - - /** Puts an existing Map on the BOTTOM of the stack (bottom meaning will be overriden by lower layers on the stack, ie everything else already there) */ - public void addToBottom(Map existingMap) { - if (existingMap == null) { - throw new IllegalArgumentException("Error: cannot add null existing Map to bottom of a MapContext"); - } - this.stackList.add(existingMap); - } - - /** Remove and returns the Map from the top of the stack; if there is only one Map on the stack it returns null and does not remove it */ - public Map pop() { - // always leave at least one Map in the List, ie never pop off the last Map - if (this.stackList.size() > 1) { - return stackList.remove(0); - } else { - return null; - } - } - - /** - * Creates a MapContext object that has the same Map objects on its stack; - * meant to be used to enable a - * situation where a parent and child context are operating simultaneously - * using two different MapContext objects, but sharing the Maps in common - */ - public MapContext standAloneStack() { - MapContext standAlone = MapContext.createMapContext(this); - return standAlone; - } - - /** - * Creates a MapContext object that has the same Map objects on its stack, - * but with a new Map pushed on the top; meant to be used to enable a - * situation where a parent and child context are operating simultaneously - * using two different MapContext objects, but sharing the Maps in common - */ - public MapContext standAloneChildStack() { - MapContext standAloneChild = MapContext.createMapContext(this); - standAloneChild.push(); - return standAloneChild; - } - - /* (non-Javadoc) - * @see java.util.Map#size() - */ - public int size() { - // a little bit tricky; to represent the apparent size we need to aggregate all keys and get a count of unique keys - // this is a bit of a slow way, but gets the best number possible - Set keys = this.keySet(); - return keys.size(); - } - - /* (non-Javadoc) - * @see java.util.Map#isEmpty() - */ - public boolean isEmpty() { - // walk the stackList and if any is not empty, return false; otherwise return true - for (Map curMap: this.stackList) { - if (!curMap.isEmpty()) { - return false; - } - } - return true; - } - - /* (non-Javadoc) - * @see java.util.Map#containsKey(java.lang.Object) - */ - public boolean containsKey(Object key) { - // walk the stackList and for the first place it is found return true; otherwise refurn false - for (Map curMap: this.stackList) { - if (curMap.containsKey(key)) { - return true; - } - } - return false; - } - - /* (non-Javadoc) - * @see java.util.Map#containsValue(java.lang.Object) - */ - public boolean containsValue(Object value) { - // walk the stackList and the entries for each Map and if nothing is in for the current key, consider it an option, otherwise ignore - Set resultKeySet = new HashSet(); - for (Map curMap: this.stackList) { - for (Map.Entry curEntry: curMap.entrySet()) { - if (!resultKeySet.contains(curEntry.getKey())) { - resultKeySet.add(curEntry.getKey()); - if (value == null) { - if (curEntry.getValue() == null) { - return true; - } - } else { - if (value.equals(curEntry.getValue())) { - return true; - } - } - } - } - } - return false; - } - - /* (non-Javadoc) - * @see java.util.Map#get(java.lang.Object) - */ - public V get(Object key) { - // walk the stackList and for the first place it is found return true; otherwise refurn false - for (Map curMap: this.stackList) { - // only return if the curMap contains the key, rather than checking for null; this allows a null at a lower level to override a value at a higher level - if (curMap.containsKey(key)) { - return curMap.get(key); - } - } - return null; - } - - /* (non-Javadoc) - * @see org.ofbiz.base.util.collections.LocalizedMap#get(java.lang.String, java.util.Locale) - */ - public V get(String name, Locale locale) { - // walk the stackList and for the first place it is found return true; otherwise refurn false - for (Map curMap: this.stackList) { - // only return if the curMap contains the key, rather than checking for null; this allows a null at a lower level to override a value at a higher level - if (curMap.containsKey(name)) { - if (curMap instanceof LocalizedMap) { - LocalizedMap lmap = UtilGenerics.cast(curMap); - return lmap.get(name, locale); - } else { - return curMap.get(name); - } - } - } - return null; - } - - /* (non-Javadoc) - * @see java.util.Map#put(java.lang.Object, java.lang.Object) - */ - public V put(K key, V value) { - // all write operations are local: only put in the Map on the top of the stack - Map currentMap = this.stackList.get(0); - return currentMap.put(key, value); - } - - /* (non-Javadoc) - * @see java.util.Map#remove(java.lang.Object) - */ - public V remove(Object key) { - // all write operations are local: only remove from the Map on the top of the stack - Map currentMap = this.stackList.get(0); - return currentMap.remove(key); - } - - /* (non-Javadoc) - * @see java.util.Map#putAll(java.util.Map) - */ - public void putAll(Map arg0) { - // all write operations are local: only put in the Map on the top of the stack - Map currentMap = this.stackList.get(0); - currentMap.putAll(arg0); - } - - /* (non-Javadoc) - * @see java.util.Map#clear() - */ - public void clear() { - // all write operations are local: only clear the Map on the top of the stack - this.stackList.get(0).clear(); - } - - /* (non-Javadoc) - * @see java.util.Map#keySet() - */ - public Set keySet() { - // walk the stackList and aggregate all keys - Set resultSet = new HashSet(); - for (Map curMap: this.stackList) { - resultSet.addAll(curMap.keySet()); - } - return Collections.unmodifiableSet(resultSet); - } - - /* (non-Javadoc) - * @see java.util.Map#values() - */ - public Collection values() { - // walk the stackList and the entries for each Map and if nothing is in for the current key, put it in - Set resultKeySet = new HashSet(); - List resultValues = new LinkedList(); - for (Map curMap: this.stackList) { - for (Map.Entry curEntry: curMap.entrySet()) { - if (!resultKeySet.contains(curEntry.getKey())) { - resultKeySet.add(curEntry.getKey()); - resultValues.add(curEntry.getValue()); - } - } - } - return Collections.unmodifiableCollection(resultValues); - } - - /* (non-Javadoc) - * @see java.util.Map#entrySet() - */ - public Set> entrySet() { - // walk the stackList and the entries for each Map and if nothing is in for the current key, put it in - Set resultKeySet = new HashSet(); - Set> resultEntrySet = new HashSet>(); - for (Map curMap: this.stackList) { - for (Map.Entry curEntry: curMap.entrySet()) { - if (!resultKeySet.contains(curEntry.getKey())) { - resultKeySet.add(curEntry.getKey()); - resultEntrySet.add(curEntry); - } - } - } - return Collections.unmodifiableSet(resultEntrySet); - } - - @Override - public String toString() { - StringBuilder fullMapString = new StringBuilder(); - int curLevel = 0; - for (Map curMap: this.stackList) { - fullMapString.append("============================== Start stack level " + curLevel + "\n"); - for (Map.Entry curEntry: curMap.entrySet()) { - - fullMapString.append("==>["); - fullMapString.append(curEntry.getKey()); - fullMapString.append("]:"); - // skip the instances of MapContext to avoid infinite loop - if (curEntry.getValue() instanceof MapContext) { - fullMapString.append(""); - } else { - fullMapString.append(curEntry.getValue()); - } - fullMapString.append("\n"); - } - fullMapString.append("============================== End stack level " + curLevel + "\n"); - curLevel++; - } - return fullMapString.toString(); - } -} +/******************************************************************************* + * 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.collections; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import org.ofbiz.base.util.UtilGenerics; + + +/** + * Map Stack + * + */ +public class MapContext implements Map, LocalizedMap { + + public static final String module = MapContext.class.getName(); + + public static final MapContext getMapContext() { + return new MapContext(); + } + + public static MapContext createMapContext() { + MapContext newValue = MapContext.getMapContext(); + // initialize with a single entry + newValue.push(); + return newValue; + } + + @SuppressWarnings("unchecked") + public static MapContext createMapContext(Map baseMap) { + MapContext newValue = MapContext.getMapContext(); + if (baseMap instanceof MapContext) { + newValue.stackList.addAll(((MapContext) baseMap).stackList); + } else { + newValue.stackList.add(0, baseMap); + } + return newValue; + } + + /** Does a shallow copy of the internal stack of the passed MapContext; enables simultaneous stacks that share common parent Maps */ + public static MapContext createMapContext(MapContext source) { + MapContext newValue = MapContext.getMapContext(); + newValue.stackList.addAll(source.stackList); + return newValue; + } + + protected MapContext() { + super(); + } + + protected List> stackList = new LinkedList>(); + + public void reset() { + stackList = new LinkedList>(); + } + + /** Puts a new Map on the top of the stack */ + public void push() { + Map newMap = new HashMap(); + this.stackList.add(0,newMap); + } + + /** Puts an existing Map on the top of the stack (top meaning will override lower layers on the stack) */ + public void push(Map existingMap) { + if (existingMap == null) { + throw new IllegalArgumentException("Error: cannot push null existing Map onto a MapContext"); + } + this.stackList.add(0, existingMap); + } + + /** Puts an existing Map on the BOTTOM of the stack (bottom meaning will be overriden by lower layers on the stack, ie everything else already there) */ + public void addToBottom(Map existingMap) { + if (existingMap == null) { + throw new IllegalArgumentException("Error: cannot add null existing Map to bottom of a MapContext"); + } + this.stackList.add(existingMap); + } + + /** Remove and returns the Map from the top of the stack; if there is only one Map on the stack it returns null and does not remove it */ + public Map pop() { + // always leave at least one Map in the List, ie never pop off the last Map + if (this.stackList.size() > 1) { + return stackList.remove(0); + } else { + return null; + } + } + + /** + * Creates a MapContext object that has the same Map objects on its stack; + * meant to be used to enable a + * situation where a parent and child context are operating simultaneously + * using two different MapContext objects, but sharing the Maps in common + */ + public MapContext standAloneStack() { + MapContext standAlone = MapContext.createMapContext(this); + return standAlone; + } + + /** + * Creates a MapContext object that has the same Map objects on its stack, + * but with a new Map pushed on the top; meant to be used to enable a + * situation where a parent and child context are operating simultaneously + * using two different MapContext objects, but sharing the Maps in common + */ + public MapContext standAloneChildStack() { + MapContext standAloneChild = MapContext.createMapContext(this); + standAloneChild.push(); + return standAloneChild; + } + + /* (non-Javadoc) + * @see java.util.Map#size() + */ + public int size() { + // a little bit tricky; to represent the apparent size we need to aggregate all keys and get a count of unique keys + // this is a bit of a slow way, but gets the best number possible + Set keys = this.keySet(); + return keys.size(); + } + + /* (non-Javadoc) + * @see java.util.Map#isEmpty() + */ + public boolean isEmpty() { + // walk the stackList and if any is not empty, return false; otherwise return true + for (Map curMap: this.stackList) { + if (!curMap.isEmpty()) { + return false; + } + } + return true; + } + + /* (non-Javadoc) + * @see java.util.Map#containsKey(java.lang.Object) + */ + public boolean containsKey(Object key) { + // walk the stackList and for the first place it is found return true; otherwise refurn false + for (Map curMap: this.stackList) { + if (curMap.containsKey(key)) { + return true; + } + } + return false; + } + + /* (non-Javadoc) + * @see java.util.Map#containsValue(java.lang.Object) + */ + public boolean containsValue(Object value) { + // walk the stackList and the entries for each Map and if nothing is in for the current key, consider it an option, otherwise ignore + Set resultKeySet = new HashSet(); + for (Map curMap: this.stackList) { + for (Map.Entry curEntry: curMap.entrySet()) { + if (!resultKeySet.contains(curEntry.getKey())) { + resultKeySet.add(curEntry.getKey()); + if (value == null) { + if (curEntry.getValue() == null) { + return true; + } + } else { + if (value.equals(curEntry.getValue())) { + return true; + } + } + } + } + } + return false; + } + + /* (non-Javadoc) + * @see java.util.Map#get(java.lang.Object) + */ + public V get(Object key) { + // walk the stackList and for the first place it is found return true; otherwise refurn false + for (Map curMap: this.stackList) { + // only return if the curMap contains the key, rather than checking for null; this allows a null at a lower level to override a value at a higher level + if (curMap.containsKey(key)) { + return curMap.get(key); + } + } + return null; + } + + /* (non-Javadoc) + * @see org.ofbiz.base.util.collections.LocalizedMap#get(java.lang.String, java.util.Locale) + */ + public V get(String name, Locale locale) { + // walk the stackList and for the first place it is found return true; otherwise refurn false + for (Map curMap: this.stackList) { + // only return if the curMap contains the key, rather than checking for null; this allows a null at a lower level to override a value at a higher level + if (curMap.containsKey(name)) { + if (curMap instanceof LocalizedMap) { + LocalizedMap lmap = UtilGenerics.cast(curMap); + return lmap.get(name, locale); + } else { + return curMap.get(name); + } + } + } + return null; + } + + /* (non-Javadoc) + * @see java.util.Map#put(java.lang.Object, java.lang.Object) + */ + public V put(K key, V value) { + // all write operations are local: only put in the Map on the top of the stack + Map currentMap = this.stackList.get(0); + return currentMap.put(key, value); + } + + /* (non-Javadoc) + * @see java.util.Map#remove(java.lang.Object) + */ + public V remove(Object key) { + // all write operations are local: only remove from the Map on the top of the stack + Map currentMap = this.stackList.get(0); + return currentMap.remove(key); + } + + /* (non-Javadoc) + * @see java.util.Map#putAll(java.util.Map) + */ + public void putAll(Map arg0) { + // all write operations are local: only put in the Map on the top of the stack + Map currentMap = this.stackList.get(0); + currentMap.putAll(arg0); + } + + /* (non-Javadoc) + * @see java.util.Map#clear() + */ + public void clear() { + // all write operations are local: only clear the Map on the top of the stack + this.stackList.get(0).clear(); + } + + /* (non-Javadoc) + * @see java.util.Map#keySet() + */ + public Set keySet() { + // walk the stackList and aggregate all keys + Set resultSet = new HashSet(); + for (Map curMap: this.stackList) { + resultSet.addAll(curMap.keySet()); + } + return Collections.unmodifiableSet(resultSet); + } + + /* (non-Javadoc) + * @see java.util.Map#values() + */ + public Collection values() { + // walk the stackList and the entries for each Map and if nothing is in for the current key, put it in + Set resultKeySet = new HashSet(); + List resultValues = new LinkedList(); + for (Map curMap: this.stackList) { + for (Map.Entry curEntry: curMap.entrySet()) { + if (!resultKeySet.contains(curEntry.getKey())) { + resultKeySet.add(curEntry.getKey()); + resultValues.add(curEntry.getValue()); + } + } + } + return Collections.unmodifiableCollection(resultValues); + } + + /* (non-Javadoc) + * @see java.util.Map#entrySet() + */ + public Set> entrySet() { + // walk the stackList and the entries for each Map and if nothing is in for the current key, put it in + Set resultKeySet = new HashSet(); + Set> resultEntrySet = new HashSet>(); + for (Map curMap: this.stackList) { + for (Map.Entry curEntry: curMap.entrySet()) { + if (!resultKeySet.contains(curEntry.getKey())) { + resultKeySet.add(curEntry.getKey()); + resultEntrySet.add(curEntry); + } + } + } + return Collections.unmodifiableSet(resultEntrySet); + } + + @Override + public String toString() { + StringBuilder fullMapString = new StringBuilder(); + int curLevel = 0; + for (Map curMap: this.stackList) { + fullMapString.append("============================== Start stack level " + curLevel + "\n"); + for (Map.Entry curEntry: curMap.entrySet()) { + + fullMapString.append("==>["); + fullMapString.append(curEntry.getKey()); + fullMapString.append("]:"); + // skip the instances of MapContext to avoid infinite loop + if (curEntry.getValue() instanceof MapContext) { + fullMapString.append(""); + } else { + fullMapString.append(curEntry.getValue()); + } + fullMapString.append("\n"); + } + fullMapString.append("============================== End stack level " + curLevel + "\n"); + curLevel++; + } + return fullMapString.toString(); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/collections/ReadOnlyMapEntry.java b/framework/base/src/org/ofbiz/base/util/collections/ReadOnlyMapEntry.java index 1911ccee9f..5e364cbd22 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/ReadOnlyMapEntry.java +++ b/framework/base/src/org/ofbiz/base/util/collections/ReadOnlyMapEntry.java @@ -1,61 +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.util.collections; - -import java.util.Map; - -import org.ofbiz.base.util.UtilObject; - -/** this class can go away when ofbiz switches to java 1.6, replaced by - * AbstractMap.SimpleImmutableEntry - */ -public class ReadOnlyMapEntry implements Map.Entry { - protected final K key; - protected final V value; - - public ReadOnlyMapEntry(K key, V value) { - this.key = key; - this.value = value; - } - - public K getKey() { - return key; - } - - public V getValue() { - return value; - } - - public V setValue(V value) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof Map.Entry)) return false; - if (this == o) return true; - Map.Entry other = (Map.Entry) o; - return UtilObject.equalsHelper(getKey(), other.getKey()) && UtilObject.equalsHelper(getValue(), other.getValue()); - } - - @Override - public int hashCode() { - return UtilObject.doHashCode(getKey()) ^ UtilObject.doHashCode(getValue()); - } -} +/******************************************************************************* + * 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.collections; + +import java.util.Map; + +import org.ofbiz.base.util.UtilObject; + +/** this class can go away when ofbiz switches to java 1.6, replaced by + * AbstractMap.SimpleImmutableEntry + */ +public class ReadOnlyMapEntry implements Map.Entry { + protected final K key; + protected final V value; + + public ReadOnlyMapEntry(K key, V value) { + this.key = key; + this.value = value; + } + + public K getKey() { + return key; + } + + public V getValue() { + return value; + } + + public V setValue(V value) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry)) return false; + if (this == o) return true; + Map.Entry other = (Map.Entry) o; + return UtilObject.equalsHelper(getKey(), other.getKey()) && UtilObject.equalsHelper(getValue(), other.getValue()); + } + + @Override + public int hashCode() { + return UtilObject.doHashCode(getKey()) ^ UtilObject.doHashCode(getValue()); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/collections/test/FlexibleMapAccessorTests.java b/framework/base/src/org/ofbiz/base/util/collections/test/FlexibleMapAccessorTests.java index 8ffca6ebb0..5a163f0d7e 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/test/FlexibleMapAccessorTests.java +++ b/framework/base/src/org/ofbiz/base/util/collections/test/FlexibleMapAccessorTests.java @@ -1,188 +1,188 @@ -/******************************************************************************* - * 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.collections.test; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.math.BigDecimal; - -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.test.GenericTestCaseBase; -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.collections.FlexibleMapAccessor; -import org.ofbiz.base.util.string.FlexibleStringExpander; - -@SourceMonitored -public class FlexibleMapAccessorTests extends GenericTestCaseBase { - private static final Locale localeToTest = new Locale("en", "US"); - private static FlexibleMapAccessor fmaEmpty = FlexibleMapAccessor.getInstance(""); - private static FlexibleMapAccessor fmaNull = FlexibleMapAccessor.getInstance(null); - - public FlexibleMapAccessorTests(String name) { - super(name); - } - - private static void fmaTest(String label, String getText, String fseText, T var, String value) { - fmaTest(label, getText, getText, fseText, null, var, value); - } - - private static void fmaTest(String label, String getText, String putText, String fseText, Locale locale, T var, String value) { - Map testMap = new HashMap(); - FlexibleMapAccessor fmaGet = FlexibleMapAccessor.getInstance(getText); - assertEquals(label + ":get-original-name", getText, fmaGet.getOriginalName()); - assertEquals(label + ":get-isEmpty", false, fmaGet.isEmpty()); - assertEquals(label + ":get-instance-equals", fmaGet, FlexibleMapAccessor.getInstance(getText)); - assertEquals(label + ":toString", getText, fmaGet.toString()); - assertNotEquals(label + ":get-not-equals-empty", fmaEmpty, fmaGet); - assertNotEquals(label + ":get-not-equals-null", fmaNull, fmaGet); - assertNotEquals(label + ":empty-not-equals-get", fmaGet, fmaEmpty); - assertNotEquals(label + ":null-not-equals-get", fmaGet, fmaNull); - assertNotEquals(label + ":get-not-equals-other", fmaGet, FlexibleMapAccessorTests.class); - assertEquals(label + ":get-toString", getText, fmaGet.toString()); - FlexibleMapAccessor fmaGetAscending = FlexibleMapAccessor.getInstance("+" + getText); - assertEquals(label + ":get-ascending-toString", "+" + getText, fmaGetAscending.toString()); - assertTrue(label + ":get-ascending-isAscending", fmaGetAscending.getIsAscending()); - FlexibleMapAccessor fmaGetDescending = FlexibleMapAccessor.getInstance("-" + getText); - assertEquals(label + ":get-descending-toString", "-" + getText, fmaGetDescending.toString()); - assertFalse(label + ":get-decending-isAscending", fmaGetDescending.getIsAscending()); - FlexibleMapAccessor fmaPut = FlexibleMapAccessor.getInstance(putText); - assertEquals(label + ":put-toString", putText, fmaPut.toString()); - assertEquals(label + ":put-original-name", putText, fmaPut.getOriginalName()); - assertEquals(label + ":put-isEmpty", false, fmaPut.isEmpty()); - assertEquals(label + ":put-instance-equals", fmaPut, FlexibleMapAccessor.getInstance(putText)); - assertNotEquals(label + ":put-not-equals-other", fmaPut, FlexibleMapAccessorTests.class); - - FlexibleStringExpander fse = FlexibleStringExpander.getInstance(fseText); - if (locale == null) { - assertNull(label + ":get-initial", fmaGet.get(testMap)); - fmaPut.put(testMap, var); - assertFalse(label + ":testMap-not-empty", testMap.isEmpty()); - assertEquals(label + ":get", var, fmaGet.get(testMap)); - assertEquals(label, value, fse.expandString(testMap)); - assertEquals(label + ":remove", var, fmaGet.remove(testMap)); - assertNull(label + ":remove-not-exist", fmaGet.remove(testMap)); - } else { - fmaPut.put(testMap, var); - assertFalse(label + ":testMap-not-empty", testMap.isEmpty()); - assertEquals(label + ":get", value, fmaGet.get(testMap, locale)); - // BUG: fmaGet modifies testMap, even tho it shouldn't - assertEquals(label + ":get", value, fmaGet.get(testMap, null)); - assertEquals(label, value, fse.expandString(testMap, locale)); - } - - testMap.clear(); - fmaPut.put(testMap, null); - assertFalse(label + ":testMap-not-empty-put-null", testMap.isEmpty()); - if (locale == null) { - assertNull(label + ":get-put-null", fmaGet.get(testMap)); - } - testMap.clear(); - Exception caught = null; - try { - fmaPut.put(null, var); - } catch (Exception e) { - caught = e; - } finally { - assertNotNull(label + ":put-null-map", caught); - assertTrue(label + ":put-null-map-isEmpty", testMap.isEmpty()); - } - Set> set = new HashSet>(); - assertFalse(label + ":not-in-set", set.contains(fmaGet)); - set.add(fmaGet); - assertTrue(label + ":in-set", set.contains(fmaGet)); - } - - private static void fmaEmptyTest(String label, String text) { - FlexibleMapAccessor> fma = FlexibleMapAccessor.getInstance(text); - assertTrue(label + ":isEmpty", fma.isEmpty()); - Map testMap = new HashMap(); - assertNull(label + ":get", fma.get(null)); - assertNull(label + ":get", fma.get(testMap)); - assertTrue(label + ":map-isEmpty-initial", testMap.isEmpty()); - fma.put(testMap, FlexibleMapAccessorTests.class); - assertTrue(label + ":map-isEmpty-map", testMap.isEmpty()); - fma.put(null, FlexibleMapAccessorTests.class); - assertTrue(label + ":map-isEmpty-null", testMap.isEmpty()); - assertSame(label + ":same-null", fmaNull, fma); - assertSame(label + ":same-empty", fmaEmpty, fma); - assertEquals(label + ":original-name", "", fma.getOriginalName()); - assertNull(label + ":remove", fma.remove(testMap)); - assertNotNull(label + ":toString", fma.toString()); - } - - // These tests rely upon FlexibleStringExpander, so they - // should follow the FlexibleStringExpander tests. - public void testFlexibleMapAccessor() { - fmaEmptyTest("fmaEmpty", ""); - fmaEmptyTest("fmaNull", null); - fmaEmptyTest("fma\"null\"", "null"); - fmaTest("UEL auto-vivify Map", "parameters.var", "Hello ${parameters.var}!", "World", "Hello World!"); - fmaTest("UEL auto-vivify List", "parameters.someList[0]", "parameters.someList[+0]", "Hello ${parameters.someList[0]}!", null, "World", "Hello World!"); - fmaTest("fse", "para${'meter'}s.var", "Hello ${parameters.var}!", "World", "Hello World!"); - fmaTest("foo", "'The total is ${total?currency(USD)}.'", "total", "The total is ${total?currency(USD)}.", localeToTest, new BigDecimal("12345678.90"), "The total is $12,345,678.90."); - assertTrue("containsNestedExpression method returns true", FlexibleMapAccessor.getInstance("Hello ${parameters.var}!").containsNestedExpression()); - assertFalse("containsNestedExpression method returns false", FlexibleMapAccessor.getInstance("Hello World!").containsNestedExpression()); - } - - public static class ThrowException { - public Object getValue() throws Exception { - throw new Exception(); - } - - public void setValue(Object value) throws Exception { - throw new Exception(); - } - } - - @SuppressWarnings("serial") - public static class CantRemoveMap extends HashMap { - @Override - public V get(Object key) { - return super.get(key); - } - - @Override - public V put(K key, V value) { - if (value == null) { - throw new IllegalArgumentException(); - } - return super.put(key, value); - } - } - - public void testVerbosityAndErrors() { - boolean isVerbose = Debug.isOn(Debug.VERBOSE); - try { - Debug.set(Debug.VERBOSE, true); - Map testMap = new CantRemoveMap(); - testMap.put("throwException", new ThrowException()); - assertNull("no var", FlexibleMapAccessor.getInstance("var").get(testMap)); - Object result = FlexibleMapAccessor.getInstance("throwException.value").get(testMap); - assertNull("get null var", result); - FlexibleMapAccessor.getInstance("throwException.value").put(testMap, this); - FlexibleMapAccessor.getInstance("throwException").remove(testMap); - assertNotNull("not removed", testMap.get("throwException")); - } finally { - Debug.set(Debug.VERBOSE, isVerbose); - } - } -} +/******************************************************************************* + * 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.collections.test; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.math.BigDecimal; + +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.test.GenericTestCaseBase; +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.collections.FlexibleMapAccessor; +import org.ofbiz.base.util.string.FlexibleStringExpander; + +@SourceMonitored +public class FlexibleMapAccessorTests extends GenericTestCaseBase { + private static final Locale localeToTest = new Locale("en", "US"); + private static FlexibleMapAccessor fmaEmpty = FlexibleMapAccessor.getInstance(""); + private static FlexibleMapAccessor fmaNull = FlexibleMapAccessor.getInstance(null); + + public FlexibleMapAccessorTests(String name) { + super(name); + } + + private static void fmaTest(String label, String getText, String fseText, T var, String value) { + fmaTest(label, getText, getText, fseText, null, var, value); + } + + private static void fmaTest(String label, String getText, String putText, String fseText, Locale locale, T var, String value) { + Map testMap = new HashMap(); + FlexibleMapAccessor fmaGet = FlexibleMapAccessor.getInstance(getText); + assertEquals(label + ":get-original-name", getText, fmaGet.getOriginalName()); + assertEquals(label + ":get-isEmpty", false, fmaGet.isEmpty()); + assertEquals(label + ":get-instance-equals", fmaGet, FlexibleMapAccessor.getInstance(getText)); + assertEquals(label + ":toString", getText, fmaGet.toString()); + assertNotEquals(label + ":get-not-equals-empty", fmaEmpty, fmaGet); + assertNotEquals(label + ":get-not-equals-null", fmaNull, fmaGet); + assertNotEquals(label + ":empty-not-equals-get", fmaGet, fmaEmpty); + assertNotEquals(label + ":null-not-equals-get", fmaGet, fmaNull); + assertNotEquals(label + ":get-not-equals-other", fmaGet, FlexibleMapAccessorTests.class); + assertEquals(label + ":get-toString", getText, fmaGet.toString()); + FlexibleMapAccessor fmaGetAscending = FlexibleMapAccessor.getInstance("+" + getText); + assertEquals(label + ":get-ascending-toString", "+" + getText, fmaGetAscending.toString()); + assertTrue(label + ":get-ascending-isAscending", fmaGetAscending.getIsAscending()); + FlexibleMapAccessor fmaGetDescending = FlexibleMapAccessor.getInstance("-" + getText); + assertEquals(label + ":get-descending-toString", "-" + getText, fmaGetDescending.toString()); + assertFalse(label + ":get-decending-isAscending", fmaGetDescending.getIsAscending()); + FlexibleMapAccessor fmaPut = FlexibleMapAccessor.getInstance(putText); + assertEquals(label + ":put-toString", putText, fmaPut.toString()); + assertEquals(label + ":put-original-name", putText, fmaPut.getOriginalName()); + assertEquals(label + ":put-isEmpty", false, fmaPut.isEmpty()); + assertEquals(label + ":put-instance-equals", fmaPut, FlexibleMapAccessor.getInstance(putText)); + assertNotEquals(label + ":put-not-equals-other", fmaPut, FlexibleMapAccessorTests.class); + + FlexibleStringExpander fse = FlexibleStringExpander.getInstance(fseText); + if (locale == null) { + assertNull(label + ":get-initial", fmaGet.get(testMap)); + fmaPut.put(testMap, var); + assertFalse(label + ":testMap-not-empty", testMap.isEmpty()); + assertEquals(label + ":get", var, fmaGet.get(testMap)); + assertEquals(label, value, fse.expandString(testMap)); + assertEquals(label + ":remove", var, fmaGet.remove(testMap)); + assertNull(label + ":remove-not-exist", fmaGet.remove(testMap)); + } else { + fmaPut.put(testMap, var); + assertFalse(label + ":testMap-not-empty", testMap.isEmpty()); + assertEquals(label + ":get", value, fmaGet.get(testMap, locale)); + // BUG: fmaGet modifies testMap, even tho it shouldn't + assertEquals(label + ":get", value, fmaGet.get(testMap, null)); + assertEquals(label, value, fse.expandString(testMap, locale)); + } + + testMap.clear(); + fmaPut.put(testMap, null); + assertFalse(label + ":testMap-not-empty-put-null", testMap.isEmpty()); + if (locale == null) { + assertNull(label + ":get-put-null", fmaGet.get(testMap)); + } + testMap.clear(); + Exception caught = null; + try { + fmaPut.put(null, var); + } catch (Exception e) { + caught = e; + } finally { + assertNotNull(label + ":put-null-map", caught); + assertTrue(label + ":put-null-map-isEmpty", testMap.isEmpty()); + } + Set> set = new HashSet>(); + assertFalse(label + ":not-in-set", set.contains(fmaGet)); + set.add(fmaGet); + assertTrue(label + ":in-set", set.contains(fmaGet)); + } + + private static void fmaEmptyTest(String label, String text) { + FlexibleMapAccessor> fma = FlexibleMapAccessor.getInstance(text); + assertTrue(label + ":isEmpty", fma.isEmpty()); + Map testMap = new HashMap(); + assertNull(label + ":get", fma.get(null)); + assertNull(label + ":get", fma.get(testMap)); + assertTrue(label + ":map-isEmpty-initial", testMap.isEmpty()); + fma.put(testMap, FlexibleMapAccessorTests.class); + assertTrue(label + ":map-isEmpty-map", testMap.isEmpty()); + fma.put(null, FlexibleMapAccessorTests.class); + assertTrue(label + ":map-isEmpty-null", testMap.isEmpty()); + assertSame(label + ":same-null", fmaNull, fma); + assertSame(label + ":same-empty", fmaEmpty, fma); + assertEquals(label + ":original-name", "", fma.getOriginalName()); + assertNull(label + ":remove", fma.remove(testMap)); + assertNotNull(label + ":toString", fma.toString()); + } + + // These tests rely upon FlexibleStringExpander, so they + // should follow the FlexibleStringExpander tests. + public void testFlexibleMapAccessor() { + fmaEmptyTest("fmaEmpty", ""); + fmaEmptyTest("fmaNull", null); + fmaEmptyTest("fma\"null\"", "null"); + fmaTest("UEL auto-vivify Map", "parameters.var", "Hello ${parameters.var}!", "World", "Hello World!"); + fmaTest("UEL auto-vivify List", "parameters.someList[0]", "parameters.someList[+0]", "Hello ${parameters.someList[0]}!", null, "World", "Hello World!"); + fmaTest("fse", "para${'meter'}s.var", "Hello ${parameters.var}!", "World", "Hello World!"); + fmaTest("foo", "'The total is ${total?currency(USD)}.'", "total", "The total is ${total?currency(USD)}.", localeToTest, new BigDecimal("12345678.90"), "The total is $12,345,678.90."); + assertTrue("containsNestedExpression method returns true", FlexibleMapAccessor.getInstance("Hello ${parameters.var}!").containsNestedExpression()); + assertFalse("containsNestedExpression method returns false", FlexibleMapAccessor.getInstance("Hello World!").containsNestedExpression()); + } + + public static class ThrowException { + public Object getValue() throws Exception { + throw new Exception(); + } + + public void setValue(Object value) throws Exception { + throw new Exception(); + } + } + + @SuppressWarnings("serial") + public static class CantRemoveMap extends HashMap { + @Override + public V get(Object key) { + return super.get(key); + } + + @Override + public V put(K key, V value) { + if (value == null) { + throw new IllegalArgumentException(); + } + return super.put(key, value); + } + } + + public void testVerbosityAndErrors() { + boolean isVerbose = Debug.isOn(Debug.VERBOSE); + try { + Debug.set(Debug.VERBOSE, true); + Map testMap = new CantRemoveMap(); + testMap.put("throwException", new ThrowException()); + assertNull("no var", FlexibleMapAccessor.getInstance("var").get(testMap)); + Object result = FlexibleMapAccessor.getInstance("throwException.value").get(testMap); + assertNull("get null var", result); + FlexibleMapAccessor.getInstance("throwException.value").put(testMap, this); + FlexibleMapAccessor.getInstance("throwException").remove(testMap); + assertNotNull("not removed", testMap.get("throwException")); + } finally { + Debug.set(Debug.VERBOSE, isVerbose); + } + } +} diff --git a/framework/base/src/org/ofbiz/base/util/collections/test/GenericMapTest.java b/framework/base/src/org/ofbiz/base/util/collections/test/GenericMapTest.java index 31dbb078f5..b8f42ddf13 100644 --- a/framework/base/src/org/ofbiz/base/util/collections/test/GenericMapTest.java +++ b/framework/base/src/org/ofbiz/base/util/collections/test/GenericMapTest.java @@ -1,171 +1,171 @@ -/******************************************************************************* - * 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.collections.test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.ofbiz.base.test.GenericTestCaseBase; -import org.ofbiz.base.util.collections.GenericMap; -import org.ofbiz.base.util.collections.GenericMapEntry; -import org.ofbiz.base.util.collections.IteratorWrapper; - -public class GenericMapTest extends GenericTestCaseBase { - @SuppressWarnings("serial") - public static class TestGenericMap extends GenericMap { - private static final String[] countNames = { - "clearInternal", - "containsKey", - "get-true", - "get-false", - "isEmpty", - "iterator-true", - "iterator-false", - "putInternal", - "putAllIterator", - "removeInternal-true", - "removeInternal-false", - "size", - }; - protected final Map counts = new HashMap(); - protected final Map proxyMap; - - protected TestGenericMap() { - this(null); - } - - protected TestGenericMap(Map srcMap) { - for (String countName: countNames) { - counts.put(countName, 0); - } - if (srcMap != null) { - proxyMap = new HashMap(srcMap); - } else { - proxyMap = new HashMap(); - } - } - - private void incrementCallCount(String name) { - counts.put(name, counts.get(name) + 1); - } - - public List getCounts() { - List result = new ArrayList(); - for (String countName: countNames) { - result.add(counts.get(countName)); - } - return result; - } - - @Override - protected void clearInternal() { - incrementCallCount("clearInternal"); - proxyMap.clear(); - } - - public boolean containsKey(Object key) { - incrementCallCount("containsKey"); - return proxyMap.containsKey(key); - } - - @Override - protected V get(Object key, boolean noteAccess) { - incrementCallCount("get-" + noteAccess); - return proxyMap.get(key); - } - - public boolean isEmpty() { - incrementCallCount("isEmpty"); - return proxyMap.isEmpty(); - } - - @Override - protected Iterator> iterator(final boolean noteAccess) { - incrementCallCount("iterator-" + noteAccess); - //return new IteratorWrapper, Map.Entry>(noteAccess, proxyMap.entrySet().iterator()) { - return new IteratorWrapper, Map.Entry>(proxyMap.entrySet().iterator()) { - @Override - protected Map.Entry convert(Map.Entry src) { - return new GenericMapEntry(TestGenericMap.this, src.getKey(), noteAccess); - } - @Override - protected void noteRemoval(Map.Entry dest, Map.Entry src) { - } - }; - } - - public V put(K key, V value) { - incrementCallCount("putInternal"); - if (!proxyMap.containsKey(key)) incrementModCount(); - return proxyMap.put(key, value); - } - - @Override - protected void putAllIterator(Iterator> it) { - incrementCallCount("putAllIterator"); - while (it.hasNext()) { - Map.Entry entry = it.next(); - proxyMap.put(entry.getKey(), entry.getValue()); - } - } - - @Override - protected V removeInternal(Object key, boolean incrementModCount) { - incrementCallCount("removeInternal-" + incrementModCount); - if (!proxyMap.containsKey(key)) return null; - if (incrementModCount) incrementModCount(); - return proxyMap.remove(key); - } - - public int size() { - incrementCallCount("size"); - return proxyMap.size(); - } - } - - public GenericMapTest(String name) { - super(name); - } - - public void testFoo() throws Exception { - TestGenericMap map = new TestGenericMap(); - map.put("a", 0); System.err.println("put a\t\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); - assertEquals("get a", Integer.valueOf(0), map.get("a")); - map.put("b", 1); System.err.println("put b\t\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); - assertEquals("get b", Integer.valueOf(1), map.get("b")); - map.put("c", 2); System.err.println("put c\t\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); - assertEquals("get c", Integer.valueOf(2), map.get("c")); - map.put("d", 3); System.err.println("put d\t\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); - assertEquals("get d", Integer.valueOf(3), map.get("d")); - map.put("c", 22); System.err.println("put c-2\t\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); - assertEquals("get c-2", Integer.valueOf(22), map.get("c")); - map.remove("b"); System.err.println("remove b\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); - assertNull("null b", map.get("b")); - map.remove("aaa"); System.err.println("remove aaa\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); - System.err.println("map=" + map); - System.err.println("counts=" + map.getCounts() + ", modCount=" + map.getModCount()); - // this seems to call size() - new HashMap(map); - System.err.println("counts=" + map.getCounts() + ", modCount=" + map.getModCount()); - } - -} +/******************************************************************************* + * 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.collections.test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.ofbiz.base.test.GenericTestCaseBase; +import org.ofbiz.base.util.collections.GenericMap; +import org.ofbiz.base.util.collections.GenericMapEntry; +import org.ofbiz.base.util.collections.IteratorWrapper; + +public class GenericMapTest extends GenericTestCaseBase { + @SuppressWarnings("serial") + public static class TestGenericMap extends GenericMap { + private static final String[] countNames = { + "clearInternal", + "containsKey", + "get-true", + "get-false", + "isEmpty", + "iterator-true", + "iterator-false", + "putInternal", + "putAllIterator", + "removeInternal-true", + "removeInternal-false", + "size", + }; + protected final Map counts = new HashMap(); + protected final Map proxyMap; + + protected TestGenericMap() { + this(null); + } + + protected TestGenericMap(Map srcMap) { + for (String countName: countNames) { + counts.put(countName, 0); + } + if (srcMap != null) { + proxyMap = new HashMap(srcMap); + } else { + proxyMap = new HashMap(); + } + } + + private void incrementCallCount(String name) { + counts.put(name, counts.get(name) + 1); + } + + public List getCounts() { + List result = new ArrayList(); + for (String countName: countNames) { + result.add(counts.get(countName)); + } + return result; + } + + @Override + protected void clearInternal() { + incrementCallCount("clearInternal"); + proxyMap.clear(); + } + + public boolean containsKey(Object key) { + incrementCallCount("containsKey"); + return proxyMap.containsKey(key); + } + + @Override + protected V get(Object key, boolean noteAccess) { + incrementCallCount("get-" + noteAccess); + return proxyMap.get(key); + } + + public boolean isEmpty() { + incrementCallCount("isEmpty"); + return proxyMap.isEmpty(); + } + + @Override + protected Iterator> iterator(final boolean noteAccess) { + incrementCallCount("iterator-" + noteAccess); + //return new IteratorWrapper, Map.Entry>(noteAccess, proxyMap.entrySet().iterator()) { + return new IteratorWrapper, Map.Entry>(proxyMap.entrySet().iterator()) { + @Override + protected Map.Entry convert(Map.Entry src) { + return new GenericMapEntry(TestGenericMap.this, src.getKey(), noteAccess); + } + @Override + protected void noteRemoval(Map.Entry dest, Map.Entry src) { + } + }; + } + + public V put(K key, V value) { + incrementCallCount("putInternal"); + if (!proxyMap.containsKey(key)) incrementModCount(); + return proxyMap.put(key, value); + } + + @Override + protected void putAllIterator(Iterator> it) { + incrementCallCount("putAllIterator"); + while (it.hasNext()) { + Map.Entry entry = it.next(); + proxyMap.put(entry.getKey(), entry.getValue()); + } + } + + @Override + protected V removeInternal(Object key, boolean incrementModCount) { + incrementCallCount("removeInternal-" + incrementModCount); + if (!proxyMap.containsKey(key)) return null; + if (incrementModCount) incrementModCount(); + return proxyMap.remove(key); + } + + public int size() { + incrementCallCount("size"); + return proxyMap.size(); + } + } + + public GenericMapTest(String name) { + super(name); + } + + public void testFoo() throws Exception { + TestGenericMap map = new TestGenericMap(); + map.put("a", 0); System.err.println("put a\t\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); + assertEquals("get a", Integer.valueOf(0), map.get("a")); + map.put("b", 1); System.err.println("put b\t\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); + assertEquals("get b", Integer.valueOf(1), map.get("b")); + map.put("c", 2); System.err.println("put c\t\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); + assertEquals("get c", Integer.valueOf(2), map.get("c")); + map.put("d", 3); System.err.println("put d\t\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); + assertEquals("get d", Integer.valueOf(3), map.get("d")); + map.put("c", 22); System.err.println("put c-2\t\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); + assertEquals("get c-2", Integer.valueOf(22), map.get("c")); + map.remove("b"); System.err.println("remove b\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); + assertNull("null b", map.get("b")); + map.remove("aaa"); System.err.println("remove aaa\tcounts=" + map.getCounts() + ", modCount=" + map.getModCount()); + System.err.println("map=" + map); + System.err.println("counts=" + map.getCounts() + ", modCount=" + map.getModCount()); + // this seems to call size() + new HashMap(map); + System.err.println("counts=" + map.getCounts() + ", modCount=" + map.getModCount()); + } + +} diff --git a/framework/base/src/org/ofbiz/base/util/string/test/FlexibleStringExpanderTests.java b/framework/base/src/org/ofbiz/base/util/string/test/FlexibleStringExpanderTests.java index 4ce52013d4..2686b91f68 100644 --- a/framework/base/src/org/ofbiz/base/util/string/test/FlexibleStringExpanderTests.java +++ b/framework/base/src/org/ofbiz/base/util/string/test/FlexibleStringExpanderTests.java @@ -1,340 +1,340 @@ -/******************************************************************************* - * 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.string.test; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -import junit.framework.TestCase; - -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.string.FlexibleStringExpander; -import org.ofbiz.base.conversion.AbstractConverter; -import org.ofbiz.base.conversion.ConversionException; -import org.ofbiz.base.conversion.Converters; - -@SourceMonitored -public class FlexibleStringExpanderTests extends TestCase { - private static final Locale localeToTest = new Locale("en", "US"); - private static final Locale badLocale = new Locale("fr"); - private static final TimeZone timeZoneToTest = TimeZone.getTimeZone("PST"); - private static final TimeZone badTimeZone = TimeZone.getTimeZone("GMT"); - - private boolean wasVerbose; - - public FlexibleStringExpanderTests(String name) { - super(name); - } - - private static void parserTest(String label, String input, boolean checkCache, String toString) { - FlexibleStringExpander fse = FlexibleStringExpander.getInstance(input, false); - //System.err.println("fse(" + fse + ").class=" + fse.getClass()); - assertEquals(label + ":toString(no-cache)", toString, fse.toString()); - fse = FlexibleStringExpander.getInstance(input, true); - assertEquals(label + ":toString(cache)", toString, fse.toString()); - if (checkCache) { - assertEquals(label + ":same-cache", fse, FlexibleStringExpander.getInstance(input, true)); - } - } - - public void testParsing() { - parserTest("visible nested replacement", "${'Hello ${var}'}!", true, "${'Hello ${var}'}!"); - parserTest("hidden (runtime) nested null callreplacement", "Hello ${${groovy:" + FlexibleStringExpanderTests.class.getName() + ".StaticReturnNull()}}World!", true, "Hello ${${groovy:" + FlexibleStringExpanderTests.class.getName() + ".StaticReturnNull()}}World!"); - parserTest("UEL integration(nested): throw Exception", "${${throwException.value}}", true, "${${throwException.value}}"); - parserTest("nested-constant-emptynest-emptynest", "${a${}${}", true, "${a${}${}"); - parserTest("null", null, true, ""); - parserTest("empty", "", true, ""); - parserTest("constant-only", "a", false, "a"); - parserTest("nested-constant-emptynest-emptynest", "${a${}${}", true, "${a${}${}"); - parserTest("bsh", "${bsh:}", true, "${bsh:}"); - parserTest("groovy", "${groovy:}", true, "${groovy:}"); - - parserTest("escaped", "\\${}", true, "\\${}"); - parserTest("constant-escaped", "a\\${}", true, "a\\${}"); - parserTest("escaped-bsd", "\\${bsh:}", true, "\\${bsh:}"); - parserTest("escaped-groovy", "\\${groovy:}", true, "\\${groovy:}"); - - parserTest("missing-}", "${", true, "${"); - parserTest("nested-constant-missing-}", "${a${}", true, "${a${}"); - parserTest("nested-constant-nested-nested-missing-}", "${a${${}", true, "${a${${}"); - parserTest("escaped-missing-}", "\\${", true, "\\${"); - parserTest("constant-escaped-missing-}", "a\\${", true, "a\\${"); - - parserTest("currency", "${?currency(", true, "${?currency("); - parserTest("currency", "${?currency()", true, "${?currency()"); - parserTest("currency", "${price?currency(", true, "${price?currency("); - parserTest("currency", "${price?currency()", true, "${price?currency()"); - parserTest("currency", "${?currency(usd", true, "${?currency(usd"); - parserTest("currency", "${?currency(usd)", true, "${?currency(usd)"); - parserTest("currency", "${price?currency(usd", true, "${price?currency(usd"); - parserTest("currency", "${price?currency(usd)", true, "${price?currency(usd)"); - parserTest("currency", "${?currency(}", true, "${?currency(}"); - parserTest("currency", "${?currency()}", true, "${?currency()}"); - parserTest("currency", "${?currency(usd}", true, "${?currency(usd}"); - parserTest("currency", "${?currency(usd)}", true, "${?currency(usd)}"); - parserTest("currency", "${price?currency(}", true, "${price?currency(}"); - parserTest("currency", "${price?currency()}", true, "${price?currency()}"); - parserTest("currency", "${price?currency(usd}", true, "${price?currency(usd}"); - parserTest("currency", "${price?currency(usd)}", true, "${price?currency(usd)}"); - parserTest("currency", "a${price?currency(usd)}b", true, "a${price?currency(usd)}b"); - } - - private static void fseTest(String label, String input, Map context, String compare, boolean isEmpty) { - fseTest(label, input, context, null, null, compare, isEmpty); - } - - private static void doFseTest(String label, String input, FlexibleStringExpander fse, Map context, TimeZone timeZone, Locale locale, String compare, Object expand, boolean isEmpty) { - assertEquals("isEmpty:" + label, isEmpty, fse.isEmpty()); - if (input == null) { - assertEquals("getOriginal():" + label, "", fse.getOriginal()); - assertEquals("toString():" + label, "", fse.toString()); - assertEquals("expandString(null):" + label, "", fse.expandString(null)); - assertEquals("expand(null):" + label, null, fse.expand(null)); - if (timeZone == null) { - assertEquals("expandString(null):" + label, "", fse.expandString(null, locale)); - assertEquals("expand(null):" + label, null, fse.expand(null, locale)); - } else { - assertEquals("expandString(null):" + label, "", fse.expandString(null, timeZone, locale)); - assertEquals("expand(null):" + label, null, fse.expand(null, timeZone, locale)); - } - } else { - assertEquals("getOriginal():" + label, input, fse.getOriginal()); - assertEquals("toString():" + label, input, fse.toString()); - assertEquals("expandString(null):" + label, input, fse.expandString(null)); - assertEquals("expand(null):" + label, null, fse.expand(null)); - if (timeZone == null) { - assertEquals("expandString(null):" + label, input, fse.expandString(null, locale)); - assertEquals("expand(null):" + label, null, fse.expand(null, locale)); - } else { - assertEquals("expandString(null):" + label, input, fse.expandString(null, timeZone, locale)); - assertEquals("expand(null):" + label, null, fse.expand(null, timeZone, locale)); - } - } - if (locale == null) { - assertEquals(label, compare, fse.expandString(context)); - assertEquals("expand:" + label, expand, fse.expand(context)); - } else { - Locale defaultLocale = Locale.getDefault(); - TimeZone defaultTimeZone = TimeZone.getDefault(); - try { - Locale.setDefault(locale); - TimeZone.setDefault(timeZone); - assertEquals(label, compare, fse.expandString(context, null, null)); - assertEquals(label, expand, fse.expand(context, null, null)); - Locale.setDefault(badLocale); - TimeZone.setDefault(badTimeZone); - assertNotSame(label, compare, fse.expandString(context, null, null)); - if (input != null) { - assertNotSame(label, expand, fse.expand(context, null, null)); - } - Map autoUserLogin = new HashMap(); - autoUserLogin.put("lastLocale", locale.toString()); - autoUserLogin.put("lastTimeZone", timeZone == null ? null : timeZone.getID()); - context.put("autoUserLogin", autoUserLogin); - assertEquals(label, compare, fse.expandString(context, null, null)); - assertEquals(label, expand, fse.expand(context, null, null)); - autoUserLogin.put("lastLocale", badLocale.toString()); - autoUserLogin.put("lastTimeZone", badTimeZone.getID()); - assertNotSame(label, compare, fse.expandString(context, null, null)); - if (input != null) { - assertNotSame(label, expand, fse.expand(context, null, null)); - } - context.remove("autoUserLogin"); - context.put("locale", locale); - context.put("timeZone", timeZone); - assertEquals(label, compare, fse.expandString(context, null, null)); - assertEquals(label, expand, fse.expand(context, null, null)); - context.put("locale", badLocale); - context.put("timeZone", badTimeZone); - assertNotSame(label, compare, fse.expandString(context, null, null)); - if (input != null) { - assertNotSame(label, expand, fse.expand(context, null, null)); - } - context.remove("locale"); - context.remove("timeZone"); - assertEquals(label, compare, fse.expandString(context, timeZone, locale)); - assertEquals(label, expand, fse.expand(context, timeZone, locale)); - assertNotSame(label, compare, fse.expandString(context, badTimeZone, badLocale)); - if (input != null) { - assertNotSame(label, expand, fse.expand(context, badTimeZone, badLocale)); - } - } finally { - Locale.setDefault(defaultLocale); - TimeZone.setDefault(defaultTimeZone); - } - } - } - - private static void fseTest(String label, String input, Map context, TimeZone timeZone, Locale locale, String compare, boolean isEmpty) { - fseTest(label, input, context, timeZone, locale, compare, compare, isEmpty); - } - - private static void fseTest(String label, String input, Map context, TimeZone timeZone, Locale locale, String compare, Object expand, boolean isEmpty) { - FlexibleStringExpander fse = FlexibleStringExpander.getInstance(input); - doFseTest(label, input, fse, context, timeZone, locale, compare, expand, isEmpty); - assertEquals("static expandString:" + label, compare, FlexibleStringExpander.expandString(input, context, timeZone, locale)); - if (input == null) { - assertEquals("static expandString(null, null):" + label, "", FlexibleStringExpander.expandString(input, null)); - assertEquals("static expandString(null, null):" + label, "", FlexibleStringExpander.expandString(input, null, locale)); - } else { - assertEquals("static expandString(input, null):" + label, input, FlexibleStringExpander.expandString(input, null)); - assertEquals("static expandString(input, null):" + label, input, FlexibleStringExpander.expandString(input, null, locale)); - } - if (!fse.isEmpty()) { - fse = FlexibleStringExpander.getInstance(input, false); - doFseTest(label, input, fse, context, timeZone, locale, compare, expand, isEmpty); - } - } - - public static String StaticReturnNull() { - return null; - } - - @Override - public void setUp() { - wasVerbose = Debug.isOn(Debug.VERBOSE); - if (getName().equals("testWithVerbosity")) { - Debug.set(Debug.VERBOSE, true); - } - Converters.registerConverter(new SpecialNumberToString()); - } - - @Override - public void tearDown() { - Debug.set(Debug.VERBOSE, wasVerbose); - } - - public static class ThrowException { - public Object getValue() throws Exception { - throw new Exception(); - } - } - - public static class ThrowNPE { - public Object getValue() { - throw new NullPointerException(); - } - } - - public static class SpecialNumberToString extends AbstractConverter { - public SpecialNumberToString() { - super(SpecialNumber.class, String.class); - } - - public String convert(SpecialNumber obj) throws ConversionException { - throw new NullPointerException(); - } - } - - @SuppressWarnings("serial") - public static class SpecialNumber extends BigDecimal { - public SpecialNumber(String value) { - super(value); - } - - @Override - public String toString() { - return getClass().getName(); - } - } - - public void testWithVerbosity() { - everythingTest(); - } - - public void testQuietly() { - everythingTest(); - } - - private void everythingTest() { - Map testMap = new HashMap(); - testMap.put("date", new java.util.Date(1234567890)); - testMap.put("usd", "USD"); - testMap.put("amount", new BigDecimal("1234567.89")); - testMap.put("blank", ""); - testMap.put("exc", "Exception"); - testMap.put("nullVar", null); - testMap.put("throwException", new ThrowException()); - testMap.put("throwNPE", new ThrowNPE()); - testMap.put("var", "World"); - testMap.put("nested", "Hello ${var}"); - testMap.put("testMap", testMap); - testMap.put("nestedNull", "Hello ${nullVar}${var}"); - testMap.put("specialNumber", new SpecialNumber("1.00")); - List testList = new ArrayList(); - testList.add("World"); - testMap.put("testList", testList); - fseTest("null FlexibleStringExpander, null map", null, null, null, null, "", null, true); - fseTest("null FlexibleStringExpander", null, testMap, null, null, "", null, true); - fseTest("null context", "Hello World!", null, null, null, "Hello World!", null, false); - fseTest("plain string", "Hello World!", testMap, null, null, "Hello World!", "Hello World!", false); - fseTest("simple replacement", "Hello ${var}!", testMap, "Hello World!", false); - fseTest("null FlexibleStringExpander with timeZone/locale", null, testMap, timeZoneToTest, localeToTest, "", null, true); - fseTest("empty FlexibleStringExpander", "", testMap, null, null, "", null, true); - fseTest("UEL integration(nested): throw Exception", "${${throwException.value}}", testMap, "", false); - fseTest("UEL integration: throw Exception", "${throwException.value}", testMap, null, null, "", null, false); - fseTest("UEL integration(nested): throw Exception", "${throw${exc}.value}", testMap, "", false); - fseTest("UEL integration(nested): throw NPE", "${throwNPE${blank}.value}", testMap, "", false); - fseTest("visible nested replacement", "${'Hello ${var}'}!", testMap, "Hello World!", false); - fseTest("blank nested replacement", "${'Hel${blank}lo ${var}'}!", testMap, "Hello World!", false); - fseTest("UEL integration(nested): null", "${${nu${nullVar}ll}}", testMap, "", false); - fseTest("UEL integration(nested): NPE", "${${nullVar.noProp}}", testMap, "", false); - fseTest("UEL integration(nested): missing", "${${noL${nullVar}ist[0]}}", testMap, "", false); - fseTest("date w/ timezone", "The date is ${date}.", testMap, timeZoneToTest, localeToTest, "The date is 1970-01-14 22:56:07.890.", "The date is 1970-01-14 22:56:07.890.", false); - fseTest("just bad", "${foobar", testMap, "${foobar", false); - fseTest("constant and bad", "Hello${foobar", testMap, "Hello${foobar", false); - fseTest("good and bad", "Hello ${var}${foobar", testMap, "Hello World${foobar", false); - fseTest("plain-currency(USD)", "${amount?currency(${usd})}", testMap, null, localeToTest, "$1,234,567.89", false); - fseTest("currency(USD)", "The total is ${amount?currency(${usd})}.", testMap, null, localeToTest, "The total is $1,234,567.89.", false); - fseTest("currency(USD): null", "The total is ${testMap.missing?currency(${usd})}.", testMap, null, localeToTest, "The total is .", false); - fseTest("currency(USD): missing", "The total is ${noList[0]?currency(${usd})}.", testMap, null, localeToTest, "The total is .", false); - fseTest("currency(USD): exception", "The total is ${throwException.value?currency(${usd})}.", testMap, null, localeToTest, "The total is .", false); - fseTest("null nested", "${${nullVar}}!", testMap, "!", false); - fseTest("bsh: script", "${bsh:return \"Hello \" + var + \"!\";}", testMap, "Hello World!", false); - fseTest("bsh: null", "${bsh:return null;}!", testMap, "!", false); - fseTest("bsh: throw Exception", "${bsh:return throwException.value;}!", testMap, "!", false); - fseTest("bsh: converter exception", "${bsh:return specialNumber;}!", testMap, SpecialNumber.class.getName() + "!", false); - fseTest("groovy: script", "${groovy:return \"Hello \" + var + \"!\";}", testMap, "Hello World!", false); - fseTest("groovy: null", "${groovy:return null;}!", testMap, "!", false); - fseTest("groovy missing property", "${groovy: return noList[0]}", testMap, null, null, "", null, false); - fseTest("groovy: throw Exception", "${groovy:return throwException.value;}!", testMap, "!", false); - fseTest("groovy: converter exception", "${groovy:return specialNumber;}!", testMap, SpecialNumber.class.getName() + "!", false); - fseTest("UEL integration: Map", "Hello ${testMap.var}!", testMap, "Hello World!", false); - fseTest("UEL integration: blank", "Hello ${testMap.blank}World!", testMap, "Hello World!", false); - fseTest("UEL integration: List", "Hello ${testList[0]}!", testMap, "Hello World!", false); - fseTest("UEL integration: null", "${null}", testMap, null, null, "", null, false); - fseTest("UEL integration: null dereference", "${nullVar.noProp}", testMap, null, null, "", null, false); - fseTest("UEL integration: throw NPE", "${" + FlexibleStringExpanderTests.class.getName() + ".ThrowNPE.noProp}", testMap, null, null, "", null, false); - fseTest("UEL integration: missing", "${noList[0]}", testMap, null, null, "", null, false); - fseTest("Escaped expression", "This is an \\${escaped} expression", testMap, "This is an ${escaped} expression", false); - fseTest("Escaped(bsh) expression", "This is an \\${bsh:escaped} expression", testMap, "This is an ${bsh:escaped} expression", false); - fseTest("Escaped(groovy) expression", "This is an \\${groovy:escaped} expression", testMap, "This is an ${groovy:escaped} expression", false); - - fseTest("nested UEL integration(return BigDecimal)", "${a${'moun'}t}", testMap, null, null, "1,234,567.89", testMap.get("amount"), false); - fseTest("UEL integration(return BigDecimal)", "${amount}", testMap, null, null, "1,234,567.89", testMap.get("amount"), false); - fseTest("bsh: return BigDecimal", "${bsh: return amount;}", testMap, null, null, "1,234,567.89", testMap.get("amount"), false); - fseTest("groovy: return BigDecimal", "${groovy: return amount;}", testMap, null, null, "1,234,567.89", testMap.get("amount"), false); - } -} +/******************************************************************************* + * 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.string.test; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.string.FlexibleStringExpander; +import org.ofbiz.base.conversion.AbstractConverter; +import org.ofbiz.base.conversion.ConversionException; +import org.ofbiz.base.conversion.Converters; + +@SourceMonitored +public class FlexibleStringExpanderTests extends TestCase { + private static final Locale localeToTest = new Locale("en", "US"); + private static final Locale badLocale = new Locale("fr"); + private static final TimeZone timeZoneToTest = TimeZone.getTimeZone("PST"); + private static final TimeZone badTimeZone = TimeZone.getTimeZone("GMT"); + + private boolean wasVerbose; + + public FlexibleStringExpanderTests(String name) { + super(name); + } + + private static void parserTest(String label, String input, boolean checkCache, String toString) { + FlexibleStringExpander fse = FlexibleStringExpander.getInstance(input, false); + //System.err.println("fse(" + fse + ").class=" + fse.getClass()); + assertEquals(label + ":toString(no-cache)", toString, fse.toString()); + fse = FlexibleStringExpander.getInstance(input, true); + assertEquals(label + ":toString(cache)", toString, fse.toString()); + if (checkCache) { + assertEquals(label + ":same-cache", fse, FlexibleStringExpander.getInstance(input, true)); + } + } + + public void testParsing() { + parserTest("visible nested replacement", "${'Hello ${var}'}!", true, "${'Hello ${var}'}!"); + parserTest("hidden (runtime) nested null callreplacement", "Hello ${${groovy:" + FlexibleStringExpanderTests.class.getName() + ".StaticReturnNull()}}World!", true, "Hello ${${groovy:" + FlexibleStringExpanderTests.class.getName() + ".StaticReturnNull()}}World!"); + parserTest("UEL integration(nested): throw Exception", "${${throwException.value}}", true, "${${throwException.value}}"); + parserTest("nested-constant-emptynest-emptynest", "${a${}${}", true, "${a${}${}"); + parserTest("null", null, true, ""); + parserTest("empty", "", true, ""); + parserTest("constant-only", "a", false, "a"); + parserTest("nested-constant-emptynest-emptynest", "${a${}${}", true, "${a${}${}"); + parserTest("bsh", "${bsh:}", true, "${bsh:}"); + parserTest("groovy", "${groovy:}", true, "${groovy:}"); + + parserTest("escaped", "\\${}", true, "\\${}"); + parserTest("constant-escaped", "a\\${}", true, "a\\${}"); + parserTest("escaped-bsd", "\\${bsh:}", true, "\\${bsh:}"); + parserTest("escaped-groovy", "\\${groovy:}", true, "\\${groovy:}"); + + parserTest("missing-}", "${", true, "${"); + parserTest("nested-constant-missing-}", "${a${}", true, "${a${}"); + parserTest("nested-constant-nested-nested-missing-}", "${a${${}", true, "${a${${}"); + parserTest("escaped-missing-}", "\\${", true, "\\${"); + parserTest("constant-escaped-missing-}", "a\\${", true, "a\\${"); + + parserTest("currency", "${?currency(", true, "${?currency("); + parserTest("currency", "${?currency()", true, "${?currency()"); + parserTest("currency", "${price?currency(", true, "${price?currency("); + parserTest("currency", "${price?currency()", true, "${price?currency()"); + parserTest("currency", "${?currency(usd", true, "${?currency(usd"); + parserTest("currency", "${?currency(usd)", true, "${?currency(usd)"); + parserTest("currency", "${price?currency(usd", true, "${price?currency(usd"); + parserTest("currency", "${price?currency(usd)", true, "${price?currency(usd)"); + parserTest("currency", "${?currency(}", true, "${?currency(}"); + parserTest("currency", "${?currency()}", true, "${?currency()}"); + parserTest("currency", "${?currency(usd}", true, "${?currency(usd}"); + parserTest("currency", "${?currency(usd)}", true, "${?currency(usd)}"); + parserTest("currency", "${price?currency(}", true, "${price?currency(}"); + parserTest("currency", "${price?currency()}", true, "${price?currency()}"); + parserTest("currency", "${price?currency(usd}", true, "${price?currency(usd}"); + parserTest("currency", "${price?currency(usd)}", true, "${price?currency(usd)}"); + parserTest("currency", "a${price?currency(usd)}b", true, "a${price?currency(usd)}b"); + } + + private static void fseTest(String label, String input, Map context, String compare, boolean isEmpty) { + fseTest(label, input, context, null, null, compare, isEmpty); + } + + private static void doFseTest(String label, String input, FlexibleStringExpander fse, Map context, TimeZone timeZone, Locale locale, String compare, Object expand, boolean isEmpty) { + assertEquals("isEmpty:" + label, isEmpty, fse.isEmpty()); + if (input == null) { + assertEquals("getOriginal():" + label, "", fse.getOriginal()); + assertEquals("toString():" + label, "", fse.toString()); + assertEquals("expandString(null):" + label, "", fse.expandString(null)); + assertEquals("expand(null):" + label, null, fse.expand(null)); + if (timeZone == null) { + assertEquals("expandString(null):" + label, "", fse.expandString(null, locale)); + assertEquals("expand(null):" + label, null, fse.expand(null, locale)); + } else { + assertEquals("expandString(null):" + label, "", fse.expandString(null, timeZone, locale)); + assertEquals("expand(null):" + label, null, fse.expand(null, timeZone, locale)); + } + } else { + assertEquals("getOriginal():" + label, input, fse.getOriginal()); + assertEquals("toString():" + label, input, fse.toString()); + assertEquals("expandString(null):" + label, input, fse.expandString(null)); + assertEquals("expand(null):" + label, null, fse.expand(null)); + if (timeZone == null) { + assertEquals("expandString(null):" + label, input, fse.expandString(null, locale)); + assertEquals("expand(null):" + label, null, fse.expand(null, locale)); + } else { + assertEquals("expandString(null):" + label, input, fse.expandString(null, timeZone, locale)); + assertEquals("expand(null):" + label, null, fse.expand(null, timeZone, locale)); + } + } + if (locale == null) { + assertEquals(label, compare, fse.expandString(context)); + assertEquals("expand:" + label, expand, fse.expand(context)); + } else { + Locale defaultLocale = Locale.getDefault(); + TimeZone defaultTimeZone = TimeZone.getDefault(); + try { + Locale.setDefault(locale); + TimeZone.setDefault(timeZone); + assertEquals(label, compare, fse.expandString(context, null, null)); + assertEquals(label, expand, fse.expand(context, null, null)); + Locale.setDefault(badLocale); + TimeZone.setDefault(badTimeZone); + assertNotSame(label, compare, fse.expandString(context, null, null)); + if (input != null) { + assertNotSame(label, expand, fse.expand(context, null, null)); + } + Map autoUserLogin = new HashMap(); + autoUserLogin.put("lastLocale", locale.toString()); + autoUserLogin.put("lastTimeZone", timeZone == null ? null : timeZone.getID()); + context.put("autoUserLogin", autoUserLogin); + assertEquals(label, compare, fse.expandString(context, null, null)); + assertEquals(label, expand, fse.expand(context, null, null)); + autoUserLogin.put("lastLocale", badLocale.toString()); + autoUserLogin.put("lastTimeZone", badTimeZone.getID()); + assertNotSame(label, compare, fse.expandString(context, null, null)); + if (input != null) { + assertNotSame(label, expand, fse.expand(context, null, null)); + } + context.remove("autoUserLogin"); + context.put("locale", locale); + context.put("timeZone", timeZone); + assertEquals(label, compare, fse.expandString(context, null, null)); + assertEquals(label, expand, fse.expand(context, null, null)); + context.put("locale", badLocale); + context.put("timeZone", badTimeZone); + assertNotSame(label, compare, fse.expandString(context, null, null)); + if (input != null) { + assertNotSame(label, expand, fse.expand(context, null, null)); + } + context.remove("locale"); + context.remove("timeZone"); + assertEquals(label, compare, fse.expandString(context, timeZone, locale)); + assertEquals(label, expand, fse.expand(context, timeZone, locale)); + assertNotSame(label, compare, fse.expandString(context, badTimeZone, badLocale)); + if (input != null) { + assertNotSame(label, expand, fse.expand(context, badTimeZone, badLocale)); + } + } finally { + Locale.setDefault(defaultLocale); + TimeZone.setDefault(defaultTimeZone); + } + } + } + + private static void fseTest(String label, String input, Map context, TimeZone timeZone, Locale locale, String compare, boolean isEmpty) { + fseTest(label, input, context, timeZone, locale, compare, compare, isEmpty); + } + + private static void fseTest(String label, String input, Map context, TimeZone timeZone, Locale locale, String compare, Object expand, boolean isEmpty) { + FlexibleStringExpander fse = FlexibleStringExpander.getInstance(input); + doFseTest(label, input, fse, context, timeZone, locale, compare, expand, isEmpty); + assertEquals("static expandString:" + label, compare, FlexibleStringExpander.expandString(input, context, timeZone, locale)); + if (input == null) { + assertEquals("static expandString(null, null):" + label, "", FlexibleStringExpander.expandString(input, null)); + assertEquals("static expandString(null, null):" + label, "", FlexibleStringExpander.expandString(input, null, locale)); + } else { + assertEquals("static expandString(input, null):" + label, input, FlexibleStringExpander.expandString(input, null)); + assertEquals("static expandString(input, null):" + label, input, FlexibleStringExpander.expandString(input, null, locale)); + } + if (!fse.isEmpty()) { + fse = FlexibleStringExpander.getInstance(input, false); + doFseTest(label, input, fse, context, timeZone, locale, compare, expand, isEmpty); + } + } + + public static String StaticReturnNull() { + return null; + } + + @Override + public void setUp() { + wasVerbose = Debug.isOn(Debug.VERBOSE); + if (getName().equals("testWithVerbosity")) { + Debug.set(Debug.VERBOSE, true); + } + Converters.registerConverter(new SpecialNumberToString()); + } + + @Override + public void tearDown() { + Debug.set(Debug.VERBOSE, wasVerbose); + } + + public static class ThrowException { + public Object getValue() throws Exception { + throw new Exception(); + } + } + + public static class ThrowNPE { + public Object getValue() { + throw new NullPointerException(); + } + } + + public static class SpecialNumberToString extends AbstractConverter { + public SpecialNumberToString() { + super(SpecialNumber.class, String.class); + } + + public String convert(SpecialNumber obj) throws ConversionException { + throw new NullPointerException(); + } + } + + @SuppressWarnings("serial") + public static class SpecialNumber extends BigDecimal { + public SpecialNumber(String value) { + super(value); + } + + @Override + public String toString() { + return getClass().getName(); + } + } + + public void testWithVerbosity() { + everythingTest(); + } + + public void testQuietly() { + everythingTest(); + } + + private void everythingTest() { + Map testMap = new HashMap(); + testMap.put("date", new java.util.Date(1234567890)); + testMap.put("usd", "USD"); + testMap.put("amount", new BigDecimal("1234567.89")); + testMap.put("blank", ""); + testMap.put("exc", "Exception"); + testMap.put("nullVar", null); + testMap.put("throwException", new ThrowException()); + testMap.put("throwNPE", new ThrowNPE()); + testMap.put("var", "World"); + testMap.put("nested", "Hello ${var}"); + testMap.put("testMap", testMap); + testMap.put("nestedNull", "Hello ${nullVar}${var}"); + testMap.put("specialNumber", new SpecialNumber("1.00")); + List testList = new ArrayList(); + testList.add("World"); + testMap.put("testList", testList); + fseTest("null FlexibleStringExpander, null map", null, null, null, null, "", null, true); + fseTest("null FlexibleStringExpander", null, testMap, null, null, "", null, true); + fseTest("null context", "Hello World!", null, null, null, "Hello World!", null, false); + fseTest("plain string", "Hello World!", testMap, null, null, "Hello World!", "Hello World!", false); + fseTest("simple replacement", "Hello ${var}!", testMap, "Hello World!", false); + fseTest("null FlexibleStringExpander with timeZone/locale", null, testMap, timeZoneToTest, localeToTest, "", null, true); + fseTest("empty FlexibleStringExpander", "", testMap, null, null, "", null, true); + fseTest("UEL integration(nested): throw Exception", "${${throwException.value}}", testMap, "", false); + fseTest("UEL integration: throw Exception", "${throwException.value}", testMap, null, null, "", null, false); + fseTest("UEL integration(nested): throw Exception", "${throw${exc}.value}", testMap, "", false); + fseTest("UEL integration(nested): throw NPE", "${throwNPE${blank}.value}", testMap, "", false); + fseTest("visible nested replacement", "${'Hello ${var}'}!", testMap, "Hello World!", false); + fseTest("blank nested replacement", "${'Hel${blank}lo ${var}'}!", testMap, "Hello World!", false); + fseTest("UEL integration(nested): null", "${${nu${nullVar}ll}}", testMap, "", false); + fseTest("UEL integration(nested): NPE", "${${nullVar.noProp}}", testMap, "", false); + fseTest("UEL integration(nested): missing", "${${noL${nullVar}ist[0]}}", testMap, "", false); + fseTest("date w/ timezone", "The date is ${date}.", testMap, timeZoneToTest, localeToTest, "The date is 1970-01-14 22:56:07.890.", "The date is 1970-01-14 22:56:07.890.", false); + fseTest("just bad", "${foobar", testMap, "${foobar", false); + fseTest("constant and bad", "Hello${foobar", testMap, "Hello${foobar", false); + fseTest("good and bad", "Hello ${var}${foobar", testMap, "Hello World${foobar", false); + fseTest("plain-currency(USD)", "${amount?currency(${usd})}", testMap, null, localeToTest, "$1,234,567.89", false); + fseTest("currency(USD)", "The total is ${amount?currency(${usd})}.", testMap, null, localeToTest, "The total is $1,234,567.89.", false); + fseTest("currency(USD): null", "The total is ${testMap.missing?currency(${usd})}.", testMap, null, localeToTest, "The total is .", false); + fseTest("currency(USD): missing", "The total is ${noList[0]?currency(${usd})}.", testMap, null, localeToTest, "The total is .", false); + fseTest("currency(USD): exception", "The total is ${throwException.value?currency(${usd})}.", testMap, null, localeToTest, "The total is .", false); + fseTest("null nested", "${${nullVar}}!", testMap, "!", false); + fseTest("bsh: script", "${bsh:return \"Hello \" + var + \"!\";}", testMap, "Hello World!", false); + fseTest("bsh: null", "${bsh:return null;}!", testMap, "!", false); + fseTest("bsh: throw Exception", "${bsh:return throwException.value;}!", testMap, "!", false); + fseTest("bsh: converter exception", "${bsh:return specialNumber;}!", testMap, SpecialNumber.class.getName() + "!", false); + fseTest("groovy: script", "${groovy:return \"Hello \" + var + \"!\";}", testMap, "Hello World!", false); + fseTest("groovy: null", "${groovy:return null;}!", testMap, "!", false); + fseTest("groovy missing property", "${groovy: return noList[0]}", testMap, null, null, "", null, false); + fseTest("groovy: throw Exception", "${groovy:return throwException.value;}!", testMap, "!", false); + fseTest("groovy: converter exception", "${groovy:return specialNumber;}!", testMap, SpecialNumber.class.getName() + "!", false); + fseTest("UEL integration: Map", "Hello ${testMap.var}!", testMap, "Hello World!", false); + fseTest("UEL integration: blank", "Hello ${testMap.blank}World!", testMap, "Hello World!", false); + fseTest("UEL integration: List", "Hello ${testList[0]}!", testMap, "Hello World!", false); + fseTest("UEL integration: null", "${null}", testMap, null, null, "", null, false); + fseTest("UEL integration: null dereference", "${nullVar.noProp}", testMap, null, null, "", null, false); + fseTest("UEL integration: throw NPE", "${" + FlexibleStringExpanderTests.class.getName() + ".ThrowNPE.noProp}", testMap, null, null, "", null, false); + fseTest("UEL integration: missing", "${noList[0]}", testMap, null, null, "", null, false); + fseTest("Escaped expression", "This is an \\${escaped} expression", testMap, "This is an ${escaped} expression", false); + fseTest("Escaped(bsh) expression", "This is an \\${bsh:escaped} expression", testMap, "This is an ${bsh:escaped} expression", false); + fseTest("Escaped(groovy) expression", "This is an \\${groovy:escaped} expression", testMap, "This is an ${groovy:escaped} expression", false); + + fseTest("nested UEL integration(return BigDecimal)", "${a${'moun'}t}", testMap, null, null, "1,234,567.89", testMap.get("amount"), false); + fseTest("UEL integration(return BigDecimal)", "${amount}", testMap, null, null, "1,234,567.89", testMap.get("amount"), false); + fseTest("bsh: return BigDecimal", "${bsh: return amount;}", testMap, null, null, "1,234,567.89", testMap.get("amount"), false); + fseTest("groovy: return BigDecimal", "${groovy: return amount;}", testMap, null, null, "1,234,567.89", testMap.get("amount"), false); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/test/IndentingWriterTests.java b/framework/base/src/org/ofbiz/base/util/test/IndentingWriterTests.java index 5b7aa84019..ba5a9312ef 100644 --- a/framework/base/src/org/ofbiz/base/util/test/IndentingWriterTests.java +++ b/framework/base/src/org/ofbiz/base/util/test/IndentingWriterTests.java @@ -1,73 +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.util.test; - -import java.io.StringWriter; - -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.util.IndentingWriter; -import org.ofbiz.base.test.GenericTestCaseBase; - -@SourceMonitored -public class IndentingWriterTests extends GenericTestCaseBase { - public IndentingWriterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - private static void doTest(String label, boolean doSpace, boolean doNewline, String wanted) throws Exception { - StringWriter sw = new StringWriter(); - IndentingWriter iw; - if (!doSpace || !doNewline) { - iw = new IndentingWriter(sw, doSpace, doNewline); - } else { - iw = new IndentingWriter(sw); - } - iw.write('a'); - iw.push(); - iw.write("b\nm"); - iw.newline(); - iw.write(new char[] {'1', '\n', '2'}); - iw.space(); - iw.write('\n'); - iw.pop(); - iw.write("e"); - iw.close(); - assertEquals(label, wanted, sw.toString()); - } - - public void testIndentingWriter() throws Exception { - StringWriter sw = new StringWriter(); - IndentingWriter iw = IndentingWriter.makeIndentingWriter(sw); - assertSame("makeIndentingWriter - pass-thru", iw, IndentingWriter.makeIndentingWriter(iw)); - doTest("IndentingWriter doSpace:doNewline", true, true, "ab\n m\n 1\n 2 \n e"); - doTest("IndentingWriter doNewline", false, true, "ab\nm\n1\n2\ne"); - doTest("IndentingWriter doSpace", true, false, "ab\n m 1\n 2 \n e"); - doTest("IndentingWriter", false, false, "ab\nm1\n2\ne"); - } -} +/******************************************************************************* + * 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.test; + +import java.io.StringWriter; + +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.util.IndentingWriter; +import org.ofbiz.base.test.GenericTestCaseBase; + +@SourceMonitored +public class IndentingWriterTests extends GenericTestCaseBase { + public IndentingWriterTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + private static void doTest(String label, boolean doSpace, boolean doNewline, String wanted) throws Exception { + StringWriter sw = new StringWriter(); + IndentingWriter iw; + if (!doSpace || !doNewline) { + iw = new IndentingWriter(sw, doSpace, doNewline); + } else { + iw = new IndentingWriter(sw); + } + iw.write('a'); + iw.push(); + iw.write("b\nm"); + iw.newline(); + iw.write(new char[] {'1', '\n', '2'}); + iw.space(); + iw.write('\n'); + iw.pop(); + iw.write("e"); + iw.close(); + assertEquals(label, wanted, sw.toString()); + } + + public void testIndentingWriter() throws Exception { + StringWriter sw = new StringWriter(); + IndentingWriter iw = IndentingWriter.makeIndentingWriter(sw); + assertSame("makeIndentingWriter - pass-thru", iw, IndentingWriter.makeIndentingWriter(iw)); + doTest("IndentingWriter doSpace:doNewline", true, true, "ab\n m\n 1\n 2 \n e"); + doTest("IndentingWriter doNewline", false, true, "ab\nm\n1\n2\ne"); + doTest("IndentingWriter doSpace", true, false, "ab\n m 1\n 2 \n e"); + doTest("IndentingWriter", false, false, "ab\nm1\n2\ne"); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/test/ObjectTypeTests.java b/framework/base/src/org/ofbiz/base/util/test/ObjectTypeTests.java index dceffefeff..fbd7a19893 100644 --- a/framework/base/src/org/ofbiz/base/util/test/ObjectTypeTests.java +++ b/framework/base/src/org/ofbiz/base/util/test/ObjectTypeTests.java @@ -1,488 +1,488 @@ -/******************************************************************************* - * 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.test; - -import java.math.BigDecimal; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; - -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.test.GenericTestCaseBase; -import org.ofbiz.base.util.GeneralException; -import org.ofbiz.base.util.ObjectType; -import org.ofbiz.base.util.TimeDuration; -import org.ofbiz.base.util.UtilDateTime; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilXml; -import org.w3c.dom.Document; - -import com.ibm.icu.util.Calendar; - -@SourceMonitored -public class ObjectTypeTests extends GenericTestCaseBase { - public static final String module = ObjectTypeTests.class.getName(); - private static final LocaleData localeData = new LocaleData("en_US", "Pacific/Wake", "fr", "GMT"); - private final TimeDuration duration = new TimeDuration(0, 0, 0, 1, 1, 1, 1); - // These numbers are all based on 1 / 128, which is a binary decimal - // that can be represented by both float and double - private final BigDecimal dcml = new BigDecimal("781.25"); - private final Double dbl = Double.valueOf("7.8125E2"); - private final Float flt = Float.valueOf("7.8125E2"); - private final Long lng = Long.valueOf("781"); - private final Integer intg = Integer.valueOf("781"); - private final Timestamp tstmp = new Timestamp(781L); - private final Timestamp ntstmp; - private final java.util.Date utlDt = new java.util.Date(781); - private final java.sql.Date sqlDt; - private final java.sql.Time sqlTm = new java.sql.Time(2096000); - private final List list; - private final Map map; - private final Set set; - - public ObjectTypeTests(String name) { - super(name); - ntstmp = new Timestamp(781L); - ntstmp.setNanos(123000000); - list = new ArrayList(); - list.add("one"); - list.add("two"); - list.add("three"); - map = new LinkedHashMap(); - map.put("one", "1"); - map.put("two", "2"); - map.put("three", "3"); - set = new LinkedHashSet(list); - Calendar cal = UtilDateTime.getCalendarInstance(localeData.goodTimeZone, localeData.goodLocale); - cal.set(1969, Calendar.DECEMBER, 31, 0, 0, 0); - cal.set(Calendar.MILLISECOND, 0); - sqlDt = new java.sql.Date(cal.getTimeInMillis()); - } - - public static class LocaleData { - public final Locale goodLocale; - public final TimeZone goodTimeZone; - public final Locale badLocale; - public final TimeZone badTimeZone; - - public LocaleData(String goodLocale, String goodTimeZone, String badLocale, String badTimeZone) { - this.goodLocale = UtilMisc.parseLocale(goodLocale); - this.goodTimeZone = TimeZone.getTimeZone(goodTimeZone); - this.badLocale = UtilMisc.parseLocale(badLocale); - this.badTimeZone = TimeZone.getTimeZone(badTimeZone); - } - } - - public static Object simpleTypeConvert(Object obj, String type, String format, TimeZone timeZone, Locale locale, boolean noTypeFail) throws GeneralException { - return ObjectType.simpleTypeConvert(obj, type, format, timeZone, locale, noTypeFail); - } - - public static void simpleTypeConvertTest(String label, Object toConvert, String type, Object wanted) throws GeneralException { - basicTest(label, toConvert); - assertEquals(label + ":null target type", toConvert, simpleTypeConvert(toConvert, null, null, null, null, true)); - assertEquals(label + ":null source object", (Object) null, simpleTypeConvert(null, type, null, null, null, true)); - assertEquals(label, wanted, simpleTypeConvert(toConvert, type, null, null, null, true)); - if (toConvert instanceof String) { - String str = (String) toConvert; - Document doc = UtilXml.makeEmptyXmlDocument(); - assertEquals(label + ":text-node proxy", wanted, simpleTypeConvert(doc.createTextNode(str), type, null, null, null, true)); - } - } - - public static void simpleTypeConvertTest(String label, Object toConvert, String type, String format, LocaleData localeData, Object wanted) throws GeneralException { - basicTest(label, toConvert); - Locale defaultLocale = Locale.getDefault(); - TimeZone defaultTimeZone = TimeZone.getDefault(); - try { - Locale.setDefault(localeData.goodLocale); - TimeZone.setDefault(localeData.goodTimeZone); - assertEquals(label + ":default-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, null, null, true)); - assertNotEquals(label + ":bad-passed-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, localeData.badTimeZone, localeData.badLocale, true)); - Locale.setDefault(localeData.badLocale); - TimeZone.setDefault(localeData.badTimeZone); - assertNotEquals(label + ":bad-default-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, null, null, true)); - assertEquals(label + ":passed-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, localeData.goodTimeZone, localeData.goodLocale, true)); - } finally { - Locale.setDefault(defaultLocale); - TimeZone.setDefault(defaultTimeZone); - } - } - - public static void simpleTypeConvertTestSingleMulti(String label, Object toConvert, String[] types, Object wanted) throws GeneralException { - for (int j = 0; j < types.length; j++) { - simpleTypeConvertTest(label + "(:" + j + ")", toConvert, types[j], wanted); - } - } - - public static void simpleTypeConvertTestMultiMulti(String label, Object[] toConvert, String[] types, Object wanted) throws GeneralException { - for (int i = 0; i < toConvert.length; i++) { - for (int j = 0; j < types.length; j++) { - simpleTypeConvertTest(label + "(" + i + ":" + j + ")", toConvert[i], types[j], wanted); - } - } - } - - public static void simpleTypeConvertTestSingleMulti(String label, Object toConvert, String[] types, String format, LocaleData localeData, Object wanted) throws GeneralException { - for (int j = 0; j < types.length; j++) { - simpleTypeConvertTest(label + "(:" + j + ")", toConvert, types[j], format, localeData, wanted); - } - } - - public static void simpleTypeConvertTestMultiMulti(String label, Object[] toConvert, String[] types, String format, LocaleData localeData, Object wanted) throws GeneralException { - for (int i = 0; i < toConvert.length; i++) { - for (int j = 0; j < types.length; j++) { - simpleTypeConvertTest(label + "(" + i + ":" + j + ")", toConvert[i], types[j], format, localeData, wanted); - } - } - } - - public static void simpleTypeConvertTestError(String label, Object toConvert, String type) throws GeneralException { - GeneralException caught = null; - try { - simpleTypeConvert(toConvert, type, null, null, null, true); - } catch (GeneralException e) { - caught = e; - } finally { - assertNotNull(label + ":caught", caught); - } - } - - public static void simpleTypeConvertTestError(String label, Object toConvert, String[] types) throws GeneralException { - simpleTypeConvertTestError(label + ":this", toConvert, GeneralException.class.getName()); - for (String type: types) { - simpleTypeConvertTestError(label + ":" + type, toConvert, type); - } - } - - public static void simpleTypeConvertTestNoError(String label, Object toConvert, String type) throws GeneralException { - assertSame(label, toConvert, simpleTypeConvert(toConvert, type, null, null, null, false)); - } - - public static void simpleTypeConvertTestNoError(String label, Object toConvert, String[] types) throws GeneralException { - simpleTypeConvertTestNoError(label + ":this", toConvert, GeneralException.class.getName()); - for (String type: types) { - simpleTypeConvertTestNoError(label + ":" + type, toConvert, type); - } - } - - public static void basicTest(String label, Object toConvert) throws GeneralException { - assertEquals(label + ":PlainString", toConvert.toString(), simpleTypeConvert(toConvert, "PlainString", null, null, null, true)); - assertSame(label + ":same", toConvert, simpleTypeConvert(toConvert, toConvert.getClass().getName(), null, null, null, true)); - assertSame(label + ":to-Object", toConvert, simpleTypeConvert(toConvert, "Object", null, null, null, true)); - assertSame(label + ":to-java.lang.Object", toConvert, simpleTypeConvert(toConvert, "java.lang.Object", null, null, null, true)); - } - - public void testLoadClassWithNonExistentClass() { - Exception exception = null; - try { - ObjectType.loadClass("foobarbaz"); - } catch (Exception e) { - exception = e; - } - assertTrue("Exception thrown by loadClass(\"foobarbaz\") is not ClassNotFoundException", exception instanceof ClassNotFoundException); - } - - public void testLoadClassWithPrimitives() { - try { - Class theClass; - theClass = ObjectType.loadClass("boolean"); - assertEquals("Wrong class returned by loadClass(\"boolean\")", (Boolean.TYPE).getName(), theClass.getName()); - theClass = ObjectType.loadClass("short"); - assertEquals("Wrong class returned by loadClass(\"short\")", (Short.TYPE).getName(), theClass.getName()); - theClass = ObjectType.loadClass("int"); - assertEquals("Wrong class returned by loadClass(\"int\")", (Integer.TYPE).getName(), theClass.getName()); - theClass = ObjectType.loadClass("long"); - assertEquals("Wrong class returned by loadClass(\"long\")", (Long.TYPE).getName(), theClass.getName()); - theClass = ObjectType.loadClass("float"); - assertEquals("Wrong class returned by loadClass(\"float\")", (Float.TYPE).getName(), theClass.getName()); - theClass = ObjectType.loadClass("double"); - assertEquals("Wrong class returned by loadClass(\"double\")", (Double.TYPE).getName(), theClass.getName()); - theClass = ObjectType.loadClass("byte"); - assertEquals("Wrong class returned by loadClass(\"byte\")", (Byte.TYPE).getName(), theClass.getName()); - theClass = ObjectType.loadClass("char"); - assertEquals("Wrong class returned by loadClass(\"char\")", (Character.TYPE).getName(), theClass.getName()); - } catch (Exception e) { - fail("Exception thrown by loadClass: " + e.getMessage()); - } - } - - public void testLoadClassWithAlias() { - try { - Class theClass; - // first try with a class full name - theClass = ObjectType.loadClass("java.lang.String"); - assertEquals("Wrong class returned by loadClass(\"java.lang.String\")", "java.lang.String", theClass.getName()); - // now try with some aliases - theClass = ObjectType.loadClass("String"); - assertEquals("Wrong class returned by loadClass(\"String\")", "java.lang.String", theClass.getName()); - theClass = ObjectType.loadClass("Object"); - assertEquals("Wrong class returned by loadClass(\"Object\")", "java.lang.Object", theClass.getName()); - theClass = ObjectType.loadClass("Date"); - assertEquals("Wrong class returned by loadClass(\"Date\")", "java.sql.Date", theClass.getName()); - } catch (Exception e) { - fail("Exception thrown by loadClass: " + e.getMessage()); - } - } - - public void testClassNotFound() { - GeneralException caught = null; - try { - ObjectType.simpleTypeConvert(this, "foobarbaz", null, null, null, false); - } catch (GeneralException e) { - caught = e; - } finally { - assertNotNull("class not found", caught); - } - } - - public void testArray() throws GeneralException { - simpleTypeConvertTestSingleMulti("Object[]->List", new Object[] {"one", "two", "three"}, new String[] {"List", "java.util.List"}, list); - simpleTypeConvertTestSingleMulti("int[]->List", new int[] {1, 2, 3}, new String[] {"List", "java.util.List"}, list(1, 2, 3)); - simpleTypeConvertTestError("Object[]->error", new Object[] {"one", "two", "three"}, new String[] {"Map"}); - simpleTypeConvertTestError("int[]->error", new int[] {1, 2, 3}, new String[] {"java.util.ArrayList", "Map"}); - } - - public void testString() throws GeneralException, Exception { - simpleTypeConvertTest("String->String", "one", "String", "one"); - simpleTypeConvertTest("String->String", "one", "java.lang.String", "one"); - simpleTypeConvertTestSingleMulti("empty-String->anything", "", new String[] {"List", "Map"}, null); - simpleTypeConvertTestError("String->error", "one", new String[] {}); - simpleTypeConvertTestMultiMulti("String->Boolean(true)", new String[] {"true", " true ", " TrUe"}, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.TRUE); - simpleTypeConvertTestMultiMulti("String->Boolean(false)", new String[] {"false", " false ", " FaLsE"}, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.FALSE); - simpleTypeConvertTestSingleMulti("String->Locale", "en_us", new String[] {"Locale", "java.util.Locale"}, localeData.goodLocale); - simpleTypeConvertTestError("String->error-Locale", "o", new String[] {"Locale", "java.util.Locale"}); - // TZ can never be null, will default to GMT if it can't be parsed(from the javadocs of java.util.TimeZone) - simpleTypeConvertTestSingleMulti("String->TimeZone", "Pacific/Wake", new String[] {"TimeZone", "java.util.TimeZone"}, localeData.goodTimeZone); - simpleTypeConvertTestSingleMulti("String->BigDecimal", "78,125E-2", new String[] {"BigDecimal", "java.math.BigDecimal"}, null, localeData, dcml); - simpleTypeConvertTestError("String->error-BigDecimal", "o", new String[] {"BigDecimal", "java.math.BigDecimal"}); - simpleTypeConvertTestSingleMulti("String->Double", "78,125E-2", new String[] {"Double", "java.lang.Double"}, null, localeData, dbl); - simpleTypeConvertTestError("String->error-Double", "o", new String[] {"Double", "java.lang.Double"}); - simpleTypeConvertTestSingleMulti("String->Float", "78,125E-2", new String[] {"Float", "java.lang.Float"}, null, localeData, flt); - simpleTypeConvertTestError("String->error-Float", "o", new String[] {"Float", "java.lang.Float"}); - simpleTypeConvertTestSingleMulti("String->Long", "78,125E-2", new String[] {"Long", "java.lang.Long"}, null, localeData, lng); - simpleTypeConvertTestError("String->error-Long", "o", new String[] {"Long", "java.lang.Long"}); - simpleTypeConvertTestSingleMulti("String->Integer", "78,125E-2", new String[] {"Integer", "java.lang.Integer"}, null, localeData, intg); - simpleTypeConvertTestError("String->error-Integer", "o", new String[] {"Integer", "java.lang.Integer"}); - - simpleTypeConvertTestSingleMulti("String->java.sql.Date", "1969-12-31", new String[] {"Date", "java.sql.Date"}, null, localeData, sqlDt); - simpleTypeConvertTestSingleMulti("String->java.sql.Date", "1969-12-31", new String[] {"Date", "java.sql.Date"}, "", localeData, sqlDt); - simpleTypeConvertTestSingleMulti("String->java.sql.Date", "12-31-1969", new String[] {"Date", "java.sql.Date"}, "MM-dd-yyyy", localeData, sqlDt); - simpleTypeConvertTestError("String->error-java.sql.Date", "o", new String[] {"Date", "java.sql.Date"}); - simpleTypeConvertTestSingleMulti("String->java.sql.Time", "12:34:56", new String[] {"Time", "java.sql.Time"}, null, localeData, sqlTm); - simpleTypeConvertTestSingleMulti("String->java.sql.Time", "12:34:56", new String[] {"Time", "java.sql.Time"}, "", localeData, sqlTm); - simpleTypeConvertTestSingleMulti("String->java.sql.Time", "563412", new String[] {"Time", "java.sql.Time"}, "ssmmHH", localeData, sqlTm); - simpleTypeConvertTestError("String->error-java.sql.Time", "o", new String[] {"Time", "java.sql.Time"}); - simpleTypeConvertTestSingleMulti("String->Timestamp", "1970-01-01 12:00:00.123", new String[] {"Timestamp", "java.sql.Timestamp"}, null, localeData, ntstmp); - simpleTypeConvertTestSingleMulti("String->Timestamp", "1970-01-01 12:00:00.123", new String[] {"Timestamp", "java.sql.Timestamp"}, "", localeData, ntstmp); - simpleTypeConvertTestSingleMulti("String->Timestamp", "01-01-1970 12:00:00/123", new String[] {"Timestamp", "java.sql.Timestamp"}, "dd-MM-yyyy HH:mm:ss/SSS", localeData, ntstmp); - simpleTypeConvertTestMultiMulti("String->Timestamp", new String[] {"1970-01-01", "1970-01-01 00:00:00", "1970-01-01 00:00:00.0", "1970-01-01 00:00:00.000"}, new String[] {"Timestamp", "java.sql.Timestamp"}, null, localeData, new Timestamp(-43200000)); - simpleTypeConvertTestError("String->error-Timestamp", "o", new String[] {"Timestamp", "java.sql.Timestamp"}); - simpleTypeConvertTestSingleMulti("String->List", "[one, two, three]", new String[] {"List", "List", "java.util.List"}, list); - simpleTypeConvertTestSingleMulti("String->List", "[one, two, three", new String[] {"List", "List", "java.util.List"}, list("[one, two, three")); - simpleTypeConvertTestSingleMulti("String->List", "one, two, three]", new String[] {"List", "List", "java.util.List"}, list("one, two, three]")); - simpleTypeConvertTestSingleMulti("String->Set", "[one, two, three]", new String[] {"Set", "Set", "java.util.Set"}, set); - simpleTypeConvertTestSingleMulti("String->Set", "[one, two, three", new String[] {"Set", "Set", "java.util.Set"}, set("[one, two, three")); - simpleTypeConvertTestSingleMulti("String->Set", "one, two, three]", new String[] {"Set", "Set", "java.util.Set"}, set("one, two, three]")); - simpleTypeConvertTestSingleMulti("String->Map", "{one=1, two=2, three=3}", new String[] {"Map", "Map", "java.util.Map"}, map); - simpleTypeConvertTestError("String->Map(error-1)", "{one=1, two=2, three=3", new String[] {"Map", "java.util.Map"}); - simpleTypeConvertTestError("String->Map(error-2)", "one=1, two=2, three=3}", new String[] {"Map", "java.util.Map"}); - simpleTypeConvertTestSingleMulti("String->TimeDuration(number)", "3,661,001", new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, null, localeData, duration); - simpleTypeConvertTestMultiMulti("String->TimeDuration(string)", new String[] {"1:1:1:1"}, new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); - simpleTypeConvertTestError("String->error-TimeDuration", "o", new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}); - } - - public void testDouble() throws GeneralException { - simpleTypeConvertTestSingleMulti("Double->String", Double.valueOf("1234567"), new String[] {"String", "java.lang.String"}, null, localeData, "1,234,567"); - simpleTypeConvertTestSingleMulti("Double->BigDecimal", dbl, new String[] {"BigDecimal", "java.math.BigDecimal"}, dcml); - simpleTypeConvertTestSingleMulti("Double->Double", dbl, new String[] {"Double", "java.lang.Double"}, new Double("781.25")); - simpleTypeConvertTestSingleMulti("Double->Float", dbl, new String[] {"Float", "java.lang.Float"}, flt); - simpleTypeConvertTestSingleMulti("Double->Long", dbl, new String[] {"Long", "java.lang.Long"}, lng); - simpleTypeConvertTestSingleMulti("Double->Integer", dbl, new String[] {"Integer", "java.lang.Integer"}, intg); - simpleTypeConvertTestSingleMulti("Double->List", dbl, new String[] {"List", "List", "java.util.List"}, list(dbl)); - simpleTypeConvertTestSingleMulti("Double->Set", dbl, new String[] {"Set", "Set", "java.util.Set"}, set(dbl)); - simpleTypeConvertTestSingleMulti("Double->TimeDuration", Double.valueOf("3661001.25"), new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); - simpleTypeConvertTestError("Double->error", dbl, new String[] {}); - } - - public void testFloat() throws GeneralException { - // does not support to java.lang variants - simpleTypeConvertTestSingleMulti("Float->String", Float.valueOf("1234567"), new String[] {"String"}, null, localeData, "1,234,567"); - simpleTypeConvertTestSingleMulti("Float->BigDecimal", flt, new String[] {"BigDecimal", "java.math.BigDecimal"}, dcml); - simpleTypeConvertTestSingleMulti("Float->Double", flt, new String[] {"Double", "java.lang.Double"}, dbl); - simpleTypeConvertTestSingleMulti("Float->Float", flt, new String[] {"Float", "java.lang.Float"}, new Float("781.25")); - simpleTypeConvertTestSingleMulti("Float->Long", flt, new String[] {"Long", "java.lang.Long"}, lng); - simpleTypeConvertTestSingleMulti("Float->Integer", flt, new String[] {"Integer", "java.lang.Integer"}, intg); - simpleTypeConvertTestSingleMulti("Float->List", flt, new String[] {"List", "List", "java.util.List"}, list(flt)); - simpleTypeConvertTestSingleMulti("Float->Set", flt, new String[] {"Set", "Set", "java.util.Set"}, set(flt)); - simpleTypeConvertTestSingleMulti("Float->TimeDuration", Float.valueOf("3661001.25"), new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); - simpleTypeConvertTestError("Float->error", flt, new String[] {}); - } - - public void testLong() throws GeneralException { - simpleTypeConvertTestSingleMulti("Long->String", Long.valueOf("1234567"), new String[] {"String", "java.lang.String"}, null, localeData, "1,234,567"); - simpleTypeConvertTestSingleMulti("Long->BigDecimal", lng, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("781")); - simpleTypeConvertTestSingleMulti("Long->Double", lng, new String[] {"Double", "java.lang.Double"}, new Double("781")); - simpleTypeConvertTestSingleMulti("Long->Float", lng, new String[] {"Float", "java.lang.Float"}, new Float("781")); - simpleTypeConvertTestSingleMulti("Long->Long", lng, new String[] {"Long", "java.lang.Long"}, new Long("781")); - simpleTypeConvertTestSingleMulti("Long->Integer", lng, new String[] {"Integer", "java.lang.Integer"}, intg); - simpleTypeConvertTestSingleMulti("Long->List", lng, new String[] {"List", "List", "java.util.List"}, list(lng)); - simpleTypeConvertTestSingleMulti("Long->Set", lng, new String[] {"Set", "Set", "java.util.Set"}, set(lng)); - simpleTypeConvertTestSingleMulti("Long->java.util.Date", 781L, new String[] {"java.util.Date"}, utlDt); - simpleTypeConvertTestSingleMulti("Long->Timestamp", lng, new String[] {"Timestamp", "java.sql.Timestamp"}, tstmp); - simpleTypeConvertTestSingleMulti("Long->TimeDuration", Long.valueOf("3661001"), new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); - simpleTypeConvertTestError("Long->error", lng, new String[] {}); - } - - public void testInteger() throws GeneralException { - simpleTypeConvertTestSingleMulti("Integer->String", Integer.valueOf("1234567"), new String[] {"String", "java.lang.String"}, null, localeData, "1,234,567"); - simpleTypeConvertTestSingleMulti("Integer->BigDecimal", intg, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("781")); - simpleTypeConvertTestSingleMulti("Integer->Double", intg, new String[] {"Double", "java.lang.Double"}, new Double("781")); - simpleTypeConvertTestSingleMulti("Integer->Float", intg, new String[] {"Float", "java.lang.Float"}, new Float("781")); - simpleTypeConvertTestSingleMulti("Integer->Long", intg, new String[] {"Long", "java.lang.Long"}, lng); - simpleTypeConvertTestSingleMulti("Integer->Integer", intg, new String[] {"Integer", "java.lang.Integer"}, Integer.valueOf("781")); - simpleTypeConvertTestSingleMulti("Integer->List", intg, new String[] {"List", "List", "java.util.List"}, list(intg)); - simpleTypeConvertTestSingleMulti("Integer->Set", intg, new String[] {"Set", "Set", "java.util.Set"}, set(intg)); - simpleTypeConvertTestSingleMulti("Integer->TimeDuration", Integer.valueOf("3661001"), new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); - simpleTypeConvertTestError("Integer->error", intg, new String[] {}); - } - - public void testBigDecimal() throws GeneralException { - simpleTypeConvertTestSingleMulti("BigDecimal->String", new BigDecimal("12345.67"), new String[] {"String", "java.lang.String"}, null, localeData, "12,345.67"); - simpleTypeConvertTestSingleMulti("BigDecimal->BigDecimal", dcml, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("781.25")); - simpleTypeConvertTestSingleMulti("BigDecimal->Double", dcml, new String[] {"Double", "java.lang.Double"}, dbl); - simpleTypeConvertTestSingleMulti("BigDecimal->Float", dcml, new String[] {"Float", "java.lang.Float"}, flt); - simpleTypeConvertTestSingleMulti("BigDecimal->Long", dcml, new String[] {"Long", "java.lang.Long"}, lng); - simpleTypeConvertTestSingleMulti("BigDecimal->Integer", dcml, new String[] {"Integer", "java.lang.Integer"}, intg); - simpleTypeConvertTestSingleMulti("BigDecimal->List", dcml, new String[] {"List", "List", "java.util.List"}, list(dcml)); - simpleTypeConvertTestSingleMulti("BigDecimal->Set", dcml, new String[] {"Set", "Set", "java.util.Set"}, set(dcml)); - simpleTypeConvertTestSingleMulti("BigDecimal->TimeDuration", new BigDecimal("3661001"), new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); - simpleTypeConvertTestError("BigDecimal->error", dcml, new String[] {}); - } - - public void testSqlDate() throws GeneralException { - simpleTypeConvertTestSingleMulti("SqlDate->String", sqlDt, new String[] {"String", "java.lang.String"}, null, localeData, "1969-12-31"); - simpleTypeConvertTestSingleMulti("SqlDate->String", sqlDt, new String[] {"String", "java.lang.String"}, "", localeData, "1969-12-31"); - simpleTypeConvertTestSingleMulti("SqlDate->String", sqlDt, new String[] {"String", "java.lang.String"}, "dd-MM-yyyy", localeData, "31-12-1969"); - simpleTypeConvertTestSingleMulti("SqlDate->SqlDate", sqlDt, new String[] {"Date", "java.sql.Date"}, new java.sql.Date(-129600000)); - simpleTypeConvertTestSingleMulti("SqlDate->Timestamp", sqlDt, new String[] {"Timestamp", "java.sql.Timestamp"}, new Timestamp(-129600000)); - simpleTypeConvertTestSingleMulti("SqlDate->List", sqlDt, new String[] {"List", "List", "java.util.List"}, list(sqlDt)); - simpleTypeConvertTestSingleMulti("SqlDate->Set", sqlDt, new String[] {"Set", "Set", "java.util.Set"}, set(sqlDt)); - simpleTypeConvertTestSingleMulti("SqlDate->Long", sqlDt, new String[] {"Long", "java.lang.Long"}, Long.valueOf("-129600000")); - simpleTypeConvertTestError("SqlDate->error", sqlDt, new String[] {"Time", "java.sql.Time"}); - } - - public void testSqlTime() throws GeneralException { - simpleTypeConvertTestSingleMulti("SqlTime->String", sqlTm, new String[] {"String", "java.lang.String"}, null, localeData, "12:34:56"); - simpleTypeConvertTestSingleMulti("SqlTime->String", sqlTm, new String[] {"String", "java.lang.String"}, "", localeData, "12:34:56"); - simpleTypeConvertTestSingleMulti("SqlTime->String", sqlTm, new String[] {"String", "java.lang.String"}, "ss:mm:HH", localeData, "56:34:12"); - simpleTypeConvertTestSingleMulti("SqlTime->SqlTime", sqlTm, new String[] {"Time", "java.sql.Time"}, new java.sql.Time(2096000)); - simpleTypeConvertTestSingleMulti("SqlTime->Timestamp", sqlTm, new String[] {"Timestamp", "java.sql.Timestamp"}, new Timestamp(2096000)); - simpleTypeConvertTestSingleMulti("SqlTime->List", sqlTm, new String[] {"List", "List", "java.util.List"}, list(sqlTm)); - simpleTypeConvertTestSingleMulti("SqlTime->Set", sqlTm, new String[] {"Set", "Set", "java.util.Set"}, set(sqlTm)); - simpleTypeConvertTestError("SqlTime->error", sqlTm, new String[] {"Date", "java.sql.Date"}); - } - - public void testTimestamp() throws GeneralException { - simpleTypeConvertTestSingleMulti("Timestamp->String", tstmp, new String[] {"String", "java.lang.String"}, null, localeData, "1970-01-01 12:00:00.781"); - simpleTypeConvertTestSingleMulti("Timestamp->String", tstmp, new String[] {"String", "java.lang.String"}, "", localeData, "1970-01-01 12:00:00.781"); - simpleTypeConvertTestSingleMulti("Timestamp->String", tstmp, new String[] {"String", "java.lang.String"}, "dd-MM-yyyy HH:mm:ss/SSS", localeData, "01-01-1970 12:00:00/781"); - simpleTypeConvertTestSingleMulti("Timestamp->Date", tstmp, new String[] {"Date", "java.sql.Date"}, new java.sql.Date(781)); - simpleTypeConvertTestSingleMulti("Timestamp->Time", tstmp, new String[] {"Time", "java.sql.Time"}, new java.sql.Time(781)); - simpleTypeConvertTestSingleMulti("Timestamp->Timestamp", tstmp, new String[] {"Timestamp", "java.sql.Timestamp"}, new Timestamp(781)); - simpleTypeConvertTestSingleMulti("Timestamp->List", tstmp, new String[] {"List", "List", "java.util.List"}, list(tstmp)); - simpleTypeConvertTestSingleMulti("Timestamp->Set", tstmp, new String[] {"Set", "Set", "java.util.Set"}, set(tstmp)); - simpleTypeConvertTestSingleMulti("Timestamp->Long", tstmp, new String[] {"Long", "java.lang.Long"}, Long.valueOf("781")); - simpleTypeConvertTestError("Timestamp->error", tstmp, new String[] {}); - } - - public void testBoolean() throws GeneralException { - simpleTypeConvertTestSingleMulti("Boolean->Boolean", true, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.TRUE); - simpleTypeConvertTestSingleMulti("Boolean->Boolean", false, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.FALSE); - simpleTypeConvertTestSingleMulti("Boolean->String", true, new String[] {"String", "java.lang.String"}, "true"); - simpleTypeConvertTestSingleMulti("Boolean->String", false, new String[] {"String", "java.lang.String"}, "false"); - simpleTypeConvertTestSingleMulti("Boolean->Integer", true, new String[] {"Integer", "java.lang.Integer"}, Integer.valueOf("1")); - simpleTypeConvertTestSingleMulti("Boolean->Integer", false, new String[] {"Integer", "java.lang.Integer"}, Integer.valueOf("0")); - simpleTypeConvertTestSingleMulti("Boolean->List", true, new String[] {"List", "List", "java.util.List"}, list(true)); - simpleTypeConvertTestSingleMulti("Boolean->Set", true, new String[] {"Set", "Set", "java.util.Set"}, set(true)); - simpleTypeConvertTestError("Boolean->error", true, new String[] {}); - } - - public void testLocale() throws GeneralException { - simpleTypeConvertTestSingleMulti("Locale->Locale", localeData.goodLocale, new String[] {"Locale", "java.util.Locale"}, localeData.goodLocale); - simpleTypeConvertTestSingleMulti("Locale->String", localeData.goodLocale, new String[] {"String", "java.lang.String"}, localeData.goodLocale.toString()); - simpleTypeConvertTestError("Locale->error", localeData.goodLocale, new String[] {}); - } - - public void testTimeZone() throws GeneralException { - simpleTypeConvertTestSingleMulti("TimeZone->TimeZone", localeData.goodTimeZone, new String[] {"TimeZone", "java.util.TimeZone"}, localeData.goodTimeZone); - simpleTypeConvertTestSingleMulti("TimeZone->String", localeData.goodTimeZone, new String[] {"String", "java.lang.String"}, localeData.goodTimeZone.getID()); - simpleTypeConvertTestError("TimeZone->error", localeData.goodTimeZone, new String[] {}); - } - - // GenericValue, org.ofbiz.entity.GenericValue - - public void testMap() throws GeneralException { - simpleTypeConvertTestSingleMulti("Map->Map", map, new String[] {"Map", "java.util.Map"}, map("one", "1", "two", "2", "three", "3")); - simpleTypeConvertTestSingleMulti("Map->String", map, new String[] {"String", "java.lang.String"}, "{one=1, two=2, three=3}"); - simpleTypeConvertTestSingleMulti("Map->List", map, new String[] {"List", "List", "java.util.List"}, list(map)); - simpleTypeConvertTestSingleMulti("Map->Set", map, new String[] {"Set", "Set", "java.util.Set"}, set(map)); - simpleTypeConvertTestError("Map->error", map, new String[] {}); - } - - public void testList() throws GeneralException { - simpleTypeConvertTestSingleMulti("List->String", list, new String[] {"String", "java.lang.String"}, "[one, two, three]"); - simpleTypeConvertTestSingleMulti("List->List", list, new String[] {"List", "java.util.List"}, list("one", "two", "three")); - simpleTypeConvertTestError("List->error", list, new String[] {}); - } - - /* - // java.nio.ByteBuffer - - public void testBuffer() throws GeneralException { - CharBuffer cbuf = CharBuffer.wrap("one, two, three"); - simpleTypeConvertTestSingleMulti("Buffer->ByteBuffer", cbuf, new String[] {"java.nio.ByteBuffer"}, ""); - } - */ - - // Node tests are done for all String-> conversions - // org.w3c.dom.Node - - public void testTimeDuration() throws GeneralException { - simpleTypeConvertTestSingleMulti("TimeDuration->String", duration, new String[] {"String", "java.lang.String"}, "0:0:0:1:1:1:1"); - simpleTypeConvertTestSingleMulti("TimeDuration->BigDecimal", duration, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("3661001")); - simpleTypeConvertTestSingleMulti("TimeDuration->Double", duration, new String[] {"Double", "java.lang.Double"}, Double.valueOf("3661001")); - simpleTypeConvertTestSingleMulti("TimeDuration->Float", duration, new String[] {"Float", "java.lang.Float"}, Float.valueOf("3661001")); - simpleTypeConvertTestSingleMulti("TimeDuration->Long", duration, new String[] {"Long", "java.lang.Long"}, Long.valueOf("3661001")); - simpleTypeConvertTestSingleMulti("TimeDuration->List", duration, new String[] {"List", "java.util.List"}, list(duration)); - simpleTypeConvertTestSingleMulti("TimeDuration->Set", duration, new String[] {"Set", "java.util.Set"}, set(duration)); - simpleTypeConvertTestError("TimeDuration->error", duration, new String[] {}); - } - - public void testOther() throws GeneralException { - simpleTypeConvertTestSingleMulti("this->String", this, new String[] {"String", "java.lang.String"}, this.toString()); - simpleTypeConvertTestError("this->error", this, new String[] {"List", "Map", "Date"}); - simpleTypeConvertTestNoError("this->no-error", this, new String[] {"List", "Map", "Date"}); - } -} +/******************************************************************************* + * 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.test; + +import java.math.BigDecimal; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TimeZone; + +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.test.GenericTestCaseBase; +import org.ofbiz.base.util.GeneralException; +import org.ofbiz.base.util.ObjectType; +import org.ofbiz.base.util.TimeDuration; +import org.ofbiz.base.util.UtilDateTime; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilXml; +import org.w3c.dom.Document; + +import com.ibm.icu.util.Calendar; + +@SourceMonitored +public class ObjectTypeTests extends GenericTestCaseBase { + public static final String module = ObjectTypeTests.class.getName(); + private static final LocaleData localeData = new LocaleData("en_US", "Pacific/Wake", "fr", "GMT"); + private final TimeDuration duration = new TimeDuration(0, 0, 0, 1, 1, 1, 1); + // These numbers are all based on 1 / 128, which is a binary decimal + // that can be represented by both float and double + private final BigDecimal dcml = new BigDecimal("781.25"); + private final Double dbl = Double.valueOf("7.8125E2"); + private final Float flt = Float.valueOf("7.8125E2"); + private final Long lng = Long.valueOf("781"); + private final Integer intg = Integer.valueOf("781"); + private final Timestamp tstmp = new Timestamp(781L); + private final Timestamp ntstmp; + private final java.util.Date utlDt = new java.util.Date(781); + private final java.sql.Date sqlDt; + private final java.sql.Time sqlTm = new java.sql.Time(2096000); + private final List list; + private final Map map; + private final Set set; + + public ObjectTypeTests(String name) { + super(name); + ntstmp = new Timestamp(781L); + ntstmp.setNanos(123000000); + list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + map = new LinkedHashMap(); + map.put("one", "1"); + map.put("two", "2"); + map.put("three", "3"); + set = new LinkedHashSet(list); + Calendar cal = UtilDateTime.getCalendarInstance(localeData.goodTimeZone, localeData.goodLocale); + cal.set(1969, Calendar.DECEMBER, 31, 0, 0, 0); + cal.set(Calendar.MILLISECOND, 0); + sqlDt = new java.sql.Date(cal.getTimeInMillis()); + } + + public static class LocaleData { + public final Locale goodLocale; + public final TimeZone goodTimeZone; + public final Locale badLocale; + public final TimeZone badTimeZone; + + public LocaleData(String goodLocale, String goodTimeZone, String badLocale, String badTimeZone) { + this.goodLocale = UtilMisc.parseLocale(goodLocale); + this.goodTimeZone = TimeZone.getTimeZone(goodTimeZone); + this.badLocale = UtilMisc.parseLocale(badLocale); + this.badTimeZone = TimeZone.getTimeZone(badTimeZone); + } + } + + public static Object simpleTypeConvert(Object obj, String type, String format, TimeZone timeZone, Locale locale, boolean noTypeFail) throws GeneralException { + return ObjectType.simpleTypeConvert(obj, type, format, timeZone, locale, noTypeFail); + } + + public static void simpleTypeConvertTest(String label, Object toConvert, String type, Object wanted) throws GeneralException { + basicTest(label, toConvert); + assertEquals(label + ":null target type", toConvert, simpleTypeConvert(toConvert, null, null, null, null, true)); + assertEquals(label + ":null source object", (Object) null, simpleTypeConvert(null, type, null, null, null, true)); + assertEquals(label, wanted, simpleTypeConvert(toConvert, type, null, null, null, true)); + if (toConvert instanceof String) { + String str = (String) toConvert; + Document doc = UtilXml.makeEmptyXmlDocument(); + assertEquals(label + ":text-node proxy", wanted, simpleTypeConvert(doc.createTextNode(str), type, null, null, null, true)); + } + } + + public static void simpleTypeConvertTest(String label, Object toConvert, String type, String format, LocaleData localeData, Object wanted) throws GeneralException { + basicTest(label, toConvert); + Locale defaultLocale = Locale.getDefault(); + TimeZone defaultTimeZone = TimeZone.getDefault(); + try { + Locale.setDefault(localeData.goodLocale); + TimeZone.setDefault(localeData.goodTimeZone); + assertEquals(label + ":default-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, null, null, true)); + assertNotEquals(label + ":bad-passed-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, localeData.badTimeZone, localeData.badLocale, true)); + Locale.setDefault(localeData.badLocale); + TimeZone.setDefault(localeData.badTimeZone); + assertNotEquals(label + ":bad-default-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, null, null, true)); + assertEquals(label + ":passed-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, localeData.goodTimeZone, localeData.goodLocale, true)); + } finally { + Locale.setDefault(defaultLocale); + TimeZone.setDefault(defaultTimeZone); + } + } + + public static void simpleTypeConvertTestSingleMulti(String label, Object toConvert, String[] types, Object wanted) throws GeneralException { + for (int j = 0; j < types.length; j++) { + simpleTypeConvertTest(label + "(:" + j + ")", toConvert, types[j], wanted); + } + } + + public static void simpleTypeConvertTestMultiMulti(String label, Object[] toConvert, String[] types, Object wanted) throws GeneralException { + for (int i = 0; i < toConvert.length; i++) { + for (int j = 0; j < types.length; j++) { + simpleTypeConvertTest(label + "(" + i + ":" + j + ")", toConvert[i], types[j], wanted); + } + } + } + + public static void simpleTypeConvertTestSingleMulti(String label, Object toConvert, String[] types, String format, LocaleData localeData, Object wanted) throws GeneralException { + for (int j = 0; j < types.length; j++) { + simpleTypeConvertTest(label + "(:" + j + ")", toConvert, types[j], format, localeData, wanted); + } + } + + public static void simpleTypeConvertTestMultiMulti(String label, Object[] toConvert, String[] types, String format, LocaleData localeData, Object wanted) throws GeneralException { + for (int i = 0; i < toConvert.length; i++) { + for (int j = 0; j < types.length; j++) { + simpleTypeConvertTest(label + "(" + i + ":" + j + ")", toConvert[i], types[j], format, localeData, wanted); + } + } + } + + public static void simpleTypeConvertTestError(String label, Object toConvert, String type) throws GeneralException { + GeneralException caught = null; + try { + simpleTypeConvert(toConvert, type, null, null, null, true); + } catch (GeneralException e) { + caught = e; + } finally { + assertNotNull(label + ":caught", caught); + } + } + + public static void simpleTypeConvertTestError(String label, Object toConvert, String[] types) throws GeneralException { + simpleTypeConvertTestError(label + ":this", toConvert, GeneralException.class.getName()); + for (String type: types) { + simpleTypeConvertTestError(label + ":" + type, toConvert, type); + } + } + + public static void simpleTypeConvertTestNoError(String label, Object toConvert, String type) throws GeneralException { + assertSame(label, toConvert, simpleTypeConvert(toConvert, type, null, null, null, false)); + } + + public static void simpleTypeConvertTestNoError(String label, Object toConvert, String[] types) throws GeneralException { + simpleTypeConvertTestNoError(label + ":this", toConvert, GeneralException.class.getName()); + for (String type: types) { + simpleTypeConvertTestNoError(label + ":" + type, toConvert, type); + } + } + + public static void basicTest(String label, Object toConvert) throws GeneralException { + assertEquals(label + ":PlainString", toConvert.toString(), simpleTypeConvert(toConvert, "PlainString", null, null, null, true)); + assertSame(label + ":same", toConvert, simpleTypeConvert(toConvert, toConvert.getClass().getName(), null, null, null, true)); + assertSame(label + ":to-Object", toConvert, simpleTypeConvert(toConvert, "Object", null, null, null, true)); + assertSame(label + ":to-java.lang.Object", toConvert, simpleTypeConvert(toConvert, "java.lang.Object", null, null, null, true)); + } + + public void testLoadClassWithNonExistentClass() { + Exception exception = null; + try { + ObjectType.loadClass("foobarbaz"); + } catch (Exception e) { + exception = e; + } + assertTrue("Exception thrown by loadClass(\"foobarbaz\") is not ClassNotFoundException", exception instanceof ClassNotFoundException); + } + + public void testLoadClassWithPrimitives() { + try { + Class theClass; + theClass = ObjectType.loadClass("boolean"); + assertEquals("Wrong class returned by loadClass(\"boolean\")", (Boolean.TYPE).getName(), theClass.getName()); + theClass = ObjectType.loadClass("short"); + assertEquals("Wrong class returned by loadClass(\"short\")", (Short.TYPE).getName(), theClass.getName()); + theClass = ObjectType.loadClass("int"); + assertEquals("Wrong class returned by loadClass(\"int\")", (Integer.TYPE).getName(), theClass.getName()); + theClass = ObjectType.loadClass("long"); + assertEquals("Wrong class returned by loadClass(\"long\")", (Long.TYPE).getName(), theClass.getName()); + theClass = ObjectType.loadClass("float"); + assertEquals("Wrong class returned by loadClass(\"float\")", (Float.TYPE).getName(), theClass.getName()); + theClass = ObjectType.loadClass("double"); + assertEquals("Wrong class returned by loadClass(\"double\")", (Double.TYPE).getName(), theClass.getName()); + theClass = ObjectType.loadClass("byte"); + assertEquals("Wrong class returned by loadClass(\"byte\")", (Byte.TYPE).getName(), theClass.getName()); + theClass = ObjectType.loadClass("char"); + assertEquals("Wrong class returned by loadClass(\"char\")", (Character.TYPE).getName(), theClass.getName()); + } catch (Exception e) { + fail("Exception thrown by loadClass: " + e.getMessage()); + } + } + + public void testLoadClassWithAlias() { + try { + Class theClass; + // first try with a class full name + theClass = ObjectType.loadClass("java.lang.String"); + assertEquals("Wrong class returned by loadClass(\"java.lang.String\")", "java.lang.String", theClass.getName()); + // now try with some aliases + theClass = ObjectType.loadClass("String"); + assertEquals("Wrong class returned by loadClass(\"String\")", "java.lang.String", theClass.getName()); + theClass = ObjectType.loadClass("Object"); + assertEquals("Wrong class returned by loadClass(\"Object\")", "java.lang.Object", theClass.getName()); + theClass = ObjectType.loadClass("Date"); + assertEquals("Wrong class returned by loadClass(\"Date\")", "java.sql.Date", theClass.getName()); + } catch (Exception e) { + fail("Exception thrown by loadClass: " + e.getMessage()); + } + } + + public void testClassNotFound() { + GeneralException caught = null; + try { + ObjectType.simpleTypeConvert(this, "foobarbaz", null, null, null, false); + } catch (GeneralException e) { + caught = e; + } finally { + assertNotNull("class not found", caught); + } + } + + public void testArray() throws GeneralException { + simpleTypeConvertTestSingleMulti("Object[]->List", new Object[] {"one", "two", "three"}, new String[] {"List", "java.util.List"}, list); + simpleTypeConvertTestSingleMulti("int[]->List", new int[] {1, 2, 3}, new String[] {"List", "java.util.List"}, list(1, 2, 3)); + simpleTypeConvertTestError("Object[]->error", new Object[] {"one", "two", "three"}, new String[] {"Map"}); + simpleTypeConvertTestError("int[]->error", new int[] {1, 2, 3}, new String[] {"java.util.ArrayList", "Map"}); + } + + public void testString() throws GeneralException, Exception { + simpleTypeConvertTest("String->String", "one", "String", "one"); + simpleTypeConvertTest("String->String", "one", "java.lang.String", "one"); + simpleTypeConvertTestSingleMulti("empty-String->anything", "", new String[] {"List", "Map"}, null); + simpleTypeConvertTestError("String->error", "one", new String[] {}); + simpleTypeConvertTestMultiMulti("String->Boolean(true)", new String[] {"true", " true ", " TrUe"}, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.TRUE); + simpleTypeConvertTestMultiMulti("String->Boolean(false)", new String[] {"false", " false ", " FaLsE"}, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.FALSE); + simpleTypeConvertTestSingleMulti("String->Locale", "en_us", new String[] {"Locale", "java.util.Locale"}, localeData.goodLocale); + simpleTypeConvertTestError("String->error-Locale", "o", new String[] {"Locale", "java.util.Locale"}); + // TZ can never be null, will default to GMT if it can't be parsed(from the javadocs of java.util.TimeZone) + simpleTypeConvertTestSingleMulti("String->TimeZone", "Pacific/Wake", new String[] {"TimeZone", "java.util.TimeZone"}, localeData.goodTimeZone); + simpleTypeConvertTestSingleMulti("String->BigDecimal", "78,125E-2", new String[] {"BigDecimal", "java.math.BigDecimal"}, null, localeData, dcml); + simpleTypeConvertTestError("String->error-BigDecimal", "o", new String[] {"BigDecimal", "java.math.BigDecimal"}); + simpleTypeConvertTestSingleMulti("String->Double", "78,125E-2", new String[] {"Double", "java.lang.Double"}, null, localeData, dbl); + simpleTypeConvertTestError("String->error-Double", "o", new String[] {"Double", "java.lang.Double"}); + simpleTypeConvertTestSingleMulti("String->Float", "78,125E-2", new String[] {"Float", "java.lang.Float"}, null, localeData, flt); + simpleTypeConvertTestError("String->error-Float", "o", new String[] {"Float", "java.lang.Float"}); + simpleTypeConvertTestSingleMulti("String->Long", "78,125E-2", new String[] {"Long", "java.lang.Long"}, null, localeData, lng); + simpleTypeConvertTestError("String->error-Long", "o", new String[] {"Long", "java.lang.Long"}); + simpleTypeConvertTestSingleMulti("String->Integer", "78,125E-2", new String[] {"Integer", "java.lang.Integer"}, null, localeData, intg); + simpleTypeConvertTestError("String->error-Integer", "o", new String[] {"Integer", "java.lang.Integer"}); + + simpleTypeConvertTestSingleMulti("String->java.sql.Date", "1969-12-31", new String[] {"Date", "java.sql.Date"}, null, localeData, sqlDt); + simpleTypeConvertTestSingleMulti("String->java.sql.Date", "1969-12-31", new String[] {"Date", "java.sql.Date"}, "", localeData, sqlDt); + simpleTypeConvertTestSingleMulti("String->java.sql.Date", "12-31-1969", new String[] {"Date", "java.sql.Date"}, "MM-dd-yyyy", localeData, sqlDt); + simpleTypeConvertTestError("String->error-java.sql.Date", "o", new String[] {"Date", "java.sql.Date"}); + simpleTypeConvertTestSingleMulti("String->java.sql.Time", "12:34:56", new String[] {"Time", "java.sql.Time"}, null, localeData, sqlTm); + simpleTypeConvertTestSingleMulti("String->java.sql.Time", "12:34:56", new String[] {"Time", "java.sql.Time"}, "", localeData, sqlTm); + simpleTypeConvertTestSingleMulti("String->java.sql.Time", "563412", new String[] {"Time", "java.sql.Time"}, "ssmmHH", localeData, sqlTm); + simpleTypeConvertTestError("String->error-java.sql.Time", "o", new String[] {"Time", "java.sql.Time"}); + simpleTypeConvertTestSingleMulti("String->Timestamp", "1970-01-01 12:00:00.123", new String[] {"Timestamp", "java.sql.Timestamp"}, null, localeData, ntstmp); + simpleTypeConvertTestSingleMulti("String->Timestamp", "1970-01-01 12:00:00.123", new String[] {"Timestamp", "java.sql.Timestamp"}, "", localeData, ntstmp); + simpleTypeConvertTestSingleMulti("String->Timestamp", "01-01-1970 12:00:00/123", new String[] {"Timestamp", "java.sql.Timestamp"}, "dd-MM-yyyy HH:mm:ss/SSS", localeData, ntstmp); + simpleTypeConvertTestMultiMulti("String->Timestamp", new String[] {"1970-01-01", "1970-01-01 00:00:00", "1970-01-01 00:00:00.0", "1970-01-01 00:00:00.000"}, new String[] {"Timestamp", "java.sql.Timestamp"}, null, localeData, new Timestamp(-43200000)); + simpleTypeConvertTestError("String->error-Timestamp", "o", new String[] {"Timestamp", "java.sql.Timestamp"}); + simpleTypeConvertTestSingleMulti("String->List", "[one, two, three]", new String[] {"List", "List", "java.util.List"}, list); + simpleTypeConvertTestSingleMulti("String->List", "[one, two, three", new String[] {"List", "List", "java.util.List"}, list("[one, two, three")); + simpleTypeConvertTestSingleMulti("String->List", "one, two, three]", new String[] {"List", "List", "java.util.List"}, list("one, two, three]")); + simpleTypeConvertTestSingleMulti("String->Set", "[one, two, three]", new String[] {"Set", "Set", "java.util.Set"}, set); + simpleTypeConvertTestSingleMulti("String->Set", "[one, two, three", new String[] {"Set", "Set", "java.util.Set"}, set("[one, two, three")); + simpleTypeConvertTestSingleMulti("String->Set", "one, two, three]", new String[] {"Set", "Set", "java.util.Set"}, set("one, two, three]")); + simpleTypeConvertTestSingleMulti("String->Map", "{one=1, two=2, three=3}", new String[] {"Map", "Map", "java.util.Map"}, map); + simpleTypeConvertTestError("String->Map(error-1)", "{one=1, two=2, three=3", new String[] {"Map", "java.util.Map"}); + simpleTypeConvertTestError("String->Map(error-2)", "one=1, two=2, three=3}", new String[] {"Map", "java.util.Map"}); + simpleTypeConvertTestSingleMulti("String->TimeDuration(number)", "3,661,001", new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, null, localeData, duration); + simpleTypeConvertTestMultiMulti("String->TimeDuration(string)", new String[] {"1:1:1:1"}, new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); + simpleTypeConvertTestError("String->error-TimeDuration", "o", new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}); + } + + public void testDouble() throws GeneralException { + simpleTypeConvertTestSingleMulti("Double->String", Double.valueOf("1234567"), new String[] {"String", "java.lang.String"}, null, localeData, "1,234,567"); + simpleTypeConvertTestSingleMulti("Double->BigDecimal", dbl, new String[] {"BigDecimal", "java.math.BigDecimal"}, dcml); + simpleTypeConvertTestSingleMulti("Double->Double", dbl, new String[] {"Double", "java.lang.Double"}, new Double("781.25")); + simpleTypeConvertTestSingleMulti("Double->Float", dbl, new String[] {"Float", "java.lang.Float"}, flt); + simpleTypeConvertTestSingleMulti("Double->Long", dbl, new String[] {"Long", "java.lang.Long"}, lng); + simpleTypeConvertTestSingleMulti("Double->Integer", dbl, new String[] {"Integer", "java.lang.Integer"}, intg); + simpleTypeConvertTestSingleMulti("Double->List", dbl, new String[] {"List", "List", "java.util.List"}, list(dbl)); + simpleTypeConvertTestSingleMulti("Double->Set", dbl, new String[] {"Set", "Set", "java.util.Set"}, set(dbl)); + simpleTypeConvertTestSingleMulti("Double->TimeDuration", Double.valueOf("3661001.25"), new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); + simpleTypeConvertTestError("Double->error", dbl, new String[] {}); + } + + public void testFloat() throws GeneralException { + // does not support to java.lang variants + simpleTypeConvertTestSingleMulti("Float->String", Float.valueOf("1234567"), new String[] {"String"}, null, localeData, "1,234,567"); + simpleTypeConvertTestSingleMulti("Float->BigDecimal", flt, new String[] {"BigDecimal", "java.math.BigDecimal"}, dcml); + simpleTypeConvertTestSingleMulti("Float->Double", flt, new String[] {"Double", "java.lang.Double"}, dbl); + simpleTypeConvertTestSingleMulti("Float->Float", flt, new String[] {"Float", "java.lang.Float"}, new Float("781.25")); + simpleTypeConvertTestSingleMulti("Float->Long", flt, new String[] {"Long", "java.lang.Long"}, lng); + simpleTypeConvertTestSingleMulti("Float->Integer", flt, new String[] {"Integer", "java.lang.Integer"}, intg); + simpleTypeConvertTestSingleMulti("Float->List", flt, new String[] {"List", "List", "java.util.List"}, list(flt)); + simpleTypeConvertTestSingleMulti("Float->Set", flt, new String[] {"Set", "Set", "java.util.Set"}, set(flt)); + simpleTypeConvertTestSingleMulti("Float->TimeDuration", Float.valueOf("3661001.25"), new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); + simpleTypeConvertTestError("Float->error", flt, new String[] {}); + } + + public void testLong() throws GeneralException { + simpleTypeConvertTestSingleMulti("Long->String", Long.valueOf("1234567"), new String[] {"String", "java.lang.String"}, null, localeData, "1,234,567"); + simpleTypeConvertTestSingleMulti("Long->BigDecimal", lng, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("781")); + simpleTypeConvertTestSingleMulti("Long->Double", lng, new String[] {"Double", "java.lang.Double"}, new Double("781")); + simpleTypeConvertTestSingleMulti("Long->Float", lng, new String[] {"Float", "java.lang.Float"}, new Float("781")); + simpleTypeConvertTestSingleMulti("Long->Long", lng, new String[] {"Long", "java.lang.Long"}, new Long("781")); + simpleTypeConvertTestSingleMulti("Long->Integer", lng, new String[] {"Integer", "java.lang.Integer"}, intg); + simpleTypeConvertTestSingleMulti("Long->List", lng, new String[] {"List", "List", "java.util.List"}, list(lng)); + simpleTypeConvertTestSingleMulti("Long->Set", lng, new String[] {"Set", "Set", "java.util.Set"}, set(lng)); + simpleTypeConvertTestSingleMulti("Long->java.util.Date", 781L, new String[] {"java.util.Date"}, utlDt); + simpleTypeConvertTestSingleMulti("Long->Timestamp", lng, new String[] {"Timestamp", "java.sql.Timestamp"}, tstmp); + simpleTypeConvertTestSingleMulti("Long->TimeDuration", Long.valueOf("3661001"), new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); + simpleTypeConvertTestError("Long->error", lng, new String[] {}); + } + + public void testInteger() throws GeneralException { + simpleTypeConvertTestSingleMulti("Integer->String", Integer.valueOf("1234567"), new String[] {"String", "java.lang.String"}, null, localeData, "1,234,567"); + simpleTypeConvertTestSingleMulti("Integer->BigDecimal", intg, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("781")); + simpleTypeConvertTestSingleMulti("Integer->Double", intg, new String[] {"Double", "java.lang.Double"}, new Double("781")); + simpleTypeConvertTestSingleMulti("Integer->Float", intg, new String[] {"Float", "java.lang.Float"}, new Float("781")); + simpleTypeConvertTestSingleMulti("Integer->Long", intg, new String[] {"Long", "java.lang.Long"}, lng); + simpleTypeConvertTestSingleMulti("Integer->Integer", intg, new String[] {"Integer", "java.lang.Integer"}, Integer.valueOf("781")); + simpleTypeConvertTestSingleMulti("Integer->List", intg, new String[] {"List", "List", "java.util.List"}, list(intg)); + simpleTypeConvertTestSingleMulti("Integer->Set", intg, new String[] {"Set", "Set", "java.util.Set"}, set(intg)); + simpleTypeConvertTestSingleMulti("Integer->TimeDuration", Integer.valueOf("3661001"), new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); + simpleTypeConvertTestError("Integer->error", intg, new String[] {}); + } + + public void testBigDecimal() throws GeneralException { + simpleTypeConvertTestSingleMulti("BigDecimal->String", new BigDecimal("12345.67"), new String[] {"String", "java.lang.String"}, null, localeData, "12,345.67"); + simpleTypeConvertTestSingleMulti("BigDecimal->BigDecimal", dcml, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("781.25")); + simpleTypeConvertTestSingleMulti("BigDecimal->Double", dcml, new String[] {"Double", "java.lang.Double"}, dbl); + simpleTypeConvertTestSingleMulti("BigDecimal->Float", dcml, new String[] {"Float", "java.lang.Float"}, flt); + simpleTypeConvertTestSingleMulti("BigDecimal->Long", dcml, new String[] {"Long", "java.lang.Long"}, lng); + simpleTypeConvertTestSingleMulti("BigDecimal->Integer", dcml, new String[] {"Integer", "java.lang.Integer"}, intg); + simpleTypeConvertTestSingleMulti("BigDecimal->List", dcml, new String[] {"List", "List", "java.util.List"}, list(dcml)); + simpleTypeConvertTestSingleMulti("BigDecimal->Set", dcml, new String[] {"Set", "Set", "java.util.Set"}, set(dcml)); + simpleTypeConvertTestSingleMulti("BigDecimal->TimeDuration", new BigDecimal("3661001"), new String[] {"TimeDuration", "org.ofbiz.base.util.TimeDuration"}, duration); + simpleTypeConvertTestError("BigDecimal->error", dcml, new String[] {}); + } + + public void testSqlDate() throws GeneralException { + simpleTypeConvertTestSingleMulti("SqlDate->String", sqlDt, new String[] {"String", "java.lang.String"}, null, localeData, "1969-12-31"); + simpleTypeConvertTestSingleMulti("SqlDate->String", sqlDt, new String[] {"String", "java.lang.String"}, "", localeData, "1969-12-31"); + simpleTypeConvertTestSingleMulti("SqlDate->String", sqlDt, new String[] {"String", "java.lang.String"}, "dd-MM-yyyy", localeData, "31-12-1969"); + simpleTypeConvertTestSingleMulti("SqlDate->SqlDate", sqlDt, new String[] {"Date", "java.sql.Date"}, new java.sql.Date(-129600000)); + simpleTypeConvertTestSingleMulti("SqlDate->Timestamp", sqlDt, new String[] {"Timestamp", "java.sql.Timestamp"}, new Timestamp(-129600000)); + simpleTypeConvertTestSingleMulti("SqlDate->List", sqlDt, new String[] {"List", "List", "java.util.List"}, list(sqlDt)); + simpleTypeConvertTestSingleMulti("SqlDate->Set", sqlDt, new String[] {"Set", "Set", "java.util.Set"}, set(sqlDt)); + simpleTypeConvertTestSingleMulti("SqlDate->Long", sqlDt, new String[] {"Long", "java.lang.Long"}, Long.valueOf("-129600000")); + simpleTypeConvertTestError("SqlDate->error", sqlDt, new String[] {"Time", "java.sql.Time"}); + } + + public void testSqlTime() throws GeneralException { + simpleTypeConvertTestSingleMulti("SqlTime->String", sqlTm, new String[] {"String", "java.lang.String"}, null, localeData, "12:34:56"); + simpleTypeConvertTestSingleMulti("SqlTime->String", sqlTm, new String[] {"String", "java.lang.String"}, "", localeData, "12:34:56"); + simpleTypeConvertTestSingleMulti("SqlTime->String", sqlTm, new String[] {"String", "java.lang.String"}, "ss:mm:HH", localeData, "56:34:12"); + simpleTypeConvertTestSingleMulti("SqlTime->SqlTime", sqlTm, new String[] {"Time", "java.sql.Time"}, new java.sql.Time(2096000)); + simpleTypeConvertTestSingleMulti("SqlTime->Timestamp", sqlTm, new String[] {"Timestamp", "java.sql.Timestamp"}, new Timestamp(2096000)); + simpleTypeConvertTestSingleMulti("SqlTime->List", sqlTm, new String[] {"List", "List", "java.util.List"}, list(sqlTm)); + simpleTypeConvertTestSingleMulti("SqlTime->Set", sqlTm, new String[] {"Set", "Set", "java.util.Set"}, set(sqlTm)); + simpleTypeConvertTestError("SqlTime->error", sqlTm, new String[] {"Date", "java.sql.Date"}); + } + + public void testTimestamp() throws GeneralException { + simpleTypeConvertTestSingleMulti("Timestamp->String", tstmp, new String[] {"String", "java.lang.String"}, null, localeData, "1970-01-01 12:00:00.781"); + simpleTypeConvertTestSingleMulti("Timestamp->String", tstmp, new String[] {"String", "java.lang.String"}, "", localeData, "1970-01-01 12:00:00.781"); + simpleTypeConvertTestSingleMulti("Timestamp->String", tstmp, new String[] {"String", "java.lang.String"}, "dd-MM-yyyy HH:mm:ss/SSS", localeData, "01-01-1970 12:00:00/781"); + simpleTypeConvertTestSingleMulti("Timestamp->Date", tstmp, new String[] {"Date", "java.sql.Date"}, new java.sql.Date(781)); + simpleTypeConvertTestSingleMulti("Timestamp->Time", tstmp, new String[] {"Time", "java.sql.Time"}, new java.sql.Time(781)); + simpleTypeConvertTestSingleMulti("Timestamp->Timestamp", tstmp, new String[] {"Timestamp", "java.sql.Timestamp"}, new Timestamp(781)); + simpleTypeConvertTestSingleMulti("Timestamp->List", tstmp, new String[] {"List", "List", "java.util.List"}, list(tstmp)); + simpleTypeConvertTestSingleMulti("Timestamp->Set", tstmp, new String[] {"Set", "Set", "java.util.Set"}, set(tstmp)); + simpleTypeConvertTestSingleMulti("Timestamp->Long", tstmp, new String[] {"Long", "java.lang.Long"}, Long.valueOf("781")); + simpleTypeConvertTestError("Timestamp->error", tstmp, new String[] {}); + } + + public void testBoolean() throws GeneralException { + simpleTypeConvertTestSingleMulti("Boolean->Boolean", true, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.TRUE); + simpleTypeConvertTestSingleMulti("Boolean->Boolean", false, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.FALSE); + simpleTypeConvertTestSingleMulti("Boolean->String", true, new String[] {"String", "java.lang.String"}, "true"); + simpleTypeConvertTestSingleMulti("Boolean->String", false, new String[] {"String", "java.lang.String"}, "false"); + simpleTypeConvertTestSingleMulti("Boolean->Integer", true, new String[] {"Integer", "java.lang.Integer"}, Integer.valueOf("1")); + simpleTypeConvertTestSingleMulti("Boolean->Integer", false, new String[] {"Integer", "java.lang.Integer"}, Integer.valueOf("0")); + simpleTypeConvertTestSingleMulti("Boolean->List", true, new String[] {"List", "List", "java.util.List"}, list(true)); + simpleTypeConvertTestSingleMulti("Boolean->Set", true, new String[] {"Set", "Set", "java.util.Set"}, set(true)); + simpleTypeConvertTestError("Boolean->error", true, new String[] {}); + } + + public void testLocale() throws GeneralException { + simpleTypeConvertTestSingleMulti("Locale->Locale", localeData.goodLocale, new String[] {"Locale", "java.util.Locale"}, localeData.goodLocale); + simpleTypeConvertTestSingleMulti("Locale->String", localeData.goodLocale, new String[] {"String", "java.lang.String"}, localeData.goodLocale.toString()); + simpleTypeConvertTestError("Locale->error", localeData.goodLocale, new String[] {}); + } + + public void testTimeZone() throws GeneralException { + simpleTypeConvertTestSingleMulti("TimeZone->TimeZone", localeData.goodTimeZone, new String[] {"TimeZone", "java.util.TimeZone"}, localeData.goodTimeZone); + simpleTypeConvertTestSingleMulti("TimeZone->String", localeData.goodTimeZone, new String[] {"String", "java.lang.String"}, localeData.goodTimeZone.getID()); + simpleTypeConvertTestError("TimeZone->error", localeData.goodTimeZone, new String[] {}); + } + + // GenericValue, org.ofbiz.entity.GenericValue + + public void testMap() throws GeneralException { + simpleTypeConvertTestSingleMulti("Map->Map", map, new String[] {"Map", "java.util.Map"}, map("one", "1", "two", "2", "three", "3")); + simpleTypeConvertTestSingleMulti("Map->String", map, new String[] {"String", "java.lang.String"}, "{one=1, two=2, three=3}"); + simpleTypeConvertTestSingleMulti("Map->List", map, new String[] {"List", "List", "java.util.List"}, list(map)); + simpleTypeConvertTestSingleMulti("Map->Set", map, new String[] {"Set", "Set", "java.util.Set"}, set(map)); + simpleTypeConvertTestError("Map->error", map, new String[] {}); + } + + public void testList() throws GeneralException { + simpleTypeConvertTestSingleMulti("List->String", list, new String[] {"String", "java.lang.String"}, "[one, two, three]"); + simpleTypeConvertTestSingleMulti("List->List", list, new String[] {"List", "java.util.List"}, list("one", "two", "three")); + simpleTypeConvertTestError("List->error", list, new String[] {}); + } + + /* + // java.nio.ByteBuffer + + public void testBuffer() throws GeneralException { + CharBuffer cbuf = CharBuffer.wrap("one, two, three"); + simpleTypeConvertTestSingleMulti("Buffer->ByteBuffer", cbuf, new String[] {"java.nio.ByteBuffer"}, ""); + } + */ + + // Node tests are done for all String-> conversions + // org.w3c.dom.Node + + public void testTimeDuration() throws GeneralException { + simpleTypeConvertTestSingleMulti("TimeDuration->String", duration, new String[] {"String", "java.lang.String"}, "0:0:0:1:1:1:1"); + simpleTypeConvertTestSingleMulti("TimeDuration->BigDecimal", duration, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("3661001")); + simpleTypeConvertTestSingleMulti("TimeDuration->Double", duration, new String[] {"Double", "java.lang.Double"}, Double.valueOf("3661001")); + simpleTypeConvertTestSingleMulti("TimeDuration->Float", duration, new String[] {"Float", "java.lang.Float"}, Float.valueOf("3661001")); + simpleTypeConvertTestSingleMulti("TimeDuration->Long", duration, new String[] {"Long", "java.lang.Long"}, Long.valueOf("3661001")); + simpleTypeConvertTestSingleMulti("TimeDuration->List", duration, new String[] {"List", "java.util.List"}, list(duration)); + simpleTypeConvertTestSingleMulti("TimeDuration->Set", duration, new String[] {"Set", "java.util.Set"}, set(duration)); + simpleTypeConvertTestError("TimeDuration->error", duration, new String[] {}); + } + + public void testOther() throws GeneralException { + simpleTypeConvertTestSingleMulti("this->String", this, new String[] {"String", "java.lang.String"}, this.toString()); + simpleTypeConvertTestError("this->error", this, new String[] {"List", "Map", "Date"}); + simpleTypeConvertTestNoError("this->no-error", this, new String[] {"List", "Map", "Date"}); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/test/ReferenceCleanerTests.java b/framework/base/src/org/ofbiz/base/util/test/ReferenceCleanerTests.java index 8b95efc1f4..526895f650 100644 --- a/framework/base/src/org/ofbiz/base/util/test/ReferenceCleanerTests.java +++ b/framework/base/src/org/ofbiz/base/util/test/ReferenceCleanerTests.java @@ -1,76 +1,76 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ -package org.ofbiz.base.util.test; - -import java.util.HashSet; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.TimeUnit; - -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.test.GenericTestCaseBase; -import org.ofbiz.base.util.ReferenceCleaner; - -@SourceMonitored -public class ReferenceCleanerTests extends GenericTestCaseBase { - public ReferenceCleanerTests(String name) { - super(name); - } - - public void testReferenceCleaner() throws Exception { - assertStaticHelperClass(ReferenceCleaner.class); - final SynchronousQueue queue = new SynchronousQueue(); - Object obj = new Object(); - ReferenceCleaner.Soft soft = new ReferenceCleaner.Soft(obj) { - public void remove() throws Exception { - queue.put("soft"); - Thread.currentThread().interrupt(); - } - }; - ReferenceCleaner.Weak weak = new ReferenceCleaner.Weak(obj) { - public void remove() throws Exception { - queue.put("weak"); - throw new RuntimeException(); - } - }; - new ReferenceCleaner.Phantom(obj) { - public void remove() throws Exception { - queue.put("phantom"); - } - }; - HashSet foundEvents = new HashSet(); - useAllMemory(); - assertSame("still-soft", obj, soft.get()); - assertSame("still-weak", obj, weak.get()); - assertNull("no event", queue.poll(100, TimeUnit.MILLISECONDS)); - obj = null; - useAllMemory(); - foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS)); - foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS)); - foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS)); - useAllMemory(); - foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS)); - foundEvents.remove(null); - assertFalse("no null", foundEvents.contains(null)); - assertNull("no-soft", soft.get()); - assertNull("no-weak", weak.get()); - assertTrue("soft event", foundEvents.contains("soft")); - assertTrue("weak event", foundEvents.contains("weak")); - assertTrue("phantom event", foundEvents.contains("phantom")); - } -} +/******************************************************************************* + * 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.test; + +import java.util.HashSet; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.TimeUnit; + +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.test.GenericTestCaseBase; +import org.ofbiz.base.util.ReferenceCleaner; + +@SourceMonitored +public class ReferenceCleanerTests extends GenericTestCaseBase { + public ReferenceCleanerTests(String name) { + super(name); + } + + public void testReferenceCleaner() throws Exception { + assertStaticHelperClass(ReferenceCleaner.class); + final SynchronousQueue queue = new SynchronousQueue(); + Object obj = new Object(); + ReferenceCleaner.Soft soft = new ReferenceCleaner.Soft(obj) { + public void remove() throws Exception { + queue.put("soft"); + Thread.currentThread().interrupt(); + } + }; + ReferenceCleaner.Weak weak = new ReferenceCleaner.Weak(obj) { + public void remove() throws Exception { + queue.put("weak"); + throw new RuntimeException(); + } + }; + new ReferenceCleaner.Phantom(obj) { + public void remove() throws Exception { + queue.put("phantom"); + } + }; + HashSet foundEvents = new HashSet(); + useAllMemory(); + assertSame("still-soft", obj, soft.get()); + assertSame("still-weak", obj, weak.get()); + assertNull("no event", queue.poll(100, TimeUnit.MILLISECONDS)); + obj = null; + useAllMemory(); + foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS)); + foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS)); + foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS)); + useAllMemory(); + foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS)); + foundEvents.remove(null); + assertFalse("no null", foundEvents.contains(null)); + assertNull("no-soft", soft.get()); + assertNull("no-weak", weak.get()); + assertTrue("soft event", foundEvents.contains("soft")); + assertTrue("weak event", foundEvents.contains("weak")); + assertTrue("phantom event", foundEvents.contains("phantom")); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/test/StringUtilTests.java b/framework/base/src/org/ofbiz/base/util/test/StringUtilTests.java index 5aab7bf70e..05fb58a73e 100644 --- a/framework/base/src/org/ofbiz/base/util/test/StringUtilTests.java +++ b/framework/base/src/org/ofbiz/base/util/test/StringUtilTests.java @@ -1,327 +1,327 @@ -/******************************************************************************* - * 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.test; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.ofbiz.base.lang.Appender; -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.util.GeneralRuntimeException; -import org.ofbiz.base.util.StringUtil; -import org.ofbiz.base.util.UtilGenerics; -import org.ofbiz.base.test.GenericTestCaseBase; - -@SourceMonitored -public class StringUtilTests extends GenericTestCaseBase { - public StringUtilTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testStringUtil() throws Exception { - assertStaticHelperClass(StringUtil.class); - assertTrue("correct INSTANCE", StringUtil.INSTANCE instanceof StringUtil); - } - - public void testInternString() { - assertSame("intern-constant", StringUtil.internString("foo"), StringUtil.internString("foo")); - assertSame("intern-new", StringUtil.internString("foo"), StringUtil.internString(new String("foo"))); - assertSame("intern-char", StringUtil.internString("foo"), StringUtil.internString(new String(new char[] {'f', 'o', 'o'}))); - assertSame("intern-null", StringUtil.internString(null), StringUtil.internString(null)); - } - - public void testReplaceString() { - assertNull("null", StringUtil.replaceString(null, "old", "new")); - assertEquals("empty old", "the old dog jumped over the old fence", StringUtil.replaceString("the old dog jumped over the old fence", "", "new")); - assertEquals("replace", "the new dog jumped over the new fence", StringUtil.replaceString("the old dog jumped over the old fence", "old", "new")); - assertEquals("replace-null", "the dog jumped over the fence", StringUtil.replaceString("the old dog jumped over the old fence", "old", null)); - assertEquals("replace-not-found", "the old dog jumped over the old fence", StringUtil.replaceString("the old dog jumped over the old fence", "cat", "feline")); - } - - public void testJoin() { - assertNull("null-list", StringUtil.join(null, ",")); - assertNull("empty-list", StringUtil.join(Collections.emptyList(), ",")); - assertEquals("single", "1", StringUtil.join(list("1"), ",")); - assertEquals("double", "1,2", StringUtil.join(list("1", "2"), ",")); - } - - public void testSplit() { - assertNull("null-string", StringUtil.split(null, ",")); - assertEquals("single", list("1"), StringUtil.split("1", ",")); - assertEquals("double", list("1", "2"), StringUtil.split("1,2", ",")); - assertEquals("no-sep", list("1", "2", "3", "4", "5", "6"), StringUtil.split("1 2\t3\n4\r5\f6", null)); - } - - public void testQuoteStrList() { - assertEquals("single", list("'1'"), StringUtil.quoteStrList(list("1"))); - assertEquals("double", list("'1'", "'2'"), StringUtil.quoteStrList(list("1", "2"))); - } - - public void testStrToMap() { - assertNull("null-string", StringUtil.strToMap(null, false)); - //assertEquals("empty", Collections.emptyMap(), StringUtil.strToMap("", false)); - assertEquals("missing =", Collections.emptyMap(), StringUtil.strToMap("1", false)); - assertEquals("single", map("1", "one"), StringUtil.strToMap("1=one")); - assertEquals("double", map("2", "two", "1", "one"), StringUtil.strToMap("1=one|2=two")); - assertEquals("double-no-trim", map(" 2 ", " two ", " 1 ", " one "), StringUtil.strToMap(" 1 = one | 2 = two ")); - assertEquals("double-trim", map("2", "two", "1", "one"), StringUtil.strToMap(" 1 = one | 2 = two ", true)); - } - - public void testMapToStr() { - assertNull("null-map", StringUtil.mapToStr(null)); - assertEquals("empty", "", StringUtil.mapToStr(Collections.emptyMap())); - assertEquals("single", "1=one", StringUtil.mapToStr(map("1", "one"))); - assertEquals("double", "1=one|2=two", StringUtil.mapToStr(map("1", "one", "2", "two"))); - assertEquals("double-with-non-string", "1=one|2=two", StringUtil.mapToStr(map("a", this, "1", "one", "2", "two", this, "a"))); - } - - public void testToMap() { - for (String s: new String[] {"", "{", "}", "}{"}) { - IllegalArgumentException caught = null; - try { - StringUtil.toMap(s); - } catch (IllegalArgumentException e) { - caught = e; - } finally { - assertNotNull("bad(" + s + ")", caught); - } - } - //assertEquals("empty", Collections.emptyMap(), StringUtil.toMap("{}")); - assertEquals("single", map("1", "one"), StringUtil.toMap("{1=one}")); - assertEquals("double", map("2", "two", "1", "one"), StringUtil.toMap("{1=one, 2=two}")); - assertEquals("double-space", map("2", "two ", " 1", "one"), StringUtil.toMap("{ 1=one, 2=two }")); - } - - public void testToList() { - for (String s: new String[] {"", "[", "]", "]["}) { - IllegalArgumentException caught = null; - try { - StringUtil.toList(s); - } catch (IllegalArgumentException e) { - caught = e; - } finally { - assertNotNull("bad(" + s + ")", caught); - } - } - //assertEquals("empty", Collections.emptyList(), StringUtil.toList("[]")); - assertEquals("single", list("1"), StringUtil.toList("[1]")); - assertEquals("double", list("1", "2"), StringUtil.toList("[1, 2]")); - assertEquals("double-space", list(" 1", "2 "), StringUtil.toList("[ 1, 2 ]")); - } - - public void testToSet() { - for (String s: new String[] {"", "[", "]", "]["}) { - IllegalArgumentException caught = null; - try { - StringUtil.toSet(s); - } catch (IllegalArgumentException e) { - caught = e; - } finally { - assertNotNull("bad(" + s + ")", caught); - } - } - //assertEquals("empty", Collections.emptySet(), StringUtil.toSet("[]")); - assertEquals("single", set("1"), StringUtil.toSet("[1]")); - assertEquals("double", set("1", "2"), StringUtil.toSet("[1, 2]")); - assertEquals("double-space", set(" 1", "2 "), StringUtil.toSet("[ 1, 2 ]")); - } - - public void testCreateMap() { - List[] badKeys = UtilGenerics.cast(new List[] {null, list("1"), list("2")}); - List[] badValues = UtilGenerics.cast(new List[] {list("one"), null, list("two", "extra")}); - for (int i = 0; i < badKeys.length; i++) { - IllegalArgumentException caught = null; - try { - StringUtil.createMap(badKeys[i], badValues[i]); - } catch (IllegalArgumentException e) { - caught = e; - } finally { - assertNotNull("bad(" + i + ")", caught); - } - } - assertEquals("parse", map("1", "one", "2", "two"), StringUtil.createMap(list("1", "2"), list("one", "two"))); - } - - public void testCleanUpPathPrefix() { - assertEquals("null", "", StringUtil.cleanUpPathPrefix(null)); - assertEquals("empty", "", StringUtil.cleanUpPathPrefix("")); - for (String s: new String[] {"\\a\\b\\c", "\\a\\b\\c\\", "a\\b\\c\\", "a\\b\\c", "/a/b/c", "/a/b/c/", "a/b/c/", "a/b/c"}) { - assertEquals("cleanup(" + s + ")", "/a/b/c", StringUtil.cleanUpPathPrefix(s)); - } - } - - public void testRemoveSpaces() { - assertEquals("", StringUtil.removeSpaces("")); - assertEquals("abcd", StringUtil.removeSpaces(" a b c d ")); - assertEquals("a\\cd", StringUtil.removeSpaces(" a \\ c d ")); - } - - public void testToHexString() { - assertEquals("16 bytes", "000102030405060708090a0b0c0d0e0f", StringUtil.toHexString(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15})); - } - - public void testCleanHexString() { - assertEquals("clean hex", "rtwertetwretw", StringUtil.cleanHexString("rtwer:tetw retw")); - } - - public void testFromHexString() { - assertEquals("16 bytes", new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, StringUtil.fromHexString("000102030405060708090a0b0c0d0e0f")); - GeneralRuntimeException caught = null; - try { - StringUtil.fromHexString("0-"); - } catch (GeneralRuntimeException e) { - caught = e; - } finally { - assertNotNull("bad-char", caught); - } - } - - public void testConvertChar() { - Map conversions = new HashMap(); - conversions.put('0', 0); conversions.put('1', 1); conversions.put('2', 2); conversions.put('3', 3); - conversions.put('4', 4); conversions.put('5', 5); conversions.put('6', 6); conversions.put('7', 7); - conversions.put('8', 8); conversions.put('9', 9); - conversions.put('a', 10); conversions.put('b', 11); conversions.put('c', 12); - conversions.put('d', 13); conversions.put('e', 14); conversions.put('f', 15); - conversions.put('A', 10); conversions.put('B', 11); conversions.put('C', 12); - conversions.put('D', 13); conversions.put('E', 14); conversions.put('F', 15); - for (int i = 0; i < 256; i++) { - Integer wanted = conversions.get((char) i); - if (wanted == null) { - Exception caught = null; - try { - StringUtil.convertChar((char) i); - } catch (Exception e) { - caught = e; - } finally { - assertNotNull(Integer.toString(i), caught); - } - } else { - assertEquals(Integer.toString(i), wanted.intValue(), StringUtil.convertChar((char) i)); - } - } - } - - public void testEncodeInt() { - assertEquals("one octet", new char[] {'0', '5'}, StringUtil.encodeInt(5, 0, new char[2])); - assertEquals("two octets", new char[] {'1', '5'}, StringUtil.encodeInt(21, 0, new char[2])); - // these next two are really weird, note the start offset being != 0. - assertEquals("three octets", new char[] {'3', '1', '5'}, StringUtil.encodeInt(789, 1, new char[3])); - assertEquals("four octets", new char[] {'7', '3', '1', '5'}, StringUtil.encodeInt(29461, 2, new char[4])); - } - - public void testRemoveNonNumeric() { - assertEquals("just numbers", "12345", StringUtil.removeNonNumeric("a1'2;3]4!5(")); - } - - public void testRemoveNumeric() { - assertEquals("only numbers", "a';]!(", StringUtil.removeNumeric("a1'2;3]4!5(")); - } - - public void testRemoveRegex() { - } - - public void testAddToNumberString() { - assertNull("null pass-thru", StringUtil.addToNumberString(null, 0)); - assertEquals("no-change", "12345", StringUtil.addToNumberString("12345", 0)); - assertEquals("increase", "112344", StringUtil.addToNumberString("12345", 99999)); - assertEquals("subtract", "00345", StringUtil.addToNumberString("12345", -12000)); - } - - public void testPadNumberString() { - assertEquals("less", "12345", StringUtil.padNumberString("12345", 3)); - assertEquals("same", "12345", StringUtil.padNumberString("12345", 5)); - assertEquals("more", "00012345", StringUtil.padNumberString("12345", 8)); - } - - public void testConvertOperatorSubstitutions() { - assertNull("null pass-thru", StringUtil.convertOperatorSubstitutions(null)); - assertEquals("none", "abc", StringUtil.convertOperatorSubstitutions("abc")); - assertEquals("none", "a'c", StringUtil.convertOperatorSubstitutions("a'c")); - assertEquals("all converions", "one && two || three > four >= five < six <= seven", StringUtil.convertOperatorSubstitutions("one @and two @or three @gt four @gteq five @lt six @lteq seven")); - } - - public void testCollapseNewlines() { - } - - public void testCollapseSpaces() { - } - - public void testCollapseCharacter() { - assertEquals("not-found", "abcdefg", StringUtil.collapseCharacter("abcdefg", '.')); - assertEquals("no-change", "abcdefg", StringUtil.collapseCharacter("abcdefg", 'a')); - assertEquals("duplicate", "abcdefa", StringUtil.collapseCharacter("aabcdefaa", 'a')); - } - - public void testWrapString() { - } - - public void testMakeStringWrapper() { - } - - protected static final class TestAppender implements Appender { - private final String s; - - protected TestAppender(String s) { - this.s = s; - } - - public StringBuilder appendTo(StringBuilder sb) { - return sb.append(s); - } - } - - public void testAppendTo() { - assertEquals("111", "[1],[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", ",").toString()); - assertEquals("011", "1],2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), null, "]", ",").toString()); - assertEquals("101", "[1,[2", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", null, ",").toString()); - assertEquals("110", "[1][2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", null).toString()); - assertEquals("11111", "[1]<,>[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", ",", ">").toString()); - assertEquals("01111", "1]<,>2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), null, "]", "<", ",", ">").toString()); - assertEquals("10111", "[1<,>[2", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", null, "<", ",", ">").toString()); - assertEquals("11011", "[1],>[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", null, ",", ">").toString()); - assertEquals("11101", "[1][2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", null, ">").toString()); - assertEquals("11110", "[1]<,[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", ",", null).toString()); - } - - public void testAppend() { - assertEquals("111", "[1],[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", ",").toString()); - assertEquals("011", "1],2]", StringUtil.append(new StringBuilder(), list("1", "2"), null, "]", ",").toString()); - assertEquals("101", "[1,[2", StringUtil.append(new StringBuilder(), list("1", "2"), "[", null, ",").toString()); - assertEquals("110", "[1][2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", null).toString()); - assertEquals("11111", "[1]<,>[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", ",", ">").toString()); - assertEquals("01111", "1]<,>2]", StringUtil.append(new StringBuilder(), list("1", "2"), null, "]", "<", ",", ">").toString()); - assertEquals("10111", "[1<,>[2", StringUtil.append(new StringBuilder(), list("1", "2"), "[", null, "<", ",", ">").toString()); - assertEquals("11011", "[1],>[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", null, ",", ">").toString()); - assertEquals("11101", "[1][2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", null, ">").toString()); - assertEquals("11110", "[1]<,[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", ",", null).toString()); - } -} +/******************************************************************************* + * 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.test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.ofbiz.base.lang.Appender; +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.util.GeneralRuntimeException; +import org.ofbiz.base.util.StringUtil; +import org.ofbiz.base.util.UtilGenerics; +import org.ofbiz.base.test.GenericTestCaseBase; + +@SourceMonitored +public class StringUtilTests extends GenericTestCaseBase { + public StringUtilTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testStringUtil() throws Exception { + assertStaticHelperClass(StringUtil.class); + assertTrue("correct INSTANCE", StringUtil.INSTANCE instanceof StringUtil); + } + + public void testInternString() { + assertSame("intern-constant", StringUtil.internString("foo"), StringUtil.internString("foo")); + assertSame("intern-new", StringUtil.internString("foo"), StringUtil.internString(new String("foo"))); + assertSame("intern-char", StringUtil.internString("foo"), StringUtil.internString(new String(new char[] {'f', 'o', 'o'}))); + assertSame("intern-null", StringUtil.internString(null), StringUtil.internString(null)); + } + + public void testReplaceString() { + assertNull("null", StringUtil.replaceString(null, "old", "new")); + assertEquals("empty old", "the old dog jumped over the old fence", StringUtil.replaceString("the old dog jumped over the old fence", "", "new")); + assertEquals("replace", "the new dog jumped over the new fence", StringUtil.replaceString("the old dog jumped over the old fence", "old", "new")); + assertEquals("replace-null", "the dog jumped over the fence", StringUtil.replaceString("the old dog jumped over the old fence", "old", null)); + assertEquals("replace-not-found", "the old dog jumped over the old fence", StringUtil.replaceString("the old dog jumped over the old fence", "cat", "feline")); + } + + public void testJoin() { + assertNull("null-list", StringUtil.join(null, ",")); + assertNull("empty-list", StringUtil.join(Collections.emptyList(), ",")); + assertEquals("single", "1", StringUtil.join(list("1"), ",")); + assertEquals("double", "1,2", StringUtil.join(list("1", "2"), ",")); + } + + public void testSplit() { + assertNull("null-string", StringUtil.split(null, ",")); + assertEquals("single", list("1"), StringUtil.split("1", ",")); + assertEquals("double", list("1", "2"), StringUtil.split("1,2", ",")); + assertEquals("no-sep", list("1", "2", "3", "4", "5", "6"), StringUtil.split("1 2\t3\n4\r5\f6", null)); + } + + public void testQuoteStrList() { + assertEquals("single", list("'1'"), StringUtil.quoteStrList(list("1"))); + assertEquals("double", list("'1'", "'2'"), StringUtil.quoteStrList(list("1", "2"))); + } + + public void testStrToMap() { + assertNull("null-string", StringUtil.strToMap(null, false)); + //assertEquals("empty", Collections.emptyMap(), StringUtil.strToMap("", false)); + assertEquals("missing =", Collections.emptyMap(), StringUtil.strToMap("1", false)); + assertEquals("single", map("1", "one"), StringUtil.strToMap("1=one")); + assertEquals("double", map("2", "two", "1", "one"), StringUtil.strToMap("1=one|2=two")); + assertEquals("double-no-trim", map(" 2 ", " two ", " 1 ", " one "), StringUtil.strToMap(" 1 = one | 2 = two ")); + assertEquals("double-trim", map("2", "two", "1", "one"), StringUtil.strToMap(" 1 = one | 2 = two ", true)); + } + + public void testMapToStr() { + assertNull("null-map", StringUtil.mapToStr(null)); + assertEquals("empty", "", StringUtil.mapToStr(Collections.emptyMap())); + assertEquals("single", "1=one", StringUtil.mapToStr(map("1", "one"))); + assertEquals("double", "1=one|2=two", StringUtil.mapToStr(map("1", "one", "2", "two"))); + assertEquals("double-with-non-string", "1=one|2=two", StringUtil.mapToStr(map("a", this, "1", "one", "2", "two", this, "a"))); + } + + public void testToMap() { + for (String s: new String[] {"", "{", "}", "}{"}) { + IllegalArgumentException caught = null; + try { + StringUtil.toMap(s); + } catch (IllegalArgumentException e) { + caught = e; + } finally { + assertNotNull("bad(" + s + ")", caught); + } + } + //assertEquals("empty", Collections.emptyMap(), StringUtil.toMap("{}")); + assertEquals("single", map("1", "one"), StringUtil.toMap("{1=one}")); + assertEquals("double", map("2", "two", "1", "one"), StringUtil.toMap("{1=one, 2=two}")); + assertEquals("double-space", map("2", "two ", " 1", "one"), StringUtil.toMap("{ 1=one, 2=two }")); + } + + public void testToList() { + for (String s: new String[] {"", "[", "]", "]["}) { + IllegalArgumentException caught = null; + try { + StringUtil.toList(s); + } catch (IllegalArgumentException e) { + caught = e; + } finally { + assertNotNull("bad(" + s + ")", caught); + } + } + //assertEquals("empty", Collections.emptyList(), StringUtil.toList("[]")); + assertEquals("single", list("1"), StringUtil.toList("[1]")); + assertEquals("double", list("1", "2"), StringUtil.toList("[1, 2]")); + assertEquals("double-space", list(" 1", "2 "), StringUtil.toList("[ 1, 2 ]")); + } + + public void testToSet() { + for (String s: new String[] {"", "[", "]", "]["}) { + IllegalArgumentException caught = null; + try { + StringUtil.toSet(s); + } catch (IllegalArgumentException e) { + caught = e; + } finally { + assertNotNull("bad(" + s + ")", caught); + } + } + //assertEquals("empty", Collections.emptySet(), StringUtil.toSet("[]")); + assertEquals("single", set("1"), StringUtil.toSet("[1]")); + assertEquals("double", set("1", "2"), StringUtil.toSet("[1, 2]")); + assertEquals("double-space", set(" 1", "2 "), StringUtil.toSet("[ 1, 2 ]")); + } + + public void testCreateMap() { + List[] badKeys = UtilGenerics.cast(new List[] {null, list("1"), list("2")}); + List[] badValues = UtilGenerics.cast(new List[] {list("one"), null, list("two", "extra")}); + for (int i = 0; i < badKeys.length; i++) { + IllegalArgumentException caught = null; + try { + StringUtil.createMap(badKeys[i], badValues[i]); + } catch (IllegalArgumentException e) { + caught = e; + } finally { + assertNotNull("bad(" + i + ")", caught); + } + } + assertEquals("parse", map("1", "one", "2", "two"), StringUtil.createMap(list("1", "2"), list("one", "two"))); + } + + public void testCleanUpPathPrefix() { + assertEquals("null", "", StringUtil.cleanUpPathPrefix(null)); + assertEquals("empty", "", StringUtil.cleanUpPathPrefix("")); + for (String s: new String[] {"\\a\\b\\c", "\\a\\b\\c\\", "a\\b\\c\\", "a\\b\\c", "/a/b/c", "/a/b/c/", "a/b/c/", "a/b/c"}) { + assertEquals("cleanup(" + s + ")", "/a/b/c", StringUtil.cleanUpPathPrefix(s)); + } + } + + public void testRemoveSpaces() { + assertEquals("", StringUtil.removeSpaces("")); + assertEquals("abcd", StringUtil.removeSpaces(" a b c d ")); + assertEquals("a\\cd", StringUtil.removeSpaces(" a \\ c d ")); + } + + public void testToHexString() { + assertEquals("16 bytes", "000102030405060708090a0b0c0d0e0f", StringUtil.toHexString(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15})); + } + + public void testCleanHexString() { + assertEquals("clean hex", "rtwertetwretw", StringUtil.cleanHexString("rtwer:tetw retw")); + } + + public void testFromHexString() { + assertEquals("16 bytes", new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, StringUtil.fromHexString("000102030405060708090a0b0c0d0e0f")); + GeneralRuntimeException caught = null; + try { + StringUtil.fromHexString("0-"); + } catch (GeneralRuntimeException e) { + caught = e; + } finally { + assertNotNull("bad-char", caught); + } + } + + public void testConvertChar() { + Map conversions = new HashMap(); + conversions.put('0', 0); conversions.put('1', 1); conversions.put('2', 2); conversions.put('3', 3); + conversions.put('4', 4); conversions.put('5', 5); conversions.put('6', 6); conversions.put('7', 7); + conversions.put('8', 8); conversions.put('9', 9); + conversions.put('a', 10); conversions.put('b', 11); conversions.put('c', 12); + conversions.put('d', 13); conversions.put('e', 14); conversions.put('f', 15); + conversions.put('A', 10); conversions.put('B', 11); conversions.put('C', 12); + conversions.put('D', 13); conversions.put('E', 14); conversions.put('F', 15); + for (int i = 0; i < 256; i++) { + Integer wanted = conversions.get((char) i); + if (wanted == null) { + Exception caught = null; + try { + StringUtil.convertChar((char) i); + } catch (Exception e) { + caught = e; + } finally { + assertNotNull(Integer.toString(i), caught); + } + } else { + assertEquals(Integer.toString(i), wanted.intValue(), StringUtil.convertChar((char) i)); + } + } + } + + public void testEncodeInt() { + assertEquals("one octet", new char[] {'0', '5'}, StringUtil.encodeInt(5, 0, new char[2])); + assertEquals("two octets", new char[] {'1', '5'}, StringUtil.encodeInt(21, 0, new char[2])); + // these next two are really weird, note the start offset being != 0. + assertEquals("three octets", new char[] {'3', '1', '5'}, StringUtil.encodeInt(789, 1, new char[3])); + assertEquals("four octets", new char[] {'7', '3', '1', '5'}, StringUtil.encodeInt(29461, 2, new char[4])); + } + + public void testRemoveNonNumeric() { + assertEquals("just numbers", "12345", StringUtil.removeNonNumeric("a1'2;3]4!5(")); + } + + public void testRemoveNumeric() { + assertEquals("only numbers", "a';]!(", StringUtil.removeNumeric("a1'2;3]4!5(")); + } + + public void testRemoveRegex() { + } + + public void testAddToNumberString() { + assertNull("null pass-thru", StringUtil.addToNumberString(null, 0)); + assertEquals("no-change", "12345", StringUtil.addToNumberString("12345", 0)); + assertEquals("increase", "112344", StringUtil.addToNumberString("12345", 99999)); + assertEquals("subtract", "00345", StringUtil.addToNumberString("12345", -12000)); + } + + public void testPadNumberString() { + assertEquals("less", "12345", StringUtil.padNumberString("12345", 3)); + assertEquals("same", "12345", StringUtil.padNumberString("12345", 5)); + assertEquals("more", "00012345", StringUtil.padNumberString("12345", 8)); + } + + public void testConvertOperatorSubstitutions() { + assertNull("null pass-thru", StringUtil.convertOperatorSubstitutions(null)); + assertEquals("none", "abc", StringUtil.convertOperatorSubstitutions("abc")); + assertEquals("none", "a'c", StringUtil.convertOperatorSubstitutions("a'c")); + assertEquals("all converions", "one && two || three > four >= five < six <= seven", StringUtil.convertOperatorSubstitutions("one @and two @or three @gt four @gteq five @lt six @lteq seven")); + } + + public void testCollapseNewlines() { + } + + public void testCollapseSpaces() { + } + + public void testCollapseCharacter() { + assertEquals("not-found", "abcdefg", StringUtil.collapseCharacter("abcdefg", '.')); + assertEquals("no-change", "abcdefg", StringUtil.collapseCharacter("abcdefg", 'a')); + assertEquals("duplicate", "abcdefa", StringUtil.collapseCharacter("aabcdefaa", 'a')); + } + + public void testWrapString() { + } + + public void testMakeStringWrapper() { + } + + protected static final class TestAppender implements Appender { + private final String s; + + protected TestAppender(String s) { + this.s = s; + } + + public StringBuilder appendTo(StringBuilder sb) { + return sb.append(s); + } + } + + public void testAppendTo() { + assertEquals("111", "[1],[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", ",").toString()); + assertEquals("011", "1],2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), null, "]", ",").toString()); + assertEquals("101", "[1,[2", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", null, ",").toString()); + assertEquals("110", "[1][2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", null).toString()); + assertEquals("11111", "[1]<,>[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", ",", ">").toString()); + assertEquals("01111", "1]<,>2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), null, "]", "<", ",", ">").toString()); + assertEquals("10111", "[1<,>[2", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", null, "<", ",", ">").toString()); + assertEquals("11011", "[1],>[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", null, ",", ">").toString()); + assertEquals("11101", "[1][2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", null, ">").toString()); + assertEquals("11110", "[1]<,[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", ",", null).toString()); + } + + public void testAppend() { + assertEquals("111", "[1],[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", ",").toString()); + assertEquals("011", "1],2]", StringUtil.append(new StringBuilder(), list("1", "2"), null, "]", ",").toString()); + assertEquals("101", "[1,[2", StringUtil.append(new StringBuilder(), list("1", "2"), "[", null, ",").toString()); + assertEquals("110", "[1][2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", null).toString()); + assertEquals("11111", "[1]<,>[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", ",", ">").toString()); + assertEquals("01111", "1]<,>2]", StringUtil.append(new StringBuilder(), list("1", "2"), null, "]", "<", ",", ">").toString()); + assertEquals("10111", "[1<,>[2", StringUtil.append(new StringBuilder(), list("1", "2"), "[", null, "<", ",", ">").toString()); + assertEquals("11011", "[1],>[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", null, ",", ">").toString()); + assertEquals("11101", "[1][2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", null, ">").toString()); + assertEquals("11110", "[1]<,[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", ",", null).toString()); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/test/UtilIOTests.java b/framework/base/src/org/ofbiz/base/util/test/UtilIOTests.java index 0a539c7ee3..dba3d2459f 100644 --- a/framework/base/src/org/ofbiz/base/util/test/UtilIOTests.java +++ b/framework/base/src/org/ofbiz/base/util/test/UtilIOTests.java @@ -1,121 +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.test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.test.GenericTestCaseBase; -import org.ofbiz.base.util.UtilIO; - -@SourceMonitored -public class UtilIOTests extends GenericTestCaseBase { - private static final byte[] trademarkBytes = new byte[] { - (byte) 0xE2, (byte) 0x84, (byte) 0xA2 - }; - public UtilIOTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testReadString() throws Exception { - readStringTest_0("unix line ending", "\n", new byte[] { 0x0A }); - readStringTest_0("mac line ending", "\r", new byte[] { 0x0D }); - readStringTest_0("windows line ending", "\r\n", new byte[] { 0x0D, 0x0A }); - } - - private static byte[] join(byte[]... parts) { - int count = 0; - for (byte[] part: parts) { - count += part.length; - } - byte[] result = new byte[count]; - int i = 0; - for (byte[] part: parts) { - System.arraycopy(part, 0, result, i, part.length); - i += part.length; - } - return result; - } - - private static void readStringTest_0(String label, String lineSeparator, byte[] extra) throws IOException { - String originalLineSeparator = System.getProperty("line.separator"); - try { - System.getProperties().put("line.separator", lineSeparator); - readStringTest_1(label + ":mark", "\u2122", join(trademarkBytes)); - readStringTest_1(label + ":mark NL", "\u2122\n", join(trademarkBytes, extra)); - readStringTest_1(label + ":NL mark", "\n\u2122", join(extra, trademarkBytes)); - } finally { - System.getProperties().put("line.separator", originalLineSeparator); - } - } - - private static void readStringTest_1(String label, String wanted, byte[] toRead) throws IOException { - assertEquals("readString bytes default:" + label, wanted, UtilIO.readString(toRead)); - assertEquals("readString bytes UTF-8:" + label, wanted, UtilIO.readString(toRead, "UTF-8")); - assertEquals("readString bytes UTF8:" + label, wanted, UtilIO.readString(toRead, UtilIO.UTF8)); - assertEquals("readString bytes offset/length default:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length)); - assertEquals("readString bytes offset/length UTF-8:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length, "UTF-8")); - assertEquals("readString bytes offset/length UTF8:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length, UtilIO.UTF8)); - assertEquals("readString stream default:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead))); - assertEquals("readString stream UTF-8:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead), "UTF-8")); - assertEquals("readString stream UTF8:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead), UtilIO.UTF8)); - } - - public void testWriteString() throws Exception { - writeStringTest_0("unix line ending", "\n", new byte[] { 0x0A }); - writeStringTest_0("mac line ending", "\r", new byte[] { 0x0D }); - writeStringTest_0("windows line ending", "\r\n", new byte[] { 0x0D, 0x0A }); - } - - private static void writeStringTest_0(String label, String lineSeparator, byte[] extra) throws IOException { - String originalLineSeparator = System.getProperty("line.separator"); - try { - System.getProperties().put("line.separator", lineSeparator); - writeStringTest_1(label + ":mark", join(trademarkBytes), "\u2122"); - writeStringTest_1(label + ":mark NL", join(trademarkBytes, extra), "\u2122\n"); - writeStringTest_1(label + ":NL mark", join(extra, trademarkBytes), "\n\u2122"); - } finally { - System.getProperties().put("line.separator", originalLineSeparator); - } - } - - private static void writeStringTest_1(String label, byte[] wanted, String toWrite) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - UtilIO.writeString(baos, toWrite); - assertEquals("writeString default:" + label, wanted, baos.toByteArray()); - baos = new ByteArrayOutputStream(); - UtilIO.writeString(baos, "UTF-8", toWrite); - assertEquals("writeString UTF-8:" + label, wanted, baos.toByteArray()); - baos = new ByteArrayOutputStream(); - UtilIO.writeString(baos, UtilIO.UTF8, toWrite); - assertEquals("writeString UTF8:" + label, wanted, baos.toByteArray()); - } -} +/******************************************************************************* + * 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.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.test.GenericTestCaseBase; +import org.ofbiz.base.util.UtilIO; + +@SourceMonitored +public class UtilIOTests extends GenericTestCaseBase { + private static final byte[] trademarkBytes = new byte[] { + (byte) 0xE2, (byte) 0x84, (byte) 0xA2 + }; + public UtilIOTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testReadString() throws Exception { + readStringTest_0("unix line ending", "\n", new byte[] { 0x0A }); + readStringTest_0("mac line ending", "\r", new byte[] { 0x0D }); + readStringTest_0("windows line ending", "\r\n", new byte[] { 0x0D, 0x0A }); + } + + private static byte[] join(byte[]... parts) { + int count = 0; + for (byte[] part: parts) { + count += part.length; + } + byte[] result = new byte[count]; + int i = 0; + for (byte[] part: parts) { + System.arraycopy(part, 0, result, i, part.length); + i += part.length; + } + return result; + } + + private static void readStringTest_0(String label, String lineSeparator, byte[] extra) throws IOException { + String originalLineSeparator = System.getProperty("line.separator"); + try { + System.getProperties().put("line.separator", lineSeparator); + readStringTest_1(label + ":mark", "\u2122", join(trademarkBytes)); + readStringTest_1(label + ":mark NL", "\u2122\n", join(trademarkBytes, extra)); + readStringTest_1(label + ":NL mark", "\n\u2122", join(extra, trademarkBytes)); + } finally { + System.getProperties().put("line.separator", originalLineSeparator); + } + } + + private static void readStringTest_1(String label, String wanted, byte[] toRead) throws IOException { + assertEquals("readString bytes default:" + label, wanted, UtilIO.readString(toRead)); + assertEquals("readString bytes UTF-8:" + label, wanted, UtilIO.readString(toRead, "UTF-8")); + assertEquals("readString bytes UTF8:" + label, wanted, UtilIO.readString(toRead, UtilIO.UTF8)); + assertEquals("readString bytes offset/length default:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length)); + assertEquals("readString bytes offset/length UTF-8:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length, "UTF-8")); + assertEquals("readString bytes offset/length UTF8:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length, UtilIO.UTF8)); + assertEquals("readString stream default:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead))); + assertEquals("readString stream UTF-8:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead), "UTF-8")); + assertEquals("readString stream UTF8:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead), UtilIO.UTF8)); + } + + public void testWriteString() throws Exception { + writeStringTest_0("unix line ending", "\n", new byte[] { 0x0A }); + writeStringTest_0("mac line ending", "\r", new byte[] { 0x0D }); + writeStringTest_0("windows line ending", "\r\n", new byte[] { 0x0D, 0x0A }); + } + + private static void writeStringTest_0(String label, String lineSeparator, byte[] extra) throws IOException { + String originalLineSeparator = System.getProperty("line.separator"); + try { + System.getProperties().put("line.separator", lineSeparator); + writeStringTest_1(label + ":mark", join(trademarkBytes), "\u2122"); + writeStringTest_1(label + ":mark NL", join(trademarkBytes, extra), "\u2122\n"); + writeStringTest_1(label + ":NL mark", join(extra, trademarkBytes), "\n\u2122"); + } finally { + System.getProperties().put("line.separator", originalLineSeparator); + } + } + + private static void writeStringTest_1(String label, byte[] wanted, String toWrite) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UtilIO.writeString(baos, toWrite); + assertEquals("writeString default:" + label, wanted, baos.toByteArray()); + baos = new ByteArrayOutputStream(); + UtilIO.writeString(baos, "UTF-8", toWrite); + assertEquals("writeString UTF-8:" + label, wanted, baos.toByteArray()); + baos = new ByteArrayOutputStream(); + UtilIO.writeString(baos, UtilIO.UTF8, toWrite); + assertEquals("writeString UTF8:" + label, wanted, baos.toByteArray()); + } +} diff --git a/framework/base/src/org/ofbiz/base/util/test/UtilMiscTests.java b/framework/base/src/org/ofbiz/base/util/test/UtilMiscTests.java index ca29947987..a8e10d21bf 100644 --- a/framework/base/src/org/ofbiz/base/util/test/UtilMiscTests.java +++ b/framework/base/src/org/ofbiz/base/util/test/UtilMiscTests.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * 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.test; - -import java.util.List; -import java.util.Locale; - -import org.ofbiz.base.test.GenericTestCaseBase; -import org.ofbiz.base.util.UtilMisc; - -public class UtilMiscTests extends GenericTestCaseBase { - - public UtilMiscTests(String name) { - super(name); - } - - public void testLocales() throws Exception { - List availableLocales = UtilMisc.availableLocales(); - for (Locale availableLocale : availableLocales) { - if (availableLocale.getDisplayName().isEmpty()) { - fail("Locale.getDisplayName() is empty"); - } - } - } -} +/******************************************************************************* + * 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.test; + +import java.util.List; +import java.util.Locale; + +import org.ofbiz.base.test.GenericTestCaseBase; +import org.ofbiz.base.util.UtilMisc; + +public class UtilMiscTests extends GenericTestCaseBase { + + public UtilMiscTests(String name) { + super(name); + } + + public void testLocales() throws Exception { + List availableLocales = UtilMisc.availableLocales(); + for (Locale availableLocale : availableLocales) { + if (availableLocale.getDisplayName().isEmpty()) { + fail("Locale.getDisplayName() is empty"); + } + } + } +} diff --git a/framework/base/src/org/ofbiz/base/util/test/UtilObjectTests.java b/framework/base/src/org/ofbiz/base/util/test/UtilObjectTests.java index ab27d47f1e..24dca7760c 100644 --- a/framework/base/src/org/ofbiz/base/util/test/UtilObjectTests.java +++ b/framework/base/src/org/ofbiz/base/util/test/UtilObjectTests.java @@ -1,340 +1,340 @@ -/******************************************************************************* - * 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.test; - -import java.io.ByteArrayInputStream; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.HashMap; -import java.util.Set; - -import org.ofbiz.base.lang.Factory; -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.test.GenericTestCaseBase; -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.GroovyUtil; -import org.ofbiz.base.util.UtilObject; - -@SourceMonitored -public class UtilObjectTests extends GenericTestCaseBase { - public UtilObjectTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testStaticHelperClass() throws Exception { - assertStaticHelperClass(UtilObject.class); - } - - public static final class ErrorInjector extends FilterInputStream { - private int after; - private final boolean onClose; - - public ErrorInjector(InputStream in, boolean onClose) { - this(in, -1, onClose); - } - - public ErrorInjector(InputStream in, int after) { - this(in, after, false); - } - - public ErrorInjector(InputStream in, int after, boolean onClose) { - super(in); - this.after = after; - this.onClose = onClose; - } - - @Override - public int read() throws IOException { - if (after == 0) { - throw new IOException(); - } - if (after > 0) { - after--; - } - return super.read(); - } - - @Override - public int read(byte[] buf) throws IOException { - return read(buf, 0, buf.length); - } - - @Override - public int read(byte[] buf, int offset, int length) throws IOException { - if (after == 0) { - throw new IOException(); - } - if (after > 0) { - if (length > after) { - length = after; - } - int r = super.read(buf, offset, length); - after -= r; - return r; - } else { - return super.read(buf, offset, length); - } - } - - @Override - public void close() throws IOException { - if (onClose) { - throw new IOException(); - } - super.close(); - } - } - - public void testErrorInjector() throws Exception { - byte[] source = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; - InputStream in = new ErrorInjector(new ByteArrayInputStream(source), true); - byte[] result = new byte[source.length]; - int r = in.read(); - assertEquals("onClose, read short length", 2, in.read(new byte[2])); - assertNotSame("onClose, not read/eof", -1, r); - assertEquals("onClose, read length", source.length - 3, in.read(result, 3, result.length - 3)); - Exception caught = null; - try { - in.close(); - } catch (IOException e) { - caught = e; - } finally { - assertNotNull("onClose, exception", caught); - } - in = new ErrorInjector(new ByteArrayInputStream(source), 4); - result = new byte[source.length]; - r = in.read(); - assertNotSame("after, not read/eof", -1, r); - assertEquals("after, read short length", 2, in.read(result, 0, 2)); - assertEquals("after, read long length", 1, in.read(result, 3, result.length - 3)); - caught = null; - try { - in.read(result, 4, result.length - 4); - } catch (IOException e) { - caught = e; - } finally { - assertNotNull("read, buffer exception", caught); - } - caught = null; - try { - in.read(); - } catch (IOException e) { - caught = e; - } finally { - assertNotNull("read, singleton exception", caught); - } - in.close(); - } - - public void testGetBytes_Stream() { - boolean errorOn = Debug.isOn(Debug.ERROR); - try { - Debug.set(Debug.ERROR, false); - byte[] source = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; - byte[] result = UtilObject.getBytes(new ByteArrayInputStream(source)); - assertNotNull("initial result", result); - assertEquals("initial equals", source, result); - assertNull("error after read", UtilObject.getBytes(new ErrorInjector(new ByteArrayInputStream(source), 3))); - byte[] closeResult = UtilObject.getBytes(new ErrorInjector(new ByteArrayInputStream(source), true)); - assertNotNull("error on close", closeResult); - assertEquals("error on close equals", source, result); - Exception caught = null; - try { - UtilObject.getBytes(null); - } catch (NullPointerException e) { - caught = e; - } finally { - assertNotNull("null stream exception", caught); - } - } finally { - Debug.set(Debug.ERROR, errorOn); - } - } - - @SuppressWarnings("serial") - public static class SerializationInjector implements Serializable { - private boolean onRead; - private boolean onWrite; - - public SerializationInjector(boolean onRead, boolean onWrite) { - this.onRead = onRead; - this.onWrite = onWrite; - } - - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - onRead = stream.readBoolean(); - onWrite = stream.readBoolean(); - if (onRead) { - throw new IOException(); - } - } - - private void writeObject(ObjectOutputStream stream) throws IOException { - if (onWrite) { - throw new IOException(); - } - stream.writeBoolean(onRead); - stream.writeBoolean(onWrite); - } - } - - public void testGetBytes_Object() { - assertNotNull("long", UtilObject.getBytes(Long.valueOf(0))); - assertNotNull("injector good", UtilObject.getBytes(new SerializationInjector(false, false))); - boolean errorOn = Debug.isOn(Debug.ERROR); - try { - Debug.set(Debug.ERROR, false); - assertNull("injector bad", UtilObject.getBytes(new SerializationInjector(false, true))); - assertNull("long", UtilObject.getBytes(this)); - } finally { - Debug.set(Debug.ERROR, errorOn); - } - } - - public void testGetObject() { - Long one = Long.valueOf(1); - byte[] oneBytes = UtilObject.getBytes(one); - assertNotNull("oneBytes", oneBytes); - assertEquals("one getObject", one, UtilObject.getObject(oneBytes)); - boolean errorOn = Debug.isOn(Debug.ERROR); - try { - Debug.set(Debug.ERROR, false); - assertNull("parse empty array", UtilObject.getObject(new byte[0])); - - // simulate a ClassNotFoundException - Object groovySerializable = GroovyUtil.eval("class foo implements java.io.Serializable { }; return new foo()", new HashMap()); - byte[] groovySerializableBytes = UtilObject.getBytes(groovySerializable); - assertNotNull("groovySerializableBytes", groovySerializableBytes); - assertNull("groovyDeserializable", UtilObject.getObject(groovySerializableBytes)); - - byte[] injectorBytes = UtilObject.getBytes(new SerializationInjector(false, false)); - assertNotNull("injectorBytes good", injectorBytes); - assertNotNull("injector good", UtilObject.getObject(injectorBytes)); - injectorBytes = UtilObject.getBytes(new SerializationInjector(true, false)); - assertNotNull("injectorBytes bad", injectorBytes); - assertNull("injector bad", UtilObject.getObject(injectorBytes)); - } finally { - Debug.set(Debug.ERROR, errorOn); - } - } - - public void testGetByteCount() throws Exception { - assertNotSame("long", 0, UtilObject.getByteCount(Long.valueOf(0))); - Exception caught = null; - try { - UtilObject.getByteCount(this); - } catch (IOException e) { - caught = e; - } finally { - assertNotNull("exception thrown", caught); - } - } - - public void testEqualsHelper() { - assertTrue("a == a", UtilObject.equalsHelper(this, this)); - assertFalse("null == a", UtilObject.equalsHelper(null, this)); - assertFalse("a == null", UtilObject.equalsHelper(this, null)); - assertTrue("null == null", UtilObject.equalsHelper(null, null)); - assertTrue("map == map", UtilObject.equalsHelper(new HashMap(), new HashMap())); - assertFalse("map == this", UtilObject.equalsHelper(new HashMap(), this)); - assertFalse("this == map", UtilObject.equalsHelper(this, new HashMap())); - } - - public void testCompareToHelper() { - Long one = Long.valueOf(1); - Long two = Long.valueOf(2); - assertComparison("one <-> two", -1, UtilObject.compareToHelper(one, two)); - assertComparison("one <-> one", 0, UtilObject.compareToHelper(one, one)); - assertComparison("two <-> one", 1, UtilObject.compareToHelper(two, one)); - assertComparison("one <-> null", 1, UtilObject.compareToHelper(one, null)); - assertComparison("null <-> one", -1, UtilObject.compareToHelper(null, one)); - } - - public void testDoHashCode() throws Exception { - UtilObject.doHashCode(this); - UtilObject.doHashCode(null); - UtilObject.doHashCode(0); - UtilObject.doHashCode(new Object[] { this, Object.class }); - UtilObject.doHashCode(new Object[] { null, Object.class }); - UtilObject.doHashCode(new int[] { 1, 3 }); - } - - public interface TestFactoryIntf extends Factory> { - } - - public static class FirstTestFactory implements TestFactoryIntf { - public Object getInstance(Set set) { - if (!set.contains("first")) return null; - if (set.contains("one")) return "ONE"; - if (set.contains("two")) return "TWO"; - if (set.contains("three")) return "THREE"; - return null; - } - } - - public static class SecondTestFactory implements TestFactoryIntf { - public Object getInstance(Set set) { - if (!set.contains("second")) return null; - if (set.contains("ONE")) return "1"; - if (set.contains("TWO")) return "2"; - if (set.contains("THREE")) return "3"; - return null; - } - } - - public void testGetObjectFromFactory() throws Exception { - assertEquals("first one", "ONE", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "one"))); - assertEquals("first two", "TWO", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "two"))); - assertEquals("first three", "THREE", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "three"))); - assertEquals("first null", "1", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "second", "ONE"))); - assertEquals("second one", "1", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "ONE"))); - assertEquals("second two", "2", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "TWO"))); - assertEquals("second three", "3", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "THREE"))); - Exception caught = null; - try { - UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first")); - } catch (ClassNotFoundException e) { - caught = e; - } finally { - assertNotNull("nothing found first", caught); - } - caught = null; - try { - UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second")); - } catch (ClassNotFoundException e) { - caught = e; - } finally { - assertNotNull("nothing found second", caught); - } - } -} +/******************************************************************************* + * 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.test; + +import java.io.ByteArrayInputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Set; + +import org.ofbiz.base.lang.Factory; +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.test.GenericTestCaseBase; +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.GroovyUtil; +import org.ofbiz.base.util.UtilObject; + +@SourceMonitored +public class UtilObjectTests extends GenericTestCaseBase { + public UtilObjectTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testStaticHelperClass() throws Exception { + assertStaticHelperClass(UtilObject.class); + } + + public static final class ErrorInjector extends FilterInputStream { + private int after; + private final boolean onClose; + + public ErrorInjector(InputStream in, boolean onClose) { + this(in, -1, onClose); + } + + public ErrorInjector(InputStream in, int after) { + this(in, after, false); + } + + public ErrorInjector(InputStream in, int after, boolean onClose) { + super(in); + this.after = after; + this.onClose = onClose; + } + + @Override + public int read() throws IOException { + if (after == 0) { + throw new IOException(); + } + if (after > 0) { + after--; + } + return super.read(); + } + + @Override + public int read(byte[] buf) throws IOException { + return read(buf, 0, buf.length); + } + + @Override + public int read(byte[] buf, int offset, int length) throws IOException { + if (after == 0) { + throw new IOException(); + } + if (after > 0) { + if (length > after) { + length = after; + } + int r = super.read(buf, offset, length); + after -= r; + return r; + } else { + return super.read(buf, offset, length); + } + } + + @Override + public void close() throws IOException { + if (onClose) { + throw new IOException(); + } + super.close(); + } + } + + public void testErrorInjector() throws Exception { + byte[] source = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + InputStream in = new ErrorInjector(new ByteArrayInputStream(source), true); + byte[] result = new byte[source.length]; + int r = in.read(); + assertEquals("onClose, read short length", 2, in.read(new byte[2])); + assertNotSame("onClose, not read/eof", -1, r); + assertEquals("onClose, read length", source.length - 3, in.read(result, 3, result.length - 3)); + Exception caught = null; + try { + in.close(); + } catch (IOException e) { + caught = e; + } finally { + assertNotNull("onClose, exception", caught); + } + in = new ErrorInjector(new ByteArrayInputStream(source), 4); + result = new byte[source.length]; + r = in.read(); + assertNotSame("after, not read/eof", -1, r); + assertEquals("after, read short length", 2, in.read(result, 0, 2)); + assertEquals("after, read long length", 1, in.read(result, 3, result.length - 3)); + caught = null; + try { + in.read(result, 4, result.length - 4); + } catch (IOException e) { + caught = e; + } finally { + assertNotNull("read, buffer exception", caught); + } + caught = null; + try { + in.read(); + } catch (IOException e) { + caught = e; + } finally { + assertNotNull("read, singleton exception", caught); + } + in.close(); + } + + public void testGetBytes_Stream() { + boolean errorOn = Debug.isOn(Debug.ERROR); + try { + Debug.set(Debug.ERROR, false); + byte[] source = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + byte[] result = UtilObject.getBytes(new ByteArrayInputStream(source)); + assertNotNull("initial result", result); + assertEquals("initial equals", source, result); + assertNull("error after read", UtilObject.getBytes(new ErrorInjector(new ByteArrayInputStream(source), 3))); + byte[] closeResult = UtilObject.getBytes(new ErrorInjector(new ByteArrayInputStream(source), true)); + assertNotNull("error on close", closeResult); + assertEquals("error on close equals", source, result); + Exception caught = null; + try { + UtilObject.getBytes(null); + } catch (NullPointerException e) { + caught = e; + } finally { + assertNotNull("null stream exception", caught); + } + } finally { + Debug.set(Debug.ERROR, errorOn); + } + } + + @SuppressWarnings("serial") + public static class SerializationInjector implements Serializable { + private boolean onRead; + private boolean onWrite; + + public SerializationInjector(boolean onRead, boolean onWrite) { + this.onRead = onRead; + this.onWrite = onWrite; + } + + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + onRead = stream.readBoolean(); + onWrite = stream.readBoolean(); + if (onRead) { + throw new IOException(); + } + } + + private void writeObject(ObjectOutputStream stream) throws IOException { + if (onWrite) { + throw new IOException(); + } + stream.writeBoolean(onRead); + stream.writeBoolean(onWrite); + } + } + + public void testGetBytes_Object() { + assertNotNull("long", UtilObject.getBytes(Long.valueOf(0))); + assertNotNull("injector good", UtilObject.getBytes(new SerializationInjector(false, false))); + boolean errorOn = Debug.isOn(Debug.ERROR); + try { + Debug.set(Debug.ERROR, false); + assertNull("injector bad", UtilObject.getBytes(new SerializationInjector(false, true))); + assertNull("long", UtilObject.getBytes(this)); + } finally { + Debug.set(Debug.ERROR, errorOn); + } + } + + public void testGetObject() { + Long one = Long.valueOf(1); + byte[] oneBytes = UtilObject.getBytes(one); + assertNotNull("oneBytes", oneBytes); + assertEquals("one getObject", one, UtilObject.getObject(oneBytes)); + boolean errorOn = Debug.isOn(Debug.ERROR); + try { + Debug.set(Debug.ERROR, false); + assertNull("parse empty array", UtilObject.getObject(new byte[0])); + + // simulate a ClassNotFoundException + Object groovySerializable = GroovyUtil.eval("class foo implements java.io.Serializable { }; return new foo()", new HashMap()); + byte[] groovySerializableBytes = UtilObject.getBytes(groovySerializable); + assertNotNull("groovySerializableBytes", groovySerializableBytes); + assertNull("groovyDeserializable", UtilObject.getObject(groovySerializableBytes)); + + byte[] injectorBytes = UtilObject.getBytes(new SerializationInjector(false, false)); + assertNotNull("injectorBytes good", injectorBytes); + assertNotNull("injector good", UtilObject.getObject(injectorBytes)); + injectorBytes = UtilObject.getBytes(new SerializationInjector(true, false)); + assertNotNull("injectorBytes bad", injectorBytes); + assertNull("injector bad", UtilObject.getObject(injectorBytes)); + } finally { + Debug.set(Debug.ERROR, errorOn); + } + } + + public void testGetByteCount() throws Exception { + assertNotSame("long", 0, UtilObject.getByteCount(Long.valueOf(0))); + Exception caught = null; + try { + UtilObject.getByteCount(this); + } catch (IOException e) { + caught = e; + } finally { + assertNotNull("exception thrown", caught); + } + } + + public void testEqualsHelper() { + assertTrue("a == a", UtilObject.equalsHelper(this, this)); + assertFalse("null == a", UtilObject.equalsHelper(null, this)); + assertFalse("a == null", UtilObject.equalsHelper(this, null)); + assertTrue("null == null", UtilObject.equalsHelper(null, null)); + assertTrue("map == map", UtilObject.equalsHelper(new HashMap(), new HashMap())); + assertFalse("map == this", UtilObject.equalsHelper(new HashMap(), this)); + assertFalse("this == map", UtilObject.equalsHelper(this, new HashMap())); + } + + public void testCompareToHelper() { + Long one = Long.valueOf(1); + Long two = Long.valueOf(2); + assertComparison("one <-> two", -1, UtilObject.compareToHelper(one, two)); + assertComparison("one <-> one", 0, UtilObject.compareToHelper(one, one)); + assertComparison("two <-> one", 1, UtilObject.compareToHelper(two, one)); + assertComparison("one <-> null", 1, UtilObject.compareToHelper(one, null)); + assertComparison("null <-> one", -1, UtilObject.compareToHelper(null, one)); + } + + public void testDoHashCode() throws Exception { + UtilObject.doHashCode(this); + UtilObject.doHashCode(null); + UtilObject.doHashCode(0); + UtilObject.doHashCode(new Object[] { this, Object.class }); + UtilObject.doHashCode(new Object[] { null, Object.class }); + UtilObject.doHashCode(new int[] { 1, 3 }); + } + + public interface TestFactoryIntf extends Factory> { + } + + public static class FirstTestFactory implements TestFactoryIntf { + public Object getInstance(Set set) { + if (!set.contains("first")) return null; + if (set.contains("one")) return "ONE"; + if (set.contains("two")) return "TWO"; + if (set.contains("three")) return "THREE"; + return null; + } + } + + public static class SecondTestFactory implements TestFactoryIntf { + public Object getInstance(Set set) { + if (!set.contains("second")) return null; + if (set.contains("ONE")) return "1"; + if (set.contains("TWO")) return "2"; + if (set.contains("THREE")) return "3"; + return null; + } + } + + public void testGetObjectFromFactory() throws Exception { + assertEquals("first one", "ONE", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "one"))); + assertEquals("first two", "TWO", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "two"))); + assertEquals("first three", "THREE", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "three"))); + assertEquals("first null", "1", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "second", "ONE"))); + assertEquals("second one", "1", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "ONE"))); + assertEquals("second two", "2", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "TWO"))); + assertEquals("second three", "3", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "THREE"))); + Exception caught = null; + try { + UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first")); + } catch (ClassNotFoundException e) { + caught = e; + } finally { + assertNotNull("nothing found first", caught); + } + caught = null; + try { + UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second")); + } catch (ClassNotFoundException e) { + caught = e; + } finally { + assertNotNull("nothing found second", caught); + } + } +} diff --git a/framework/common/src/org/ofbiz/common/JsLanguageFileMappingCreator.java b/framework/common/src/org/ofbiz/common/JsLanguageFileMappingCreator.java index 2167f00480..be52ea701f 100644 --- a/framework/common/src/org/ofbiz/common/JsLanguageFileMappingCreator.java +++ b/framework/common/src/org/ofbiz/common/JsLanguageFileMappingCreator.java @@ -1,206 +1,206 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ - -package org.ofbiz.common; - -import java.io.File; -import java.io.StringWriter; -import java.io.Writer; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.commons.io.FileUtils; -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.FileUtil; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.template.FreeMarkerWorker; -import org.ofbiz.service.DispatchContext; -import org.ofbiz.service.ServiceUtil; - -// Use the createJsLanguageFileMapping service to create or update the JsLanguageFilesMapping.java. You will still need to compile thereafter - -public class JsLanguageFileMappingCreator { - - private static final String module = JsLanguageFileMappingCreator.class.getName(); - - public static Map createJsLanguageFileMapping(DispatchContext ctx, Map context) { - Map result = ServiceUtil.returnSuccess(); - String encoding = (String) context.get("encoding"); // default value: UTF-8 - - List localeList = UtilMisc.availableLocales(); - Map jQueryLocaleFile = new LinkedHashMap(); - Map dateJsLocaleFile = new LinkedHashMap(); - Map validationLocaleFile = new LinkedHashMap(); - Map dateTimePickerLocaleFile = new LinkedHashMap(); - - // setup some variables to locate the js files - String componentRoot = "component://images/webapp"; - String jqueryUiLocaleRelPath = "/images/jquery/ui/i18n/"; - String dateJsLocaleRelPath = "/images/jquery/plugins/datejs/"; - String validateRelPath = "/images/jquery/plugins/validate/localization/"; - String dateTimePickerJsLocaleRelPath = "/images/jquery/plugins/datetimepicker/localization/"; - String jsFilePostFix = ".js"; - String dateJsLocalePrefix = "date-"; - String validateLocalePrefix = "messages_"; - //String validateMethLocalePrefix = "methods__"; - String jqueryUiLocalePrefix = "jquery.ui.datepicker-"; - String dateTimePickerPrefix = "jquery-ui-timepicker-"; - String defaultLocaleDateJs = "en-US"; - String defaultLocaleJquery = "en"; // Beware to keep the OFBiz specific jquery.ui.datepicker-en.js file when upgrading... - - for (Locale locale : localeList) { - String displayCountry = locale.toString(); - String modifiedDisplayCountry = null; - String modifiedDisplayCountryForValidation = null; - if (displayCountry.contains("_")) { - modifiedDisplayCountry = displayCountry.replace("_", "-"); - modifiedDisplayCountryForValidation = displayCountry; // messages*.js use "_" not "-" as others - } else { - modifiedDisplayCountry = displayCountry; - } - - String strippedLocale = locale.getLanguage(); - - File file = null; - String fileUrl = null; - - /* - * Try to open the date-js language file - */ - String fileName = componentRoot + dateJsLocaleRelPath + dateJsLocalePrefix + modifiedDisplayCountry + jsFilePostFix; - file = FileUtil.getFile(fileName); - - if (file.exists()) { - fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + modifiedDisplayCountry + jsFilePostFix; - } else { - // Try to guess a language - String tmpLocale = strippedLocale + "-" + strippedLocale.toUpperCase(); - fileName = componentRoot + dateJsLocaleRelPath + dateJsLocalePrefix + tmpLocale + jsFilePostFix; - file = FileUtil.getFile(fileName); - if (file.exists()) { - fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + tmpLocale + jsFilePostFix; - } else { - // use language en-US as fallback - fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + defaultLocaleDateJs + jsFilePostFix; - } - } - dateJsLocaleFile.put(displayCountry, fileUrl); - - /* - * Try to open the jquery validation language file - */ - if (modifiedDisplayCountryForValidation != null) { // Try 1st lang_country - fileName = componentRoot + validateRelPath + validateLocalePrefix + modifiedDisplayCountryForValidation + jsFilePostFix; - file = FileUtil.getFile(fileName); - if (file.exists()) { - fileUrl = validateRelPath + validateLocalePrefix + modifiedDisplayCountryForValidation + jsFilePostFix; - } else { // lang only - fileName = componentRoot + validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix; - file = FileUtil.getFile(fileName); - if (file.exists()) { - fileUrl = validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix; - } else { - // use default language en as fallback - fileUrl = validateRelPath + validateLocalePrefix + defaultLocaleJquery + jsFilePostFix; - } - } - } else { // Then try lang only - fileName = componentRoot + validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix; - file = FileUtil.getFile(fileName); - if (file.exists()) { - fileUrl = validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix; - } else { - // use default language en as fallback - fileUrl = validateRelPath + validateLocalePrefix + defaultLocaleJquery + jsFilePostFix; - } - } - validationLocaleFile.put(displayCountry, fileUrl); - - /* - * Try to open the jquery timepicker language file - */ - fileName = componentRoot + jqueryUiLocaleRelPath + jqueryUiLocalePrefix + strippedLocale + jsFilePostFix; - file = FileUtil.getFile(fileName); - - if (file.exists()) { - fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + strippedLocale + jsFilePostFix; - } else { - // Try to guess a language - fileName = componentRoot + jqueryUiLocaleRelPath + jqueryUiLocalePrefix + modifiedDisplayCountry + jsFilePostFix; - file = FileUtil.getFile(fileName); - if (file.exists()) { - fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + modifiedDisplayCountry + jsFilePostFix; - } else { - // use default language en as fallback - fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + defaultLocaleJquery + jsFilePostFix; - } - } - jQueryLocaleFile.put(displayCountry, fileUrl); - - /* - * Try to open the datetimepicker language file - */ - fileName = componentRoot + dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + strippedLocale + jsFilePostFix; - file = FileUtil.getFile(fileName); - - if (file.exists()) { - fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + strippedLocale + jsFilePostFix; - } else { - // Try to guess a language - fileName = componentRoot + dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + modifiedDisplayCountry + jsFilePostFix; - file = FileUtil.getFile(fileName); - if (file.exists()) { - fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + modifiedDisplayCountry + jsFilePostFix; - } else { - // use default language en as fallback - fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + defaultLocaleJquery + jsFilePostFix; - } - } - dateTimePickerLocaleFile.put(displayCountry, fileUrl); - } - - // check the template file - String template = "framework/common/template/JsLanguageFilesMapping.ftl"; - String output = "framework/common/src/org/ofbiz/common/JsLanguageFilesMapping.java"; - Map mapWrapper = new HashMap(); - mapWrapper.put("datejs", dateJsLocaleFile); - mapWrapper.put("jquery", jQueryLocaleFile); - mapWrapper.put("validation", validationLocaleFile); - mapWrapper.put("dateTime", dateTimePickerLocaleFile); - - // some magic to create a new java file: render it as FTL - Writer writer = new StringWriter(); - try { - FreeMarkerWorker.renderTemplateAtLocation(template, mapWrapper, writer); - // write it as a Java file - File file = new File(output); - FileUtils.writeStringToFile(file, writer.toString(), encoding); - } - catch (Exception e) { - Debug.logError(e, module); - return ServiceUtil.returnError("The Outputfile could not be created: " + e.getMessage()); - } - - return result; - } - -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ + +package org.ofbiz.common; + +import java.io.File; +import java.io.StringWriter; +import java.io.Writer; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.apache.commons.io.FileUtils; +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.FileUtil; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.template.FreeMarkerWorker; +import org.ofbiz.service.DispatchContext; +import org.ofbiz.service.ServiceUtil; + +// Use the createJsLanguageFileMapping service to create or update the JsLanguageFilesMapping.java. You will still need to compile thereafter + +public class JsLanguageFileMappingCreator { + + private static final String module = JsLanguageFileMappingCreator.class.getName(); + + public static Map createJsLanguageFileMapping(DispatchContext ctx, Map context) { + Map result = ServiceUtil.returnSuccess(); + String encoding = (String) context.get("encoding"); // default value: UTF-8 + + List localeList = UtilMisc.availableLocales(); + Map jQueryLocaleFile = new LinkedHashMap(); + Map dateJsLocaleFile = new LinkedHashMap(); + Map validationLocaleFile = new LinkedHashMap(); + Map dateTimePickerLocaleFile = new LinkedHashMap(); + + // setup some variables to locate the js files + String componentRoot = "component://images/webapp"; + String jqueryUiLocaleRelPath = "/images/jquery/ui/i18n/"; + String dateJsLocaleRelPath = "/images/jquery/plugins/datejs/"; + String validateRelPath = "/images/jquery/plugins/validate/localization/"; + String dateTimePickerJsLocaleRelPath = "/images/jquery/plugins/datetimepicker/localization/"; + String jsFilePostFix = ".js"; + String dateJsLocalePrefix = "date-"; + String validateLocalePrefix = "messages_"; + //String validateMethLocalePrefix = "methods__"; + String jqueryUiLocalePrefix = "jquery.ui.datepicker-"; + String dateTimePickerPrefix = "jquery-ui-timepicker-"; + String defaultLocaleDateJs = "en-US"; + String defaultLocaleJquery = "en"; // Beware to keep the OFBiz specific jquery.ui.datepicker-en.js file when upgrading... + + for (Locale locale : localeList) { + String displayCountry = locale.toString(); + String modifiedDisplayCountry = null; + String modifiedDisplayCountryForValidation = null; + if (displayCountry.contains("_")) { + modifiedDisplayCountry = displayCountry.replace("_", "-"); + modifiedDisplayCountryForValidation = displayCountry; // messages*.js use "_" not "-" as others + } else { + modifiedDisplayCountry = displayCountry; + } + + String strippedLocale = locale.getLanguage(); + + File file = null; + String fileUrl = null; + + /* + * Try to open the date-js language file + */ + String fileName = componentRoot + dateJsLocaleRelPath + dateJsLocalePrefix + modifiedDisplayCountry + jsFilePostFix; + file = FileUtil.getFile(fileName); + + if (file.exists()) { + fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + modifiedDisplayCountry + jsFilePostFix; + } else { + // Try to guess a language + String tmpLocale = strippedLocale + "-" + strippedLocale.toUpperCase(); + fileName = componentRoot + dateJsLocaleRelPath + dateJsLocalePrefix + tmpLocale + jsFilePostFix; + file = FileUtil.getFile(fileName); + if (file.exists()) { + fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + tmpLocale + jsFilePostFix; + } else { + // use language en-US as fallback + fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + defaultLocaleDateJs + jsFilePostFix; + } + } + dateJsLocaleFile.put(displayCountry, fileUrl); + + /* + * Try to open the jquery validation language file + */ + if (modifiedDisplayCountryForValidation != null) { // Try 1st lang_country + fileName = componentRoot + validateRelPath + validateLocalePrefix + modifiedDisplayCountryForValidation + jsFilePostFix; + file = FileUtil.getFile(fileName); + if (file.exists()) { + fileUrl = validateRelPath + validateLocalePrefix + modifiedDisplayCountryForValidation + jsFilePostFix; + } else { // lang only + fileName = componentRoot + validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix; + file = FileUtil.getFile(fileName); + if (file.exists()) { + fileUrl = validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix; + } else { + // use default language en as fallback + fileUrl = validateRelPath + validateLocalePrefix + defaultLocaleJquery + jsFilePostFix; + } + } + } else { // Then try lang only + fileName = componentRoot + validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix; + file = FileUtil.getFile(fileName); + if (file.exists()) { + fileUrl = validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix; + } else { + // use default language en as fallback + fileUrl = validateRelPath + validateLocalePrefix + defaultLocaleJquery + jsFilePostFix; + } + } + validationLocaleFile.put(displayCountry, fileUrl); + + /* + * Try to open the jquery timepicker language file + */ + fileName = componentRoot + jqueryUiLocaleRelPath + jqueryUiLocalePrefix + strippedLocale + jsFilePostFix; + file = FileUtil.getFile(fileName); + + if (file.exists()) { + fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + strippedLocale + jsFilePostFix; + } else { + // Try to guess a language + fileName = componentRoot + jqueryUiLocaleRelPath + jqueryUiLocalePrefix + modifiedDisplayCountry + jsFilePostFix; + file = FileUtil.getFile(fileName); + if (file.exists()) { + fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + modifiedDisplayCountry + jsFilePostFix; + } else { + // use default language en as fallback + fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + defaultLocaleJquery + jsFilePostFix; + } + } + jQueryLocaleFile.put(displayCountry, fileUrl); + + /* + * Try to open the datetimepicker language file + */ + fileName = componentRoot + dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + strippedLocale + jsFilePostFix; + file = FileUtil.getFile(fileName); + + if (file.exists()) { + fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + strippedLocale + jsFilePostFix; + } else { + // Try to guess a language + fileName = componentRoot + dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + modifiedDisplayCountry + jsFilePostFix; + file = FileUtil.getFile(fileName); + if (file.exists()) { + fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + modifiedDisplayCountry + jsFilePostFix; + } else { + // use default language en as fallback + fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + defaultLocaleJquery + jsFilePostFix; + } + } + dateTimePickerLocaleFile.put(displayCountry, fileUrl); + } + + // check the template file + String template = "framework/common/template/JsLanguageFilesMapping.ftl"; + String output = "framework/common/src/org/ofbiz/common/JsLanguageFilesMapping.java"; + Map mapWrapper = new HashMap(); + mapWrapper.put("datejs", dateJsLocaleFile); + mapWrapper.put("jquery", jQueryLocaleFile); + mapWrapper.put("validation", validationLocaleFile); + mapWrapper.put("dateTime", dateTimePickerLocaleFile); + + // some magic to create a new java file: render it as FTL + Writer writer = new StringWriter(); + try { + FreeMarkerWorker.renderTemplateAtLocation(template, mapWrapper, writer); + // write it as a Java file + File file = new File(output); + FileUtils.writeStringToFile(file, writer.toString(), encoding); + } + catch (Exception e) { + Debug.logError(e, module); + return ServiceUtil.returnError("The Outputfile could not be created: " + e.getMessage()); + } + + return result; + } + +} diff --git a/framework/common/src/org/ofbiz/common/JsLanguageFilesMapping.java b/framework/common/src/org/ofbiz/common/JsLanguageFilesMapping.java index fc5d650e5c..25f16afb43 100644 --- a/framework/common/src/org/ofbiz/common/JsLanguageFilesMapping.java +++ b/framework/common/src/org/ofbiz/common/JsLanguageFilesMapping.java @@ -1,702 +1,702 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ - - -package org.ofbiz.common; - -import java.util.LinkedHashMap; -import java.util.Map; - - -public final class JsLanguageFilesMapping { - - // DO NOT EDIT THIS FILE! THIS IS AUTO GENERATED AND WILL GET WRITTEN OVER PERIODICALLY WHEN THE DATA CHANGE - // Rather use the createJsLanguageFileMapping service to create or update it. You will still need to compile thereafter - - public static class datejs { - - private static Map localeFiles = new LinkedHashMap(); - private static String defaultDateJs = "/images/jquery/plugins/datejs/date-en-US.js"; - - static { - localeFiles.put("sq", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("sq_AL", "/images/jquery/plugins/datejs/date-sq-AL.js"); - localeFiles.put("ar", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("ar_DZ", "/images/jquery/plugins/datejs/date-ar-DZ.js"); - localeFiles.put("ar_BH", "/images/jquery/plugins/datejs/date-ar-BH.js"); - localeFiles.put("ar_EG", "/images/jquery/plugins/datejs/date-ar-EG.js"); - localeFiles.put("ar_IQ", "/images/jquery/plugins/datejs/date-ar-IQ.js"); - localeFiles.put("ar_JO", "/images/jquery/plugins/datejs/date-ar-JO.js"); - localeFiles.put("ar_KW", "/images/jquery/plugins/datejs/date-ar-KW.js"); - localeFiles.put("ar_LB", "/images/jquery/plugins/datejs/date-ar-LB.js"); - localeFiles.put("ar_LY", "/images/jquery/plugins/datejs/date-ar-LY.js"); - localeFiles.put("ar_MA", "/images/jquery/plugins/datejs/date-ar-MA.js"); - localeFiles.put("ar_OM", "/images/jquery/plugins/datejs/date-ar-OM.js"); - localeFiles.put("ar_QA", "/images/jquery/plugins/datejs/date-ar-QA.js"); - localeFiles.put("ar_SA", "/images/jquery/plugins/datejs/date-ar-SA.js"); - localeFiles.put("ar_SD", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("ar_SY", "/images/jquery/plugins/datejs/date-ar-SY.js"); - localeFiles.put("ar_TN", "/images/jquery/plugins/datejs/date-ar-TN.js"); - localeFiles.put("ar_AE", "/images/jquery/plugins/datejs/date-ar-AE.js"); - localeFiles.put("ar_YE", "/images/jquery/plugins/datejs/date-ar-YE.js"); - localeFiles.put("be", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("be_BY", "/images/jquery/plugins/datejs/date-be-BY.js"); - localeFiles.put("bg", "/images/jquery/plugins/datejs/date-bg-BG.js"); - localeFiles.put("bg_BG", "/images/jquery/plugins/datejs/date-bg-BG.js"); - localeFiles.put("ca", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("ca_ES", "/images/jquery/plugins/datejs/date-ca-ES.js"); - localeFiles.put("zh", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("zh_CN", "/images/jquery/plugins/datejs/date-zh-CN.js"); - localeFiles.put("zh_HK", "/images/jquery/plugins/datejs/date-zh-HK.js"); - localeFiles.put("zh_SG", "/images/jquery/plugins/datejs/date-zh-SG.js"); - localeFiles.put("zh_TW", "/images/jquery/plugins/datejs/date-zh-TW.js"); - localeFiles.put("hr", "/images/jquery/plugins/datejs/date-hr-HR.js"); - localeFiles.put("hr_HR", "/images/jquery/plugins/datejs/date-hr-HR.js"); - localeFiles.put("cs", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("cs_CZ", "/images/jquery/plugins/datejs/date-cs-CZ.js"); - localeFiles.put("da", "/images/jquery/plugins/datejs/date-da-DA.js"); - localeFiles.put("da_DK", "/images/jquery/plugins/datejs/date-da-DK.js"); - localeFiles.put("nl", "/images/jquery/plugins/datejs/date-nl-NL.js"); - localeFiles.put("nl_BE", "/images/jquery/plugins/datejs/date-nl-BE.js"); - localeFiles.put("nl_NL", "/images/jquery/plugins/datejs/date-nl-NL.js"); - localeFiles.put("en", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("en_AU", "/images/jquery/plugins/datejs/date-en-AU.js"); - localeFiles.put("en_CA", "/images/jquery/plugins/datejs/date-en-CA.js"); - localeFiles.put("en_IN", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("en_IE", "/images/jquery/plugins/datejs/date-en-IE.js"); - localeFiles.put("en_MT", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("en_NZ", "/images/jquery/plugins/datejs/date-en-NZ.js"); - localeFiles.put("en_PH", "/images/jquery/plugins/datejs/date-en-PH.js"); - localeFiles.put("en_SG", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("en_ZA", "/images/jquery/plugins/datejs/date-en-ZA.js"); - localeFiles.put("en_GB", "/images/jquery/plugins/datejs/date-en-GB.js"); - localeFiles.put("en_US", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("et", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("et_EE", "/images/jquery/plugins/datejs/date-et-EE.js"); - localeFiles.put("fi", "/images/jquery/plugins/datejs/date-fi-FI.js"); - localeFiles.put("fi_FI", "/images/jquery/plugins/datejs/date-fi-FI.js"); - localeFiles.put("fr", "/images/jquery/plugins/datejs/date-fr-FR.js"); - localeFiles.put("fr_BE", "/images/jquery/plugins/datejs/date-fr-BE.js"); - localeFiles.put("fr_CA", "/images/jquery/plugins/datejs/date-fr-CA.js"); - localeFiles.put("fr_FR", "/images/jquery/plugins/datejs/date-fr-FR.js"); - localeFiles.put("fr_LU", "/images/jquery/plugins/datejs/date-fr-LU.js"); - localeFiles.put("fr_CH", "/images/jquery/plugins/datejs/date-fr-CH.js"); - localeFiles.put("de", "/images/jquery/plugins/datejs/date-de-DE.js"); - localeFiles.put("de_AT", "/images/jquery/plugins/datejs/date-de-AT.js"); - localeFiles.put("de_DE", "/images/jquery/plugins/datejs/date-de-DE.js"); - localeFiles.put("de_LU", "/images/jquery/plugins/datejs/date-de-LU.js"); - localeFiles.put("de_CH", "/images/jquery/plugins/datejs/date-de-CH.js"); - localeFiles.put("el", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("el_CY", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("el_GR", "/images/jquery/plugins/datejs/date-el-GR.js"); - localeFiles.put("iw", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("iw_IL", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("hi_IN", "/images/jquery/plugins/datejs/date-hi-IN.js"); - localeFiles.put("hu", "/images/jquery/plugins/datejs/date-hu-HU.js"); - localeFiles.put("hu_HU", "/images/jquery/plugins/datejs/date-hu-HU.js"); - localeFiles.put("is", "/images/jquery/plugins/datejs/date-is-IS.js"); - localeFiles.put("is_IS", "/images/jquery/plugins/datejs/date-is-IS.js"); - localeFiles.put("in", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("in_ID", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("ga", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("ga_IE", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("it", "/images/jquery/plugins/datejs/date-it-IT.js"); - localeFiles.put("it_IT", "/images/jquery/plugins/datejs/date-it-IT.js"); - localeFiles.put("it_CH", "/images/jquery/plugins/datejs/date-it-CH.js"); - localeFiles.put("ja", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("ja_JP", "/images/jquery/plugins/datejs/date-ja-JP.js"); - localeFiles.put("ja_JP_JP", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("ko", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("ko_KR", "/images/jquery/plugins/datejs/date-ko-KR.js"); - localeFiles.put("lv", "/images/jquery/plugins/datejs/date-lv-LV.js"); - localeFiles.put("lv_LV", "/images/jquery/plugins/datejs/date-lv-LV.js"); - localeFiles.put("lt", "/images/jquery/plugins/datejs/date-lt-LT.js"); - localeFiles.put("lt_LT", "/images/jquery/plugins/datejs/date-lt-LT.js"); - localeFiles.put("mk", "/images/jquery/plugins/datejs/date-mk-MK.js"); - localeFiles.put("mk_MK", "/images/jquery/plugins/datejs/date-mk-MK.js"); - localeFiles.put("ms", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("ms_MY", "/images/jquery/plugins/datejs/date-ms-MY.js"); - localeFiles.put("mt", "/images/jquery/plugins/datejs/date-mt-MT.js"); - localeFiles.put("mt_MT", "/images/jquery/plugins/datejs/date-mt-MT.js"); - localeFiles.put("no", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("no_NO", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("no_NO_NY", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("pl", "/images/jquery/plugins/datejs/date-pl-PL.js"); - localeFiles.put("pl_PL", "/images/jquery/plugins/datejs/date-pl-PL.js"); - localeFiles.put("pt", "/images/jquery/plugins/datejs/date-pt-PT.js"); - localeFiles.put("pt_BR", "/images/jquery/plugins/datejs/date-pt-BR.js"); - localeFiles.put("pt_PT", "/images/jquery/plugins/datejs/date-pt-PT.js"); - localeFiles.put("ro", "/images/jquery/plugins/datejs/date-ro-RO.js"); - localeFiles.put("ro_RO", "/images/jquery/plugins/datejs/date-ro-RO.js"); - localeFiles.put("ru", "/images/jquery/plugins/datejs/date-ru-RU.js"); - localeFiles.put("ru_RU", "/images/jquery/plugins/datejs/date-ru-RU.js"); - localeFiles.put("sr", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("sr_BA", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("sr_ME", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("sr_CS", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("sr_RS", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("sk", "/images/jquery/plugins/datejs/date-sk-SK.js"); - localeFiles.put("sk_SK", "/images/jquery/plugins/datejs/date-sk-SK.js"); - localeFiles.put("sl", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("sl_SI", "/images/jquery/plugins/datejs/date-sl-SI.js"); - localeFiles.put("es", "/images/jquery/plugins/datejs/date-es-ES.js"); - localeFiles.put("es_AR", "/images/jquery/plugins/datejs/date-es-AR.js"); - localeFiles.put("es_BO", "/images/jquery/plugins/datejs/date-es-BO.js"); - localeFiles.put("es_CL", "/images/jquery/plugins/datejs/date-es-CL.js"); - localeFiles.put("es_CO", "/images/jquery/plugins/datejs/date-es-CO.js"); - localeFiles.put("es_CR", "/images/jquery/plugins/datejs/date-es-CR.js"); - localeFiles.put("es_DO", "/images/jquery/plugins/datejs/date-es-DO.js"); - localeFiles.put("es_EC", "/images/jquery/plugins/datejs/date-es-EC.js"); - localeFiles.put("es_SV", "/images/jquery/plugins/datejs/date-es-SV.js"); - localeFiles.put("es_GT", "/images/jquery/plugins/datejs/date-es-GT.js"); - localeFiles.put("es_HN", "/images/jquery/plugins/datejs/date-es-HN.js"); - localeFiles.put("es_MX", "/images/jquery/plugins/datejs/date-es-MX.js"); - localeFiles.put("es_NI", "/images/jquery/plugins/datejs/date-es-NI.js"); - localeFiles.put("es_PA", "/images/jquery/plugins/datejs/date-es-PA.js"); - localeFiles.put("es_PY", "/images/jquery/plugins/datejs/date-es-PY.js"); - localeFiles.put("es_PE", "/images/jquery/plugins/datejs/date-es-PE.js"); - localeFiles.put("es_PR", "/images/jquery/plugins/datejs/date-es-PR.js"); - localeFiles.put("es_ES", "/images/jquery/plugins/datejs/date-es-ES.js"); - localeFiles.put("es_US", "/images/jquery/plugins/datejs/date-es-ES.js"); - localeFiles.put("es_UY", "/images/jquery/plugins/datejs/date-es-UY.js"); - localeFiles.put("es_VE", "/images/jquery/plugins/datejs/date-es-VE.js"); - localeFiles.put("sv", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("sv_SE", "/images/jquery/plugins/datejs/date-sv-SE.js"); - localeFiles.put("th", "/images/jquery/plugins/datejs/date-th-TH.js"); - localeFiles.put("th_TH", "/images/jquery/plugins/datejs/date-th-TH.js"); - localeFiles.put("th_TH_TH", "/images/jquery/plugins/datejs/date-th-TH.js"); - localeFiles.put("tr", "/images/jquery/plugins/datejs/date-tr-TR.js"); - localeFiles.put("tr_TR", "/images/jquery/plugins/datejs/date-tr-TR.js"); - localeFiles.put("uk", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("uk_UA", "/images/jquery/plugins/datejs/date-uk-UA.js"); - localeFiles.put("vi", "/images/jquery/plugins/datejs/date-en-US.js"); - localeFiles.put("vi_VN", "/images/jquery/plugins/datejs/date-vi-VN.js"); - } - - public static String getFilePath(String locale) { - if (datejs.localeFiles.containsKey(locale)) { - return datejs.localeFiles.get(locale); - } - return datejs.defaultDateJs; - } - - } - - public static class jquery { - private static Map localeFiles = new LinkedHashMap(); - private static String defaultDateJs = "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"; - - static { - localeFiles.put("sq", "/images/jquery/ui/i18n/jquery.ui.datepicker-sq.js"); - localeFiles.put("sq_AL", "/images/jquery/ui/i18n/jquery.ui.datepicker-sq.js"); - localeFiles.put("ar", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_DZ", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_BH", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_EG", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_IQ", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_JO", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_KW", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_LB", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_LY", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_MA", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_OM", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_QA", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_SA", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_SD", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_SY", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_TN", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_AE", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("ar_YE", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); - localeFiles.put("be", "/images/jquery/ui/i18n/jquery.ui.datepicker-be.js"); - localeFiles.put("be_BY", "/images/jquery/ui/i18n/jquery.ui.datepicker-be.js"); - localeFiles.put("bg", "/images/jquery/ui/i18n/jquery.ui.datepicker-bg.js"); - localeFiles.put("bg_BG", "/images/jquery/ui/i18n/jquery.ui.datepicker-bg.js"); - localeFiles.put("ca", "/images/jquery/ui/i18n/jquery.ui.datepicker-ca.js"); - localeFiles.put("ca_ES", "/images/jquery/ui/i18n/jquery.ui.datepicker-ca.js"); - localeFiles.put("zh", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("zh_CN", "/images/jquery/ui/i18n/jquery.ui.datepicker-zh-CN.js"); - localeFiles.put("zh_HK", "/images/jquery/ui/i18n/jquery.ui.datepicker-zh-HK.js"); - localeFiles.put("zh_SG", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("zh_TW", "/images/jquery/ui/i18n/jquery.ui.datepicker-zh-TW.js"); - localeFiles.put("hr", "/images/jquery/ui/i18n/jquery.ui.datepicker-hr.js"); - localeFiles.put("hr_HR", "/images/jquery/ui/i18n/jquery.ui.datepicker-hr.js"); - localeFiles.put("cs", "/images/jquery/ui/i18n/jquery.ui.datepicker-cs.js"); - localeFiles.put("cs_CZ", "/images/jquery/ui/i18n/jquery.ui.datepicker-cs.js"); - localeFiles.put("da", "/images/jquery/ui/i18n/jquery.ui.datepicker-da.js"); - localeFiles.put("da_DK", "/images/jquery/ui/i18n/jquery.ui.datepicker-da.js"); - localeFiles.put("nl", "/images/jquery/ui/i18n/jquery.ui.datepicker-nl.js"); - localeFiles.put("nl_BE", "/images/jquery/ui/i18n/jquery.ui.datepicker-nl.js"); - localeFiles.put("nl_NL", "/images/jquery/ui/i18n/jquery.ui.datepicker-nl.js"); - localeFiles.put("en", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_AU", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_CA", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_IN", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_IE", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_MT", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_NZ", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_PH", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_SG", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_ZA", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_GB", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("en_US", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("et", "/images/jquery/ui/i18n/jquery.ui.datepicker-et.js"); - localeFiles.put("et_EE", "/images/jquery/ui/i18n/jquery.ui.datepicker-et.js"); - localeFiles.put("fi", "/images/jquery/ui/i18n/jquery.ui.datepicker-fi.js"); - localeFiles.put("fi_FI", "/images/jquery/ui/i18n/jquery.ui.datepicker-fi.js"); - localeFiles.put("fr", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); - localeFiles.put("fr_BE", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); - localeFiles.put("fr_CA", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); - localeFiles.put("fr_FR", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); - localeFiles.put("fr_LU", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); - localeFiles.put("fr_CH", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); - localeFiles.put("de", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js"); - localeFiles.put("de_AT", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js"); - localeFiles.put("de_DE", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js"); - localeFiles.put("de_LU", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js"); - localeFiles.put("de_CH", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js"); - localeFiles.put("el", "/images/jquery/ui/i18n/jquery.ui.datepicker-el.js"); - localeFiles.put("el_CY", "/images/jquery/ui/i18n/jquery.ui.datepicker-el.js"); - localeFiles.put("el_GR", "/images/jquery/ui/i18n/jquery.ui.datepicker-el.js"); - localeFiles.put("iw", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("iw_IL", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("hi_IN", "/images/jquery/ui/i18n/jquery.ui.datepicker-hi.js"); - localeFiles.put("hu", "/images/jquery/ui/i18n/jquery.ui.datepicker-hu.js"); - localeFiles.put("hu_HU", "/images/jquery/ui/i18n/jquery.ui.datepicker-hu.js"); - localeFiles.put("is", "/images/jquery/ui/i18n/jquery.ui.datepicker-is.js"); - localeFiles.put("is_IS", "/images/jquery/ui/i18n/jquery.ui.datepicker-is.js"); - localeFiles.put("in", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("in_ID", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("ga", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("ga_IE", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("it", "/images/jquery/ui/i18n/jquery.ui.datepicker-it.js"); - localeFiles.put("it_IT", "/images/jquery/ui/i18n/jquery.ui.datepicker-it.js"); - localeFiles.put("it_CH", "/images/jquery/ui/i18n/jquery.ui.datepicker-it.js"); - localeFiles.put("ja", "/images/jquery/ui/i18n/jquery.ui.datepicker-ja.js"); - localeFiles.put("ja_JP", "/images/jquery/ui/i18n/jquery.ui.datepicker-ja.js"); - localeFiles.put("ja_JP_JP", "/images/jquery/ui/i18n/jquery.ui.datepicker-ja.js"); - localeFiles.put("ko", "/images/jquery/ui/i18n/jquery.ui.datepicker-ko.js"); - localeFiles.put("ko_KR", "/images/jquery/ui/i18n/jquery.ui.datepicker-ko.js"); - localeFiles.put("lv", "/images/jquery/ui/i18n/jquery.ui.datepicker-lv.js"); - localeFiles.put("lv_LV", "/images/jquery/ui/i18n/jquery.ui.datepicker-lv.js"); - localeFiles.put("lt", "/images/jquery/ui/i18n/jquery.ui.datepicker-lt.js"); - localeFiles.put("lt_LT", "/images/jquery/ui/i18n/jquery.ui.datepicker-lt.js"); - localeFiles.put("mk", "/images/jquery/ui/i18n/jquery.ui.datepicker-mk.js"); - localeFiles.put("mk_MK", "/images/jquery/ui/i18n/jquery.ui.datepicker-mk.js"); - localeFiles.put("ms", "/images/jquery/ui/i18n/jquery.ui.datepicker-ms.js"); - localeFiles.put("ms_MY", "/images/jquery/ui/i18n/jquery.ui.datepicker-ms.js"); - localeFiles.put("mt", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("mt_MT", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); - localeFiles.put("no", "/images/jquery/ui/i18n/jquery.ui.datepicker-no.js"); - localeFiles.put("no_NO", "/images/jquery/ui/i18n/jquery.ui.datepicker-no.js"); - localeFiles.put("no_NO_NY", "/images/jquery/ui/i18n/jquery.ui.datepicker-no.js"); - localeFiles.put("pl", "/images/jquery/ui/i18n/jquery.ui.datepicker-pl.js"); - localeFiles.put("pl_PL", "/images/jquery/ui/i18n/jquery.ui.datepicker-pl.js"); - localeFiles.put("pt", "/images/jquery/ui/i18n/jquery.ui.datepicker-pt.js"); - localeFiles.put("pt_BR", "/images/jquery/ui/i18n/jquery.ui.datepicker-pt.js"); - localeFiles.put("pt_PT", "/images/jquery/ui/i18n/jquery.ui.datepicker-pt.js"); - localeFiles.put("ro", "/images/jquery/ui/i18n/jquery.ui.datepicker-ro.js"); - localeFiles.put("ro_RO", "/images/jquery/ui/i18n/jquery.ui.datepicker-ro.js"); - localeFiles.put("ru", "/images/jquery/ui/i18n/jquery.ui.datepicker-ru.js"); - localeFiles.put("ru_RU", "/images/jquery/ui/i18n/jquery.ui.datepicker-ru.js"); - localeFiles.put("sr", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js"); - localeFiles.put("sr_BA", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js"); - localeFiles.put("sr_ME", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js"); - localeFiles.put("sr_CS", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js"); - localeFiles.put("sr_RS", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js"); - localeFiles.put("sk", "/images/jquery/ui/i18n/jquery.ui.datepicker-sk.js"); - localeFiles.put("sk_SK", "/images/jquery/ui/i18n/jquery.ui.datepicker-sk.js"); - localeFiles.put("sl", "/images/jquery/ui/i18n/jquery.ui.datepicker-sl.js"); - localeFiles.put("sl_SI", "/images/jquery/ui/i18n/jquery.ui.datepicker-sl.js"); - localeFiles.put("es", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_AR", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_BO", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_CL", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_CO", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_CR", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_DO", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_EC", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_SV", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_GT", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_HN", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_MX", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_NI", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_PA", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_PY", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_PE", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_PR", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_ES", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_US", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_UY", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("es_VE", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); - localeFiles.put("sv", "/images/jquery/ui/i18n/jquery.ui.datepicker-sv.js"); - localeFiles.put("sv_SE", "/images/jquery/ui/i18n/jquery.ui.datepicker-sv.js"); - localeFiles.put("th", "/images/jquery/ui/i18n/jquery.ui.datepicker-th.js"); - localeFiles.put("th_TH", "/images/jquery/ui/i18n/jquery.ui.datepicker-th.js"); - localeFiles.put("th_TH_TH", "/images/jquery/ui/i18n/jquery.ui.datepicker-th.js"); - localeFiles.put("tr", "/images/jquery/ui/i18n/jquery.ui.datepicker-tr.js"); - localeFiles.put("tr_TR", "/images/jquery/ui/i18n/jquery.ui.datepicker-tr.js"); - localeFiles.put("uk", "/images/jquery/ui/i18n/jquery.ui.datepicker-uk.js"); - localeFiles.put("uk_UA", "/images/jquery/ui/i18n/jquery.ui.datepicker-uk.js"); - localeFiles.put("vi", "/images/jquery/ui/i18n/jquery.ui.datepicker-vi.js"); - localeFiles.put("vi_VN", "/images/jquery/ui/i18n/jquery.ui.datepicker-vi.js"); - } - - public static String getFilePath(String locale) { - if (datejs.localeFiles.containsKey(locale)) { - return jquery.localeFiles.get(locale); - } - return jquery.defaultDateJs; - } - - } - - public static class validation { - private static Map localeFiles = new LinkedHashMap(); - private static String defaultValidation = "/images/webapp/images/jquery/plugins/validate/localization/messages_en.js"; - - static { - localeFiles.put("sq", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("sq_AL", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("ar", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_DZ", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_BH", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_EG", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_IQ", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_JO", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_KW", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_LB", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_LY", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_MA", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_OM", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_QA", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_SA", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_SD", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_SY", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_TN", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_AE", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("ar_YE", "/images/jquery/plugins/validate/localization/messages_ar.js"); - localeFiles.put("be", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("be_BY", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("bg", "/images/jquery/plugins/validate/localization/messages_bg.js"); - localeFiles.put("bg_BG", "/images/jquery/plugins/validate/localization/messages_bg.js"); - localeFiles.put("ca", "/images/jquery/plugins/validate/localization/messages_ca.js"); - localeFiles.put("ca_ES", "/images/jquery/plugins/validate/localization/messages_ca.js"); - localeFiles.put("zh", "/images/jquery/plugins/validate/localization/messages_zh.js"); - localeFiles.put("zh_CN", "/images/jquery/plugins/validate/localization/messages_zh.js"); - localeFiles.put("zh_HK", "/images/jquery/plugins/validate/localization/messages_zh.js"); - localeFiles.put("zh_SG", "/images/jquery/plugins/validate/localization/messages_zh.js"); - localeFiles.put("zh_TW", "/images/jquery/plugins/validate/localization/messages_zh_TW.js"); - localeFiles.put("hr", "/images/jquery/plugins/validate/localization/messages_hr.js"); - localeFiles.put("hr_HR", "/images/jquery/plugins/validate/localization/messages_hr.js"); - localeFiles.put("cs", "/images/jquery/plugins/validate/localization/messages_cs.js"); - localeFiles.put("cs_CZ", "/images/jquery/plugins/validate/localization/messages_cs.js"); - localeFiles.put("da", "/images/jquery/plugins/validate/localization/messages_da.js"); - localeFiles.put("da_DK", "/images/jquery/plugins/validate/localization/messages_da.js"); - localeFiles.put("nl", "/images/jquery/plugins/validate/localization/messages_nl.js"); - localeFiles.put("nl_BE", "/images/jquery/plugins/validate/localization/messages_nl.js"); - localeFiles.put("nl_NL", "/images/jquery/plugins/validate/localization/messages_nl.js"); - localeFiles.put("en", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_AU", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_CA", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_IN", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_IE", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_MT", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_NZ", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_PH", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_SG", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_ZA", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_GB", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("en_US", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("et", "/images/jquery/plugins/validate/localization/messages_et.js"); - localeFiles.put("et_EE", "/images/jquery/plugins/validate/localization/messages_et.js"); - localeFiles.put("fi", "/images/jquery/plugins/validate/localization/messages_fi.js"); - localeFiles.put("fi_FI", "/images/jquery/plugins/validate/localization/messages_fi.js"); - localeFiles.put("fr", "/images/jquery/plugins/validate/localization/messages_fr.js"); - localeFiles.put("fr_BE", "/images/jquery/plugins/validate/localization/messages_fr.js"); - localeFiles.put("fr_CA", "/images/jquery/plugins/validate/localization/messages_fr.js"); - localeFiles.put("fr_FR", "/images/jquery/plugins/validate/localization/messages_fr.js"); - localeFiles.put("fr_LU", "/images/jquery/plugins/validate/localization/messages_fr.js"); - localeFiles.put("fr_CH", "/images/jquery/plugins/validate/localization/messages_fr.js"); - localeFiles.put("de", "/images/jquery/plugins/validate/localization/messages_de.js"); - localeFiles.put("de_AT", "/images/jquery/plugins/validate/localization/messages_de.js"); - localeFiles.put("de_DE", "/images/jquery/plugins/validate/localization/messages_de.js"); - localeFiles.put("de_LU", "/images/jquery/plugins/validate/localization/messages_de.js"); - localeFiles.put("de_CH", "/images/jquery/plugins/validate/localization/messages_de.js"); - localeFiles.put("el", "/images/jquery/plugins/validate/localization/messages_el.js"); - localeFiles.put("el_CY", "/images/jquery/plugins/validate/localization/messages_el.js"); - localeFiles.put("el_GR", "/images/jquery/plugins/validate/localization/messages_el.js"); - localeFiles.put("iw", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("iw_IL", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("hi_IN", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("hu", "/images/jquery/plugins/validate/localization/messages_hu.js"); - localeFiles.put("hu_HU", "/images/jquery/plugins/validate/localization/messages_hu.js"); - localeFiles.put("is", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("is_IS", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("in", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("in_ID", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("ga", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("ga_IE", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("it", "/images/jquery/plugins/validate/localization/messages_it.js"); - localeFiles.put("it_IT", "/images/jquery/plugins/validate/localization/messages_it.js"); - localeFiles.put("it_CH", "/images/jquery/plugins/validate/localization/messages_it.js"); - localeFiles.put("ja", "/images/jquery/plugins/validate/localization/messages_ja.js"); - localeFiles.put("ja_JP", "/images/jquery/plugins/validate/localization/messages_ja.js"); - localeFiles.put("ja_JP_JP", "/images/jquery/plugins/validate/localization/messages_ja.js"); - localeFiles.put("ko", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("ko_KR", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("lv", "/images/jquery/plugins/validate/localization/messages_lv.js"); - localeFiles.put("lv_LV", "/images/jquery/plugins/validate/localization/messages_lv.js"); - localeFiles.put("lt", "/images/jquery/plugins/validate/localization/messages_lt.js"); - localeFiles.put("lt_LT", "/images/jquery/plugins/validate/localization/messages_lt.js"); - localeFiles.put("mk", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("mk_MK", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("ms", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("ms_MY", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("mt", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("mt_MT", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("no", "/images/jquery/plugins/validate/localization/messages_no.js"); - localeFiles.put("no_NO", "/images/jquery/plugins/validate/localization/messages_no.js"); - localeFiles.put("no_NO_NY", "/images/jquery/plugins/validate/localization/messages_no.js"); - localeFiles.put("pl", "/images/jquery/plugins/validate/localization/messages_pl.js"); - localeFiles.put("pl_PL", "/images/jquery/plugins/validate/localization/messages_pl.js"); - localeFiles.put("pt", "/images/jquery/plugins/validate/localization/messages_en.js"); - localeFiles.put("pt_BR", "/images/jquery/plugins/validate/localization/messages_pt_BR.js"); - localeFiles.put("pt_PT", "/images/jquery/plugins/validate/localization/messages_pt_PT.js"); - localeFiles.put("ro", "/images/jquery/plugins/validate/localization/messages_ro.js"); - localeFiles.put("ro_RO", "/images/jquery/plugins/validate/localization/messages_ro.js"); - localeFiles.put("ru", "/images/jquery/plugins/validate/localization/messages_ru.js"); - localeFiles.put("ru_RU", "/images/jquery/plugins/validate/localization/messages_ru.js"); - localeFiles.put("sr", "/images/jquery/plugins/validate/localization/messages_sr.js"); - localeFiles.put("sr_BA", "/images/jquery/plugins/validate/localization/messages_sr.js"); - localeFiles.put("sr_ME", "/images/jquery/plugins/validate/localization/messages_sr.js"); - localeFiles.put("sr_CS", "/images/jquery/plugins/validate/localization/messages_sr.js"); - localeFiles.put("sr_RS", "/images/jquery/plugins/validate/localization/messages_sr.js"); - localeFiles.put("sk", "/images/jquery/plugins/validate/localization/messages_sk.js"); - localeFiles.put("sk_SK", "/images/jquery/plugins/validate/localization/messages_sk.js"); - localeFiles.put("sl", "/images/jquery/plugins/validate/localization/messages_sl.js"); - localeFiles.put("sl_SI", "/images/jquery/plugins/validate/localization/messages_sl.js"); - localeFiles.put("es", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_AR", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_BO", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_CL", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_CO", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_CR", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_DO", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_EC", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_SV", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_GT", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_HN", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_MX", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_NI", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_PA", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_PY", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_PE", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_PR", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_ES", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_US", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_UY", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("es_VE", "/images/jquery/plugins/validate/localization/messages_es.js"); - localeFiles.put("sv", "/images/jquery/plugins/validate/localization/messages_sv.js"); - localeFiles.put("sv_SE", "/images/jquery/plugins/validate/localization/messages_sv.js"); - localeFiles.put("th", "/images/jquery/plugins/validate/localization/messages_th.js"); - localeFiles.put("th_TH", "/images/jquery/plugins/validate/localization/messages_th.js"); - localeFiles.put("th_TH_TH", "/images/jquery/plugins/validate/localization/messages_th.js"); - localeFiles.put("tr", "/images/jquery/plugins/validate/localization/messages_tr.js"); - localeFiles.put("tr_TR", "/images/jquery/plugins/validate/localization/messages_tr.js"); - localeFiles.put("uk", "/images/jquery/plugins/validate/localization/messages_uk.js"); - localeFiles.put("uk_UA", "/images/jquery/plugins/validate/localization/messages_uk.js"); - localeFiles.put("vi", "/images/jquery/plugins/validate/localization/messages_vi.js"); - localeFiles.put("vi_VN", "/images/jquery/plugins/validate/localization/messages_vi.js"); - } - - public static String getFilePath(String locale) { - if (validation.localeFiles.containsKey(locale)) { - return validation.localeFiles.get(locale); - } - return validation.defaultValidation; - } - } - - public static class dateTime { - private static Map localeFiles = new LinkedHashMap(); - private static String defaultDateTime = "/images/webapp/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"; - - static { - localeFiles.put("sq", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("sq_AL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_DZ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_BH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_EG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_IQ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_JO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_KW", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_LB", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_LY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_MA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_OM", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_QA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_SA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_SD", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_SY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_TN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_AE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ar_YE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("be", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("be_BY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("bg", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-bg.js"); - localeFiles.put("bg_BG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-bg.js"); - localeFiles.put("ca", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ca.js"); - localeFiles.put("ca_ES", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ca.js"); - localeFiles.put("zh", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("zh_CN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-zh-CN.js"); - localeFiles.put("zh_HK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-zh-HK.js"); - localeFiles.put("zh_SG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("zh_TW", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-zh-TW.js"); - localeFiles.put("hr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hr.js"); - localeFiles.put("hr_HR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hr.js"); - localeFiles.put("cs", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-cs.js"); - localeFiles.put("cs_CZ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-cs.js"); - localeFiles.put("da", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-da.js"); - localeFiles.put("da_DK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-da.js"); - localeFiles.put("nl", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-nl.js"); - localeFiles.put("nl_BE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-nl.js"); - localeFiles.put("nl_NL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-nl.js"); - localeFiles.put("en", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_AU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_CA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_IN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_IE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_MT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_NZ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_PH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_SG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_ZA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_GB", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("en_US", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("et", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-et.js"); - localeFiles.put("et_EE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-et.js"); - localeFiles.put("fi", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fi.js"); - localeFiles.put("fi_FI", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fi.js"); - localeFiles.put("fr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); - localeFiles.put("fr_BE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); - localeFiles.put("fr_CA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); - localeFiles.put("fr_FR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); - localeFiles.put("fr_LU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); - localeFiles.put("fr_CH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); - localeFiles.put("de", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js"); - localeFiles.put("de_AT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js"); - localeFiles.put("de_DE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js"); - localeFiles.put("de_LU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js"); - localeFiles.put("de_CH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js"); - localeFiles.put("el", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-el.js"); - localeFiles.put("el_CY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-el.js"); - localeFiles.put("el_GR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-el.js"); - localeFiles.put("iw", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("iw_IL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("hi_IN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("hu", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hu.js"); - localeFiles.put("hu_HU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hu.js"); - localeFiles.put("is", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("is_IS", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("in", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("in_ID", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ga", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ga_IE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("it", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-it.js"); - localeFiles.put("it_IT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-it.js"); - localeFiles.put("it_CH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-it.js"); - localeFiles.put("ja", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ja.js"); - localeFiles.put("ja_JP", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ja.js"); - localeFiles.put("ja_JP_JP", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ja.js"); - localeFiles.put("ko", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ko.js"); - localeFiles.put("ko_KR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ko.js"); - localeFiles.put("lv", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("lv_LV", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("lt", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-lt.js"); - localeFiles.put("lt_LT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-lt.js"); - localeFiles.put("mk", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("mk_MK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ms", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("ms_MY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("mt", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("mt_MT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("no", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-no.js"); - localeFiles.put("no_NO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-no.js"); - localeFiles.put("no_NO_NY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-no.js"); - localeFiles.put("pl", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pl.js"); - localeFiles.put("pl_PL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pl.js"); - localeFiles.put("pt", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pt.js"); - localeFiles.put("pt_BR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pt.js"); - localeFiles.put("pt_PT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pt.js"); - localeFiles.put("ro", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ro.js"); - localeFiles.put("ro_RO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ro.js"); - localeFiles.put("ru", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ru.js"); - localeFiles.put("ru_RU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ru.js"); - localeFiles.put("sr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("sr_BA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("sr_ME", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("sr_CS", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("sr_RS", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sr-RS.js"); - localeFiles.put("sk", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sk.js"); - localeFiles.put("sk_SK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sk.js"); - localeFiles.put("sl", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("sl_SI", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); - localeFiles.put("es", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_AR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_BO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_CL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_CO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_CR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_DO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_EC", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_SV", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_GT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_HN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_MX", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_NI", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_PA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_PY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_PE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_PR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_ES", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_US", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_UY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("es_VE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); - localeFiles.put("sv", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sv.js"); - localeFiles.put("sv_SE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sv.js"); - localeFiles.put("th", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-th.js"); - localeFiles.put("th_TH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-th.js"); - localeFiles.put("th_TH_TH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-th.js"); - localeFiles.put("tr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-tr.js"); - localeFiles.put("tr_TR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-tr.js"); - localeFiles.put("uk", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-uk.js"); - localeFiles.put("uk_UA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-uk.js"); - localeFiles.put("vi", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-vi.js"); - localeFiles.put("vi_VN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-vi.js"); - } - - public static String getFilePath(String locale) { - if (dateTime.localeFiles.containsKey(locale)) { - return dateTime.localeFiles.get(locale); - } - return dateTime.defaultDateTime; - } - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ + + +package org.ofbiz.common; + +import java.util.LinkedHashMap; +import java.util.Map; + + +public final class JsLanguageFilesMapping { + + // DO NOT EDIT THIS FILE! THIS IS AUTO GENERATED AND WILL GET WRITTEN OVER PERIODICALLY WHEN THE DATA CHANGE + // Rather use the createJsLanguageFileMapping service to create or update it. You will still need to compile thereafter + + public static class datejs { + + private static Map localeFiles = new LinkedHashMap(); + private static String defaultDateJs = "/images/jquery/plugins/datejs/date-en-US.js"; + + static { + localeFiles.put("sq", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("sq_AL", "/images/jquery/plugins/datejs/date-sq-AL.js"); + localeFiles.put("ar", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("ar_DZ", "/images/jquery/plugins/datejs/date-ar-DZ.js"); + localeFiles.put("ar_BH", "/images/jquery/plugins/datejs/date-ar-BH.js"); + localeFiles.put("ar_EG", "/images/jquery/plugins/datejs/date-ar-EG.js"); + localeFiles.put("ar_IQ", "/images/jquery/plugins/datejs/date-ar-IQ.js"); + localeFiles.put("ar_JO", "/images/jquery/plugins/datejs/date-ar-JO.js"); + localeFiles.put("ar_KW", "/images/jquery/plugins/datejs/date-ar-KW.js"); + localeFiles.put("ar_LB", "/images/jquery/plugins/datejs/date-ar-LB.js"); + localeFiles.put("ar_LY", "/images/jquery/plugins/datejs/date-ar-LY.js"); + localeFiles.put("ar_MA", "/images/jquery/plugins/datejs/date-ar-MA.js"); + localeFiles.put("ar_OM", "/images/jquery/plugins/datejs/date-ar-OM.js"); + localeFiles.put("ar_QA", "/images/jquery/plugins/datejs/date-ar-QA.js"); + localeFiles.put("ar_SA", "/images/jquery/plugins/datejs/date-ar-SA.js"); + localeFiles.put("ar_SD", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("ar_SY", "/images/jquery/plugins/datejs/date-ar-SY.js"); + localeFiles.put("ar_TN", "/images/jquery/plugins/datejs/date-ar-TN.js"); + localeFiles.put("ar_AE", "/images/jquery/plugins/datejs/date-ar-AE.js"); + localeFiles.put("ar_YE", "/images/jquery/plugins/datejs/date-ar-YE.js"); + localeFiles.put("be", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("be_BY", "/images/jquery/plugins/datejs/date-be-BY.js"); + localeFiles.put("bg", "/images/jquery/plugins/datejs/date-bg-BG.js"); + localeFiles.put("bg_BG", "/images/jquery/plugins/datejs/date-bg-BG.js"); + localeFiles.put("ca", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("ca_ES", "/images/jquery/plugins/datejs/date-ca-ES.js"); + localeFiles.put("zh", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("zh_CN", "/images/jquery/plugins/datejs/date-zh-CN.js"); + localeFiles.put("zh_HK", "/images/jquery/plugins/datejs/date-zh-HK.js"); + localeFiles.put("zh_SG", "/images/jquery/plugins/datejs/date-zh-SG.js"); + localeFiles.put("zh_TW", "/images/jquery/plugins/datejs/date-zh-TW.js"); + localeFiles.put("hr", "/images/jquery/plugins/datejs/date-hr-HR.js"); + localeFiles.put("hr_HR", "/images/jquery/plugins/datejs/date-hr-HR.js"); + localeFiles.put("cs", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("cs_CZ", "/images/jquery/plugins/datejs/date-cs-CZ.js"); + localeFiles.put("da", "/images/jquery/plugins/datejs/date-da-DA.js"); + localeFiles.put("da_DK", "/images/jquery/plugins/datejs/date-da-DK.js"); + localeFiles.put("nl", "/images/jquery/plugins/datejs/date-nl-NL.js"); + localeFiles.put("nl_BE", "/images/jquery/plugins/datejs/date-nl-BE.js"); + localeFiles.put("nl_NL", "/images/jquery/plugins/datejs/date-nl-NL.js"); + localeFiles.put("en", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("en_AU", "/images/jquery/plugins/datejs/date-en-AU.js"); + localeFiles.put("en_CA", "/images/jquery/plugins/datejs/date-en-CA.js"); + localeFiles.put("en_IN", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("en_IE", "/images/jquery/plugins/datejs/date-en-IE.js"); + localeFiles.put("en_MT", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("en_NZ", "/images/jquery/plugins/datejs/date-en-NZ.js"); + localeFiles.put("en_PH", "/images/jquery/plugins/datejs/date-en-PH.js"); + localeFiles.put("en_SG", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("en_ZA", "/images/jquery/plugins/datejs/date-en-ZA.js"); + localeFiles.put("en_GB", "/images/jquery/plugins/datejs/date-en-GB.js"); + localeFiles.put("en_US", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("et", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("et_EE", "/images/jquery/plugins/datejs/date-et-EE.js"); + localeFiles.put("fi", "/images/jquery/plugins/datejs/date-fi-FI.js"); + localeFiles.put("fi_FI", "/images/jquery/plugins/datejs/date-fi-FI.js"); + localeFiles.put("fr", "/images/jquery/plugins/datejs/date-fr-FR.js"); + localeFiles.put("fr_BE", "/images/jquery/plugins/datejs/date-fr-BE.js"); + localeFiles.put("fr_CA", "/images/jquery/plugins/datejs/date-fr-CA.js"); + localeFiles.put("fr_FR", "/images/jquery/plugins/datejs/date-fr-FR.js"); + localeFiles.put("fr_LU", "/images/jquery/plugins/datejs/date-fr-LU.js"); + localeFiles.put("fr_CH", "/images/jquery/plugins/datejs/date-fr-CH.js"); + localeFiles.put("de", "/images/jquery/plugins/datejs/date-de-DE.js"); + localeFiles.put("de_AT", "/images/jquery/plugins/datejs/date-de-AT.js"); + localeFiles.put("de_DE", "/images/jquery/plugins/datejs/date-de-DE.js"); + localeFiles.put("de_LU", "/images/jquery/plugins/datejs/date-de-LU.js"); + localeFiles.put("de_CH", "/images/jquery/plugins/datejs/date-de-CH.js"); + localeFiles.put("el", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("el_CY", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("el_GR", "/images/jquery/plugins/datejs/date-el-GR.js"); + localeFiles.put("iw", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("iw_IL", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("hi_IN", "/images/jquery/plugins/datejs/date-hi-IN.js"); + localeFiles.put("hu", "/images/jquery/plugins/datejs/date-hu-HU.js"); + localeFiles.put("hu_HU", "/images/jquery/plugins/datejs/date-hu-HU.js"); + localeFiles.put("is", "/images/jquery/plugins/datejs/date-is-IS.js"); + localeFiles.put("is_IS", "/images/jquery/plugins/datejs/date-is-IS.js"); + localeFiles.put("in", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("in_ID", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("ga", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("ga_IE", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("it", "/images/jquery/plugins/datejs/date-it-IT.js"); + localeFiles.put("it_IT", "/images/jquery/plugins/datejs/date-it-IT.js"); + localeFiles.put("it_CH", "/images/jquery/plugins/datejs/date-it-CH.js"); + localeFiles.put("ja", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("ja_JP", "/images/jquery/plugins/datejs/date-ja-JP.js"); + localeFiles.put("ja_JP_JP", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("ko", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("ko_KR", "/images/jquery/plugins/datejs/date-ko-KR.js"); + localeFiles.put("lv", "/images/jquery/plugins/datejs/date-lv-LV.js"); + localeFiles.put("lv_LV", "/images/jquery/plugins/datejs/date-lv-LV.js"); + localeFiles.put("lt", "/images/jquery/plugins/datejs/date-lt-LT.js"); + localeFiles.put("lt_LT", "/images/jquery/plugins/datejs/date-lt-LT.js"); + localeFiles.put("mk", "/images/jquery/plugins/datejs/date-mk-MK.js"); + localeFiles.put("mk_MK", "/images/jquery/plugins/datejs/date-mk-MK.js"); + localeFiles.put("ms", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("ms_MY", "/images/jquery/plugins/datejs/date-ms-MY.js"); + localeFiles.put("mt", "/images/jquery/plugins/datejs/date-mt-MT.js"); + localeFiles.put("mt_MT", "/images/jquery/plugins/datejs/date-mt-MT.js"); + localeFiles.put("no", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("no_NO", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("no_NO_NY", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("pl", "/images/jquery/plugins/datejs/date-pl-PL.js"); + localeFiles.put("pl_PL", "/images/jquery/plugins/datejs/date-pl-PL.js"); + localeFiles.put("pt", "/images/jquery/plugins/datejs/date-pt-PT.js"); + localeFiles.put("pt_BR", "/images/jquery/plugins/datejs/date-pt-BR.js"); + localeFiles.put("pt_PT", "/images/jquery/plugins/datejs/date-pt-PT.js"); + localeFiles.put("ro", "/images/jquery/plugins/datejs/date-ro-RO.js"); + localeFiles.put("ro_RO", "/images/jquery/plugins/datejs/date-ro-RO.js"); + localeFiles.put("ru", "/images/jquery/plugins/datejs/date-ru-RU.js"); + localeFiles.put("ru_RU", "/images/jquery/plugins/datejs/date-ru-RU.js"); + localeFiles.put("sr", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("sr_BA", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("sr_ME", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("sr_CS", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("sr_RS", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("sk", "/images/jquery/plugins/datejs/date-sk-SK.js"); + localeFiles.put("sk_SK", "/images/jquery/plugins/datejs/date-sk-SK.js"); + localeFiles.put("sl", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("sl_SI", "/images/jquery/plugins/datejs/date-sl-SI.js"); + localeFiles.put("es", "/images/jquery/plugins/datejs/date-es-ES.js"); + localeFiles.put("es_AR", "/images/jquery/plugins/datejs/date-es-AR.js"); + localeFiles.put("es_BO", "/images/jquery/plugins/datejs/date-es-BO.js"); + localeFiles.put("es_CL", "/images/jquery/plugins/datejs/date-es-CL.js"); + localeFiles.put("es_CO", "/images/jquery/plugins/datejs/date-es-CO.js"); + localeFiles.put("es_CR", "/images/jquery/plugins/datejs/date-es-CR.js"); + localeFiles.put("es_DO", "/images/jquery/plugins/datejs/date-es-DO.js"); + localeFiles.put("es_EC", "/images/jquery/plugins/datejs/date-es-EC.js"); + localeFiles.put("es_SV", "/images/jquery/plugins/datejs/date-es-SV.js"); + localeFiles.put("es_GT", "/images/jquery/plugins/datejs/date-es-GT.js"); + localeFiles.put("es_HN", "/images/jquery/plugins/datejs/date-es-HN.js"); + localeFiles.put("es_MX", "/images/jquery/plugins/datejs/date-es-MX.js"); + localeFiles.put("es_NI", "/images/jquery/plugins/datejs/date-es-NI.js"); + localeFiles.put("es_PA", "/images/jquery/plugins/datejs/date-es-PA.js"); + localeFiles.put("es_PY", "/images/jquery/plugins/datejs/date-es-PY.js"); + localeFiles.put("es_PE", "/images/jquery/plugins/datejs/date-es-PE.js"); + localeFiles.put("es_PR", "/images/jquery/plugins/datejs/date-es-PR.js"); + localeFiles.put("es_ES", "/images/jquery/plugins/datejs/date-es-ES.js"); + localeFiles.put("es_US", "/images/jquery/plugins/datejs/date-es-ES.js"); + localeFiles.put("es_UY", "/images/jquery/plugins/datejs/date-es-UY.js"); + localeFiles.put("es_VE", "/images/jquery/plugins/datejs/date-es-VE.js"); + localeFiles.put("sv", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("sv_SE", "/images/jquery/plugins/datejs/date-sv-SE.js"); + localeFiles.put("th", "/images/jquery/plugins/datejs/date-th-TH.js"); + localeFiles.put("th_TH", "/images/jquery/plugins/datejs/date-th-TH.js"); + localeFiles.put("th_TH_TH", "/images/jquery/plugins/datejs/date-th-TH.js"); + localeFiles.put("tr", "/images/jquery/plugins/datejs/date-tr-TR.js"); + localeFiles.put("tr_TR", "/images/jquery/plugins/datejs/date-tr-TR.js"); + localeFiles.put("uk", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("uk_UA", "/images/jquery/plugins/datejs/date-uk-UA.js"); + localeFiles.put("vi", "/images/jquery/plugins/datejs/date-en-US.js"); + localeFiles.put("vi_VN", "/images/jquery/plugins/datejs/date-vi-VN.js"); + } + + public static String getFilePath(String locale) { + if (datejs.localeFiles.containsKey(locale)) { + return datejs.localeFiles.get(locale); + } + return datejs.defaultDateJs; + } + + } + + public static class jquery { + private static Map localeFiles = new LinkedHashMap(); + private static String defaultDateJs = "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"; + + static { + localeFiles.put("sq", "/images/jquery/ui/i18n/jquery.ui.datepicker-sq.js"); + localeFiles.put("sq_AL", "/images/jquery/ui/i18n/jquery.ui.datepicker-sq.js"); + localeFiles.put("ar", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_DZ", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_BH", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_EG", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_IQ", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_JO", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_KW", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_LB", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_LY", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_MA", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_OM", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_QA", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_SA", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_SD", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_SY", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_TN", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_AE", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("ar_YE", "/images/jquery/ui/i18n/jquery.ui.datepicker-ar.js"); + localeFiles.put("be", "/images/jquery/ui/i18n/jquery.ui.datepicker-be.js"); + localeFiles.put("be_BY", "/images/jquery/ui/i18n/jquery.ui.datepicker-be.js"); + localeFiles.put("bg", "/images/jquery/ui/i18n/jquery.ui.datepicker-bg.js"); + localeFiles.put("bg_BG", "/images/jquery/ui/i18n/jquery.ui.datepicker-bg.js"); + localeFiles.put("ca", "/images/jquery/ui/i18n/jquery.ui.datepicker-ca.js"); + localeFiles.put("ca_ES", "/images/jquery/ui/i18n/jquery.ui.datepicker-ca.js"); + localeFiles.put("zh", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("zh_CN", "/images/jquery/ui/i18n/jquery.ui.datepicker-zh-CN.js"); + localeFiles.put("zh_HK", "/images/jquery/ui/i18n/jquery.ui.datepicker-zh-HK.js"); + localeFiles.put("zh_SG", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("zh_TW", "/images/jquery/ui/i18n/jquery.ui.datepicker-zh-TW.js"); + localeFiles.put("hr", "/images/jquery/ui/i18n/jquery.ui.datepicker-hr.js"); + localeFiles.put("hr_HR", "/images/jquery/ui/i18n/jquery.ui.datepicker-hr.js"); + localeFiles.put("cs", "/images/jquery/ui/i18n/jquery.ui.datepicker-cs.js"); + localeFiles.put("cs_CZ", "/images/jquery/ui/i18n/jquery.ui.datepicker-cs.js"); + localeFiles.put("da", "/images/jquery/ui/i18n/jquery.ui.datepicker-da.js"); + localeFiles.put("da_DK", "/images/jquery/ui/i18n/jquery.ui.datepicker-da.js"); + localeFiles.put("nl", "/images/jquery/ui/i18n/jquery.ui.datepicker-nl.js"); + localeFiles.put("nl_BE", "/images/jquery/ui/i18n/jquery.ui.datepicker-nl.js"); + localeFiles.put("nl_NL", "/images/jquery/ui/i18n/jquery.ui.datepicker-nl.js"); + localeFiles.put("en", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_AU", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_CA", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_IN", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_IE", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_MT", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_NZ", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_PH", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_SG", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_ZA", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_GB", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("en_US", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("et", "/images/jquery/ui/i18n/jquery.ui.datepicker-et.js"); + localeFiles.put("et_EE", "/images/jquery/ui/i18n/jquery.ui.datepicker-et.js"); + localeFiles.put("fi", "/images/jquery/ui/i18n/jquery.ui.datepicker-fi.js"); + localeFiles.put("fi_FI", "/images/jquery/ui/i18n/jquery.ui.datepicker-fi.js"); + localeFiles.put("fr", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); + localeFiles.put("fr_BE", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); + localeFiles.put("fr_CA", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); + localeFiles.put("fr_FR", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); + localeFiles.put("fr_LU", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); + localeFiles.put("fr_CH", "/images/jquery/ui/i18n/jquery.ui.datepicker-fr.js"); + localeFiles.put("de", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js"); + localeFiles.put("de_AT", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js"); + localeFiles.put("de_DE", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js"); + localeFiles.put("de_LU", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js"); + localeFiles.put("de_CH", "/images/jquery/ui/i18n/jquery.ui.datepicker-de.js"); + localeFiles.put("el", "/images/jquery/ui/i18n/jquery.ui.datepicker-el.js"); + localeFiles.put("el_CY", "/images/jquery/ui/i18n/jquery.ui.datepicker-el.js"); + localeFiles.put("el_GR", "/images/jquery/ui/i18n/jquery.ui.datepicker-el.js"); + localeFiles.put("iw", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("iw_IL", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("hi_IN", "/images/jquery/ui/i18n/jquery.ui.datepicker-hi.js"); + localeFiles.put("hu", "/images/jquery/ui/i18n/jquery.ui.datepicker-hu.js"); + localeFiles.put("hu_HU", "/images/jquery/ui/i18n/jquery.ui.datepicker-hu.js"); + localeFiles.put("is", "/images/jquery/ui/i18n/jquery.ui.datepicker-is.js"); + localeFiles.put("is_IS", "/images/jquery/ui/i18n/jquery.ui.datepicker-is.js"); + localeFiles.put("in", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("in_ID", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("ga", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("ga_IE", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("it", "/images/jquery/ui/i18n/jquery.ui.datepicker-it.js"); + localeFiles.put("it_IT", "/images/jquery/ui/i18n/jquery.ui.datepicker-it.js"); + localeFiles.put("it_CH", "/images/jquery/ui/i18n/jquery.ui.datepicker-it.js"); + localeFiles.put("ja", "/images/jquery/ui/i18n/jquery.ui.datepicker-ja.js"); + localeFiles.put("ja_JP", "/images/jquery/ui/i18n/jquery.ui.datepicker-ja.js"); + localeFiles.put("ja_JP_JP", "/images/jquery/ui/i18n/jquery.ui.datepicker-ja.js"); + localeFiles.put("ko", "/images/jquery/ui/i18n/jquery.ui.datepicker-ko.js"); + localeFiles.put("ko_KR", "/images/jquery/ui/i18n/jquery.ui.datepicker-ko.js"); + localeFiles.put("lv", "/images/jquery/ui/i18n/jquery.ui.datepicker-lv.js"); + localeFiles.put("lv_LV", "/images/jquery/ui/i18n/jquery.ui.datepicker-lv.js"); + localeFiles.put("lt", "/images/jquery/ui/i18n/jquery.ui.datepicker-lt.js"); + localeFiles.put("lt_LT", "/images/jquery/ui/i18n/jquery.ui.datepicker-lt.js"); + localeFiles.put("mk", "/images/jquery/ui/i18n/jquery.ui.datepicker-mk.js"); + localeFiles.put("mk_MK", "/images/jquery/ui/i18n/jquery.ui.datepicker-mk.js"); + localeFiles.put("ms", "/images/jquery/ui/i18n/jquery.ui.datepicker-ms.js"); + localeFiles.put("ms_MY", "/images/jquery/ui/i18n/jquery.ui.datepicker-ms.js"); + localeFiles.put("mt", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("mt_MT", "/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"); + localeFiles.put("no", "/images/jquery/ui/i18n/jquery.ui.datepicker-no.js"); + localeFiles.put("no_NO", "/images/jquery/ui/i18n/jquery.ui.datepicker-no.js"); + localeFiles.put("no_NO_NY", "/images/jquery/ui/i18n/jquery.ui.datepicker-no.js"); + localeFiles.put("pl", "/images/jquery/ui/i18n/jquery.ui.datepicker-pl.js"); + localeFiles.put("pl_PL", "/images/jquery/ui/i18n/jquery.ui.datepicker-pl.js"); + localeFiles.put("pt", "/images/jquery/ui/i18n/jquery.ui.datepicker-pt.js"); + localeFiles.put("pt_BR", "/images/jquery/ui/i18n/jquery.ui.datepicker-pt.js"); + localeFiles.put("pt_PT", "/images/jquery/ui/i18n/jquery.ui.datepicker-pt.js"); + localeFiles.put("ro", "/images/jquery/ui/i18n/jquery.ui.datepicker-ro.js"); + localeFiles.put("ro_RO", "/images/jquery/ui/i18n/jquery.ui.datepicker-ro.js"); + localeFiles.put("ru", "/images/jquery/ui/i18n/jquery.ui.datepicker-ru.js"); + localeFiles.put("ru_RU", "/images/jquery/ui/i18n/jquery.ui.datepicker-ru.js"); + localeFiles.put("sr", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js"); + localeFiles.put("sr_BA", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js"); + localeFiles.put("sr_ME", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js"); + localeFiles.put("sr_CS", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js"); + localeFiles.put("sr_RS", "/images/jquery/ui/i18n/jquery.ui.datepicker-sr.js"); + localeFiles.put("sk", "/images/jquery/ui/i18n/jquery.ui.datepicker-sk.js"); + localeFiles.put("sk_SK", "/images/jquery/ui/i18n/jquery.ui.datepicker-sk.js"); + localeFiles.put("sl", "/images/jquery/ui/i18n/jquery.ui.datepicker-sl.js"); + localeFiles.put("sl_SI", "/images/jquery/ui/i18n/jquery.ui.datepicker-sl.js"); + localeFiles.put("es", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_AR", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_BO", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_CL", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_CO", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_CR", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_DO", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_EC", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_SV", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_GT", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_HN", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_MX", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_NI", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_PA", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_PY", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_PE", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_PR", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_ES", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_US", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_UY", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("es_VE", "/images/jquery/ui/i18n/jquery.ui.datepicker-es.js"); + localeFiles.put("sv", "/images/jquery/ui/i18n/jquery.ui.datepicker-sv.js"); + localeFiles.put("sv_SE", "/images/jquery/ui/i18n/jquery.ui.datepicker-sv.js"); + localeFiles.put("th", "/images/jquery/ui/i18n/jquery.ui.datepicker-th.js"); + localeFiles.put("th_TH", "/images/jquery/ui/i18n/jquery.ui.datepicker-th.js"); + localeFiles.put("th_TH_TH", "/images/jquery/ui/i18n/jquery.ui.datepicker-th.js"); + localeFiles.put("tr", "/images/jquery/ui/i18n/jquery.ui.datepicker-tr.js"); + localeFiles.put("tr_TR", "/images/jquery/ui/i18n/jquery.ui.datepicker-tr.js"); + localeFiles.put("uk", "/images/jquery/ui/i18n/jquery.ui.datepicker-uk.js"); + localeFiles.put("uk_UA", "/images/jquery/ui/i18n/jquery.ui.datepicker-uk.js"); + localeFiles.put("vi", "/images/jquery/ui/i18n/jquery.ui.datepicker-vi.js"); + localeFiles.put("vi_VN", "/images/jquery/ui/i18n/jquery.ui.datepicker-vi.js"); + } + + public static String getFilePath(String locale) { + if (datejs.localeFiles.containsKey(locale)) { + return jquery.localeFiles.get(locale); + } + return jquery.defaultDateJs; + } + + } + + public static class validation { + private static Map localeFiles = new LinkedHashMap(); + private static String defaultValidation = "/images/webapp/images/jquery/plugins/validate/localization/messages_en.js"; + + static { + localeFiles.put("sq", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("sq_AL", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("ar", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_DZ", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_BH", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_EG", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_IQ", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_JO", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_KW", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_LB", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_LY", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_MA", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_OM", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_QA", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_SA", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_SD", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_SY", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_TN", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_AE", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("ar_YE", "/images/jquery/plugins/validate/localization/messages_ar.js"); + localeFiles.put("be", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("be_BY", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("bg", "/images/jquery/plugins/validate/localization/messages_bg.js"); + localeFiles.put("bg_BG", "/images/jquery/plugins/validate/localization/messages_bg.js"); + localeFiles.put("ca", "/images/jquery/plugins/validate/localization/messages_ca.js"); + localeFiles.put("ca_ES", "/images/jquery/plugins/validate/localization/messages_ca.js"); + localeFiles.put("zh", "/images/jquery/plugins/validate/localization/messages_zh.js"); + localeFiles.put("zh_CN", "/images/jquery/plugins/validate/localization/messages_zh.js"); + localeFiles.put("zh_HK", "/images/jquery/plugins/validate/localization/messages_zh.js"); + localeFiles.put("zh_SG", "/images/jquery/plugins/validate/localization/messages_zh.js"); + localeFiles.put("zh_TW", "/images/jquery/plugins/validate/localization/messages_zh_TW.js"); + localeFiles.put("hr", "/images/jquery/plugins/validate/localization/messages_hr.js"); + localeFiles.put("hr_HR", "/images/jquery/plugins/validate/localization/messages_hr.js"); + localeFiles.put("cs", "/images/jquery/plugins/validate/localization/messages_cs.js"); + localeFiles.put("cs_CZ", "/images/jquery/plugins/validate/localization/messages_cs.js"); + localeFiles.put("da", "/images/jquery/plugins/validate/localization/messages_da.js"); + localeFiles.put("da_DK", "/images/jquery/plugins/validate/localization/messages_da.js"); + localeFiles.put("nl", "/images/jquery/plugins/validate/localization/messages_nl.js"); + localeFiles.put("nl_BE", "/images/jquery/plugins/validate/localization/messages_nl.js"); + localeFiles.put("nl_NL", "/images/jquery/plugins/validate/localization/messages_nl.js"); + localeFiles.put("en", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_AU", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_CA", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_IN", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_IE", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_MT", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_NZ", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_PH", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_SG", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_ZA", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_GB", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("en_US", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("et", "/images/jquery/plugins/validate/localization/messages_et.js"); + localeFiles.put("et_EE", "/images/jquery/plugins/validate/localization/messages_et.js"); + localeFiles.put("fi", "/images/jquery/plugins/validate/localization/messages_fi.js"); + localeFiles.put("fi_FI", "/images/jquery/plugins/validate/localization/messages_fi.js"); + localeFiles.put("fr", "/images/jquery/plugins/validate/localization/messages_fr.js"); + localeFiles.put("fr_BE", "/images/jquery/plugins/validate/localization/messages_fr.js"); + localeFiles.put("fr_CA", "/images/jquery/plugins/validate/localization/messages_fr.js"); + localeFiles.put("fr_FR", "/images/jquery/plugins/validate/localization/messages_fr.js"); + localeFiles.put("fr_LU", "/images/jquery/plugins/validate/localization/messages_fr.js"); + localeFiles.put("fr_CH", "/images/jquery/plugins/validate/localization/messages_fr.js"); + localeFiles.put("de", "/images/jquery/plugins/validate/localization/messages_de.js"); + localeFiles.put("de_AT", "/images/jquery/plugins/validate/localization/messages_de.js"); + localeFiles.put("de_DE", "/images/jquery/plugins/validate/localization/messages_de.js"); + localeFiles.put("de_LU", "/images/jquery/plugins/validate/localization/messages_de.js"); + localeFiles.put("de_CH", "/images/jquery/plugins/validate/localization/messages_de.js"); + localeFiles.put("el", "/images/jquery/plugins/validate/localization/messages_el.js"); + localeFiles.put("el_CY", "/images/jquery/plugins/validate/localization/messages_el.js"); + localeFiles.put("el_GR", "/images/jquery/plugins/validate/localization/messages_el.js"); + localeFiles.put("iw", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("iw_IL", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("hi_IN", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("hu", "/images/jquery/plugins/validate/localization/messages_hu.js"); + localeFiles.put("hu_HU", "/images/jquery/plugins/validate/localization/messages_hu.js"); + localeFiles.put("is", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("is_IS", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("in", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("in_ID", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("ga", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("ga_IE", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("it", "/images/jquery/plugins/validate/localization/messages_it.js"); + localeFiles.put("it_IT", "/images/jquery/plugins/validate/localization/messages_it.js"); + localeFiles.put("it_CH", "/images/jquery/plugins/validate/localization/messages_it.js"); + localeFiles.put("ja", "/images/jquery/plugins/validate/localization/messages_ja.js"); + localeFiles.put("ja_JP", "/images/jquery/plugins/validate/localization/messages_ja.js"); + localeFiles.put("ja_JP_JP", "/images/jquery/plugins/validate/localization/messages_ja.js"); + localeFiles.put("ko", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("ko_KR", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("lv", "/images/jquery/plugins/validate/localization/messages_lv.js"); + localeFiles.put("lv_LV", "/images/jquery/plugins/validate/localization/messages_lv.js"); + localeFiles.put("lt", "/images/jquery/plugins/validate/localization/messages_lt.js"); + localeFiles.put("lt_LT", "/images/jquery/plugins/validate/localization/messages_lt.js"); + localeFiles.put("mk", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("mk_MK", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("ms", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("ms_MY", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("mt", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("mt_MT", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("no", "/images/jquery/plugins/validate/localization/messages_no.js"); + localeFiles.put("no_NO", "/images/jquery/plugins/validate/localization/messages_no.js"); + localeFiles.put("no_NO_NY", "/images/jquery/plugins/validate/localization/messages_no.js"); + localeFiles.put("pl", "/images/jquery/plugins/validate/localization/messages_pl.js"); + localeFiles.put("pl_PL", "/images/jquery/plugins/validate/localization/messages_pl.js"); + localeFiles.put("pt", "/images/jquery/plugins/validate/localization/messages_en.js"); + localeFiles.put("pt_BR", "/images/jquery/plugins/validate/localization/messages_pt_BR.js"); + localeFiles.put("pt_PT", "/images/jquery/plugins/validate/localization/messages_pt_PT.js"); + localeFiles.put("ro", "/images/jquery/plugins/validate/localization/messages_ro.js"); + localeFiles.put("ro_RO", "/images/jquery/plugins/validate/localization/messages_ro.js"); + localeFiles.put("ru", "/images/jquery/plugins/validate/localization/messages_ru.js"); + localeFiles.put("ru_RU", "/images/jquery/plugins/validate/localization/messages_ru.js"); + localeFiles.put("sr", "/images/jquery/plugins/validate/localization/messages_sr.js"); + localeFiles.put("sr_BA", "/images/jquery/plugins/validate/localization/messages_sr.js"); + localeFiles.put("sr_ME", "/images/jquery/plugins/validate/localization/messages_sr.js"); + localeFiles.put("sr_CS", "/images/jquery/plugins/validate/localization/messages_sr.js"); + localeFiles.put("sr_RS", "/images/jquery/plugins/validate/localization/messages_sr.js"); + localeFiles.put("sk", "/images/jquery/plugins/validate/localization/messages_sk.js"); + localeFiles.put("sk_SK", "/images/jquery/plugins/validate/localization/messages_sk.js"); + localeFiles.put("sl", "/images/jquery/plugins/validate/localization/messages_sl.js"); + localeFiles.put("sl_SI", "/images/jquery/plugins/validate/localization/messages_sl.js"); + localeFiles.put("es", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_AR", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_BO", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_CL", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_CO", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_CR", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_DO", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_EC", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_SV", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_GT", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_HN", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_MX", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_NI", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_PA", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_PY", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_PE", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_PR", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_ES", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_US", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_UY", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("es_VE", "/images/jquery/plugins/validate/localization/messages_es.js"); + localeFiles.put("sv", "/images/jquery/plugins/validate/localization/messages_sv.js"); + localeFiles.put("sv_SE", "/images/jquery/plugins/validate/localization/messages_sv.js"); + localeFiles.put("th", "/images/jquery/plugins/validate/localization/messages_th.js"); + localeFiles.put("th_TH", "/images/jquery/plugins/validate/localization/messages_th.js"); + localeFiles.put("th_TH_TH", "/images/jquery/plugins/validate/localization/messages_th.js"); + localeFiles.put("tr", "/images/jquery/plugins/validate/localization/messages_tr.js"); + localeFiles.put("tr_TR", "/images/jquery/plugins/validate/localization/messages_tr.js"); + localeFiles.put("uk", "/images/jquery/plugins/validate/localization/messages_uk.js"); + localeFiles.put("uk_UA", "/images/jquery/plugins/validate/localization/messages_uk.js"); + localeFiles.put("vi", "/images/jquery/plugins/validate/localization/messages_vi.js"); + localeFiles.put("vi_VN", "/images/jquery/plugins/validate/localization/messages_vi.js"); + } + + public static String getFilePath(String locale) { + if (validation.localeFiles.containsKey(locale)) { + return validation.localeFiles.get(locale); + } + return validation.defaultValidation; + } + } + + public static class dateTime { + private static Map localeFiles = new LinkedHashMap(); + private static String defaultDateTime = "/images/webapp/images/jquery/ui/i18n/jquery.ui.datepicker-en.js"; + + static { + localeFiles.put("sq", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("sq_AL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_DZ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_BH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_EG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_IQ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_JO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_KW", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_LB", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_LY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_MA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_OM", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_QA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_SA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_SD", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_SY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_TN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_AE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ar_YE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("be", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("be_BY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("bg", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-bg.js"); + localeFiles.put("bg_BG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-bg.js"); + localeFiles.put("ca", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ca.js"); + localeFiles.put("ca_ES", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ca.js"); + localeFiles.put("zh", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("zh_CN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-zh-CN.js"); + localeFiles.put("zh_HK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-zh-HK.js"); + localeFiles.put("zh_SG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("zh_TW", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-zh-TW.js"); + localeFiles.put("hr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hr.js"); + localeFiles.put("hr_HR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hr.js"); + localeFiles.put("cs", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-cs.js"); + localeFiles.put("cs_CZ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-cs.js"); + localeFiles.put("da", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-da.js"); + localeFiles.put("da_DK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-da.js"); + localeFiles.put("nl", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-nl.js"); + localeFiles.put("nl_BE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-nl.js"); + localeFiles.put("nl_NL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-nl.js"); + localeFiles.put("en", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_AU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_CA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_IN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_IE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_MT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_NZ", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_PH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_SG", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_ZA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_GB", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("en_US", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("et", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-et.js"); + localeFiles.put("et_EE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-et.js"); + localeFiles.put("fi", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fi.js"); + localeFiles.put("fi_FI", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fi.js"); + localeFiles.put("fr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); + localeFiles.put("fr_BE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); + localeFiles.put("fr_CA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); + localeFiles.put("fr_FR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); + localeFiles.put("fr_LU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); + localeFiles.put("fr_CH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-fr.js"); + localeFiles.put("de", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js"); + localeFiles.put("de_AT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js"); + localeFiles.put("de_DE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js"); + localeFiles.put("de_LU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js"); + localeFiles.put("de_CH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-de.js"); + localeFiles.put("el", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-el.js"); + localeFiles.put("el_CY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-el.js"); + localeFiles.put("el_GR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-el.js"); + localeFiles.put("iw", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("iw_IL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("hi_IN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("hu", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hu.js"); + localeFiles.put("hu_HU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-hu.js"); + localeFiles.put("is", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("is_IS", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("in", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("in_ID", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ga", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ga_IE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("it", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-it.js"); + localeFiles.put("it_IT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-it.js"); + localeFiles.put("it_CH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-it.js"); + localeFiles.put("ja", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ja.js"); + localeFiles.put("ja_JP", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ja.js"); + localeFiles.put("ja_JP_JP", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ja.js"); + localeFiles.put("ko", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ko.js"); + localeFiles.put("ko_KR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ko.js"); + localeFiles.put("lv", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("lv_LV", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("lt", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-lt.js"); + localeFiles.put("lt_LT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-lt.js"); + localeFiles.put("mk", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("mk_MK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ms", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("ms_MY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("mt", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("mt_MT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("no", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-no.js"); + localeFiles.put("no_NO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-no.js"); + localeFiles.put("no_NO_NY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-no.js"); + localeFiles.put("pl", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pl.js"); + localeFiles.put("pl_PL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pl.js"); + localeFiles.put("pt", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pt.js"); + localeFiles.put("pt_BR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pt.js"); + localeFiles.put("pt_PT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-pt.js"); + localeFiles.put("ro", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ro.js"); + localeFiles.put("ro_RO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ro.js"); + localeFiles.put("ru", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ru.js"); + localeFiles.put("ru_RU", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-ru.js"); + localeFiles.put("sr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("sr_BA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("sr_ME", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("sr_CS", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("sr_RS", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sr-RS.js"); + localeFiles.put("sk", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sk.js"); + localeFiles.put("sk_SK", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sk.js"); + localeFiles.put("sl", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("sl_SI", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-en.js"); + localeFiles.put("es", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_AR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_BO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_CL", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_CO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_CR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_DO", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_EC", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_SV", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_GT", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_HN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_MX", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_NI", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_PA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_PY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_PE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_PR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_ES", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_US", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_UY", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("es_VE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-es.js"); + localeFiles.put("sv", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sv.js"); + localeFiles.put("sv_SE", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-sv.js"); + localeFiles.put("th", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-th.js"); + localeFiles.put("th_TH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-th.js"); + localeFiles.put("th_TH_TH", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-th.js"); + localeFiles.put("tr", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-tr.js"); + localeFiles.put("tr_TR", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-tr.js"); + localeFiles.put("uk", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-uk.js"); + localeFiles.put("uk_UA", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-uk.js"); + localeFiles.put("vi", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-vi.js"); + localeFiles.put("vi_VN", "/images/jquery/plugins/datetimepicker/localization/jquery-ui-timepicker-vi.js"); + } + + public static String getFilePath(String locale) { + if (dateTime.localeFiles.containsKey(locale)) { + return dateTime.localeFiles.get(locale); + } + return dateTime.defaultDateTime; + } + } +} diff --git a/framework/common/src/org/ofbiz/common/authentication/AuthHelper.java b/framework/common/src/org/ofbiz/common/authentication/AuthHelper.java index 1f8553eeff..fe94a21569 100644 --- a/framework/common/src/org/ofbiz/common/authentication/AuthHelper.java +++ b/framework/common/src/org/ofbiz/common/authentication/AuthHelper.java @@ -1,129 +1,129 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ - -package org.ofbiz.common.authentication; - -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Iterator; -import java.util.ServiceLoader; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.common.authentication.api.Authenticator; -import org.ofbiz.common.authentication.api.AuthenticatorException; -import org.ofbiz.service.LocalDispatcher; - -/** - * AuthHelper - */ -public class AuthHelper { - - private static final String module = AuthHelper.class.getName(); - protected static List authenticators = new ArrayList(); - protected static boolean authenticatorsLoaded = false; - - - public static boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException { - if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); - for (Authenticator auth : authenticators) { - boolean pass = auth.authenticate(username, password, isServiceAuth); - if (pass) { - return true; - } else if (auth.isSingleAuthenticator()) { - throw new AuthenticatorException(); - } - } - return false; - } - - public static void logout(String username) throws AuthenticatorException { - if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); - for (Authenticator auth : authenticators) { - auth.logout(username); - } - } - - public static void syncUser(String username) throws AuthenticatorException { - if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); - for (Authenticator auth : authenticators) { - if (auth.isUserSynchronized()) { - auth.syncUser(username); - } - } - } - - public static void updatePassword(String username, String password, String newPassword) throws AuthenticatorException { - if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); - for (Authenticator auth : authenticators) { - auth.updatePassword(username, password, newPassword); - } - } - - public static boolean authenticatorsLoaded() { - return authenticatorsLoaded; - } - - public static void loadAuthenticators(LocalDispatcher dispatcher) { - if (!authenticatorsLoaded) { - loadAuthenticators_internal(dispatcher); - } - } - - private synchronized static void loadAuthenticators_internal(LocalDispatcher dispatcher) { - if (!authenticatorsLoaded) { - Iterator it = ServiceLoader.load(Authenticator.class, getContextClassLoader()).iterator(); - while (it.hasNext()) { - try { - Authenticator auth = it.next(); - if (auth.isEnabled()) { - auth.initialize(dispatcher); - authenticators.add(auth); - } - } catch (ClassCastException e) { - Debug.logError(e, module); - } - } - - Collections.sort(authenticators, new AuthenticationComparator()); - authenticatorsLoaded = true; - } - } - - /* Do not move this into a shared global util class; doing so - * would mean the method would have to be public, and then it - * could be called by any other non-secure source. - */ - private static ClassLoader getContextClassLoader() { - return AccessController.doPrivileged( - new PrivilegedAction() { - public ClassLoader run() { - ClassLoader cl = null; - try { - cl = Thread.currentThread().getContextClassLoader(); - } catch (SecurityException e) { - Debug.logError(e, e.getMessage(), module); - } - return cl; - } - }); - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ + +package org.ofbiz.common.authentication; + +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Iterator; +import java.util.ServiceLoader; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.common.authentication.api.Authenticator; +import org.ofbiz.common.authentication.api.AuthenticatorException; +import org.ofbiz.service.LocalDispatcher; + +/** + * AuthHelper + */ +public class AuthHelper { + + private static final String module = AuthHelper.class.getName(); + protected static List authenticators = new ArrayList(); + protected static boolean authenticatorsLoaded = false; + + + public static boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException { + if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); + for (Authenticator auth : authenticators) { + boolean pass = auth.authenticate(username, password, isServiceAuth); + if (pass) { + return true; + } else if (auth.isSingleAuthenticator()) { + throw new AuthenticatorException(); + } + } + return false; + } + + public static void logout(String username) throws AuthenticatorException { + if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); + for (Authenticator auth : authenticators) { + auth.logout(username); + } + } + + public static void syncUser(String username) throws AuthenticatorException { + if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); + for (Authenticator auth : authenticators) { + if (auth.isUserSynchronized()) { + auth.syncUser(username); + } + } + } + + public static void updatePassword(String username, String password, String newPassword) throws AuthenticatorException { + if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); + for (Authenticator auth : authenticators) { + auth.updatePassword(username, password, newPassword); + } + } + + public static boolean authenticatorsLoaded() { + return authenticatorsLoaded; + } + + public static void loadAuthenticators(LocalDispatcher dispatcher) { + if (!authenticatorsLoaded) { + loadAuthenticators_internal(dispatcher); + } + } + + private synchronized static void loadAuthenticators_internal(LocalDispatcher dispatcher) { + if (!authenticatorsLoaded) { + Iterator it = ServiceLoader.load(Authenticator.class, getContextClassLoader()).iterator(); + while (it.hasNext()) { + try { + Authenticator auth = it.next(); + if (auth.isEnabled()) { + auth.initialize(dispatcher); + authenticators.add(auth); + } + } catch (ClassCastException e) { + Debug.logError(e, module); + } + } + + Collections.sort(authenticators, new AuthenticationComparator()); + authenticatorsLoaded = true; + } + } + + /* Do not move this into a shared global util class; doing so + * would mean the method would have to be public, and then it + * could be called by any other non-secure source. + */ + private static ClassLoader getContextClassLoader() { + return AccessController.doPrivileged( + new PrivilegedAction() { + public ClassLoader run() { + ClassLoader cl = null; + try { + cl = Thread.currentThread().getContextClassLoader(); + } catch (SecurityException e) { + Debug.logError(e, e.getMessage(), module); + } + return cl; + } + }); + } +} diff --git a/framework/common/src/org/ofbiz/common/authentication/AuthenticationComparator.java b/framework/common/src/org/ofbiz/common/authentication/AuthenticationComparator.java index e4b43bfc4f..d987f3301f 100644 --- a/framework/common/src/org/ofbiz/common/authentication/AuthenticationComparator.java +++ b/framework/common/src/org/ofbiz/common/authentication/AuthenticationComparator.java @@ -1,76 +1,76 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ - -package org.ofbiz.common.authentication; - -import java.util.Comparator; - -import org.ofbiz.common.authentication.api.Authenticator; - -/** - * AuthenticationComparator - * - * Used to sort Authenticators by weight - */ -public class AuthenticationComparator implements Comparator { - - /** - * Compares its two arguments for order. Returns a negative integer, - * zero, or a positive integer as the first argument is less than, equal - * to, or greater than the second.

- *

- * The implementor must ensure that sgn(compare(x, y)) == - * -sgn(compare(y, x)) for all x and y. (This - * implies that compare(x, y) must throw an exception if and only - * if compare(y, x) throws an exception.)

- *

- * The implementor must also ensure that the relation is transitive: - * ((compare(x, y)>0) && (compare(y, z)>0)) implies - * compare(x, z)>0.

- *

- * Finally, the implementer must ensure that compare(x, y)==0 - * implies that sgn(compare(x, z))==sgn(compare(y, z)) for all - * z.

- *

- * It is generally the case, but not strictly required that - * (compare(x, y)==0) == (x.equals(y)). Generally speaking, - * any comparator that violates this condition should clearly indicate - * this fact. The recommended language is "Note: this comparator - * imposes orderings that are inconsistent with equals." - * - * @param a1 the first object to be compared. - * @param a2 the second object to be compared. - * @return a negative integer, zero, or a positive integer as the - * first argument is less than, equal to, or greater than the - * second. - * @throws ClassCastException if the arguments' types prevent them from - * being compared by this Comparator. - */ - public int compare(Authenticator a1, Authenticator a2) { - if (a1.getWeight() < a2.getWeight()) { - return -1; - } else if (a1.getWeight() > a2.getWeight()) { - return 1; - } else if (!a1.getClass().equals(a2.getClass())) { - return -1; - } else { - return a1.getClass().getName().compareTo(a2.getClass().getName()); - } - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ + +package org.ofbiz.common.authentication; + +import java.util.Comparator; + +import org.ofbiz.common.authentication.api.Authenticator; + +/** + * AuthenticationComparator + * + * Used to sort Authenticators by weight + */ +public class AuthenticationComparator implements Comparator { + + /** + * Compares its two arguments for order. Returns a negative integer, + * zero, or a positive integer as the first argument is less than, equal + * to, or greater than the second.

+ *

+ * The implementor must ensure that sgn(compare(x, y)) == + * -sgn(compare(y, x)) for all x and y. (This + * implies that compare(x, y) must throw an exception if and only + * if compare(y, x) throws an exception.)

+ *

+ * The implementor must also ensure that the relation is transitive: + * ((compare(x, y)>0) && (compare(y, z)>0)) implies + * compare(x, z)>0.

+ *

+ * Finally, the implementer must ensure that compare(x, y)==0 + * implies that sgn(compare(x, z))==sgn(compare(y, z)) for all + * z.

+ *

+ * It is generally the case, but not strictly required that + * (compare(x, y)==0) == (x.equals(y)). Generally speaking, + * any comparator that violates this condition should clearly indicate + * this fact. The recommended language is "Note: this comparator + * imposes orderings that are inconsistent with equals." + * + * @param a1 the first object to be compared. + * @param a2 the second object to be compared. + * @return a negative integer, zero, or a positive integer as the + * first argument is less than, equal to, or greater than the + * second. + * @throws ClassCastException if the arguments' types prevent them from + * being compared by this Comparator. + */ + public int compare(Authenticator a1, Authenticator a2) { + if (a1.getWeight() < a2.getWeight()) { + return -1; + } else if (a1.getWeight() > a2.getWeight()) { + return 1; + } else if (!a1.getClass().equals(a2.getClass())) { + return -1; + } else { + return a1.getClass().getName().compareTo(a2.getClass().getName()); + } + } +} diff --git a/framework/common/src/org/ofbiz/common/authentication/api/Authenticator.java b/framework/common/src/org/ofbiz/common/authentication/api/Authenticator.java index 0550cdeb12..f1c9302c14 100644 --- a/framework/common/src/org/ofbiz/common/authentication/api/Authenticator.java +++ b/framework/common/src/org/ofbiz/common/authentication/api/Authenticator.java @@ -1,97 +1,97 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ - -package org.ofbiz.common.authentication.api; - -import org.ofbiz.service.LocalDispatcher; - -/** - * Authenticator - * - * Classes which implement this interface (directly) will be auto-discovered and loaded as Authenticators - * as long as isEnabled() returns true. All implementations MUST be in the org.ofbiz top level package in - * order to be discovered. - */ -public interface Authenticator { - - /** - * Method called when authenticator is first initialized (the delegator - * object can be obtained from the LocalDispatcher) - * @param dispatcher The LocalDispatcher to use for this Authenticator - */ - public void initialize(LocalDispatcher dispatcher); - - /** - * Method to authenticate a user - * @param username User's username - * @param password User's password - * @param isServiceAuth true if authentication is for a service call - * @return true if the user is authenticated - * @throws AuthenticatorException when a fatal error occurs during authentication - */ - public boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException; - - /** - * Logs a user out - * @param username User's username - * @throws AuthenticatorException when logout fails - */ - public void logout(String username) throws AuthenticatorException; - - /** - * Reads user information and syncs it to OFBiz (i.e. UserLogin, Person, etc) - * Note: when creating a UserLogin object, be sure to set 'externalAuthId' - * @param username User's username - * @throws AuthenticatorException user synchronization fails - */ - public void syncUser(String username) throws AuthenticatorException; - - /** - * Updates a user's password - * @param username User's username - * @param password User's current password - * @param newPassword User's new password - * @throws AuthenticatorException when update password fails - */ - public void updatePassword(String username, String password, String newPassword) throws AuthenticatorException; - - /** - * Weight of this authenticator (lower weights are run first) - * @return the weight of this Authenticator - */ - public float getWeight(); - - /** - * Is the user synchronized back to OFBiz - * @return true if the user record is copied to the OFB database - */ - public boolean isUserSynchronized(); - - /** - * Is this expected to be the only authenticator, if so errors will be thrown when users cannot be found - * @return true if this is expected to be the only Authenticator - */ - public boolean isSingleAuthenticator(); - - /** - * Flag to test if this Authenticator is enabled - * @return true if the Authenticator is enabled - */ - public boolean isEnabled(); -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ + +package org.ofbiz.common.authentication.api; + +import org.ofbiz.service.LocalDispatcher; + +/** + * Authenticator + * + * Classes which implement this interface (directly) will be auto-discovered and loaded as Authenticators + * as long as isEnabled() returns true. All implementations MUST be in the org.ofbiz top level package in + * order to be discovered. + */ +public interface Authenticator { + + /** + * Method called when authenticator is first initialized (the delegator + * object can be obtained from the LocalDispatcher) + * @param dispatcher The LocalDispatcher to use for this Authenticator + */ + public void initialize(LocalDispatcher dispatcher); + + /** + * Method to authenticate a user + * @param username User's username + * @param password User's password + * @param isServiceAuth true if authentication is for a service call + * @return true if the user is authenticated + * @throws AuthenticatorException when a fatal error occurs during authentication + */ + public boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException; + + /** + * Logs a user out + * @param username User's username + * @throws AuthenticatorException when logout fails + */ + public void logout(String username) throws AuthenticatorException; + + /** + * Reads user information and syncs it to OFBiz (i.e. UserLogin, Person, etc) + * Note: when creating a UserLogin object, be sure to set 'externalAuthId' + * @param username User's username + * @throws AuthenticatorException user synchronization fails + */ + public void syncUser(String username) throws AuthenticatorException; + + /** + * Updates a user's password + * @param username User's username + * @param password User's current password + * @param newPassword User's new password + * @throws AuthenticatorException when update password fails + */ + public void updatePassword(String username, String password, String newPassword) throws AuthenticatorException; + + /** + * Weight of this authenticator (lower weights are run first) + * @return the weight of this Authenticator + */ + public float getWeight(); + + /** + * Is the user synchronized back to OFBiz + * @return true if the user record is copied to the OFB database + */ + public boolean isUserSynchronized(); + + /** + * Is this expected to be the only authenticator, if so errors will be thrown when users cannot be found + * @return true if this is expected to be the only Authenticator + */ + public boolean isSingleAuthenticator(); + + /** + * Flag to test if this Authenticator is enabled + * @return true if the Authenticator is enabled + */ + public boolean isEnabled(); +} diff --git a/framework/common/src/org/ofbiz/common/authentication/api/AuthenticatorException.java b/framework/common/src/org/ofbiz/common/authentication/api/AuthenticatorException.java index afee4a557a..246a8c4619 100644 --- a/framework/common/src/org/ofbiz/common/authentication/api/AuthenticatorException.java +++ b/framework/common/src/org/ofbiz/common/authentication/api/AuthenticatorException.java @@ -1,102 +1,102 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ - -package org.ofbiz.common.authentication.api; - -import java.util.List; - -import org.ofbiz.base.util.GeneralException; - -/** - * AuthenticatorException - */ -public class AuthenticatorException extends GeneralException { - - private static final long serialVersionUID = 2836939874682240962L; - - /** - * Creates new GeneralException without detail message. - */ - public AuthenticatorException() { - super(); - } - - /** - * Constructs an GeneralException with the specified detail message. - * - * @param msg the detail message. - */ - public AuthenticatorException(String msg) { - super(msg); - } - - /** - * Constructs an GeneralException with the specified detail message and nested Exception. - * - * @param msg the detail message. - * @param nested the nested exception. - */ - public AuthenticatorException(String msg, Throwable nested) { - super(msg, nested); - } - - /** - * Constructs an GeneralException with the specified detail message and nested Exception. - * - * @param nested the nested exception. - */ - public AuthenticatorException(Throwable nested) { - super(nested); - } - - /** - * Constructs an GeneralException with the specified detail message, list and nested Exception. - * - * @param msg the detail message. - * @param messages error message list. - */ - public AuthenticatorException(String msg, List messages) { - super(msg, messages); - } - - /** - * Constructs an GeneralException with the specified detail message, list and nested Exception. - * - * @param msg the detail message. - * @param messages error message list. - * @param nested the nested exception - */ - public AuthenticatorException(String msg, List messages, Throwable nested) { - super(msg, messages, nested); - } - - /** - * Constructs an GeneralException with the specified detail message list and nested Exception. - * - * @param messages error message list. - * @param nested the nested exception. - */ - public AuthenticatorException(List messages, Throwable nested) { - super(messages, nested); - } - - public AuthenticatorException(List messages) { - super(messages); - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ + +package org.ofbiz.common.authentication.api; + +import java.util.List; + +import org.ofbiz.base.util.GeneralException; + +/** + * AuthenticatorException + */ +public class AuthenticatorException extends GeneralException { + + private static final long serialVersionUID = 2836939874682240962L; + + /** + * Creates new GeneralException without detail message. + */ + public AuthenticatorException() { + super(); + } + + /** + * Constructs an GeneralException with the specified detail message. + * + * @param msg the detail message. + */ + public AuthenticatorException(String msg) { + super(msg); + } + + /** + * Constructs an GeneralException with the specified detail message and nested Exception. + * + * @param msg the detail message. + * @param nested the nested exception. + */ + public AuthenticatorException(String msg, Throwable nested) { + super(msg, nested); + } + + /** + * Constructs an GeneralException with the specified detail message and nested Exception. + * + * @param nested the nested exception. + */ + public AuthenticatorException(Throwable nested) { + super(nested); + } + + /** + * Constructs an GeneralException with the specified detail message, list and nested Exception. + * + * @param msg the detail message. + * @param messages error message list. + */ + public AuthenticatorException(String msg, List messages) { + super(msg, messages); + } + + /** + * Constructs an GeneralException with the specified detail message, list and nested Exception. + * + * @param msg the detail message. + * @param messages error message list. + * @param nested the nested exception + */ + public AuthenticatorException(String msg, List messages, Throwable nested) { + super(msg, messages, nested); + } + + /** + * Constructs an GeneralException with the specified detail message list and nested Exception. + * + * @param messages error message list. + * @param nested the nested exception. + */ + public AuthenticatorException(List messages, Throwable nested) { + super(messages, nested); + } + + public AuthenticatorException(List messages) { + super(messages); + } +} diff --git a/framework/common/src/org/ofbiz/common/authentication/example/TestFailAuthenticator.java b/framework/common/src/org/ofbiz/common/authentication/example/TestFailAuthenticator.java index 9f1113dd94..bfe1c2b461 100644 --- a/framework/common/src/org/ofbiz/common/authentication/example/TestFailAuthenticator.java +++ b/framework/common/src/org/ofbiz/common/authentication/example/TestFailAuthenticator.java @@ -1,138 +1,138 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ - -package org.ofbiz.common.authentication.example; - -import org.ofbiz.common.authentication.api.Authenticator; -import org.ofbiz.common.authentication.api.AuthenticatorException; -import org.ofbiz.service.LocalDispatcher; -import org.ofbiz.entity.Delegator; -import org.ofbiz.base.util.Debug; - -/** - * LocalAuthenticator - */ -public class TestFailAuthenticator implements Authenticator { - - private static final String module = TestFailAuthenticator.class.getName(); - protected Delegator delegator; - protected LocalDispatcher dispatcher; - protected float weight = 1; - - /** - * Method called when authenticator is first initialized (the delegator - * object can be obtained from the LocalDispatcher) - * - * @param dispatcher The LocalDispatcher to use for this Authenticator - */ - public void initialize(LocalDispatcher dispatcher) { - this.dispatcher = dispatcher; - this.delegator = dispatcher.getDelegator(); - Debug.logInfo(this.getClass().getName() + " Authenticator initialized", module); - } - - /** - * Method to authenticate a user - * - * @param username User's username - * @param password User's password - * @param isServiceAuth true if authentication is for a service call - * @return true if the user is authenticated - * @throws org.ofbiz.common.authentication.api.AuthenticatorException - * when a fatal error occurs during authentication - */ - public boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException { - Debug.logInfo(this.getClass().getName() + " Authenticator authenticate() -- returning false", module); - return false; - } - - /** - * Logs a user out - * - * @param username User's username - * @throws org.ofbiz.common.authentication.api.AuthenticatorException - * when logout fails - */ - public void logout(String username) throws AuthenticatorException { - Debug.logInfo(this.getClass().getName() + " Authenticator logout()", module); - } - - /** - * Reads user information and syncs it to OFBiz (i.e. UserLogin, Person, etc) - * - * @param username User's username - * @throws org.ofbiz.common.authentication.api.AuthenticatorException - * user synchronization fails - */ - public void syncUser(String username) throws AuthenticatorException { - Debug.logInfo(this.getClass().getName() + " Authenticator syncUser()", module); - // no user info to sync - } - - /** - * Updates a user's password - * - * @param username User's username - * @param password User's current password - * @param newPassword User's new password - * @throws org.ofbiz.common.authentication.api.AuthenticatorException - * when update password fails - */ - public void updatePassword(String username, String password, String newPassword) throws AuthenticatorException { - Debug.logInfo(this.getClass().getName() + " Authenticator updatePassword()", module); - } - - /** - * Weight of this authenticator (lower weights are run first) - * - * @return the weight of this Authenticator - */ - public float getWeight() { - return 1; - } - - /** - * Is the user synchronized back to OFBiz - * - * @return true if the user record is copied to the OFB database - */ - public boolean isUserSynchronized() { - Debug.logInfo(this.getClass().getName() + " Authenticator isUserSynchronized()", module); - return true; - } - - /** - * Is this expected to be the only authenticator, if so errors will be thrown when users cannot be found - * - * @return true if this is expected to be the only Authenticator - */ - public boolean isSingleAuthenticator() { - Debug.logInfo(this.getClass().getName() + " Authenticator isSingleAuthenticator()", module); - return false; - } - - /** - * Flag to test if this Authenticator is enabled - * - * @return true if the Authenticator is enabled - */ - public boolean isEnabled() { - return false; - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ + +package org.ofbiz.common.authentication.example; + +import org.ofbiz.common.authentication.api.Authenticator; +import org.ofbiz.common.authentication.api.AuthenticatorException; +import org.ofbiz.service.LocalDispatcher; +import org.ofbiz.entity.Delegator; +import org.ofbiz.base.util.Debug; + +/** + * LocalAuthenticator + */ +public class TestFailAuthenticator implements Authenticator { + + private static final String module = TestFailAuthenticator.class.getName(); + protected Delegator delegator; + protected LocalDispatcher dispatcher; + protected float weight = 1; + + /** + * Method called when authenticator is first initialized (the delegator + * object can be obtained from the LocalDispatcher) + * + * @param dispatcher The LocalDispatcher to use for this Authenticator + */ + public void initialize(LocalDispatcher dispatcher) { + this.dispatcher = dispatcher; + this.delegator = dispatcher.getDelegator(); + Debug.logInfo(this.getClass().getName() + " Authenticator initialized", module); + } + + /** + * Method to authenticate a user + * + * @param username User's username + * @param password User's password + * @param isServiceAuth true if authentication is for a service call + * @return true if the user is authenticated + * @throws org.ofbiz.common.authentication.api.AuthenticatorException + * when a fatal error occurs during authentication + */ + public boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException { + Debug.logInfo(this.getClass().getName() + " Authenticator authenticate() -- returning false", module); + return false; + } + + /** + * Logs a user out + * + * @param username User's username + * @throws org.ofbiz.common.authentication.api.AuthenticatorException + * when logout fails + */ + public void logout(String username) throws AuthenticatorException { + Debug.logInfo(this.getClass().getName() + " Authenticator logout()", module); + } + + /** + * Reads user information and syncs it to OFBiz (i.e. UserLogin, Person, etc) + * + * @param username User's username + * @throws org.ofbiz.common.authentication.api.AuthenticatorException + * user synchronization fails + */ + public void syncUser(String username) throws AuthenticatorException { + Debug.logInfo(this.getClass().getName() + " Authenticator syncUser()", module); + // no user info to sync + } + + /** + * Updates a user's password + * + * @param username User's username + * @param password User's current password + * @param newPassword User's new password + * @throws org.ofbiz.common.authentication.api.AuthenticatorException + * when update password fails + */ + public void updatePassword(String username, String password, String newPassword) throws AuthenticatorException { + Debug.logInfo(this.getClass().getName() + " Authenticator updatePassword()", module); + } + + /** + * Weight of this authenticator (lower weights are run first) + * + * @return the weight of this Authenticator + */ + public float getWeight() { + return 1; + } + + /** + * Is the user synchronized back to OFBiz + * + * @return true if the user record is copied to the OFB database + */ + public boolean isUserSynchronized() { + Debug.logInfo(this.getClass().getName() + " Authenticator isUserSynchronized()", module); + return true; + } + + /** + * Is this expected to be the only authenticator, if so errors will be thrown when users cannot be found + * + * @return true if this is expected to be the only Authenticator + */ + public boolean isSingleAuthenticator() { + Debug.logInfo(this.getClass().getName() + " Authenticator isSingleAuthenticator()", module); + return false; + } + + /** + * Flag to test if this Authenticator is enabled + * + * @return true if the Authenticator is enabled + */ + public boolean isEnabled() { + return false; + } +} diff --git a/framework/common/src/org/ofbiz/common/authentication/example/TestPassAuthenticator.java b/framework/common/src/org/ofbiz/common/authentication/example/TestPassAuthenticator.java index 282e105e5d..e2f7ce6277 100644 --- a/framework/common/src/org/ofbiz/common/authentication/example/TestPassAuthenticator.java +++ b/framework/common/src/org/ofbiz/common/authentication/example/TestPassAuthenticator.java @@ -1,57 +1,57 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ - -package org.ofbiz.common.authentication.example; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.common.authentication.api.AuthenticatorException; - -/** - * TestPassAuthenticator - */ -public class TestPassAuthenticator extends TestFailAuthenticator { - - private static final String module = TestPassAuthenticator.class.getName(); - - /** - * Method to authenticate a user - * - * @param username User's username - * @param password User's password - * @param isServiceAuth true if authentication is for a service call - * @return true if the user is authenticated - * @throws org.ofbiz.common.authentication.api.AuthenticatorException - * when a fatal error occurs during authentication - */ - @Override - public boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException { - Debug.logInfo(this.getClass().getName() + " Authenticator authenticate() -- returning false", module); - return true; - } - - /** - * Flag to test if this Authenticator is enabled - * - * @return true if the Authenticator is enabled - */ - @Override - public boolean isEnabled() { - return false; - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ + +package org.ofbiz.common.authentication.example; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.common.authentication.api.AuthenticatorException; + +/** + * TestPassAuthenticator + */ +public class TestPassAuthenticator extends TestFailAuthenticator { + + private static final String module = TestPassAuthenticator.class.getName(); + + /** + * Method to authenticate a user + * + * @param username User's username + * @param password User's password + * @param isServiceAuth true if authentication is for a service call + * @return true if the user is authenticated + * @throws org.ofbiz.common.authentication.api.AuthenticatorException + * when a fatal error occurs during authentication + */ + @Override + public boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException { + Debug.logInfo(this.getClass().getName() + " Authenticator authenticate() -- returning false", module); + return true; + } + + /** + * Flag to test if this Authenticator is enabled + * + * @return true if the Authenticator is enabled + */ + @Override + public boolean isEnabled() { + return false; + } +} diff --git a/framework/entity/src/org/ofbiz/entity/util/EntityClassLoader.java b/framework/entity/src/org/ofbiz/entity/util/EntityClassLoader.java index 3473fbaca5..4211f064a4 100644 --- a/framework/entity/src/org/ofbiz/entity/util/EntityClassLoader.java +++ b/framework/entity/src/org/ofbiz/entity/util/EntityClassLoader.java @@ -1,212 +1,212 @@ -/* - * 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.entity.util; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; - -import org.ofbiz.base.util.Assert; -import org.ofbiz.base.util.cache.UtilCache; -import org.ofbiz.entity.Delegator; -import org.ofbiz.entity.DelegatorFactory; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.entity.condition.EntityCondition; -import org.ofbiz.entity.condition.EntityOperator; - -/** - * A class loader that retrieves Java resources from the - * JavaResource entity. The entity is searched for the - * resource(s), and if it is not found, searching is delegated - * to the parent class loader. - * - */ -public final class EntityClassLoader extends ClassLoader { - - private static final ThreadLocal inFind = new ThreadLocal(); // Guards against infinite recursion - private static final URLStreamHandler streamHandler = new EntityURLStreamHandler(); - private static final UtilCache misses = UtilCache.createUtilCache("entity.classloader.misses", 500, 0, true); - - public static ClassLoader getInstance(String delegatorName, ClassLoader parent) { - Assert.notNull("delegatorName", delegatorName, "parent", parent); - if (parent instanceof EntityClassLoader) { - EntityClassLoader ecl = (EntityClassLoader) parent; - if (delegatorName.equals(ecl.delegatorName)) { - return ecl; - } - return new EntityClassLoader(delegatorName, ecl.getParent()); - } - return new EntityClassLoader(delegatorName, parent); - } - - private final String delegatorName; - - private EntityClassLoader(String delegatorName, ClassLoader parent) { - super(parent); - this.delegatorName = delegatorName; - } - - @Override - protected URL findResource(String name) { - URL url = null; - if (!isInFind()) { - String key = delegatorName.concat(":").concat(name); - if (misses.containsKey(key)) { - return null; - } - try { - inFind.set(Boolean.TRUE); - Delegator delegator = DelegatorFactory.getDelegator(delegatorName); - GenericValue resourceValue = delegator.findOne("JavaResource", true, "resourceName", name); - if (resourceValue != null) { - url = newUrl(resourceValue); - } else { - misses.put(key, key); - } - } catch (Exception e) { - throw new EntityClassLoaderException(e); - } finally { - inFind.set(Boolean.FALSE); - } - } - return url; - } - - @Override - protected Enumeration findResources(String name) throws IOException { - Enumeration urlEnum = null; - if (!isInFind()) { - String key = delegatorName.concat(":").concat(name); - if (misses.containsKey(key)) { - return null; - } - try { - inFind.set(Boolean.TRUE); - Delegator delegator = DelegatorFactory.getDelegator(delegatorName); - EntityCondition condition = EntityCondition.makeCondition("resourceName", EntityOperator.LIKE, name); - List resourceValues = delegator.findList("JavaResource", condition, null, null, null, true); - if (!resourceValues.isEmpty()) { - List urls = new ArrayList(resourceValues.size()); - for (GenericValue resourceValue : resourceValues) { - urls.add(newUrl(resourceValue)); - } - urlEnum = Collections.enumeration(urls); - } else { - misses.put(key, key); - } - } catch (Exception e) { - throw new EntityClassLoaderException(e); - } finally { - inFind.set(Boolean.FALSE); - } - } - return urlEnum; - } - - public String getDelegatorName() { - return delegatorName; - } - - @Override - public URL getResource(String name) { - Assert.notEmpty("name", name); - URL url = findResource(name); - if (url == null) { - url = getParent().getResource(name); - } - return url; - } - - @Override - public Enumeration getResources(String name) throws IOException { - Assert.notEmpty("name", name); - Enumeration urlEnum = findResources(name); - if (urlEnum == null) { - urlEnum = getParent().getResources(name); - } - return urlEnum; - } - - private boolean isInFind() { - Boolean inFindValue = inFind.get(); - if (inFindValue == null) { - inFindValue = Boolean.FALSE; - inFind.set(inFindValue); - } - return inFindValue; - } - - private URL newUrl(GenericValue resourceValue) throws MalformedURLException { - return new URL("entity", resourceValue.getDelegator().getDelegatorName(), -1, "/".concat(resourceValue - .getString("resourceName")), streamHandler); - } - - private static class EntityURLStreamHandler extends URLStreamHandler { - - @Override - protected URLConnection openConnection(URL url) throws IOException { - Assert.notNull("url", url); - try { - Delegator delegator = DelegatorFactory.getDelegator(url.getHost()); - String resourceName = url.getFile(); - if (resourceName.startsWith("/")) { - resourceName = resourceName.substring(1); - } - GenericValue resourceValue = delegator.findOne("JavaResource", true, "resourceName", resourceName); - return new EntityURLConnection(url, resourceValue.getBytes("resourceValue")); - } catch (Exception e) { - throw new EntityClassLoaderException(e); - } - } - } - - private static class EntityURLConnection extends URLConnection { - - private final byte[] data; - - private EntityURLConnection(URL url, byte[] data) { - super(url); - this.data = data; - } - - @Override - public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream(data); - } - - @Override - public void connect() throws IOException { - } - } - - @SuppressWarnings("serial") - public static class EntityClassLoaderException extends RuntimeException { - public EntityClassLoaderException(Throwable cause) { - super(cause); - } - } -} +/* + * 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.entity.util; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; + +import org.ofbiz.base.util.Assert; +import org.ofbiz.base.util.cache.UtilCache; +import org.ofbiz.entity.Delegator; +import org.ofbiz.entity.DelegatorFactory; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.entity.condition.EntityCondition; +import org.ofbiz.entity.condition.EntityOperator; + +/** + * A class loader that retrieves Java resources from the + * JavaResource entity. The entity is searched for the + * resource(s), and if it is not found, searching is delegated + * to the parent class loader. + * + */ +public final class EntityClassLoader extends ClassLoader { + + private static final ThreadLocal inFind = new ThreadLocal(); // Guards against infinite recursion + private static final URLStreamHandler streamHandler = new EntityURLStreamHandler(); + private static final UtilCache misses = UtilCache.createUtilCache("entity.classloader.misses", 500, 0, true); + + public static ClassLoader getInstance(String delegatorName, ClassLoader parent) { + Assert.notNull("delegatorName", delegatorName, "parent", parent); + if (parent instanceof EntityClassLoader) { + EntityClassLoader ecl = (EntityClassLoader) parent; + if (delegatorName.equals(ecl.delegatorName)) { + return ecl; + } + return new EntityClassLoader(delegatorName, ecl.getParent()); + } + return new EntityClassLoader(delegatorName, parent); + } + + private final String delegatorName; + + private EntityClassLoader(String delegatorName, ClassLoader parent) { + super(parent); + this.delegatorName = delegatorName; + } + + @Override + protected URL findResource(String name) { + URL url = null; + if (!isInFind()) { + String key = delegatorName.concat(":").concat(name); + if (misses.containsKey(key)) { + return null; + } + try { + inFind.set(Boolean.TRUE); + Delegator delegator = DelegatorFactory.getDelegator(delegatorName); + GenericValue resourceValue = delegator.findOne("JavaResource", true, "resourceName", name); + if (resourceValue != null) { + url = newUrl(resourceValue); + } else { + misses.put(key, key); + } + } catch (Exception e) { + throw new EntityClassLoaderException(e); + } finally { + inFind.set(Boolean.FALSE); + } + } + return url; + } + + @Override + protected Enumeration findResources(String name) throws IOException { + Enumeration urlEnum = null; + if (!isInFind()) { + String key = delegatorName.concat(":").concat(name); + if (misses.containsKey(key)) { + return null; + } + try { + inFind.set(Boolean.TRUE); + Delegator delegator = DelegatorFactory.getDelegator(delegatorName); + EntityCondition condition = EntityCondition.makeCondition("resourceName", EntityOperator.LIKE, name); + List resourceValues = delegator.findList("JavaResource", condition, null, null, null, true); + if (!resourceValues.isEmpty()) { + List urls = new ArrayList(resourceValues.size()); + for (GenericValue resourceValue : resourceValues) { + urls.add(newUrl(resourceValue)); + } + urlEnum = Collections.enumeration(urls); + } else { + misses.put(key, key); + } + } catch (Exception e) { + throw new EntityClassLoaderException(e); + } finally { + inFind.set(Boolean.FALSE); + } + } + return urlEnum; + } + + public String getDelegatorName() { + return delegatorName; + } + + @Override + public URL getResource(String name) { + Assert.notEmpty("name", name); + URL url = findResource(name); + if (url == null) { + url = getParent().getResource(name); + } + return url; + } + + @Override + public Enumeration getResources(String name) throws IOException { + Assert.notEmpty("name", name); + Enumeration urlEnum = findResources(name); + if (urlEnum == null) { + urlEnum = getParent().getResources(name); + } + return urlEnum; + } + + private boolean isInFind() { + Boolean inFindValue = inFind.get(); + if (inFindValue == null) { + inFindValue = Boolean.FALSE; + inFind.set(inFindValue); + } + return inFindValue; + } + + private URL newUrl(GenericValue resourceValue) throws MalformedURLException { + return new URL("entity", resourceValue.getDelegator().getDelegatorName(), -1, "/".concat(resourceValue + .getString("resourceName")), streamHandler); + } + + private static class EntityURLStreamHandler extends URLStreamHandler { + + @Override + protected URLConnection openConnection(URL url) throws IOException { + Assert.notNull("url", url); + try { + Delegator delegator = DelegatorFactory.getDelegator(url.getHost()); + String resourceName = url.getFile(); + if (resourceName.startsWith("/")) { + resourceName = resourceName.substring(1); + } + GenericValue resourceValue = delegator.findOne("JavaResource", true, "resourceName", resourceName); + return new EntityURLConnection(url, resourceValue.getBytes("resourceValue")); + } catch (Exception e) { + throw new EntityClassLoaderException(e); + } + } + } + + private static class EntityURLConnection extends URLConnection { + + private final byte[] data; + + private EntityURLConnection(URL url, byte[] data) { + super(url); + this.data = data; + } + + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(data); + } + + @Override + public void connect() throws IOException { + } + } + + @SuppressWarnings("serial") + public static class EntityClassLoaderException extends RuntimeException { + public EntityClassLoaderException(Throwable cause) { + super(cause); + } + } +} diff --git a/framework/minilang/src/org/ofbiz/minilang/method/callops/CallScript.java b/framework/minilang/src/org/ofbiz/minilang/method/callops/CallScript.java index 2b81cf52db..d279371629 100644 --- a/framework/minilang/src/org/ofbiz/minilang/method/callops/CallScript.java +++ b/framework/minilang/src/org/ofbiz/minilang/method/callops/CallScript.java @@ -1,149 +1,149 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ -package org.ofbiz.minilang.method.callops; - -import org.ofbiz.base.util.ScriptUtil; -import org.ofbiz.base.util.Scriptlet; -import org.ofbiz.base.util.StringUtil; -import org.ofbiz.base.util.UtilXml; -import org.ofbiz.minilang.MiniLangException; -import org.ofbiz.minilang.MiniLangRuntimeException; -import org.ofbiz.minilang.MiniLangUtil; -import org.ofbiz.minilang.MiniLangValidate; -import org.ofbiz.minilang.SimpleMethod; -import org.ofbiz.minilang.method.MethodContext; -import org.ofbiz.minilang.method.MethodOperation; -import org.w3c.dom.Element; - -/** - * Implements the <script> element. - * - * @see Mini-language Reference - */ -public final class CallScript extends MethodOperation { - - public static final String module = CallScript.class.getName(); - - // This method is needed only during the v1 to v2 transition - private static boolean autoCorrect(Element element) { - String errorListAttr = element.getAttribute("error-list-name"); - if (errorListAttr.length() > 0) { - element.removeAttribute("error-list-name"); - return true; - } - return false; - } - - /* - * Developers - the location attribute is a constant for security reasons. - * Script invocations should always be hard-coded. - */ - private final String location; - private final String method; - private final Scriptlet scriptlet; - - public CallScript(Element element, SimpleMethod simpleMethod) throws MiniLangException { - super(element, simpleMethod); - if (MiniLangValidate.validationOn()) { - MiniLangValidate.attributeNames(simpleMethod, element, "location", "script"); - MiniLangValidate.requireAnyAttribute(simpleMethod, element, "location", "script"); - MiniLangValidate.constantAttributes(simpleMethod, element, "location"); - MiniLangValidate.scriptAttributes(simpleMethod, element, "script"); - MiniLangValidate.noChildElements(simpleMethod, element); - } - boolean elementModified = autoCorrect(element); - if (elementModified && MiniLangUtil.autoCorrectOn()) { - MiniLangUtil.flagDocumentAsCorrected(element); - } - String scriptLocation = element.getAttribute("location"); - if (scriptLocation.isEmpty()) { - this.location = null; - this.method = null; - } else { - int pos = scriptLocation.lastIndexOf("#"); - if (pos == -1) { - this.location = scriptLocation; - this.method = null; - } else { - this.location = scriptLocation.substring(0, pos); - this.method = scriptLocation.substring(pos + 1); - } - } - String inlineScript = element.getAttribute("script"); - if (inlineScript.isEmpty()) { - inlineScript = UtilXml.elementValue(element); - } - if (inlineScript != null && MiniLangUtil.containsScript(inlineScript)) { - this.scriptlet = new Scriptlet(StringUtil.convertOperatorSubstitutions(inlineScript)); - } else { - this.scriptlet = null; - } - } - - @Override - public boolean exec(MethodContext methodContext) throws MiniLangException { - if (this.location != null) { - if (location.endsWith(".xml")) { - SimpleMethod.runSimpleMethod(location, method, methodContext); - } else { - ScriptUtil.executeScript(this.location, this.method, methodContext.getEnvMap()); - } - } - if (this.scriptlet != null) { - try { - this.scriptlet.executeScript(methodContext.getEnvMap()); - } catch (Exception e) { - throw new MiniLangRuntimeException(e.getMessage(), this); - } - } - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(""); - } - - if (displayField instanceof DisplayEntityField) { - this.makeHyperlinkString(writer, ((DisplayEntityField) displayField).getSubHyperlink(), context); - } - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderHyperlinkField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.HyperlinkField) - */ - public void renderHyperlinkField(Appendable writer, Map context, HyperlinkField hyperlinkField) throws IOException { - this.request.setAttribute("image", hyperlinkField.getImageLocation(context)); - ModelFormField modelFormField = hyperlinkField.getModelFormField(); - String description = encode(hyperlinkField.getDescription(context), modelFormField, context); - String confirmation = encode(hyperlinkField.getConfirmation(context), modelFormField, context); - WidgetWorker.makeHyperlinkByType(writer, hyperlinkField.getLinkType(), modelFormField.getWidgetStyle(), hyperlinkField.getUrlMode(), hyperlinkField.getTarget(context), - hyperlinkField.getParameterMap(context), description, hyperlinkField.getTargetWindow(context), confirmation, modelFormField, - this.request, this.response, context); - this.appendTooltip(writer, context, modelFormField); - //appendWhitespace(writer); - } - - public void makeHyperlinkString(Appendable writer, ModelFormField.SubHyperlink subHyperlink, Map context) throws IOException { - if (subHyperlink == null) { - return; - } - if (subHyperlink.shouldUse(context)) { - writer.append(' '); - String description = encode(subHyperlink.getDescription(context), subHyperlink.getModelFormField(), context); - WidgetWorker.makeHyperlinkByType(writer, subHyperlink.getLinkType(), subHyperlink.getStyle(context), subHyperlink.getUrlMode(), subHyperlink.getTarget(context), - subHyperlink.getParameterMap(context), description, subHyperlink.getTargetWindow(context), null, subHyperlink.getModelFormField(), - this.request, this.response, context); - } - } - - private String encode(String value, ModelFormField modelFormField, Map context) { - if (UtilValidate.isEmpty(value)) { - return value; - } - UtilCodec.SimpleEncoder encoder = (UtilCodec.SimpleEncoder)context.get("simpleEncoder"); - if (modelFormField.getEncodeOutput() && encoder != null) { - value = encoder.encode(value); - } else { - value = internalEncoder.encode(value); - } - return value; - } - - public void renderMenuField(Appendable writer, Map context, MenuField menuField) throws IOException { - menuField.renderFieldString(writer, context, null); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderTextField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.TextField) - */ - public void renderTextField(Appendable writer, Map context, TextField textField) throws IOException { - ModelFormField modelFormField = textField.getModelFormField(); - - writer.append(" updateAreas = modelFormField.getOnChangeUpdateAreas(); - boolean ajaxEnabled = updateAreas != null && this.javaScriptEnabled; - if (!textField.getClientAutocompleteField() || ajaxEnabled) { - writer.append(" autocomplete=\"off\""); - } - - writer.append("/>"); - - this.addAsterisks(writer, context, modelFormField); - - this.makeHyperlinkString(writer, textField.getSubHyperlink(), context); - - this.appendTooltip(writer, context, modelFormField); - - if (ajaxEnabled) { - appendWhitespace(writer); - writer.append(""); - } - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderTextareaField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.TextareaField) - */ - public void renderTextareaField(Appendable writer, Map context, TextareaField textareaField) throws IOException { - ModelFormField modelFormField = textareaField.getModelFormField(); - - writer.append("'); - - String value = modelFormField.getEntry(context, textareaField.getDefaultValue(context)); - if (UtilValidate.isNotEmpty(value)) { - writer.append(value); - } - - writer.append(""); - - if (textareaField.getVisualEditorEnable()) { - writer.append(""); - writer.append(""); - writer.append(""); - } - - this.addAsterisks(writer, context, modelFormField); - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderDateTimeField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.DateTimeField) - */ - public void renderDateTimeField(Appendable writer, Map context, DateTimeField dateTimeField) throws IOException { - String macroLibraryPath = UtilProperties.getPropertyValue("widget", "screen.formrenderer"); - try { - MacroFormRenderer macroFormRenderer = new MacroFormRenderer(macroLibraryPath, this.request, this.response); - macroFormRenderer.renderDateTimeField(writer, context, dateTimeField); - } catch (TemplateException e) { - Debug.logError(e, "Error rendering screen thru ftl macro: renderDateTimeField", module); - } catch (IOException e) { - Debug.logError(e, "Error rendering screen thru ftl, macro: renderDateTimeField", module); - } - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderDropDownField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.DropDownField) - */ - public void renderDropDownField(Appendable writer, Map context, DropDownField dropDownField) throws IOException { - ModelFormField modelFormField = dropDownField.getModelFormField(); - ModelForm modelForm = modelFormField.getModelForm(); - ModelFormField.AutoComplete autoComplete = dropDownField.getAutoComplete(); - boolean ajaxEnabled = autoComplete != null && this.javaScriptEnabled; - List allOptionValues = dropDownField.getAllOptionValues(context, WidgetWorker.getDelegator(context)); - - String event = modelFormField.getEvent(); - String action = modelFormField.getAction(context); - - String currentValue = modelFormField.getEntry(context); - // Get the current value's description from the option value. If there - // is a localized version it will be there. - String currentDescription = null; - if (UtilValidate.isNotEmpty(currentValue)) { - for (ModelFormField.OptionValue optionValue : allOptionValues) { - if (encode(optionValue.getKey(), modelFormField, context).equals(currentValue)) { - currentDescription = optionValue.getDescription(); - break; - } - } - } - - if (ajaxEnabled) { - writer.append(""); - - appendWhitespace(writer); - writer.append(""); - - appendWhitespace(writer); - writer.append(""); - } else { - writer.append('"'); - - if (UtilValidate.isNotEmpty(idName)) { - writer.append(" id=\""); - writer.append(idName); - writer.append('"'); - } - - if (dropDownField.getAllowMultiple()) { - writer.append(" multiple=\"multiple\""); - } - - int otherFieldSize = dropDownField.getOtherFieldSize(); - String otherFieldName = dropDownField.getParameterNameOther(context); - if (otherFieldSize > 0) { - //writer.append(" onchange=\"alert('ONCHANGE, process_choice:' + process_choice)\""); - //writer.append(" onchange='test_js()' "); - writer.append(" onchange=\"process_choice(this,document."); - writer.append(modelForm.getName()); - writer.append("."); - writer.append(otherFieldName); - writer.append(")\" "); - } - - if (UtilValidate.isNotEmpty(event) && UtilValidate.isNotEmpty(action)) { - writer.append(" "); - writer.append(event); - writer.append("=\""); - writer.append(action); - writer.append('"'); - } - - writer.append(" size=\"").append(dropDownField.getSize()).append("\">"); - - // if the current value should go first, stick it in - if (UtilValidate.isNotEmpty(currentValue) && "first-in-list".equals(dropDownField.getCurrent())) { - writer.append(""); - String explicitDescription = (currentDescription != null ? currentDescription : dropDownField.getCurrentDescription(context)); - if (UtilValidate.isNotEmpty(explicitDescription)) { - writer.append(encode(explicitDescription, modelFormField, context)); - } else { - String description = FieldInfoWithOptions.getDescriptionForOptionKey(currentValue, allOptionValues); - writer.append(encode(description, modelFormField, context)); - } - writer.append(""); - - // add a "separator" option - writer.append(""); - } - - // if allow empty is true, add an empty option - if (dropDownField.getAllowEmpty()) { - writer.append(""); - } - - // list out all options according to the option list - for (ModelFormField.OptionValue optionValue: allOptionValues) { - String noCurrentSelectedKey = dropDownField.getNoCurrentSelectedKey(context); - writer.append(""); - writer.append(encode(optionValue.getDescription(), modelFormField, context)); - writer.append(""); - } - - writer.append(""); - - - // Adapted from work by Yucca Korpela - // http://www.cs.tut.fi/~jkorpela/forms/combo.html - if (otherFieldSize > 0) { - - String fieldName = modelFormField.getParameterName(context); - Map dataMap = UtilGenerics.checkMap(modelFormField.getMap(context)); - if (dataMap == null) { - dataMap = context; - } - Object otherValueObj = dataMap.get(otherFieldName); - String otherValue = (otherValueObj == null) ? "" : otherValueObj.toString(); - - writer.append(""); - writer.append("\n"); - } - } - - this.makeHyperlinkString(writer, dropDownField.getSubHyperlink(), context); - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderCheckField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.CheckField) - */ - public void renderCheckField(Appendable writer, Map context, CheckField checkField) throws IOException { - ModelFormField modelFormField = checkField.getModelFormField(); - String currentValue = modelFormField.getEntry(context); - Boolean allChecked = checkField.isAllChecked(context); - - List allOptionValues = checkField.getAllOptionValues(context, WidgetWorker.getDelegator(context)); - String event = modelFormField.getEvent(); - String action = modelFormField.getAction(context); - - // list out all options according to the option list - for (ModelFormField.OptionValue optionValue: allOptionValues) { - - writer.append(""); - - writer.append(encode(optionValue.getDescription(), modelFormField, context)); - } - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderRadioField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.RadioField) - */ - public void renderRadioField(Appendable writer, Map context, RadioField radioField) throws IOException { - ModelFormField modelFormField = radioField.getModelFormField(); - List allOptionValues = radioField.getAllOptionValues(context, WidgetWorker.getDelegator(context)); - String currentValue = modelFormField.getEntry(context); - String event = modelFormField.getEvent(); - String action = modelFormField.getAction(context); - - // list out all options according to the option list - for (ModelFormField.OptionValue optionValue: allOptionValues) { - - writer.append(""); - - writer.append(encode(optionValue.getDescription(), modelFormField, context)); - writer.append(""); - } - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderSubmitField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.SubmitField) - */ - public void renderSubmitField(Appendable writer, Map context, SubmitField submitField) throws IOException { - ModelFormField modelFormField = submitField.getModelFormField(); - ModelForm modelForm = modelFormField.getModelForm(); - String event = null; - String action = null; - String confirmation = encode(submitField.getConfirmation(context), modelFormField, context); - - if ("text-link".equals(submitField.getButtonType())) { - writer.append(""); - - writer.append(encode(modelFormField.getTitle(context), modelFormField, context)); - - writer.append(""); - } else if ("image".equals(submitField.getButtonType())) { - writer.append(""); - } else { - // default to "button" - - String formId = modelForm.getContainerId(); - List updateAreas = modelForm.getOnSubmitUpdateAreas(); - // This is here for backwards compatibility. Use on-event-update-area - // elements instead. - String backgroundSubmitRefreshTarget = submitField.getBackgroundSubmitRefreshTarget(context); - if (UtilValidate.isNotEmpty(backgroundSubmitRefreshTarget)) { - if (updateAreas == null) { - updateAreas = new LinkedList(); - } - updateAreas.add(new ModelForm.UpdateArea("submit", formId, backgroundSubmitRefreshTarget)); - } - - boolean ajaxEnabled = (UtilValidate.isNotEmpty(updateAreas) || UtilValidate.isNotEmpty(backgroundSubmitRefreshTarget)) && this.javaScriptEnabled; - if (ajaxEnabled) { - writer.append(""); - } - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderResetField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.ResetField) - */ - public void renderResetField(Appendable writer, Map context, ResetField resetField) throws IOException { - ModelFormField modelFormField = resetField.getModelFormField(); - - writer.append(""); - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderHiddenField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.HiddenField) - */ - public void renderHiddenField(Appendable writer, Map context, HiddenField hiddenField) throws IOException { - ModelFormField modelFormField = hiddenField.getModelFormField(); - String value = hiddenField.getValue(context); - this.renderHiddenField(writer, context, modelFormField, value); - } - - public void renderHiddenField(Appendable writer, Map context, ModelFormField modelFormField, String value) throws IOException { - writer.append(""); - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderIgnoredField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.IgnoredField) - */ - public void renderIgnoredField(Appendable writer, Map context, IgnoredField ignoredField) throws IOException { - // do nothing, it's an ignored field; could add a comment or something if we wanted to - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFieldTitle(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField) - */ - public void renderFieldTitle(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { - String tempTitleText = modelFormField.getTitle(context); - String titleText = UtilHttp.encodeAmpersands(tempTitleText); - - if (UtilValidate.isNotEmpty(titleText)) { - // copied from MacroFormRenderer renderFieldTitle - String displayHelpText = UtilProperties.getPropertyValue("widget.properties", "widget.form.displayhelpText"); - String helpText = null; - if ("Y".equals(displayHelpText)) { - Delegator delegator = WidgetWorker.getDelegator(context); - Locale locale = (Locale)context.get("locale"); - String entityName = modelFormField.getEntityName(); - String fieldName = modelFormField.getFieldName(); - helpText = UtilHelpText.getEntityFieldDescription(entityName, fieldName, delegator, locale); - } - if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle()) || UtilValidate.isNotEmpty(helpText)) { - writer.append(""); - } - if (" ".equals(titleText)) { - // If the title content is just a blank then render it colling renderFormatEmptySpace: - // the method will set its content to work fine in most browser - this.renderFormatEmptySpace(writer, context, modelFormField.getModelForm()); - } else { - renderHyperlinkTitle(writer, context, modelFormField, titleText); - } - - if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { - writer.append(""); - } - - //appendWhitespace(writer); - } - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFieldTitle(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField) - */ - public void renderSingleFormFieldTitle(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { - boolean requiredField = modelFormField.getRequiredField(); - if (requiredField) { - - String requiredStyle = modelFormField.getRequiredFieldStyle(); - if (UtilValidate.isEmpty(requiredStyle)) { - requiredStyle = modelFormField.getTitleStyle(); - } - - if (UtilValidate.isNotEmpty(requiredStyle)) { - writer.append(""); - } - renderHyperlinkTitle(writer, context, modelFormField, modelFormField.getTitle(context)); - if (UtilValidate.isNotEmpty(requiredStyle)) { - writer.append(""); - } - - //appendWhitespace(writer); - } else { - renderFieldTitle(writer, context, modelFormField); - } - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { - this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context); - renderBeginningBoundaryComment(writer, "Form Widget - Form Element", modelForm); - writer.append("

"); - - boolean useRowSubmit = modelForm.getUseRowSubmit(); - if (useRowSubmit) { - writer.append(""); - } - - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(""); - String focusFieldName = FormRenderer.getFocusFieldName(modelForm, context); - if (UtilValidate.isNotEmpty(focusFieldName)) { - appendWhitespace(writer); - writer.append(""); - } - appendWhitespace(writer); - renderEndingBoundaryComment(writer, "Form Widget - Form Element", modelForm); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderMultiFormClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { - for (ModelFormField submitField: modelForm.getMultiSubmitFields()) { - if (submitField != null) { - - // Threw this in that as a hack to keep the submit button from expanding the first field - // Needs a more rugged solution - // WARNING: this method (renderMultiFormClose) must be called after the - // table that contains the list has been closed (to avoid validation errors) so - // we cannot call here the methods renderFormatItemRowCell*: for this reason - // they are now commented. - - // this.renderFormatItemRowCellOpen(writer, context, modelForm, submitField); - // this.renderFormatItemRowCellClose(writer, context, modelForm, submitField); - - // this.renderFormatItemRowCellOpen(writer, context, modelForm, submitField); - - submitField.renderFieldString(writer, context, this); - - // this.renderFormatItemRowCellClose(writer, context, modelForm, submitField); - - } - } - writer.append(""); - appendWhitespace(writer); - - // see if there is anything that needs to be added outside of the multi-form - Map wholeFormContext = UtilGenerics.checkMap(context.get("wholeFormContext")); - Appendable postMultiFormWriter = wholeFormContext != null ? (Appendable) wholeFormContext.get("postMultiFormWriter") : null; - if (postMultiFormWriter != null) { - writer.append(postMultiFormWriter.toString()); - appendWhitespace(writer); - } - - renderEndingBoundaryComment(writer, "Form Widget - Form Element (Multi)", modelForm); - } - - public void renderFormatListWrapperOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { - - Map inputFields = UtilGenerics.checkMap(context.get("requestParameters")); - Map queryStringMap = UtilGenerics.toMap(context.get("queryStringMap")); - if (UtilValidate.isNotEmpty(queryStringMap)) { - inputFields.putAll(queryStringMap); - } - if (modelForm.getType().equals("multi")) { - inputFields = UtilHttp.removeMultiFormParameters(inputFields); - } - String queryString = UtilHttp.urlEncodeArgs(inputFields); - context.put("_QBESTRING_", queryString); - - this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context); - renderBeginningBoundaryComment(writer, "Form Widget", modelForm); - - if (this.renderPagination) { - this.renderNextPrev(writer, context, modelForm); - } - writer.append(" "); - appendWhitespace(writer); - } - - public void renderFormatListWrapperClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append("
"); - - appendWhitespace(writer); - if (this.renderPagination) { - this.renderNextPrev(writer, context, modelForm); - } - renderEndingBoundaryComment(writer, "Form Widget - Formal List Wrapper", modelForm); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormatHeaderRowOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(" "); - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormatHeaderRowClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(" "); - - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowCellOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm, org.ofbiz.widget.model.ModelFormField, int positionSpan) - */ - public void renderFormatHeaderRowCellOpen(Appendable writer, Map context, ModelForm modelForm, ModelFormField modelFormField, int positionSpan) throws IOException { - writer.append(" 1) { - writer.append(" colspan=\""); - writer.append(Integer.toString(positionSpan)); - writer.append("\""); - } - if (UtilValidate.isNotEmpty(areaStyle)) { - writer.append(" class=\""); - writer.append(areaStyle); - writer.append("\""); - } - writer.append(">"); - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm, org.ofbiz.widget.model.ModelFormField) - */ - public void renderFormatHeaderRowCellClose(Appendable writer, Map context, ModelForm modelForm, ModelFormField modelFormField) throws IOException { - writer.append(""); - appendWhitespace(writer); - } - - public void renderFormatHeaderRowFormCellOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(" "); - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowFormCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormatHeaderRowFormCellClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(""); - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowFormCellTitleSeparator(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm, boolean) - */ - public void renderFormatHeaderRowFormCellTitleSeparator(Appendable writer, Map context, ModelForm modelForm, ModelFormField modelFormField, boolean isLast) throws IOException { - - String titleStyle = modelFormField.getTitleStyle(); - if (UtilValidate.isNotEmpty(titleStyle)) { - writer.append(""); - } - if (isLast) { - writer.append(" - "); - } else { - writer.append(" - "); - } - if (UtilValidate.isNotEmpty(titleStyle)) { - writer.append(""); - } - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormatItemRowOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { - Integer itemIndex = (Integer)context.get("itemIndex"); - - writer.append(" "); - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormatItemRowClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(" "); - - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowCellOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm, org.ofbiz.widget.model.ModelFormField) - */ - public void renderFormatItemRowCellOpen(Appendable writer, Map context, ModelForm modelForm, ModelFormField modelFormField, int positionSpan) throws IOException { - writer.append(" 1) { - writer.append(" colspan=\""); - writer.append(Integer.toString(positionSpan)); - writer.append("\""); - } - if (UtilValidate.isNotEmpty(areaStyle)) { - writer.append(" class=\""); - writer.append(areaStyle); - writer.append("\""); - } - writer.append(">"); - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm, org.ofbiz.widget.model.ModelFormField) - */ - public void renderFormatItemRowCellClose(Appendable writer, Map context, ModelForm modelForm, ModelFormField modelFormField) throws IOException { - writer.append(""); - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowFormCellOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormatItemRowFormCellOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(" "); - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowFormCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormatItemRowFormCellClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(""); - appendWhitespace(writer); - } - - public void renderFormatSingleWrapperOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(" "); - appendWhitespace(writer); - } - - public void renderFormatSingleWrapperClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append("
"); - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormatFieldRowOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(" "); - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) - */ - public void renderFormatFieldRowClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(" "); - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowTitleCellOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField) - */ - public void renderFormatFieldRowTitleCellOpen(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { - writer.append(" "); - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowTitleCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField) - */ - public void renderFormatFieldRowTitleCellClose(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { - writer.append(""); - appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowSpacerCell(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField) - */ - public void renderFormatFieldRowSpacerCell(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { - // Embedded styling - bad idea - //writer.append(" "); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowWidgetCellOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField, int) - */ - public void renderFormatFieldRowWidgetCellOpen(Appendable writer, Map context, ModelFormField modelFormField, int positions, int positionSpan, Integer nextPositionInRow) throws IOException { -// writer.append(" 1) { -// writer.append("30"); -// } else { -// writer.append("80"); -// } -// writer.append("%\""); - writer.append(" 0) { - writer.append(" colspan=\""); - // do a span of 1 for this column, plus 3 columns for each spanned - //position or each blank position that this will be filling in - writer.append(Integer.toString(1 + (positionSpan * 3))); - writer.append("\""); - } - String areaStyle = modelFormField.getWidgetAreaStyle(); - if (UtilValidate.isNotEmpty(areaStyle)) { - writer.append(" class=\""); - writer.append(areaStyle); - writer.append("\""); - } - writer.append(">"); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowWidgetCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField, int) - */ - public void renderFormatFieldRowWidgetCellClose(Appendable writer, Map context, ModelFormField modelFormField, int positions, int positionSpan, Integer nextPositionInRow) throws IOException { - writer.append(""); - appendWhitespace(writer); - } - - public void renderFormatEmptySpace(Appendable writer, Map context, ModelForm modelForm) throws IOException { - writer.append(" "); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderTextFindField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.TextFindField) - */ - public void renderTextFindField(Appendable writer, Map context, TextFindField textFindField) throws IOException { - - ModelFormField modelFormField = textFindField.getModelFormField(); - - String defaultOption = textFindField.getDefaultOption(); - Locale locale = (Locale)context.get("locale"); - if (!textFindField.getHideOptions()) { - String opEquals = UtilProperties.getMessage("conditional", "equals", locale); - String opBeginsWith = UtilProperties.getMessage("conditional", "begins_with", locale); - String opContains = UtilProperties.getMessage("conditional", "contains", locale); - String opIsEmpty = UtilProperties.getMessage("conditional", "is_empty", locale); - String opNotEqual = UtilProperties.getMessage("conditional", "not_equal", locale); - writer.append(" "); - } else { - writer.append(" "); - } - - writer.append(""); - - if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { - writer.append(" "); - } - - String ignoreCase = UtilProperties.getMessage("conditional", "ignore_case", locale); - boolean ignCase = textFindField.getIgnoreCase(); - - if (!textFindField.getHideIgnoreCase()) { - writer.append(" "); - writer.append(ignoreCase); - } else { - writer.append(""); - } - - if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { - writer.append(""); - } - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderRangeFindField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.RangeFindField) - */ - public void renderRangeFindField(Appendable writer, Map context, RangeFindField rangeFindField) throws IOException { - - ModelFormField modelFormField = rangeFindField.getModelFormField(); - Locale locale = (Locale)context.get("locale"); - String opEquals = UtilProperties.getMessage("conditional", "equals", locale); - String opGreaterThan = UtilProperties.getMessage("conditional", "greater_than", locale); - String opGreaterThanEquals = UtilProperties.getMessage("conditional", "greater_than_equals", locale); - String opLessThan = UtilProperties.getMessage("conditional", "less_than", locale); - String opLessThanEquals = UtilProperties.getMessage("conditional", "less_than_equals", locale); - //String opIsEmpty = UtilProperties.getMessage("conditional", "is_empty", locale); - - writer.append(""); - - if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { - writer.append(" "); - } - - String defaultOptionFrom = rangeFindField.getDefaultOptionFrom(); - writer.append(" "); - - writer.append(""); - - writer.append("
"); - - writer.append(""); - - String defaultOptionThru = rangeFindField.getDefaultOptionThru(); - writer.append(" "); - - if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { - writer.append(""); - } - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderDateFindField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.DateFindField) - */ - public void renderDateFindField(Appendable writer, Map context, DateFindField dateFindField) throws IOException { - ModelFormField modelFormField = dateFindField.getModelFormField(); - - Locale locale = (Locale)context.get("locale"); - String opEquals = UtilProperties.getMessage("conditional", "equals", locale); - String opGreaterThan = UtilProperties.getMessage("conditional", "greater_than", locale); - String opSameDay = UtilProperties.getMessage("conditional", "same_day", locale); - String opGreaterThanFromDayStart = UtilProperties.getMessage("conditional", - "greater_than_from_day_start", locale); - String opLessThan = UtilProperties.getMessage("conditional", "less_than", locale); - String opUpToDay = UtilProperties.getMessage("conditional", "up_to_day", locale); - String opUpThruDay = UtilProperties.getMessage("conditional", "up_thru_day", locale); - String opIsEmpty = UtilProperties.getMessage("conditional", "is_empty", locale); - - Map uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap")); - if (uiLabelMap == null) { - Debug.logWarning("Could not find uiLabelMap in context", module); - } - String localizedInputTitle = "", localizedIconTitle = ""; - - writer.append(" maxlength) { - value = value.substring(0, maxlength); - } - writer.append(" value=\""); - writer.append(value); - writer.append('"'); - } - - writer.append(" size=\""); - writer.append(Integer.toString(size)); - writer.append('"'); - - writer.append(" maxlength=\""); - writer.append(Integer.toString(maxlength)); - writer.append('"'); - - writer.append("/>"); - - // search for a localized label for the icon - if (uiLabelMap != null) { - localizedIconTitle = uiLabelMap.get("CommonViewCalendar"); - } - ModelForm modelForm = modelFormField.getModelForm(); - // add calendar pop-up button and seed data IF this is not a "time" type date-find - if (!"time".equals(dateFindField.getType())) { - if ("date".equals(dateFindField.getType())) { - writer.append(""); - - writer.append("\"");"); - } - - if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { - writer.append(" "); - } - - String defaultOptionFrom = dateFindField.getDefaultOptionFrom(); - writer.append(" "); - - if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { - writer.append(" "); - } - - writer.append("
"); - - writer.append(" maxlength) { - value = value.substring(0, maxlength); - } - writer.append(" value=\""); - writer.append(value); - writer.append('"'); - } - - writer.append(" size=\""); - writer.append(Integer.toString(size)); - writer.append('"'); - - writer.append(" maxlength=\""); - writer.append(Integer.toString(maxlength)); - writer.append('"'); - - writer.append("/>"); - - // add calendar pop-up button and seed data IF this is not a "time" type date-find - if (!"time".equals(dateFindField.getType())) { - if ("date".equals(dateFindField.getType())) { - writer.append(""); - - writer.append("\"");"); - } - - if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { - writer.append(" "); - } - - String defaultOptionThru = dateFindField.getDefaultOptionThru(); - writer.append(" "); - - if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { - writer.append(""); - } - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderLookupField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.LookupField) - */ - public void renderLookupField(Appendable writer, Map context, LookupField lookupField) throws IOException { - ModelFormField modelFormField = lookupField.getModelFormField(); - - writer.append(" updateAreas = modelFormField.getOnChangeUpdateAreas(); - boolean ajaxEnabled = updateAreas != null && this.javaScriptEnabled; - if (!lookupField.getClientAutocompleteField() || ajaxEnabled) { - writer.append(" autocomplete=\"off\""); - } - - writer.append("/>"); - ModelForm modelForm = modelFormField.getModelForm(); - // add lookup pop-up button - String descriptionFieldName = lookupField.getDescriptionFieldName(); - if (UtilValidate.isNotEmpty(descriptionFieldName)) { - writer.append(" targetParameterList = lookupField.getTargetParameterList(); - for (String targetParameter: targetParameterList) { - // named like: document.${formName}.${targetParameter}.value - writer.append(", document."); - writer.append(FormRenderer.getCurrentFormName(modelForm, context)); - writer.append("."); - writer.append(targetParameter); - writer.append(".value"); - } - writer.append(");\">"); - writer.append("\"Lookup\"/"); - - this.addAsterisks(writer, context, modelFormField); - - this.makeHyperlinkString(writer, lookupField.getSubHyperlink(), context); - this.appendTooltip(writer, context, modelFormField); - - if (ajaxEnabled) { - appendWhitespace(writer); - writer.append(""); - } - appendWhitespace(writer); - - //appendWhitespace(writer); - } - - protected String appendExternalLoginKey(String target) { - String result = target; - String sessionId = ";jsessionid=" + request.getSession().getId(); - int questionIndex = target.indexOf("?"); - if (questionIndex == -1) { - result += sessionId; - } else { - result = result.replace("?", sessionId + "?"); - } - return result; - } - - private int getActualPageSize(Map context) { - Integer value = (Integer) context.get("actualPageSize"); - return value != null ? value.intValue() : (getHighIndex(context) - getLowIndex(context)); - } - - private int getHighIndex(Map context) { - Integer value = (Integer) context.get("highIndex"); - return value != null ? value.intValue() : 0; - } - - private int getListSize(Map context) { - Integer value = (Integer) context.get("listSize"); - return value != null ? value.intValue() : 0; - } - - private int getLowIndex(Map context) { - Integer value = (Integer) context.get("lowIndex"); - return value != null ? value.intValue() : 0; - } - - public void renderNextPrev(Appendable writer, Map context, ModelForm modelForm) throws IOException { - boolean ajaxEnabled = false; - List updateAreas = modelForm.getOnPaginateUpdateAreas(); - String targetService = modelForm.getPaginateTarget(context); - if (this.javaScriptEnabled) { - if (UtilValidate.isNotEmpty(updateAreas)) { - ajaxEnabled = true; - } - } - if (targetService == null) { - targetService = "${targetService}"; - } - if (UtilValidate.isEmpty(targetService) && updateAreas == null) { - Debug.logWarning("Cannot paginate because TargetService is empty for the form: " + modelForm.getName(), module); - return; - } - - // get the parameterized pagination index and size fields - int paginatorNumber = WidgetWorker.getPaginatorNumber(context); - String viewIndexParam = modelForm.getMultiPaginateIndexField(context); - String viewSizeParam = modelForm.getMultiPaginateSizeField(context); - - int viewIndex = Paginator.getViewIndex(modelForm, context); - int viewSize = Paginator.getViewSize(modelForm, context); - int listSize = getListSize(context); - - int lowIndex = getLowIndex(context); - int highIndex = getHighIndex(context); - int actualPageSize = getActualPageSize(context); - - // if this is all there seems to be (if listSize < 0, then size is unknown) - if (actualPageSize >= listSize && listSize >= 0) return; - - // needed for the "Page" and "rows" labels - Map uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap")); - String pageLabel = ""; - String commonDisplaying = ""; - if (uiLabelMap == null) { - Debug.logWarning("Could not find uiLabelMap in context", module); - } else { - pageLabel = uiLabelMap.get("CommonPage"); - Map messageMap = UtilMisc.toMap("lowCount", Integer.valueOf(lowIndex + 1), "highCount", Integer.valueOf(lowIndex + actualPageSize), "total", Integer.valueOf(listSize)); - commonDisplaying = UtilProperties.getMessage("CommonUiLabels", "CommonDisplaying", messageMap, (Locale) context.get("locale")); - } - - // for legacy support, the viewSizeParam is VIEW_SIZE and viewIndexParam is VIEW_INDEX when the fields are "viewSize" and "viewIndex" - if (viewIndexParam.equals("viewIndex" + "_" + paginatorNumber)) viewIndexParam = "VIEW_INDEX" + "_" + paginatorNumber; - if (viewSizeParam.equals("viewSize" + "_" + paginatorNumber)) viewSizeParam = "VIEW_SIZE" + "_" + paginatorNumber; - - String str = (String) context.get("_QBESTRING_"); - - // strip legacy viewIndex/viewSize params from the query string - String queryString = UtilHttp.stripViewParamsFromQueryString(str, "" + paginatorNumber); - - // strip parametrized index/size params from the query string - HashSet paramNames = new HashSet(); - paramNames.add(viewIndexParam); - paramNames.add(viewSizeParam); - queryString = UtilHttp.stripNamedParamsFromQueryString(queryString, paramNames); - - String anchor = ""; - String paginateAnchor = modelForm.getPaginateTargetAnchor(); - if (paginateAnchor != null) anchor = "#" + paginateAnchor; - - // Create separate url path String and request parameters String, - // add viewIndex/viewSize parameters to request parameter String - String urlPath = UtilHttp.removeQueryStringFromTarget(targetService); - StringBuilder prepLinkBuffer = new StringBuilder(); - String prepLinkQueryString = UtilHttp.getQueryStringFromTarget(targetService); - if (prepLinkQueryString != null) { - prepLinkBuffer.append(prepLinkQueryString); - } - if (prepLinkBuffer.indexOf("?") < 0) { - prepLinkBuffer.append("?"); - } else if (prepLinkBuffer.indexOf("?", prepLinkBuffer.length() - 1) > 0) { - prepLinkBuffer.append("&"); - } - if (!UtilValidate.isEmpty(queryString) && !queryString.equals("null")) { - prepLinkBuffer.append(queryString).append("&"); - } - prepLinkBuffer.append(viewSizeParam).append("=").append(viewSize).append("&").append(viewIndexParam).append("="); - String prepLinkText = prepLinkBuffer.toString(); - if (ajaxEnabled) { - // Prepare params for prototype.js - prepLinkText = prepLinkText.replace("?", ""); - prepLinkText = prepLinkText.replace("&", "&"); - } - - writer.append("
"); - appendWhitespace(writer); - writer.append("
    "); - appendWhitespace(writer); - - String linkText; - - // First button - writer.append("
  • 0) { - writer.append("\">").append(modelForm.getPaginateFirstLabel(context)).append(""); - } else { - // disabled button - writer.append("-disabled\">").append(modelForm.getPaginateFirstLabel(context)); - } - writer.append("
  • "); - appendWhitespace(writer); - - // Previous button - writer.append("
  • 0) { - writer.append("\">").append(modelForm.getPaginatePreviousLabel(context)).append(""); - } else { - // disabled button - writer.append("-disabled\">").append(modelForm.getPaginatePreviousLabel(context)); - } - writer.append("
  • "); - appendWhitespace(writer); - - // Page select dropdown - if (listSize > 0 && this.javaScriptEnabled) { - writer.append("
  • ").append(pageLabel).append("
  • "); - } - - // show row count - writer.append("
  • "); - writer.append(commonDisplaying); - writer.append("
  • "); - appendWhitespace(writer); - - // Next button - writer.append("
  • ").append(modelForm.getPaginateNextLabel(context)).append(""); - } else { - // disabled button - writer.append("-disabled\">").append(modelForm.getPaginateNextLabel(context)); - } - writer.append("
  • "); - appendWhitespace(writer); - - // Last button - writer.append("
  • ").append(modelForm.getPaginateLastLabel(context)).append(""); - } else { - // disabled button - writer.append("-disabled\">").append(modelForm.getPaginateLastLabel(context)); - } - writer.append("
  • "); - appendWhitespace(writer); - - writer.append("
"); - appendWhitespace(writer); - writer.append("
"); - appendWhitespace(writer); - } - - public void renderSortField(Appendable writer, Map context, ModelFormField modelFormField, String titleText) throws IOException { - boolean ajaxEnabled = false; - ModelForm modelForm = modelFormField.getModelForm(); - List updateAreas = modelForm.getOnPaginateUpdateAreas(); - String targetService = modelForm.getPaginateTarget(context); - if (this.javaScriptEnabled) { - if (UtilValidate.isNotEmpty(updateAreas)) { - ajaxEnabled = true; - } - } - if (targetService == null) { - targetService = "${targetService}"; - } - if (UtilValidate.isEmpty(targetService) && updateAreas == null) { - Debug.logWarning("Cannot sort because TargetService is empty for the form: " + modelForm.getName(), module); - return; - } - - String str = (String) context.get("_QBESTRING_"); - String oldSortField = modelForm.getSortField(context); - String sortFieldStyle = modelFormField.getSortFieldStyle(); - - // if the entry-name is defined use this instead of field name - String columnField = modelFormField.getEntryName(); - if (UtilValidate.isEmpty(columnField)) { - columnField = modelFormField.getFieldName(); - } - - // switch beetween asc/desc order - String newSortField = columnField; - if (UtilValidate.isNotEmpty(oldSortField)) { - if (oldSortField.equals(columnField)) { - newSortField = "-" + columnField; - sortFieldStyle = modelFormField.getSortFieldStyleDesc(); - } else if (oldSortField.equals("-" + columnField)) { - newSortField = columnField; - sortFieldStyle = modelFormField.getSortFieldStyleAsc(); - } - } - - // strip sortField param from the query string - HashSet paramName = new HashSet(); - paramName.add("sortField"); - String queryString = UtilHttp.stripNamedParamsFromQueryString(str, paramName); - String urlPath = UtilHttp.removeQueryStringFromTarget(targetService); - StringBuilder prepLinkBuffer = new StringBuilder(); - String prepLinkQueryString = UtilHttp.getQueryStringFromTarget(targetService); - if (prepLinkQueryString != null) { - prepLinkBuffer.append(prepLinkQueryString); - } - if (prepLinkBuffer.indexOf("?") < 0) { - prepLinkBuffer.append("?"); - } else if (prepLinkBuffer.indexOf("?", prepLinkBuffer.length() - 1) > 0) { - prepLinkBuffer.append("&"); - } - if (!UtilValidate.isEmpty(queryString) && !queryString.equals("null")) { - prepLinkBuffer.append(queryString).append("&"); - } - prepLinkBuffer.append("sortField").append("=").append(newSortField); - String prepLinkText = prepLinkBuffer.toString(); - if (ajaxEnabled) { - prepLinkText = prepLinkText.replace("?", ""); - prepLinkText = prepLinkText.replace("&", "&"); - } - - writer.append("").append(titleText).append(""); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderFileField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.FileField) - */ - public void renderFileField(Appendable writer, Map context, FileField textField) throws IOException { - ModelFormField modelFormField = textField.getModelFormField(); - - writer.append(""); - - this.makeHyperlinkString(writer, textField.getSubHyperlink(), context); - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderPasswordField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.PasswordField) - */ - public void renderPasswordField(Appendable writer, Map context, PasswordField passwordField) throws IOException { - ModelFormField modelFormField = passwordField.getModelFormField(); - - writer.append(""); - - this.addAsterisks(writer, context, modelFormField); - - this.makeHyperlinkString(writer, passwordField.getSubHyperlink(), context); - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.form.FormStringRenderer#renderImageField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.ImageField) - */ - public void renderImageField(Appendable writer, Map context, ImageField imageField) throws IOException { - ModelFormField modelFormField = imageField.getModelFormField(); - - writer.append(""); - - this.makeHyperlinkString(writer, imageField.getSubHyperlink(), context); - - this.appendTooltip(writer, context, modelFormField); - - //appendWhitespace(writer); - } - - public void renderFieldGroupOpen(Appendable writer, Map context, ModelForm.FieldGroup fieldGroup) throws IOException { - String style = fieldGroup.getStyle(); - String id = fieldGroup.getId(); - FlexibleStringExpander titleNotExpanded = FlexibleStringExpander.getInstance(fieldGroup.getTitle()); - String title = titleNotExpanded.expandString(context); - Boolean collapsed = fieldGroup.initiallyCollapsed(); - String collapsibleAreaId = fieldGroup.getId() + "_body"; - - if (UtilValidate.isNotEmpty(style) || UtilValidate.isNotEmpty(id) || UtilValidate.isNotEmpty(title)) { - - writer.append("
"); - - writer.append("
"); - - if (fieldGroup.collapsible()) { - String expandToolTip = null; - String collapseToolTip = null; - Map uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap")); - //Map paramMap = UtilGenerics.checkMap(context.get("requestParameters")); - if (uiLabelMap != null) { - expandToolTip = (String) uiLabelMap.get("CommonExpand"); - collapseToolTip = (String) uiLabelMap.get("CommonCollapse"); - } - - writer.append(""); - - appendWhitespace(writer); - } - writer.append(""); - - if (UtilValidate.isNotEmpty(title)) { - writer.append("
"); - writer.append(title); - writer.append("
"); - } - - writer.append("
"); - - writer.append("
"); - } - } - - public void renderFieldGroupClose(Appendable writer, Map context, ModelForm.FieldGroup fieldGroup) throws IOException { - String style = fieldGroup.getStyle(); - String id = fieldGroup.getId(); - String title = fieldGroup.getTitle(); - if (UtilValidate.isNotEmpty(style) || UtilValidate.isNotEmpty(id) || UtilValidate.isNotEmpty(title)) { - writer.append("
"); - writer.append("
"); - } - } - - // TODO: Remove embedded styling - public void renderBanner(Appendable writer, Map context, ModelForm.Banner banner) throws IOException { - writer.append(" "); - String style = banner.getStyle(context); - String leftStyle = banner.getLeftTextStyle(context); - if (UtilValidate.isEmpty(leftStyle)) leftStyle = style; - String rightStyle = banner.getRightTextStyle(context); - if (UtilValidate.isEmpty(rightStyle)) rightStyle = style; - - String leftText = banner.getLeftText(context); - if (UtilValidate.isNotEmpty(leftText)) { - writer.append(" "); - } - - String text = banner.getText(context); - if (UtilValidate.isNotEmpty(text)) { - writer.append(" "); - } - - String rightText = banner.getRightText(context); - if (UtilValidate.isNotEmpty(rightText)) { - writer.append(" "); - } - writer.append("
"); - if (UtilValidate.isNotEmpty(leftStyle)) { - writer.append(""); - } - writer.append(leftText); - if (UtilValidate.isNotEmpty(leftStyle)) { - writer.append(""); - } - writer.append(""); - if (UtilValidate.isNotEmpty(style)) { - writer.append(""); - } - writer.append(text); - if (UtilValidate.isNotEmpty(style)) { - writer.append(""); - } - writer.append(""); - if (UtilValidate.isNotEmpty(rightStyle)) { - writer.append(""); - } - writer.append(rightText); - if (UtilValidate.isNotEmpty(rightStyle)) { - writer.append(""); - } - writer.append("
"); - } - - /** - * Renders a link for the column header fields when there is a header-link="" specified in the tag, using - * style from header-link-style="". Also renders a selectAll checkbox in multi forms. - * @param writer - * @param context - * @param modelFormField - * @param titleText - */ - public void renderHyperlinkTitle(Appendable writer, Map context, ModelFormField modelFormField, String titleText) throws IOException { - if (UtilValidate.isNotEmpty(modelFormField.getHeaderLink())) { - StringBuilder targetBuffer = new StringBuilder(); - FlexibleStringExpander target = FlexibleStringExpander.getInstance(modelFormField.getHeaderLink()); - String fullTarget = target.expandString(context); - targetBuffer.append(fullTarget); - String targetType = CommonWidgetModels.Link.DEFAULT_URL_MODE; - if (UtilValidate.isNotEmpty(targetBuffer.toString()) && targetBuffer.toString().toLowerCase().startsWith("javascript:")) { - targetType="plain"; - } - WidgetWorker.makeHyperlinkString(writer, modelFormField.getHeaderLinkStyle(), targetType, targetBuffer.toString(), null, titleText, null, modelFormField, this.request, this.response, null, null); - } else if (modelFormField.isSortField()) { - renderSortField (writer, context, modelFormField, titleText); - } else if (modelFormField.isRowSubmit()) { - if (UtilValidate.isNotEmpty(titleText)) writer.append(titleText).append("
"); - writer.append(""); - } else { - writer.append(titleText); - } - } - - public void renderContainerFindField(Appendable writer, Map context, ContainerField containerField) throws IOException { - writer.append("
"); - } - - /** Create an ajaxXxxx JavaScript CSV string from a list of UpdateArea objects. See - * selectall.js. - * @param updateAreas - * @param extraParams Renderer-supplied additional target parameters - * @param context - * @return Parameter string or empty string if no UpdateArea objects were found - */ - public String createAjaxParamsFromUpdateAreas(List updateAreas, String extraParams, Map context) { - if (updateAreas == null) { - return ""; - } - StringBuilder ajaxUrl = new StringBuilder(); - boolean firstLoop = true; - for (ModelForm.UpdateArea updateArea : updateAreas) { - if (firstLoop) { - firstLoop = false; - } else { - ajaxUrl.append(","); - } - String targetUrl = updateArea.getAreaTarget(context); - String ajaxParams = getAjaxParamsFromTarget(targetUrl); - if (UtilValidate.isNotEmpty(extraParams)) { - if (ajaxParams.length() > 0 && !extraParams.startsWith("&")) { - ajaxParams += "&"; - } - ajaxParams += extraParams; - } - ajaxUrl.append(updateArea.getAreaId()).append(","); - try { - appendOfbizUrl(ajaxUrl, UtilHttp.removeQueryStringFromTarget(targetUrl)); - } catch (IOException e) { - throw UtilMisc.initCause(new InternalError(e.getMessage()), e); - } - ajaxUrl.append(",").append(ajaxParams); - } - return ajaxUrl.toString(); - } -} +/******************************************************************************* + * 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.widget.renderer.html; + +import java.io.IOException; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.UtilCodec; +import org.ofbiz.base.util.UtilGenerics; +import org.ofbiz.base.util.UtilHttp; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilProperties; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.base.util.string.FlexibleStringExpander; +import org.ofbiz.base.util.template.FreeMarkerWorker; +import org.ofbiz.entity.Delegator; +import org.ofbiz.webapp.control.RequestHandler; +import org.ofbiz.webapp.taglib.ContentUrlTag; +import org.ofbiz.widget.WidgetWorker; +import org.ofbiz.widget.model.CommonWidgetModels; +import org.ofbiz.widget.model.ModelForm; +import org.ofbiz.widget.model.ModelFormField; +import org.ofbiz.widget.model.ModelFormField.CheckField; +import org.ofbiz.widget.model.ModelFormField.ContainerField; +import org.ofbiz.widget.model.ModelFormField.DateFindField; +import org.ofbiz.widget.model.ModelFormField.DateTimeField; +import org.ofbiz.widget.model.ModelFormField.DisplayEntityField; +import org.ofbiz.widget.model.ModelFormField.DisplayField; +import org.ofbiz.widget.model.ModelFormField.DropDownField; +import org.ofbiz.widget.model.ModelFormField.FieldInfoWithOptions; +import org.ofbiz.widget.model.ModelFormField.FileField; +import org.ofbiz.widget.model.ModelFormField.HiddenField; +import org.ofbiz.widget.model.ModelFormField.HyperlinkField; +import org.ofbiz.widget.model.ModelFormField.IgnoredField; +import org.ofbiz.widget.model.ModelFormField.ImageField; +import org.ofbiz.widget.model.ModelFormField.LookupField; +import org.ofbiz.widget.model.ModelFormField.MenuField; +import org.ofbiz.widget.model.ModelFormField.PasswordField; +import org.ofbiz.widget.model.ModelFormField.RadioField; +import org.ofbiz.widget.model.ModelFormField.RangeFindField; +import org.ofbiz.widget.model.ModelFormField.ResetField; +import org.ofbiz.widget.model.ModelFormField.SubmitField; +import org.ofbiz.widget.model.ModelFormField.TextField; +import org.ofbiz.widget.model.ModelFormField.TextFindField; +import org.ofbiz.widget.model.ModelFormField.TextareaField; +import org.ofbiz.widget.model.ModelWidget; +import org.ofbiz.widget.renderer.FormRenderer; +import org.ofbiz.widget.renderer.FormStringRenderer; +import org.ofbiz.widget.renderer.Paginator; +import org.ofbiz.widget.renderer.UtilHelpText; +import org.ofbiz.widget.renderer.macro.MacroFormRenderer; + +import freemarker.template.TemplateException; + +/** + * Widget Library - HTML Form Renderer implementation + */ +public class HtmlFormRenderer extends HtmlWidgetRenderer implements FormStringRenderer { + + public static final String module = HtmlFormRenderer.class.getName(); + + protected HttpServletRequest request; + protected HttpServletResponse response; + protected RequestHandler rh; + protected String lastFieldGroupId = ""; + protected boolean renderPagination = true; + protected boolean javaScriptEnabled = false; + private UtilCodec.SimpleEncoder internalEncoder; + + protected HtmlFormRenderer() {} + + public HtmlFormRenderer(HttpServletRequest request, HttpServletResponse response) { + this.request = request; + this.response = response; + ServletContext ctx = (ServletContext) request.getAttribute("servletContext"); + this.rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_"); + this.javaScriptEnabled = UtilHttp.isJavaScriptEnabled(request); + internalEncoder = UtilCodec.getEncoder("string"); + } + + public boolean getRenderPagination() { + return this.renderPagination; + } + + public void setRenderPagination(boolean renderPagination) { + this.renderPagination = renderPagination; + } + + public void appendOfbizUrl(Appendable writer, String location) throws IOException { + writer.append(this.rh.makeLink(this.request, this.response, location)); + } + + public void appendContentUrl(Appendable writer, String location) throws IOException { + ContentUrlTag.appendContentPrefix(this.request, writer); + writer.append(location); + } + + public void appendTooltip(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { + // render the tooltip, in other methods too + String tooltip = modelFormField.getTooltip(context); + if (UtilValidate.isNotEmpty(tooltip)) { + writer.append(""); + writer.append(tooltip); + writer.append(""); + } + } + + public void addAsterisks(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { + + boolean requiredField = modelFormField.getRequiredField(); + if (requiredField) { + String requiredStyle = modelFormField.getRequiredFieldStyle(); + + if (UtilValidate.isEmpty(requiredStyle)) { + writer.append("*"); + } + } + } + + public void appendClassNames(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { + String className = modelFormField.getWidgetStyle(); + if (UtilValidate.isNotEmpty(className) || modelFormField.shouldBeRed(context)) { + writer.append(" class=\""); + writer.append(className); + // add a style of red if redWhen is true + if (modelFormField.shouldBeRed(context)) { + writer.append(" alert"); + } + writer.append('"'); + } + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderDisplayField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.DisplayField) + */ + public void renderDisplayField(Appendable writer, Map context, DisplayField displayField) throws IOException { + ModelFormField modelFormField = displayField.getModelFormField(); + + StringBuilder str = new StringBuilder(); + + String idName = modelFormField.getCurrentContainerId(context); + + if (UtilValidate.isNotEmpty(modelFormField.getWidgetStyle()) || modelFormField.shouldBeRed(context)) { + str.append("'); + } + + if (str.length() > 0) { + writer.append(str.toString()); + } + String description = displayField.getDescription(context); + //Replace new lines with
+ description = description.replaceAll("\n", "
"); + + if (UtilValidate.isEmpty(description)) { + this.renderFormatEmptySpace(writer, context, modelFormField.getModelForm()); + } else { + writer.append(description); + } + + if (str.length() > 0) { + writer.append("
"); + } + + ModelFormField.InPlaceEditor inPlaceEditor = displayField.getInPlaceEditor(); + boolean ajaxEnabled = inPlaceEditor != null && this.javaScriptEnabled; + + if (ajaxEnabled) { + writer.append(""); + } + + if (displayField instanceof DisplayEntityField) { + this.makeHyperlinkString(writer, ((DisplayEntityField) displayField).getSubHyperlink(), context); + } + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderHyperlinkField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.HyperlinkField) + */ + public void renderHyperlinkField(Appendable writer, Map context, HyperlinkField hyperlinkField) throws IOException { + this.request.setAttribute("image", hyperlinkField.getImageLocation(context)); + ModelFormField modelFormField = hyperlinkField.getModelFormField(); + String description = encode(hyperlinkField.getDescription(context), modelFormField, context); + String confirmation = encode(hyperlinkField.getConfirmation(context), modelFormField, context); + WidgetWorker.makeHyperlinkByType(writer, hyperlinkField.getLinkType(), modelFormField.getWidgetStyle(), hyperlinkField.getUrlMode(), hyperlinkField.getTarget(context), + hyperlinkField.getParameterMap(context), description, hyperlinkField.getTargetWindow(context), confirmation, modelFormField, + this.request, this.response, context); + this.appendTooltip(writer, context, modelFormField); + //appendWhitespace(writer); + } + + public void makeHyperlinkString(Appendable writer, ModelFormField.SubHyperlink subHyperlink, Map context) throws IOException { + if (subHyperlink == null) { + return; + } + if (subHyperlink.shouldUse(context)) { + writer.append(' '); + String description = encode(subHyperlink.getDescription(context), subHyperlink.getModelFormField(), context); + WidgetWorker.makeHyperlinkByType(writer, subHyperlink.getLinkType(), subHyperlink.getStyle(context), subHyperlink.getUrlMode(), subHyperlink.getTarget(context), + subHyperlink.getParameterMap(context), description, subHyperlink.getTargetWindow(context), null, subHyperlink.getModelFormField(), + this.request, this.response, context); + } + } + + private String encode(String value, ModelFormField modelFormField, Map context) { + if (UtilValidate.isEmpty(value)) { + return value; + } + UtilCodec.SimpleEncoder encoder = (UtilCodec.SimpleEncoder)context.get("simpleEncoder"); + if (modelFormField.getEncodeOutput() && encoder != null) { + value = encoder.encode(value); + } else { + value = internalEncoder.encode(value); + } + return value; + } + + public void renderMenuField(Appendable writer, Map context, MenuField menuField) throws IOException { + menuField.renderFieldString(writer, context, null); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderTextField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.TextField) + */ + public void renderTextField(Appendable writer, Map context, TextField textField) throws IOException { + ModelFormField modelFormField = textField.getModelFormField(); + + writer.append(" updateAreas = modelFormField.getOnChangeUpdateAreas(); + boolean ajaxEnabled = updateAreas != null && this.javaScriptEnabled; + if (!textField.getClientAutocompleteField() || ajaxEnabled) { + writer.append(" autocomplete=\"off\""); + } + + writer.append("/>"); + + this.addAsterisks(writer, context, modelFormField); + + this.makeHyperlinkString(writer, textField.getSubHyperlink(), context); + + this.appendTooltip(writer, context, modelFormField); + + if (ajaxEnabled) { + appendWhitespace(writer); + writer.append(""); + } + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderTextareaField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.TextareaField) + */ + public void renderTextareaField(Appendable writer, Map context, TextareaField textareaField) throws IOException { + ModelFormField modelFormField = textareaField.getModelFormField(); + + writer.append("'); + + String value = modelFormField.getEntry(context, textareaField.getDefaultValue(context)); + if (UtilValidate.isNotEmpty(value)) { + writer.append(value); + } + + writer.append(""); + + if (textareaField.getVisualEditorEnable()) { + writer.append(""); + writer.append(""); + writer.append(""); + } + + this.addAsterisks(writer, context, modelFormField); + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderDateTimeField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.DateTimeField) + */ + public void renderDateTimeField(Appendable writer, Map context, DateTimeField dateTimeField) throws IOException { + String macroLibraryPath = UtilProperties.getPropertyValue("widget", "screen.formrenderer"); + try { + MacroFormRenderer macroFormRenderer = new MacroFormRenderer(macroLibraryPath, this.request, this.response); + macroFormRenderer.renderDateTimeField(writer, context, dateTimeField); + } catch (TemplateException e) { + Debug.logError(e, "Error rendering screen thru ftl macro: renderDateTimeField", module); + } catch (IOException e) { + Debug.logError(e, "Error rendering screen thru ftl, macro: renderDateTimeField", module); + } + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderDropDownField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.DropDownField) + */ + public void renderDropDownField(Appendable writer, Map context, DropDownField dropDownField) throws IOException { + ModelFormField modelFormField = dropDownField.getModelFormField(); + ModelForm modelForm = modelFormField.getModelForm(); + ModelFormField.AutoComplete autoComplete = dropDownField.getAutoComplete(); + boolean ajaxEnabled = autoComplete != null && this.javaScriptEnabled; + List allOptionValues = dropDownField.getAllOptionValues(context, WidgetWorker.getDelegator(context)); + + String event = modelFormField.getEvent(); + String action = modelFormField.getAction(context); + + String currentValue = modelFormField.getEntry(context); + // Get the current value's description from the option value. If there + // is a localized version it will be there. + String currentDescription = null; + if (UtilValidate.isNotEmpty(currentValue)) { + for (ModelFormField.OptionValue optionValue : allOptionValues) { + if (encode(optionValue.getKey(), modelFormField, context).equals(currentValue)) { + currentDescription = optionValue.getDescription(); + break; + } + } + } + + if (ajaxEnabled) { + writer.append(""); + + appendWhitespace(writer); + writer.append(""); + + appendWhitespace(writer); + writer.append(""); + } else { + writer.append('"'); + + if (UtilValidate.isNotEmpty(idName)) { + writer.append(" id=\""); + writer.append(idName); + writer.append('"'); + } + + if (dropDownField.getAllowMultiple()) { + writer.append(" multiple=\"multiple\""); + } + + int otherFieldSize = dropDownField.getOtherFieldSize(); + String otherFieldName = dropDownField.getParameterNameOther(context); + if (otherFieldSize > 0) { + //writer.append(" onchange=\"alert('ONCHANGE, process_choice:' + process_choice)\""); + //writer.append(" onchange='test_js()' "); + writer.append(" onchange=\"process_choice(this,document."); + writer.append(modelForm.getName()); + writer.append("."); + writer.append(otherFieldName); + writer.append(")\" "); + } + + if (UtilValidate.isNotEmpty(event) && UtilValidate.isNotEmpty(action)) { + writer.append(" "); + writer.append(event); + writer.append("=\""); + writer.append(action); + writer.append('"'); + } + + writer.append(" size=\"").append(dropDownField.getSize()).append("\">"); + + // if the current value should go first, stick it in + if (UtilValidate.isNotEmpty(currentValue) && "first-in-list".equals(dropDownField.getCurrent())) { + writer.append(""); + String explicitDescription = (currentDescription != null ? currentDescription : dropDownField.getCurrentDescription(context)); + if (UtilValidate.isNotEmpty(explicitDescription)) { + writer.append(encode(explicitDescription, modelFormField, context)); + } else { + String description = FieldInfoWithOptions.getDescriptionForOptionKey(currentValue, allOptionValues); + writer.append(encode(description, modelFormField, context)); + } + writer.append(""); + + // add a "separator" option + writer.append(""); + } + + // if allow empty is true, add an empty option + if (dropDownField.getAllowEmpty()) { + writer.append(""); + } + + // list out all options according to the option list + for (ModelFormField.OptionValue optionValue: allOptionValues) { + String noCurrentSelectedKey = dropDownField.getNoCurrentSelectedKey(context); + writer.append(""); + writer.append(encode(optionValue.getDescription(), modelFormField, context)); + writer.append(""); + } + + writer.append(""); + + + // Adapted from work by Yucca Korpela + // http://www.cs.tut.fi/~jkorpela/forms/combo.html + if (otherFieldSize > 0) { + + String fieldName = modelFormField.getParameterName(context); + Map dataMap = UtilGenerics.checkMap(modelFormField.getMap(context)); + if (dataMap == null) { + dataMap = context; + } + Object otherValueObj = dataMap.get(otherFieldName); + String otherValue = (otherValueObj == null) ? "" : otherValueObj.toString(); + + writer.append(""); + writer.append("\n"); + } + } + + this.makeHyperlinkString(writer, dropDownField.getSubHyperlink(), context); + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderCheckField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.CheckField) + */ + public void renderCheckField(Appendable writer, Map context, CheckField checkField) throws IOException { + ModelFormField modelFormField = checkField.getModelFormField(); + String currentValue = modelFormField.getEntry(context); + Boolean allChecked = checkField.isAllChecked(context); + + List allOptionValues = checkField.getAllOptionValues(context, WidgetWorker.getDelegator(context)); + String event = modelFormField.getEvent(); + String action = modelFormField.getAction(context); + + // list out all options according to the option list + for (ModelFormField.OptionValue optionValue: allOptionValues) { + + writer.append(""); + + writer.append(encode(optionValue.getDescription(), modelFormField, context)); + } + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderRadioField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.RadioField) + */ + public void renderRadioField(Appendable writer, Map context, RadioField radioField) throws IOException { + ModelFormField modelFormField = radioField.getModelFormField(); + List allOptionValues = radioField.getAllOptionValues(context, WidgetWorker.getDelegator(context)); + String currentValue = modelFormField.getEntry(context); + String event = modelFormField.getEvent(); + String action = modelFormField.getAction(context); + + // list out all options according to the option list + for (ModelFormField.OptionValue optionValue: allOptionValues) { + + writer.append(""); + + writer.append(encode(optionValue.getDescription(), modelFormField, context)); + writer.append(""); + } + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderSubmitField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.SubmitField) + */ + public void renderSubmitField(Appendable writer, Map context, SubmitField submitField) throws IOException { + ModelFormField modelFormField = submitField.getModelFormField(); + ModelForm modelForm = modelFormField.getModelForm(); + String event = null; + String action = null; + String confirmation = encode(submitField.getConfirmation(context), modelFormField, context); + + if ("text-link".equals(submitField.getButtonType())) { + writer.append(""); + + writer.append(encode(modelFormField.getTitle(context), modelFormField, context)); + + writer.append(""); + } else if ("image".equals(submitField.getButtonType())) { + writer.append(""); + } else { + // default to "button" + + String formId = modelForm.getContainerId(); + List updateAreas = modelForm.getOnSubmitUpdateAreas(); + // This is here for backwards compatibility. Use on-event-update-area + // elements instead. + String backgroundSubmitRefreshTarget = submitField.getBackgroundSubmitRefreshTarget(context); + if (UtilValidate.isNotEmpty(backgroundSubmitRefreshTarget)) { + if (updateAreas == null) { + updateAreas = new LinkedList(); + } + updateAreas.add(new ModelForm.UpdateArea("submit", formId, backgroundSubmitRefreshTarget)); + } + + boolean ajaxEnabled = (UtilValidate.isNotEmpty(updateAreas) || UtilValidate.isNotEmpty(backgroundSubmitRefreshTarget)) && this.javaScriptEnabled; + if (ajaxEnabled) { + writer.append(""); + } + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderResetField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.ResetField) + */ + public void renderResetField(Appendable writer, Map context, ResetField resetField) throws IOException { + ModelFormField modelFormField = resetField.getModelFormField(); + + writer.append(""); + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderHiddenField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.HiddenField) + */ + public void renderHiddenField(Appendable writer, Map context, HiddenField hiddenField) throws IOException { + ModelFormField modelFormField = hiddenField.getModelFormField(); + String value = hiddenField.getValue(context); + this.renderHiddenField(writer, context, modelFormField, value); + } + + public void renderHiddenField(Appendable writer, Map context, ModelFormField modelFormField, String value) throws IOException { + writer.append(""); + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderIgnoredField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.IgnoredField) + */ + public void renderIgnoredField(Appendable writer, Map context, IgnoredField ignoredField) throws IOException { + // do nothing, it's an ignored field; could add a comment or something if we wanted to + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFieldTitle(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField) + */ + public void renderFieldTitle(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { + String tempTitleText = modelFormField.getTitle(context); + String titleText = UtilHttp.encodeAmpersands(tempTitleText); + + if (UtilValidate.isNotEmpty(titleText)) { + // copied from MacroFormRenderer renderFieldTitle + String displayHelpText = UtilProperties.getPropertyValue("widget.properties", "widget.form.displayhelpText"); + String helpText = null; + if ("Y".equals(displayHelpText)) { + Delegator delegator = WidgetWorker.getDelegator(context); + Locale locale = (Locale)context.get("locale"); + String entityName = modelFormField.getEntityName(); + String fieldName = modelFormField.getFieldName(); + helpText = UtilHelpText.getEntityFieldDescription(entityName, fieldName, delegator, locale); + } + if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle()) || UtilValidate.isNotEmpty(helpText)) { + writer.append(""); + } + if (" ".equals(titleText)) { + // If the title content is just a blank then render it colling renderFormatEmptySpace: + // the method will set its content to work fine in most browser + this.renderFormatEmptySpace(writer, context, modelFormField.getModelForm()); + } else { + renderHyperlinkTitle(writer, context, modelFormField, titleText); + } + + if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { + writer.append(""); + } + + //appendWhitespace(writer); + } + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFieldTitle(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField) + */ + public void renderSingleFormFieldTitle(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { + boolean requiredField = modelFormField.getRequiredField(); + if (requiredField) { + + String requiredStyle = modelFormField.getRequiredFieldStyle(); + if (UtilValidate.isEmpty(requiredStyle)) { + requiredStyle = modelFormField.getTitleStyle(); + } + + if (UtilValidate.isNotEmpty(requiredStyle)) { + writer.append(""); + } + renderHyperlinkTitle(writer, context, modelFormField, modelFormField.getTitle(context)); + if (UtilValidate.isNotEmpty(requiredStyle)) { + writer.append(""); + } + + //appendWhitespace(writer); + } else { + renderFieldTitle(writer, context, modelFormField); + } + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { + this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context); + renderBeginningBoundaryComment(writer, "Form Widget - Form Element", modelForm); + writer.append("
"); + + boolean useRowSubmit = modelForm.getUseRowSubmit(); + if (useRowSubmit) { + writer.append(""); + } + + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(""); + String focusFieldName = FormRenderer.getFocusFieldName(modelForm, context); + if (UtilValidate.isNotEmpty(focusFieldName)) { + appendWhitespace(writer); + writer.append(""); + } + appendWhitespace(writer); + renderEndingBoundaryComment(writer, "Form Widget - Form Element", modelForm); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderMultiFormClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { + for (ModelFormField submitField: modelForm.getMultiSubmitFields()) { + if (submitField != null) { + + // Threw this in that as a hack to keep the submit button from expanding the first field + // Needs a more rugged solution + // WARNING: this method (renderMultiFormClose) must be called after the + // table that contains the list has been closed (to avoid validation errors) so + // we cannot call here the methods renderFormatItemRowCell*: for this reason + // they are now commented. + + // this.renderFormatItemRowCellOpen(writer, context, modelForm, submitField); + // this.renderFormatItemRowCellClose(writer, context, modelForm, submitField); + + // this.renderFormatItemRowCellOpen(writer, context, modelForm, submitField); + + submitField.renderFieldString(writer, context, this); + + // this.renderFormatItemRowCellClose(writer, context, modelForm, submitField); + + } + } + writer.append(""); + appendWhitespace(writer); + + // see if there is anything that needs to be added outside of the multi-form + Map wholeFormContext = UtilGenerics.checkMap(context.get("wholeFormContext")); + Appendable postMultiFormWriter = wholeFormContext != null ? (Appendable) wholeFormContext.get("postMultiFormWriter") : null; + if (postMultiFormWriter != null) { + writer.append(postMultiFormWriter.toString()); + appendWhitespace(writer); + } + + renderEndingBoundaryComment(writer, "Form Widget - Form Element (Multi)", modelForm); + } + + public void renderFormatListWrapperOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { + + Map inputFields = UtilGenerics.checkMap(context.get("requestParameters")); + Map queryStringMap = UtilGenerics.toMap(context.get("queryStringMap")); + if (UtilValidate.isNotEmpty(queryStringMap)) { + inputFields.putAll(queryStringMap); + } + if (modelForm.getType().equals("multi")) { + inputFields = UtilHttp.removeMultiFormParameters(inputFields); + } + String queryString = UtilHttp.urlEncodeArgs(inputFields); + context.put("_QBESTRING_", queryString); + + this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context); + renderBeginningBoundaryComment(writer, "Form Widget", modelForm); + + if (this.renderPagination) { + this.renderNextPrev(writer, context, modelForm); + } + writer.append(" "); + appendWhitespace(writer); + } + + public void renderFormatListWrapperClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append("
"); + + appendWhitespace(writer); + if (this.renderPagination) { + this.renderNextPrev(writer, context, modelForm); + } + renderEndingBoundaryComment(writer, "Form Widget - Formal List Wrapper", modelForm); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormatHeaderRowOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(" "); + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormatHeaderRowClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(" "); + + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowCellOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm, org.ofbiz.widget.model.ModelFormField, int positionSpan) + */ + public void renderFormatHeaderRowCellOpen(Appendable writer, Map context, ModelForm modelForm, ModelFormField modelFormField, int positionSpan) throws IOException { + writer.append(" 1) { + writer.append(" colspan=\""); + writer.append(Integer.toString(positionSpan)); + writer.append("\""); + } + if (UtilValidate.isNotEmpty(areaStyle)) { + writer.append(" class=\""); + writer.append(areaStyle); + writer.append("\""); + } + writer.append(">"); + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm, org.ofbiz.widget.model.ModelFormField) + */ + public void renderFormatHeaderRowCellClose(Appendable writer, Map context, ModelForm modelForm, ModelFormField modelFormField) throws IOException { + writer.append(""); + appendWhitespace(writer); + } + + public void renderFormatHeaderRowFormCellOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(" "); + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowFormCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormatHeaderRowFormCellClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(""); + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatHeaderRowFormCellTitleSeparator(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm, boolean) + */ + public void renderFormatHeaderRowFormCellTitleSeparator(Appendable writer, Map context, ModelForm modelForm, ModelFormField modelFormField, boolean isLast) throws IOException { + + String titleStyle = modelFormField.getTitleStyle(); + if (UtilValidate.isNotEmpty(titleStyle)) { + writer.append(""); + } + if (isLast) { + writer.append(" - "); + } else { + writer.append(" - "); + } + if (UtilValidate.isNotEmpty(titleStyle)) { + writer.append(""); + } + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormatItemRowOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { + Integer itemIndex = (Integer)context.get("itemIndex"); + + writer.append(" "); + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormatItemRowClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(" "); + + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowCellOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm, org.ofbiz.widget.model.ModelFormField) + */ + public void renderFormatItemRowCellOpen(Appendable writer, Map context, ModelForm modelForm, ModelFormField modelFormField, int positionSpan) throws IOException { + writer.append(" 1) { + writer.append(" colspan=\""); + writer.append(Integer.toString(positionSpan)); + writer.append("\""); + } + if (UtilValidate.isNotEmpty(areaStyle)) { + writer.append(" class=\""); + writer.append(areaStyle); + writer.append("\""); + } + writer.append(">"); + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm, org.ofbiz.widget.model.ModelFormField) + */ + public void renderFormatItemRowCellClose(Appendable writer, Map context, ModelForm modelForm, ModelFormField modelFormField) throws IOException { + writer.append(""); + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowFormCellOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormatItemRowFormCellOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(" "); + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatItemRowFormCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormatItemRowFormCellClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(""); + appendWhitespace(writer); + } + + public void renderFormatSingleWrapperOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(" "); + appendWhitespace(writer); + } + + public void renderFormatSingleWrapperClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append("
"); + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormatFieldRowOpen(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(" "); + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowClose(java.io.Writer, java.util.Map, org.ofbiz.widget.form.model.ModelForm) + */ + public void renderFormatFieldRowClose(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(" "); + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowTitleCellOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField) + */ + public void renderFormatFieldRowTitleCellOpen(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { + writer.append(" "); + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowTitleCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField) + */ + public void renderFormatFieldRowTitleCellClose(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { + writer.append(""); + appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowSpacerCell(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField) + */ + public void renderFormatFieldRowSpacerCell(Appendable writer, Map context, ModelFormField modelFormField) throws IOException { + // Embedded styling - bad idea + //writer.append(" "); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowWidgetCellOpen(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField, int) + */ + public void renderFormatFieldRowWidgetCellOpen(Appendable writer, Map context, ModelFormField modelFormField, int positions, int positionSpan, Integer nextPositionInRow) throws IOException { +// writer.append(" 1) { +// writer.append("30"); +// } else { +// writer.append("80"); +// } +// writer.append("%\""); + writer.append(" 0) { + writer.append(" colspan=\""); + // do a span of 1 for this column, plus 3 columns for each spanned + //position or each blank position that this will be filling in + writer.append(Integer.toString(1 + (positionSpan * 3))); + writer.append("\""); + } + String areaStyle = modelFormField.getWidgetAreaStyle(); + if (UtilValidate.isNotEmpty(areaStyle)) { + writer.append(" class=\""); + writer.append(areaStyle); + writer.append("\""); + } + writer.append(">"); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFormatFieldRowWidgetCellClose(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField, int) + */ + public void renderFormatFieldRowWidgetCellClose(Appendable writer, Map context, ModelFormField modelFormField, int positions, int positionSpan, Integer nextPositionInRow) throws IOException { + writer.append(""); + appendWhitespace(writer); + } + + public void renderFormatEmptySpace(Appendable writer, Map context, ModelForm modelForm) throws IOException { + writer.append(" "); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderTextFindField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.TextFindField) + */ + public void renderTextFindField(Appendable writer, Map context, TextFindField textFindField) throws IOException { + + ModelFormField modelFormField = textFindField.getModelFormField(); + + String defaultOption = textFindField.getDefaultOption(); + Locale locale = (Locale)context.get("locale"); + if (!textFindField.getHideOptions()) { + String opEquals = UtilProperties.getMessage("conditional", "equals", locale); + String opBeginsWith = UtilProperties.getMessage("conditional", "begins_with", locale); + String opContains = UtilProperties.getMessage("conditional", "contains", locale); + String opIsEmpty = UtilProperties.getMessage("conditional", "is_empty", locale); + String opNotEqual = UtilProperties.getMessage("conditional", "not_equal", locale); + writer.append(" "); + } else { + writer.append(" "); + } + + writer.append(""); + + if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { + writer.append(" "); + } + + String ignoreCase = UtilProperties.getMessage("conditional", "ignore_case", locale); + boolean ignCase = textFindField.getIgnoreCase(); + + if (!textFindField.getHideIgnoreCase()) { + writer.append(" "); + writer.append(ignoreCase); + } else { + writer.append(""); + } + + if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { + writer.append(""); + } + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderRangeFindField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.RangeFindField) + */ + public void renderRangeFindField(Appendable writer, Map context, RangeFindField rangeFindField) throws IOException { + + ModelFormField modelFormField = rangeFindField.getModelFormField(); + Locale locale = (Locale)context.get("locale"); + String opEquals = UtilProperties.getMessage("conditional", "equals", locale); + String opGreaterThan = UtilProperties.getMessage("conditional", "greater_than", locale); + String opGreaterThanEquals = UtilProperties.getMessage("conditional", "greater_than_equals", locale); + String opLessThan = UtilProperties.getMessage("conditional", "less_than", locale); + String opLessThanEquals = UtilProperties.getMessage("conditional", "less_than_equals", locale); + //String opIsEmpty = UtilProperties.getMessage("conditional", "is_empty", locale); + + writer.append(""); + + if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { + writer.append(" "); + } + + String defaultOptionFrom = rangeFindField.getDefaultOptionFrom(); + writer.append(" "); + + writer.append(""); + + writer.append("
"); + + writer.append(""); + + String defaultOptionThru = rangeFindField.getDefaultOptionThru(); + writer.append(" "); + + if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { + writer.append(""); + } + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderDateFindField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.DateFindField) + */ + public void renderDateFindField(Appendable writer, Map context, DateFindField dateFindField) throws IOException { + ModelFormField modelFormField = dateFindField.getModelFormField(); + + Locale locale = (Locale)context.get("locale"); + String opEquals = UtilProperties.getMessage("conditional", "equals", locale); + String opGreaterThan = UtilProperties.getMessage("conditional", "greater_than", locale); + String opSameDay = UtilProperties.getMessage("conditional", "same_day", locale); + String opGreaterThanFromDayStart = UtilProperties.getMessage("conditional", + "greater_than_from_day_start", locale); + String opLessThan = UtilProperties.getMessage("conditional", "less_than", locale); + String opUpToDay = UtilProperties.getMessage("conditional", "up_to_day", locale); + String opUpThruDay = UtilProperties.getMessage("conditional", "up_thru_day", locale); + String opIsEmpty = UtilProperties.getMessage("conditional", "is_empty", locale); + + Map uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap")); + if (uiLabelMap == null) { + Debug.logWarning("Could not find uiLabelMap in context", module); + } + String localizedInputTitle = "", localizedIconTitle = ""; + + writer.append(" maxlength) { + value = value.substring(0, maxlength); + } + writer.append(" value=\""); + writer.append(value); + writer.append('"'); + } + + writer.append(" size=\""); + writer.append(Integer.toString(size)); + writer.append('"'); + + writer.append(" maxlength=\""); + writer.append(Integer.toString(maxlength)); + writer.append('"'); + + writer.append("/>"); + + // search for a localized label for the icon + if (uiLabelMap != null) { + localizedIconTitle = uiLabelMap.get("CommonViewCalendar"); + } + ModelForm modelForm = modelFormField.getModelForm(); + // add calendar pop-up button and seed data IF this is not a "time" type date-find + if (!"time".equals(dateFindField.getType())) { + if ("date".equals(dateFindField.getType())) { + writer.append(""); + + writer.append("\"");"); + } + + if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { + writer.append(" "); + } + + String defaultOptionFrom = dateFindField.getDefaultOptionFrom(); + writer.append(" "); + + if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { + writer.append(" "); + } + + writer.append("
"); + + writer.append(" maxlength) { + value = value.substring(0, maxlength); + } + writer.append(" value=\""); + writer.append(value); + writer.append('"'); + } + + writer.append(" size=\""); + writer.append(Integer.toString(size)); + writer.append('"'); + + writer.append(" maxlength=\""); + writer.append(Integer.toString(maxlength)); + writer.append('"'); + + writer.append("/>"); + + // add calendar pop-up button and seed data IF this is not a "time" type date-find + if (!"time".equals(dateFindField.getType())) { + if ("date".equals(dateFindField.getType())) { + writer.append(""); + + writer.append("\"");"); + } + + if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { + writer.append(" "); + } + + String defaultOptionThru = dateFindField.getDefaultOptionThru(); + writer.append(" "); + + if (UtilValidate.isNotEmpty(modelFormField.getTitleStyle())) { + writer.append(""); + } + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderLookupField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.LookupField) + */ + public void renderLookupField(Appendable writer, Map context, LookupField lookupField) throws IOException { + ModelFormField modelFormField = lookupField.getModelFormField(); + + writer.append(" updateAreas = modelFormField.getOnChangeUpdateAreas(); + boolean ajaxEnabled = updateAreas != null && this.javaScriptEnabled; + if (!lookupField.getClientAutocompleteField() || ajaxEnabled) { + writer.append(" autocomplete=\"off\""); + } + + writer.append("/>"); + ModelForm modelForm = modelFormField.getModelForm(); + // add lookup pop-up button + String descriptionFieldName = lookupField.getDescriptionFieldName(); + if (UtilValidate.isNotEmpty(descriptionFieldName)) { + writer.append(" targetParameterList = lookupField.getTargetParameterList(); + for (String targetParameter: targetParameterList) { + // named like: document.${formName}.${targetParameter}.value + writer.append(", document."); + writer.append(FormRenderer.getCurrentFormName(modelForm, context)); + writer.append("."); + writer.append(targetParameter); + writer.append(".value"); + } + writer.append(");\">"); + writer.append("\"Lookup\"/"); + + this.addAsterisks(writer, context, modelFormField); + + this.makeHyperlinkString(writer, lookupField.getSubHyperlink(), context); + this.appendTooltip(writer, context, modelFormField); + + if (ajaxEnabled) { + appendWhitespace(writer); + writer.append(""); + } + appendWhitespace(writer); + + //appendWhitespace(writer); + } + + protected String appendExternalLoginKey(String target) { + String result = target; + String sessionId = ";jsessionid=" + request.getSession().getId(); + int questionIndex = target.indexOf("?"); + if (questionIndex == -1) { + result += sessionId; + } else { + result = result.replace("?", sessionId + "?"); + } + return result; + } + + private int getActualPageSize(Map context) { + Integer value = (Integer) context.get("actualPageSize"); + return value != null ? value.intValue() : (getHighIndex(context) - getLowIndex(context)); + } + + private int getHighIndex(Map context) { + Integer value = (Integer) context.get("highIndex"); + return value != null ? value.intValue() : 0; + } + + private int getListSize(Map context) { + Integer value = (Integer) context.get("listSize"); + return value != null ? value.intValue() : 0; + } + + private int getLowIndex(Map context) { + Integer value = (Integer) context.get("lowIndex"); + return value != null ? value.intValue() : 0; + } + + public void renderNextPrev(Appendable writer, Map context, ModelForm modelForm) throws IOException { + boolean ajaxEnabled = false; + List updateAreas = modelForm.getOnPaginateUpdateAreas(); + String targetService = modelForm.getPaginateTarget(context); + if (this.javaScriptEnabled) { + if (UtilValidate.isNotEmpty(updateAreas)) { + ajaxEnabled = true; + } + } + if (targetService == null) { + targetService = "${targetService}"; + } + if (UtilValidate.isEmpty(targetService) && updateAreas == null) { + Debug.logWarning("Cannot paginate because TargetService is empty for the form: " + modelForm.getName(), module); + return; + } + + // get the parameterized pagination index and size fields + int paginatorNumber = WidgetWorker.getPaginatorNumber(context); + String viewIndexParam = modelForm.getMultiPaginateIndexField(context); + String viewSizeParam = modelForm.getMultiPaginateSizeField(context); + + int viewIndex = Paginator.getViewIndex(modelForm, context); + int viewSize = Paginator.getViewSize(modelForm, context); + int listSize = getListSize(context); + + int lowIndex = getLowIndex(context); + int highIndex = getHighIndex(context); + int actualPageSize = getActualPageSize(context); + + // if this is all there seems to be (if listSize < 0, then size is unknown) + if (actualPageSize >= listSize && listSize >= 0) return; + + // needed for the "Page" and "rows" labels + Map uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap")); + String pageLabel = ""; + String commonDisplaying = ""; + if (uiLabelMap == null) { + Debug.logWarning("Could not find uiLabelMap in context", module); + } else { + pageLabel = uiLabelMap.get("CommonPage"); + Map messageMap = UtilMisc.toMap("lowCount", Integer.valueOf(lowIndex + 1), "highCount", Integer.valueOf(lowIndex + actualPageSize), "total", Integer.valueOf(listSize)); + commonDisplaying = UtilProperties.getMessage("CommonUiLabels", "CommonDisplaying", messageMap, (Locale) context.get("locale")); + } + + // for legacy support, the viewSizeParam is VIEW_SIZE and viewIndexParam is VIEW_INDEX when the fields are "viewSize" and "viewIndex" + if (viewIndexParam.equals("viewIndex" + "_" + paginatorNumber)) viewIndexParam = "VIEW_INDEX" + "_" + paginatorNumber; + if (viewSizeParam.equals("viewSize" + "_" + paginatorNumber)) viewSizeParam = "VIEW_SIZE" + "_" + paginatorNumber; + + String str = (String) context.get("_QBESTRING_"); + + // strip legacy viewIndex/viewSize params from the query string + String queryString = UtilHttp.stripViewParamsFromQueryString(str, "" + paginatorNumber); + + // strip parametrized index/size params from the query string + HashSet paramNames = new HashSet(); + paramNames.add(viewIndexParam); + paramNames.add(viewSizeParam); + queryString = UtilHttp.stripNamedParamsFromQueryString(queryString, paramNames); + + String anchor = ""; + String paginateAnchor = modelForm.getPaginateTargetAnchor(); + if (paginateAnchor != null) anchor = "#" + paginateAnchor; + + // Create separate url path String and request parameters String, + // add viewIndex/viewSize parameters to request parameter String + String urlPath = UtilHttp.removeQueryStringFromTarget(targetService); + StringBuilder prepLinkBuffer = new StringBuilder(); + String prepLinkQueryString = UtilHttp.getQueryStringFromTarget(targetService); + if (prepLinkQueryString != null) { + prepLinkBuffer.append(prepLinkQueryString); + } + if (prepLinkBuffer.indexOf("?") < 0) { + prepLinkBuffer.append("?"); + } else if (prepLinkBuffer.indexOf("?", prepLinkBuffer.length() - 1) > 0) { + prepLinkBuffer.append("&"); + } + if (!UtilValidate.isEmpty(queryString) && !queryString.equals("null")) { + prepLinkBuffer.append(queryString).append("&"); + } + prepLinkBuffer.append(viewSizeParam).append("=").append(viewSize).append("&").append(viewIndexParam).append("="); + String prepLinkText = prepLinkBuffer.toString(); + if (ajaxEnabled) { + // Prepare params for prototype.js + prepLinkText = prepLinkText.replace("?", ""); + prepLinkText = prepLinkText.replace("&", "&"); + } + + writer.append("
"); + appendWhitespace(writer); + writer.append("
    "); + appendWhitespace(writer); + + String linkText; + + // First button + writer.append("
  • 0) { + writer.append("\">").append(modelForm.getPaginateFirstLabel(context)).append(""); + } else { + // disabled button + writer.append("-disabled\">").append(modelForm.getPaginateFirstLabel(context)); + } + writer.append("
  • "); + appendWhitespace(writer); + + // Previous button + writer.append("
  • 0) { + writer.append("\">").append(modelForm.getPaginatePreviousLabel(context)).append(""); + } else { + // disabled button + writer.append("-disabled\">").append(modelForm.getPaginatePreviousLabel(context)); + } + writer.append("
  • "); + appendWhitespace(writer); + + // Page select dropdown + if (listSize > 0 && this.javaScriptEnabled) { + writer.append("
  • ").append(pageLabel).append("
  • "); + } + + // show row count + writer.append("
  • "); + writer.append(commonDisplaying); + writer.append("
  • "); + appendWhitespace(writer); + + // Next button + writer.append("
  • ").append(modelForm.getPaginateNextLabel(context)).append(""); + } else { + // disabled button + writer.append("-disabled\">").append(modelForm.getPaginateNextLabel(context)); + } + writer.append("
  • "); + appendWhitespace(writer); + + // Last button + writer.append("
  • ").append(modelForm.getPaginateLastLabel(context)).append(""); + } else { + // disabled button + writer.append("-disabled\">").append(modelForm.getPaginateLastLabel(context)); + } + writer.append("
  • "); + appendWhitespace(writer); + + writer.append("
"); + appendWhitespace(writer); + writer.append("
"); + appendWhitespace(writer); + } + + public void renderSortField(Appendable writer, Map context, ModelFormField modelFormField, String titleText) throws IOException { + boolean ajaxEnabled = false; + ModelForm modelForm = modelFormField.getModelForm(); + List updateAreas = modelForm.getOnPaginateUpdateAreas(); + String targetService = modelForm.getPaginateTarget(context); + if (this.javaScriptEnabled) { + if (UtilValidate.isNotEmpty(updateAreas)) { + ajaxEnabled = true; + } + } + if (targetService == null) { + targetService = "${targetService}"; + } + if (UtilValidate.isEmpty(targetService) && updateAreas == null) { + Debug.logWarning("Cannot sort because TargetService is empty for the form: " + modelForm.getName(), module); + return; + } + + String str = (String) context.get("_QBESTRING_"); + String oldSortField = modelForm.getSortField(context); + String sortFieldStyle = modelFormField.getSortFieldStyle(); + + // if the entry-name is defined use this instead of field name + String columnField = modelFormField.getEntryName(); + if (UtilValidate.isEmpty(columnField)) { + columnField = modelFormField.getFieldName(); + } + + // switch beetween asc/desc order + String newSortField = columnField; + if (UtilValidate.isNotEmpty(oldSortField)) { + if (oldSortField.equals(columnField)) { + newSortField = "-" + columnField; + sortFieldStyle = modelFormField.getSortFieldStyleDesc(); + } else if (oldSortField.equals("-" + columnField)) { + newSortField = columnField; + sortFieldStyle = modelFormField.getSortFieldStyleAsc(); + } + } + + // strip sortField param from the query string + HashSet paramName = new HashSet(); + paramName.add("sortField"); + String queryString = UtilHttp.stripNamedParamsFromQueryString(str, paramName); + String urlPath = UtilHttp.removeQueryStringFromTarget(targetService); + StringBuilder prepLinkBuffer = new StringBuilder(); + String prepLinkQueryString = UtilHttp.getQueryStringFromTarget(targetService); + if (prepLinkQueryString != null) { + prepLinkBuffer.append(prepLinkQueryString); + } + if (prepLinkBuffer.indexOf("?") < 0) { + prepLinkBuffer.append("?"); + } else if (prepLinkBuffer.indexOf("?", prepLinkBuffer.length() - 1) > 0) { + prepLinkBuffer.append("&"); + } + if (!UtilValidate.isEmpty(queryString) && !queryString.equals("null")) { + prepLinkBuffer.append(queryString).append("&"); + } + prepLinkBuffer.append("sortField").append("=").append(newSortField); + String prepLinkText = prepLinkBuffer.toString(); + if (ajaxEnabled) { + prepLinkText = prepLinkText.replace("?", ""); + prepLinkText = prepLinkText.replace("&", "&"); + } + + writer.append("").append(titleText).append(""); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderFileField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.FileField) + */ + public void renderFileField(Appendable writer, Map context, FileField textField) throws IOException { + ModelFormField modelFormField = textField.getModelFormField(); + + writer.append(""); + + this.makeHyperlinkString(writer, textField.getSubHyperlink(), context); + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderPasswordField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.PasswordField) + */ + public void renderPasswordField(Appendable writer, Map context, PasswordField passwordField) throws IOException { + ModelFormField modelFormField = passwordField.getModelFormField(); + + writer.append(""); + + this.addAsterisks(writer, context, modelFormField); + + this.makeHyperlinkString(writer, passwordField.getSubHyperlink(), context); + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.form.FormStringRenderer#renderImageField(java.io.Writer, java.util.Map, org.ofbiz.widget.model.ModelFormField.ImageField) + */ + public void renderImageField(Appendable writer, Map context, ImageField imageField) throws IOException { + ModelFormField modelFormField = imageField.getModelFormField(); + + writer.append(""); + + this.makeHyperlinkString(writer, imageField.getSubHyperlink(), context); + + this.appendTooltip(writer, context, modelFormField); + + //appendWhitespace(writer); + } + + public void renderFieldGroupOpen(Appendable writer, Map context, ModelForm.FieldGroup fieldGroup) throws IOException { + String style = fieldGroup.getStyle(); + String id = fieldGroup.getId(); + FlexibleStringExpander titleNotExpanded = FlexibleStringExpander.getInstance(fieldGroup.getTitle()); + String title = titleNotExpanded.expandString(context); + Boolean collapsed = fieldGroup.initiallyCollapsed(); + String collapsibleAreaId = fieldGroup.getId() + "_body"; + + if (UtilValidate.isNotEmpty(style) || UtilValidate.isNotEmpty(id) || UtilValidate.isNotEmpty(title)) { + + writer.append("
"); + + writer.append("
"); + + if (fieldGroup.collapsible()) { + String expandToolTip = null; + String collapseToolTip = null; + Map uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap")); + //Map paramMap = UtilGenerics.checkMap(context.get("requestParameters")); + if (uiLabelMap != null) { + expandToolTip = (String) uiLabelMap.get("CommonExpand"); + collapseToolTip = (String) uiLabelMap.get("CommonCollapse"); + } + + writer.append(""); + + appendWhitespace(writer); + } + writer.append(""); + + if (UtilValidate.isNotEmpty(title)) { + writer.append("
"); + writer.append(title); + writer.append("
"); + } + + writer.append("
"); + + writer.append("
"); + } + } + + public void renderFieldGroupClose(Appendable writer, Map context, ModelForm.FieldGroup fieldGroup) throws IOException { + String style = fieldGroup.getStyle(); + String id = fieldGroup.getId(); + String title = fieldGroup.getTitle(); + if (UtilValidate.isNotEmpty(style) || UtilValidate.isNotEmpty(id) || UtilValidate.isNotEmpty(title)) { + writer.append("
"); + writer.append("
"); + } + } + + // TODO: Remove embedded styling + public void renderBanner(Appendable writer, Map context, ModelForm.Banner banner) throws IOException { + writer.append(" "); + String style = banner.getStyle(context); + String leftStyle = banner.getLeftTextStyle(context); + if (UtilValidate.isEmpty(leftStyle)) leftStyle = style; + String rightStyle = banner.getRightTextStyle(context); + if (UtilValidate.isEmpty(rightStyle)) rightStyle = style; + + String leftText = banner.getLeftText(context); + if (UtilValidate.isNotEmpty(leftText)) { + writer.append(" "); + } + + String text = banner.getText(context); + if (UtilValidate.isNotEmpty(text)) { + writer.append(" "); + } + + String rightText = banner.getRightText(context); + if (UtilValidate.isNotEmpty(rightText)) { + writer.append(" "); + } + writer.append("
"); + if (UtilValidate.isNotEmpty(leftStyle)) { + writer.append(""); + } + writer.append(leftText); + if (UtilValidate.isNotEmpty(leftStyle)) { + writer.append(""); + } + writer.append(""); + if (UtilValidate.isNotEmpty(style)) { + writer.append(""); + } + writer.append(text); + if (UtilValidate.isNotEmpty(style)) { + writer.append(""); + } + writer.append(""); + if (UtilValidate.isNotEmpty(rightStyle)) { + writer.append(""); + } + writer.append(rightText); + if (UtilValidate.isNotEmpty(rightStyle)) { + writer.append(""); + } + writer.append("
"); + } + + /** + * Renders a link for the column header fields when there is a header-link="" specified in the tag, using + * style from header-link-style="". Also renders a selectAll checkbox in multi forms. + * @param writer + * @param context + * @param modelFormField + * @param titleText + */ + public void renderHyperlinkTitle(Appendable writer, Map context, ModelFormField modelFormField, String titleText) throws IOException { + if (UtilValidate.isNotEmpty(modelFormField.getHeaderLink())) { + StringBuilder targetBuffer = new StringBuilder(); + FlexibleStringExpander target = FlexibleStringExpander.getInstance(modelFormField.getHeaderLink()); + String fullTarget = target.expandString(context); + targetBuffer.append(fullTarget); + String targetType = CommonWidgetModels.Link.DEFAULT_URL_MODE; + if (UtilValidate.isNotEmpty(targetBuffer.toString()) && targetBuffer.toString().toLowerCase().startsWith("javascript:")) { + targetType="plain"; + } + WidgetWorker.makeHyperlinkString(writer, modelFormField.getHeaderLinkStyle(), targetType, targetBuffer.toString(), null, titleText, null, modelFormField, this.request, this.response, null, null); + } else if (modelFormField.isSortField()) { + renderSortField (writer, context, modelFormField, titleText); + } else if (modelFormField.isRowSubmit()) { + if (UtilValidate.isNotEmpty(titleText)) writer.append(titleText).append("
"); + writer.append(""); + } else { + writer.append(titleText); + } + } + + public void renderContainerFindField(Appendable writer, Map context, ContainerField containerField) throws IOException { + writer.append("
"); + } + + /** Create an ajaxXxxx JavaScript CSV string from a list of UpdateArea objects. See + * selectall.js. + * @param updateAreas + * @param extraParams Renderer-supplied additional target parameters + * @param context + * @return Parameter string or empty string if no UpdateArea objects were found + */ + public String createAjaxParamsFromUpdateAreas(List updateAreas, String extraParams, Map context) { + if (updateAreas == null) { + return ""; + } + StringBuilder ajaxUrl = new StringBuilder(); + boolean firstLoop = true; + for (ModelForm.UpdateArea updateArea : updateAreas) { + if (firstLoop) { + firstLoop = false; + } else { + ajaxUrl.append(","); + } + String targetUrl = updateArea.getAreaTarget(context); + String ajaxParams = getAjaxParamsFromTarget(targetUrl); + if (UtilValidate.isNotEmpty(extraParams)) { + if (ajaxParams.length() > 0 && !extraParams.startsWith("&")) { + ajaxParams += "&"; + } + ajaxParams += extraParams; + } + ajaxUrl.append(updateArea.getAreaId()).append(","); + try { + appendOfbizUrl(ajaxUrl, UtilHttp.removeQueryStringFromTarget(targetUrl)); + } catch (IOException e) { + throw UtilMisc.initCause(new InternalError(e.getMessage()), e); + } + ajaxUrl.append(",").append(ajaxParams); + } + return ajaxUrl.toString(); + } +} diff --git a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlFormWrapper.java b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlFormWrapper.java index 3718ea0223..ffa9eb9e81 100644 --- a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlFormWrapper.java +++ b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlFormWrapper.java @@ -1,200 +1,200 @@ -/******************************************************************************* - * 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.widget.renderer.html; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.parsers.ParserConfigurationException; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.UtilGenerics; -import org.ofbiz.base.util.UtilHttp; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.base.util.collections.MapStack; -import org.ofbiz.entity.Delegator; -import org.ofbiz.service.LocalDispatcher; -import org.ofbiz.widget.model.FormFactory; -import org.ofbiz.widget.model.ModelForm; -import org.ofbiz.widget.renderer.FormRenderer; -import org.ofbiz.widget.renderer.FormStringRenderer; -import org.xml.sax.SAXException; - - -/** - * Widget Library - HTML Form Wrapper class - makes it easy to do the setup and render of a form - */ -public class HtmlFormWrapper { - - public static final String module = HtmlFormWrapper.class.getName(); - - protected String resourceName; - protected String formName; - protected HttpServletRequest request; - protected HttpServletResponse response; - protected ModelForm modelForm; - protected FormStringRenderer renderer; - protected Map context; - - protected HtmlFormWrapper() {} - - public HtmlFormWrapper(String resourceName, String formName, HttpServletRequest request, HttpServletResponse response) - throws IOException, SAXException, ParserConfigurationException { - this.resourceName = resourceName; - this.formName = formName; - this.request = request; - this.response = response; - Delegator delegator = null; - try { - delegator = (Delegator) request.getAttribute("delegator"); - LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); - this.modelForm = FormFactory.getFormFromLocation(resourceName, formName, delegator.getModelReader(), dispatcher.getDispatchContext()); - } catch (IllegalArgumentException iae) { - Debug.logWarning("Could not find form with name [" + formName + "] in class resource [" + resourceName + "], will try to load it using relative path syntax.", module); - this.modelForm = FormFactory.getFormFromWebappContext(resourceName, formName, request); - } - - this.renderer = new HtmlFormRenderer(request, response); - - this.context = new HashMap(); - Map parameterMap = UtilHttp.getParameterMap(request); - context.put("parameters", parameterMap); - - //make sure the locale is in the context - context.put("locale", UtilHttp.getLocale(request)); - //make sure the timeZone is in the context - context.put("timeZone", UtilHttp.getTimeZone(request)); - - // if there was an error message, this is an error - if (UtilValidate.isNotEmpty(request.getAttribute("_ERROR_MESSAGE_"))) { - context.put("isError", Boolean.TRUE); - } else { - context.put("isError", Boolean.FALSE); - } - - // if a parameter was passed saying this is an error, it is an error - if ("true".equals(parameterMap.get("isError"))) { - context.put("isError", Boolean.TRUE); - } - - Map uiLabelMap = UtilGenerics.cast(request.getAttribute("uiLabelMap")); - if (UtilValidate.isNotEmpty(uiLabelMap) && context.get("uiLabelMap") == null) { - Debug.logInfo("Got uiLabelMap: " + uiLabelMap, module); - context.put("uiLabelMap", uiLabelMap); - } - if (UtilValidate.isNotEmpty(delegator) && context.get("delegator") == null) { - context.put("delegator", delegator); - } - } - - @SuppressWarnings("unchecked") - public StringWriter renderFormString(Object contextStack) throws Exception { - if (contextStack instanceof MapStack) { - return renderFormString((MapStack) contextStack); - } else { - Debug.logWarning("Call renderFormString with a non-MapStack: " + (contextStack == null ? "null" : contextStack.getClass().getName()), module); - return renderFormString(); - } - } - public StringWriter renderFormString(MapStack contextStack) throws Exception { - // create a new context with the current context on the bottom - contextStack.push(this.context); - StringWriter buffer = new StringWriter(); - FormRenderer formRenderer = new FormRenderer(modelForm, renderer); - formRenderer.render(buffer, contextStack); - contextStack.pop(); - return buffer; - } - public StringWriter renderFormString() throws Exception { - StringWriter buffer = new StringWriter(); - FormRenderer formRenderer = new FormRenderer(modelForm, renderer); - formRenderer.render(buffer, context); - return buffer; - } - - /** - * Tells the form library whether this is a response to an error or not. - * Defaults on initialization according to the presense of an errorMessage - * in the request or if an isError parameter was passed to the page with - * the value "true". If true then the prefilled values will come from the - * parameters Map instead of the value Map. - */ - public void setIsError(boolean isError) { - this.context.put("isError", Boolean.valueOf(isError)); - } - - public boolean getIsError() { - Boolean isErrorBoolean = (Boolean) this.context.get("isError"); - if (isErrorBoolean == null) { - return false; - } else { - return isErrorBoolean.booleanValue(); - } - } - - /** - * The "useRequestParameters" value in the form context tells the form library - * to use the request parameters to fill in values instead of the value map. - * This is generally used when it is an empty form to pre-set inital values. - * This is automatically set to false for list and multi forms. For related - * functionality see the setIsError method. - * - * @param useRequestParameters - */ - public void setUseRequestParameters(boolean useRequestParameters) { - this.context.put("useRequestParameters", Boolean.valueOf(useRequestParameters)); - } - - public boolean getUseRequestParameters() { - Boolean useRequestParametersBoolean = (Boolean) this.context.get("useRequestParameters"); - if (useRequestParametersBoolean == null) { - return false; - } else { - return useRequestParametersBoolean.booleanValue(); - } - } - - public void setFormOverrideName(String formName) { - this.context.put("formName", formName); - } - - public void putInContext(String name, Object value) { - this.context.put(name, value); - } - - public Object getFromContext(String name) { - return this.context.get(name); - } - - public ModelForm getModelForm() { - return modelForm; - } - - public FormStringRenderer getRenderer() { - return renderer; - } - - public void setRenderer(FormStringRenderer renderer) { - this.renderer = renderer; - } -} +/******************************************************************************* + * 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.widget.renderer.html; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.UtilGenerics; +import org.ofbiz.base.util.UtilHttp; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.base.util.collections.MapStack; +import org.ofbiz.entity.Delegator; +import org.ofbiz.service.LocalDispatcher; +import org.ofbiz.widget.model.FormFactory; +import org.ofbiz.widget.model.ModelForm; +import org.ofbiz.widget.renderer.FormRenderer; +import org.ofbiz.widget.renderer.FormStringRenderer; +import org.xml.sax.SAXException; + + +/** + * Widget Library - HTML Form Wrapper class - makes it easy to do the setup and render of a form + */ +public class HtmlFormWrapper { + + public static final String module = HtmlFormWrapper.class.getName(); + + protected String resourceName; + protected String formName; + protected HttpServletRequest request; + protected HttpServletResponse response; + protected ModelForm modelForm; + protected FormStringRenderer renderer; + protected Map context; + + protected HtmlFormWrapper() {} + + public HtmlFormWrapper(String resourceName, String formName, HttpServletRequest request, HttpServletResponse response) + throws IOException, SAXException, ParserConfigurationException { + this.resourceName = resourceName; + this.formName = formName; + this.request = request; + this.response = response; + Delegator delegator = null; + try { + delegator = (Delegator) request.getAttribute("delegator"); + LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); + this.modelForm = FormFactory.getFormFromLocation(resourceName, formName, delegator.getModelReader(), dispatcher.getDispatchContext()); + } catch (IllegalArgumentException iae) { + Debug.logWarning("Could not find form with name [" + formName + "] in class resource [" + resourceName + "], will try to load it using relative path syntax.", module); + this.modelForm = FormFactory.getFormFromWebappContext(resourceName, formName, request); + } + + this.renderer = new HtmlFormRenderer(request, response); + + this.context = new HashMap(); + Map parameterMap = UtilHttp.getParameterMap(request); + context.put("parameters", parameterMap); + + //make sure the locale is in the context + context.put("locale", UtilHttp.getLocale(request)); + //make sure the timeZone is in the context + context.put("timeZone", UtilHttp.getTimeZone(request)); + + // if there was an error message, this is an error + if (UtilValidate.isNotEmpty(request.getAttribute("_ERROR_MESSAGE_"))) { + context.put("isError", Boolean.TRUE); + } else { + context.put("isError", Boolean.FALSE); + } + + // if a parameter was passed saying this is an error, it is an error + if ("true".equals(parameterMap.get("isError"))) { + context.put("isError", Boolean.TRUE); + } + + Map uiLabelMap = UtilGenerics.cast(request.getAttribute("uiLabelMap")); + if (UtilValidate.isNotEmpty(uiLabelMap) && context.get("uiLabelMap") == null) { + Debug.logInfo("Got uiLabelMap: " + uiLabelMap, module); + context.put("uiLabelMap", uiLabelMap); + } + if (UtilValidate.isNotEmpty(delegator) && context.get("delegator") == null) { + context.put("delegator", delegator); + } + } + + @SuppressWarnings("unchecked") + public StringWriter renderFormString(Object contextStack) throws Exception { + if (contextStack instanceof MapStack) { + return renderFormString((MapStack) contextStack); + } else { + Debug.logWarning("Call renderFormString with a non-MapStack: " + (contextStack == null ? "null" : contextStack.getClass().getName()), module); + return renderFormString(); + } + } + public StringWriter renderFormString(MapStack contextStack) throws Exception { + // create a new context with the current context on the bottom + contextStack.push(this.context); + StringWriter buffer = new StringWriter(); + FormRenderer formRenderer = new FormRenderer(modelForm, renderer); + formRenderer.render(buffer, contextStack); + contextStack.pop(); + return buffer; + } + public StringWriter renderFormString() throws Exception { + StringWriter buffer = new StringWriter(); + FormRenderer formRenderer = new FormRenderer(modelForm, renderer); + formRenderer.render(buffer, context); + return buffer; + } + + /** + * Tells the form library whether this is a response to an error or not. + * Defaults on initialization according to the presense of an errorMessage + * in the request or if an isError parameter was passed to the page with + * the value "true". If true then the prefilled values will come from the + * parameters Map instead of the value Map. + */ + public void setIsError(boolean isError) { + this.context.put("isError", Boolean.valueOf(isError)); + } + + public boolean getIsError() { + Boolean isErrorBoolean = (Boolean) this.context.get("isError"); + if (isErrorBoolean == null) { + return false; + } else { + return isErrorBoolean.booleanValue(); + } + } + + /** + * The "useRequestParameters" value in the form context tells the form library + * to use the request parameters to fill in values instead of the value map. + * This is generally used when it is an empty form to pre-set inital values. + * This is automatically set to false for list and multi forms. For related + * functionality see the setIsError method. + * + * @param useRequestParameters + */ + public void setUseRequestParameters(boolean useRequestParameters) { + this.context.put("useRequestParameters", Boolean.valueOf(useRequestParameters)); + } + + public boolean getUseRequestParameters() { + Boolean useRequestParametersBoolean = (Boolean) this.context.get("useRequestParameters"); + if (useRequestParametersBoolean == null) { + return false; + } else { + return useRequestParametersBoolean.booleanValue(); + } + } + + public void setFormOverrideName(String formName) { + this.context.put("formName", formName); + } + + public void putInContext(String name, Object value) { + this.context.put(name, value); + } + + public Object getFromContext(String name) { + return this.context.get(name); + } + + public ModelForm getModelForm() { + return modelForm; + } + + public FormStringRenderer getRenderer() { + return renderer; + } + + public void setRenderer(FormStringRenderer renderer) { + this.renderer = renderer; + } +} diff --git a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuRenderer.java b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuRenderer.java index 15531a3302..2a8c10cc52 100644 --- a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuRenderer.java +++ b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuRenderer.java @@ -1,592 +1,592 @@ -/******************************************************************************* - * 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.widget.renderer.html; - -import java.io.IOException; -import java.math.BigDecimal; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.ofbiz.base.util.StringUtil; -import org.ofbiz.base.util.UtilCodec; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.entity.Delegator; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.webapp.control.RequestHandler; -import org.ofbiz.webapp.taglib.ContentUrlTag; -import org.ofbiz.widget.WidgetWorker; -import org.ofbiz.widget.model.CommonWidgetModels.Image; -import org.ofbiz.widget.model.ModelMenu; -import org.ofbiz.widget.model.ModelMenuItem; -import org.ofbiz.widget.model.ModelMenuItem.MenuLink; -import org.ofbiz.widget.model.ModelWidget; -import org.ofbiz.widget.renderer.MenuStringRenderer; - -/** - * Widget Library - HTML Menu Renderer implementation - */ -public class HtmlMenuRenderer extends HtmlWidgetRenderer implements MenuStringRenderer { - - HttpServletRequest request; - HttpServletResponse response; - protected String userLoginIdAtPermGrant; - protected String permissionErrorMessage = ""; - - public static final String module = HtmlMenuRenderer.class.getName(); - - protected HtmlMenuRenderer() {} - - public HtmlMenuRenderer(HttpServletRequest request, HttpServletResponse response) { - this.request = request; - this.response = response; - } - - public void appendOfbizUrl(Appendable writer, String location) throws IOException { - ServletContext ctx = (ServletContext) request.getAttribute("servletContext"); - if (ctx == null) { - //if (Debug.infoOn()) Debug.logInfo("in appendOfbizUrl, ctx is null(0): buffer=" + buffer.toString() + " location:" + location, ""); - HttpSession session = request.getSession(); - if (session != null) { - ctx = session.getServletContext(); - } else { - //if (Debug.infoOn()) Debug.logInfo("in appendOfbizUrl, session is null(1)", ""); - } - if (ctx == null) { - throw new RuntimeException("ctx is null. location:" + location); - } - //if (Debug.infoOn()) Debug.logInfo("in appendOfbizUrl, ctx is NOT null(2)", ""); - } - Delegator delegator = (Delegator)request.getAttribute("delegator"); - if (delegator == null) { - //if (Debug.infoOn()) Debug.logInfo("in appendOfbizUrl, delegator is null(5)", ""); - } - RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_"); - // make and append the link - String s = rh.makeLink(this.request, this.response, location); - if (s.indexOf("null") >= 0) { - //if (Debug.infoOn()) Debug.logInfo("in appendOfbizUrl(3), url: " + s, ""); - } - writer.append(s); - } - - public void appendContentUrl(Appendable writer, String location) throws IOException { - ServletContext ctx = (ServletContext) this.request.getAttribute("servletContext"); - if (ctx == null) { - //if (Debug.infoOn()) Debug.logInfo("in appendContentUrl, ctx is null(0): buffer=" + buffer.toString() + " location:" + location, ""); - HttpSession session = request.getSession(); - if (session != null) { - ctx = session.getServletContext(); - } else { - //if (Debug.infoOn()) Debug.logInfo("in appendContentUrl, session is null(1)", ""); - } - if (ctx == null) { - throw new RuntimeException("ctx is null. location:" + location); - } - //if (Debug.infoOn()) Debug.logInfo("in appendContentUrl, ctx is NOT null(2)", ""); - this.request.setAttribute("servletContext", ctx); - } - Delegator delegator = (Delegator) request.getAttribute("delegator"); - if (delegator == null) { - //if (Debug.infoOn()) Debug.logInfo("in appendContentUrl, delegator is null(6)", ""); - } - StringBuilder buffer = new StringBuilder(); - ContentUrlTag.appendContentPrefix(this.request, buffer); - writer.append(buffer.toString()); - writer.append(location); - } - - public void appendTooltip(Appendable writer, Map context, ModelMenuItem modelMenuItem) throws IOException { - // render the tooltip - String tooltip = modelMenuItem.getTooltip(context); - if (UtilValidate.isNotEmpty(tooltip)) { - writer.append(""); - } - } - - public void renderFormatSimpleWrapperRows(Appendable writer, Map context, Object menuObj) throws IOException { - List menuItemList = ((ModelMenu) menuObj).getMenuItemList(); - for (ModelMenuItem currentMenuItem: menuItemList) { - renderMenuItem(writer, context, currentMenuItem); - } - } - - public void renderMenuItem(Appendable writer, Map context, ModelMenuItem menuItem) throws IOException { - - //Debug.logInfo("in renderMenuItem, menuItem:" + menuItem.getName() + " context:" + context ,""); - boolean hideThisItem = isHideIfSelected(menuItem, context); - //if (Debug.infoOn()) Debug.logInfo("in HtmlMenuRendererImage, hideThisItem:" + hideThisItem,""); - if (hideThisItem) - return; - - String style = menuItem.getWidgetStyle(); - - if (menuItem.isSelected(context)) { - style = menuItem.getSelectedStyle(); - if (UtilValidate.isEmpty(style)) { - style = "selected"; - } - } - - if (this.isDisableIfEmpty(menuItem, context)) { - style = menuItem.getDisabledTitleStyle(); - } - - writer.append(" "); - - MenuLink link = menuItem.getLink(); - //if (Debug.infoOn()) Debug.logInfo("in HtmlMenuRendererImage, link(0):" + link,""); - if (link != null) { - renderLink(writer, context, link); - } else { - String txt = menuItem.getTitle(context); - UtilCodec.SimpleEncoder simpleEncoder = (UtilCodec.SimpleEncoder) context.get("simpleEncoder"); - if (simpleEncoder != null) { - txt = simpleEncoder.encode(txt); - } - writer.append(txt); - - } - if (!menuItem.getMenuItemList().isEmpty()) { - appendWhitespace(writer); - writer.append("
    "); - appendWhitespace(writer); - for (ModelMenuItem childMenuItem : menuItem.getMenuItemList()) { - childMenuItem.renderMenuItemString(writer, context, this); - } - writer.append("
"); - appendWhitespace(writer); - } - - writer.append(""); - - appendWhitespace(writer); - } - - public boolean isDisableIfEmpty(ModelMenuItem menuItem, Map context) { - boolean disabled = false; - String disableIfEmpty = menuItem.getDisableIfEmpty(); - if (UtilValidate.isNotEmpty(disableIfEmpty)) { - List keys = StringUtil.split(disableIfEmpty, "|"); - for (String key: keys) { - Object obj = context.get(key); - if (obj == null) { - disabled = true; - break; - } - } - } - return disabled; - } - -/* - public String buildDivStr(ModelMenuItem menuItem, Map context) { - String divStr = ""; - divStr = menuItem.getTitle(context); - return divStr; - } -*/ - public void renderMenuOpen(Appendable writer, Map context, ModelMenu modelMenu) throws IOException { - - //Debug.logInfo("in HtmlMenuRenderer, userLoginIdHasChanged:" + userLoginIdHasChanged,""); - this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context); - renderBeginningBoundaryComment(writer, "Menu Widget", modelMenu); - writer.append(""); - appendWhitespace(writer); - String menuTitle = modelMenu.getTitle(context); - if (UtilValidate.isNotEmpty(menuTitle)) { - writer.append("

").append(menuTitle).append("

"); - appendWhitespace(writer); - } - if (modelMenu.renderedMenuItemCount(context) > 0) { - writer.append("
    "); - appendWhitespace(writer); - writer.append("
  • "); - appendWhitespace(writer); - writer.append("
      "); - appendWhitespace(writer); - } - } - - /* (non-Javadoc) - * @see org.ofbiz.widget.menu.MenuStringRenderer#renderMenuClose(java.io.Writer, java.util.Map, org.ofbiz.widget.menu.ModelMenu) - */ - public void renderMenuClose(Appendable writer, Map context, ModelMenu modelMenu) throws IOException { - // TODO: div can't be directly inside an UL - String fillStyle = modelMenu.getFillStyle(); - if (UtilValidate.isNotEmpty(fillStyle)) { - writer.append("
       
      "); - } - //String menuContainerStyle = modelMenu.getMenuContainerStyle(context); - if (modelMenu.renderedMenuItemCount(context) > 0) { - writer.append("
    "); - appendWhitespace(writer); - writer.append("
  • "); - appendWhitespace(writer); - writer.append("
"); - appendWhitespace(writer); - } - writer.append("
"); - appendWhitespace(writer); - writer.append("
"); - appendWhitespace(writer); - renderEndingBoundaryComment(writer, "Menu Widget", modelMenu); - - GenericValue userLogin = (GenericValue)request.getSession().getAttribute("userLogin"); - if (userLogin != null) { - String userLoginId = userLogin.getString("userLoginId"); - //request.getSession().setAttribute("userLoginIdAtPermGrant", userLoginId); - setUserLoginIdAtPermGrant(userLoginId); - //Debug.logInfo("in HtmlMenuRenderer, userLoginId(Close):" + userLoginId + " userLoginIdAtPermGrant:" + request.getSession().getAttribute("userLoginIdAtPermGrant"),""); - } else { - request.getSession().setAttribute("userLoginIdAtPermGrant", null); - } - } - - public void renderFormatSimpleWrapperOpen(Appendable writer, Map context, ModelMenu modelMenu) throws IOException { - //appendWhitespace(writer); - } - - public void renderFormatSimpleWrapperClose(Appendable writer, Map context, ModelMenu modelMenu) throws IOException { - //appendWhitespace(writer); - } - - public void setRequest(HttpServletRequest request) { - this.request = request; - } - - public void setResponse(HttpServletResponse response) { - this.response = response; - } - - - /** - * @param string - */ - public void setUserLoginIdAtPermGrant(String string) { - //Debug.logInfo("in HtmlMenuRenderer, userLoginIdAtPermGrant(setUserLoginIdAtPermGrant):" + string,""); - this.userLoginIdAtPermGrant = string; - } - - public String getUserLoginIdAtPermGrant() { - return this.userLoginIdAtPermGrant; - } - - public boolean isHideIfSelected(ModelMenuItem menuItem, Map context) { - ModelMenu menu = menuItem.getModelMenu(); - String currentMenuItemName = menu.getSelectedMenuItemContextFieldName(context); - String currentItemName = menuItem.getName(); - Boolean hideIfSelected = menuItem.getHideIfSelected(); - //Debug.logInfo("in HtmlMenuRenderer, currentMenuItemName:" + currentMenuItemName + " currentItemName:" + currentItemName + " hideIfSelected:" + hideIfSelected,""); - return (hideIfSelected != null && hideIfSelected.booleanValue() && currentMenuItemName != null && currentMenuItemName.equals(currentItemName)); - } - - - public boolean userLoginIdHasChanged() { - boolean hasChanged = false; - GenericValue userLogin = (GenericValue)request.getSession().getAttribute("userLogin"); - userLoginIdAtPermGrant = getUserLoginIdAtPermGrant(); - //userLoginIdAtPermGrant = (String)request.getSession().getAttribute("userLoginIdAtPermGrant"); - String userLoginId = null; - if (userLogin != null) - userLoginId = userLogin.getString("userLoginId"); - //Debug.logInfo("in HtmlMenuRenderer, userLoginId:" + userLoginId + " userLoginIdAtPermGrant:" + userLoginIdAtPermGrant ,""); - if ((userLoginId == null && userLoginIdAtPermGrant != null) - || (userLoginId != null && userLoginIdAtPermGrant == null) - || ((userLoginId != null && userLoginIdAtPermGrant != null) - && !userLoginId.equals(userLoginIdAtPermGrant))) { - hasChanged = true; - } else { - if (userLoginIdAtPermGrant != null) - hasChanged = true; - else - hasChanged = false; - - userLoginIdAtPermGrant = null; - } - return hasChanged; - } - - public String getTitle(ModelMenuItem menuItem, Map context) { - String title = null; - title = menuItem.getTitle(context); - return title; - } - - public void renderLink(Appendable writer, Map context, ModelMenuItem.MenuLink link) throws IOException { - String target = link.getTarget(context); - ModelMenuItem menuItem = link.getLinkMenuItem(); - if (isDisableIfEmpty(menuItem, context)) { - target = null; - } - - if (UtilValidate.isNotEmpty(target)) { - HttpServletResponse response = (HttpServletResponse) context.get("response"); - HttpServletRequest request = (HttpServletRequest) context.get("request"); - - String targetWindow = link.getTargetWindow(context); - String uniqueItemName = menuItem.getModelMenu().getName() + "_" + menuItem.getName() + "_LF_" + UtilMisc.addToBigDecimalInMap(context, "menuUniqueItemIndex", BigDecimal.ONE); - - String linkType = WidgetWorker.determineAutoLinkType(link.getLinkType(), target, link.getUrlMode(), request); - if ("hidden-form".equals(linkType)) { - writer.append("
"); - - UtilCodec.SimpleEncoder simpleEncoder = (UtilCodec.SimpleEncoder) context.get("simpleEncoder"); - for (Map.Entry parameter: link.getParameterMap(context).entrySet()) { - writer.append(""); - } - - writer.append(""); - } - - writer.append(""); - } - - // the text - Image img = link.getImage(); - if (img != null) { - renderImage(writer, context, img); - writer.append(" " + link.getText(context)); - } else { - writer.append(link.getText(context)); - } - - if (UtilValidate.isNotEmpty(target)) { - // close tag - writer.append(""); - } - - /* NOTE DEJ20090316: This was here as a comment and not sure what it is for or if it is useful... can probably be safely removed in the future if still not used/needed - boolean isSelected = menuItem.isSelected(context); - - String style = null; - - if (isSelected) { - style = menuItem.getSelectedStyle(); - } else { - style = link.getStyle(context); - if (UtilValidate.isEmpty(style)) - style = menuItem.getTitleStyle(); - if (UtilValidate.isEmpty(style)) - style = menuItem.getWidgetStyle(); - } - - if (menuItem.getDisabled()) { - style = menuItem.getDisabledTitleStyle(); - } - - if (UtilValidate.isNotEmpty(style)) { - writer.append(" class=\""); - writer.append(style); - writer.append("\""); - } - */ - } - - public void renderImage(Appendable writer, Map context, Image image) throws IOException { - // open tag - writer.append(""); - } -} +/******************************************************************************* + * 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.widget.renderer.html; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.ofbiz.base.util.StringUtil; +import org.ofbiz.base.util.UtilCodec; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.Delegator; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.webapp.control.RequestHandler; +import org.ofbiz.webapp.taglib.ContentUrlTag; +import org.ofbiz.widget.WidgetWorker; +import org.ofbiz.widget.model.CommonWidgetModels.Image; +import org.ofbiz.widget.model.ModelMenu; +import org.ofbiz.widget.model.ModelMenuItem; +import org.ofbiz.widget.model.ModelMenuItem.MenuLink; +import org.ofbiz.widget.model.ModelWidget; +import org.ofbiz.widget.renderer.MenuStringRenderer; + +/** + * Widget Library - HTML Menu Renderer implementation + */ +public class HtmlMenuRenderer extends HtmlWidgetRenderer implements MenuStringRenderer { + + HttpServletRequest request; + HttpServletResponse response; + protected String userLoginIdAtPermGrant; + protected String permissionErrorMessage = ""; + + public static final String module = HtmlMenuRenderer.class.getName(); + + protected HtmlMenuRenderer() {} + + public HtmlMenuRenderer(HttpServletRequest request, HttpServletResponse response) { + this.request = request; + this.response = response; + } + + public void appendOfbizUrl(Appendable writer, String location) throws IOException { + ServletContext ctx = (ServletContext) request.getAttribute("servletContext"); + if (ctx == null) { + //if (Debug.infoOn()) Debug.logInfo("in appendOfbizUrl, ctx is null(0): buffer=" + buffer.toString() + " location:" + location, ""); + HttpSession session = request.getSession(); + if (session != null) { + ctx = session.getServletContext(); + } else { + //if (Debug.infoOn()) Debug.logInfo("in appendOfbizUrl, session is null(1)", ""); + } + if (ctx == null) { + throw new RuntimeException("ctx is null. location:" + location); + } + //if (Debug.infoOn()) Debug.logInfo("in appendOfbizUrl, ctx is NOT null(2)", ""); + } + Delegator delegator = (Delegator)request.getAttribute("delegator"); + if (delegator == null) { + //if (Debug.infoOn()) Debug.logInfo("in appendOfbizUrl, delegator is null(5)", ""); + } + RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_"); + // make and append the link + String s = rh.makeLink(this.request, this.response, location); + if (s.indexOf("null") >= 0) { + //if (Debug.infoOn()) Debug.logInfo("in appendOfbizUrl(3), url: " + s, ""); + } + writer.append(s); + } + + public void appendContentUrl(Appendable writer, String location) throws IOException { + ServletContext ctx = (ServletContext) this.request.getAttribute("servletContext"); + if (ctx == null) { + //if (Debug.infoOn()) Debug.logInfo("in appendContentUrl, ctx is null(0): buffer=" + buffer.toString() + " location:" + location, ""); + HttpSession session = request.getSession(); + if (session != null) { + ctx = session.getServletContext(); + } else { + //if (Debug.infoOn()) Debug.logInfo("in appendContentUrl, session is null(1)", ""); + } + if (ctx == null) { + throw new RuntimeException("ctx is null. location:" + location); + } + //if (Debug.infoOn()) Debug.logInfo("in appendContentUrl, ctx is NOT null(2)", ""); + this.request.setAttribute("servletContext", ctx); + } + Delegator delegator = (Delegator) request.getAttribute("delegator"); + if (delegator == null) { + //if (Debug.infoOn()) Debug.logInfo("in appendContentUrl, delegator is null(6)", ""); + } + StringBuilder buffer = new StringBuilder(); + ContentUrlTag.appendContentPrefix(this.request, buffer); + writer.append(buffer.toString()); + writer.append(location); + } + + public void appendTooltip(Appendable writer, Map context, ModelMenuItem modelMenuItem) throws IOException { + // render the tooltip + String tooltip = modelMenuItem.getTooltip(context); + if (UtilValidate.isNotEmpty(tooltip)) { + writer.append(""); + } + } + + public void renderFormatSimpleWrapperRows(Appendable writer, Map context, Object menuObj) throws IOException { + List menuItemList = ((ModelMenu) menuObj).getMenuItemList(); + for (ModelMenuItem currentMenuItem: menuItemList) { + renderMenuItem(writer, context, currentMenuItem); + } + } + + public void renderMenuItem(Appendable writer, Map context, ModelMenuItem menuItem) throws IOException { + + //Debug.logInfo("in renderMenuItem, menuItem:" + menuItem.getName() + " context:" + context ,""); + boolean hideThisItem = isHideIfSelected(menuItem, context); + //if (Debug.infoOn()) Debug.logInfo("in HtmlMenuRendererImage, hideThisItem:" + hideThisItem,""); + if (hideThisItem) + return; + + String style = menuItem.getWidgetStyle(); + + if (menuItem.isSelected(context)) { + style = menuItem.getSelectedStyle(); + if (UtilValidate.isEmpty(style)) { + style = "selected"; + } + } + + if (this.isDisableIfEmpty(menuItem, context)) { + style = menuItem.getDisabledTitleStyle(); + } + + writer.append(" "); + + MenuLink link = menuItem.getLink(); + //if (Debug.infoOn()) Debug.logInfo("in HtmlMenuRendererImage, link(0):" + link,""); + if (link != null) { + renderLink(writer, context, link); + } else { + String txt = menuItem.getTitle(context); + UtilCodec.SimpleEncoder simpleEncoder = (UtilCodec.SimpleEncoder) context.get("simpleEncoder"); + if (simpleEncoder != null) { + txt = simpleEncoder.encode(txt); + } + writer.append(txt); + + } + if (!menuItem.getMenuItemList().isEmpty()) { + appendWhitespace(writer); + writer.append("
    "); + appendWhitespace(writer); + for (ModelMenuItem childMenuItem : menuItem.getMenuItemList()) { + childMenuItem.renderMenuItemString(writer, context, this); + } + writer.append("
"); + appendWhitespace(writer); + } + + writer.append(""); + + appendWhitespace(writer); + } + + public boolean isDisableIfEmpty(ModelMenuItem menuItem, Map context) { + boolean disabled = false; + String disableIfEmpty = menuItem.getDisableIfEmpty(); + if (UtilValidate.isNotEmpty(disableIfEmpty)) { + List keys = StringUtil.split(disableIfEmpty, "|"); + for (String key: keys) { + Object obj = context.get(key); + if (obj == null) { + disabled = true; + break; + } + } + } + return disabled; + } + +/* + public String buildDivStr(ModelMenuItem menuItem, Map context) { + String divStr = ""; + divStr = menuItem.getTitle(context); + return divStr; + } +*/ + public void renderMenuOpen(Appendable writer, Map context, ModelMenu modelMenu) throws IOException { + + //Debug.logInfo("in HtmlMenuRenderer, userLoginIdHasChanged:" + userLoginIdHasChanged,""); + this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context); + renderBeginningBoundaryComment(writer, "Menu Widget", modelMenu); + writer.append(""); + appendWhitespace(writer); + String menuTitle = modelMenu.getTitle(context); + if (UtilValidate.isNotEmpty(menuTitle)) { + writer.append("

").append(menuTitle).append("

"); + appendWhitespace(writer); + } + if (modelMenu.renderedMenuItemCount(context) > 0) { + writer.append("
    "); + appendWhitespace(writer); + writer.append("
  • "); + appendWhitespace(writer); + writer.append("
      "); + appendWhitespace(writer); + } + } + + /* (non-Javadoc) + * @see org.ofbiz.widget.menu.MenuStringRenderer#renderMenuClose(java.io.Writer, java.util.Map, org.ofbiz.widget.menu.ModelMenu) + */ + public void renderMenuClose(Appendable writer, Map context, ModelMenu modelMenu) throws IOException { + // TODO: div can't be directly inside an UL + String fillStyle = modelMenu.getFillStyle(); + if (UtilValidate.isNotEmpty(fillStyle)) { + writer.append("
       
      "); + } + //String menuContainerStyle = modelMenu.getMenuContainerStyle(context); + if (modelMenu.renderedMenuItemCount(context) > 0) { + writer.append("
    "); + appendWhitespace(writer); + writer.append("
  • "); + appendWhitespace(writer); + writer.append("
"); + appendWhitespace(writer); + } + writer.append("
"); + appendWhitespace(writer); + writer.append("
"); + appendWhitespace(writer); + renderEndingBoundaryComment(writer, "Menu Widget", modelMenu); + + GenericValue userLogin = (GenericValue)request.getSession().getAttribute("userLogin"); + if (userLogin != null) { + String userLoginId = userLogin.getString("userLoginId"); + //request.getSession().setAttribute("userLoginIdAtPermGrant", userLoginId); + setUserLoginIdAtPermGrant(userLoginId); + //Debug.logInfo("in HtmlMenuRenderer, userLoginId(Close):" + userLoginId + " userLoginIdAtPermGrant:" + request.getSession().getAttribute("userLoginIdAtPermGrant"),""); + } else { + request.getSession().setAttribute("userLoginIdAtPermGrant", null); + } + } + + public void renderFormatSimpleWrapperOpen(Appendable writer, Map context, ModelMenu modelMenu) throws IOException { + //appendWhitespace(writer); + } + + public void renderFormatSimpleWrapperClose(Appendable writer, Map context, ModelMenu modelMenu) throws IOException { + //appendWhitespace(writer); + } + + public void setRequest(HttpServletRequest request) { + this.request = request; + } + + public void setResponse(HttpServletResponse response) { + this.response = response; + } + + + /** + * @param string + */ + public void setUserLoginIdAtPermGrant(String string) { + //Debug.logInfo("in HtmlMenuRenderer, userLoginIdAtPermGrant(setUserLoginIdAtPermGrant):" + string,""); + this.userLoginIdAtPermGrant = string; + } + + public String getUserLoginIdAtPermGrant() { + return this.userLoginIdAtPermGrant; + } + + public boolean isHideIfSelected(ModelMenuItem menuItem, Map context) { + ModelMenu menu = menuItem.getModelMenu(); + String currentMenuItemName = menu.getSelectedMenuItemContextFieldName(context); + String currentItemName = menuItem.getName(); + Boolean hideIfSelected = menuItem.getHideIfSelected(); + //Debug.logInfo("in HtmlMenuRenderer, currentMenuItemName:" + currentMenuItemName + " currentItemName:" + currentItemName + " hideIfSelected:" + hideIfSelected,""); + return (hideIfSelected != null && hideIfSelected.booleanValue() && currentMenuItemName != null && currentMenuItemName.equals(currentItemName)); + } + + + public boolean userLoginIdHasChanged() { + boolean hasChanged = false; + GenericValue userLogin = (GenericValue)request.getSession().getAttribute("userLogin"); + userLoginIdAtPermGrant = getUserLoginIdAtPermGrant(); + //userLoginIdAtPermGrant = (String)request.getSession().getAttribute("userLoginIdAtPermGrant"); + String userLoginId = null; + if (userLogin != null) + userLoginId = userLogin.getString("userLoginId"); + //Debug.logInfo("in HtmlMenuRenderer, userLoginId:" + userLoginId + " userLoginIdAtPermGrant:" + userLoginIdAtPermGrant ,""); + if ((userLoginId == null && userLoginIdAtPermGrant != null) + || (userLoginId != null && userLoginIdAtPermGrant == null) + || ((userLoginId != null && userLoginIdAtPermGrant != null) + && !userLoginId.equals(userLoginIdAtPermGrant))) { + hasChanged = true; + } else { + if (userLoginIdAtPermGrant != null) + hasChanged = true; + else + hasChanged = false; + + userLoginIdAtPermGrant = null; + } + return hasChanged; + } + + public String getTitle(ModelMenuItem menuItem, Map context) { + String title = null; + title = menuItem.getTitle(context); + return title; + } + + public void renderLink(Appendable writer, Map context, ModelMenuItem.MenuLink link) throws IOException { + String target = link.getTarget(context); + ModelMenuItem menuItem = link.getLinkMenuItem(); + if (isDisableIfEmpty(menuItem, context)) { + target = null; + } + + if (UtilValidate.isNotEmpty(target)) { + HttpServletResponse response = (HttpServletResponse) context.get("response"); + HttpServletRequest request = (HttpServletRequest) context.get("request"); + + String targetWindow = link.getTargetWindow(context); + String uniqueItemName = menuItem.getModelMenu().getName() + "_" + menuItem.getName() + "_LF_" + UtilMisc.addToBigDecimalInMap(context, "menuUniqueItemIndex", BigDecimal.ONE); + + String linkType = WidgetWorker.determineAutoLinkType(link.getLinkType(), target, link.getUrlMode(), request); + if ("hidden-form".equals(linkType)) { + writer.append("
"); + + UtilCodec.SimpleEncoder simpleEncoder = (UtilCodec.SimpleEncoder) context.get("simpleEncoder"); + for (Map.Entry parameter: link.getParameterMap(context).entrySet()) { + writer.append(""); + } + + writer.append(""); + } + + writer.append(""); + } + + // the text + Image img = link.getImage(); + if (img != null) { + renderImage(writer, context, img); + writer.append(" " + link.getText(context)); + } else { + writer.append(link.getText(context)); + } + + if (UtilValidate.isNotEmpty(target)) { + // close tag + writer.append(""); + } + + /* NOTE DEJ20090316: This was here as a comment and not sure what it is for or if it is useful... can probably be safely removed in the future if still not used/needed + boolean isSelected = menuItem.isSelected(context); + + String style = null; + + if (isSelected) { + style = menuItem.getSelectedStyle(); + } else { + style = link.getStyle(context); + if (UtilValidate.isEmpty(style)) + style = menuItem.getTitleStyle(); + if (UtilValidate.isEmpty(style)) + style = menuItem.getWidgetStyle(); + } + + if (menuItem.getDisabled()) { + style = menuItem.getDisabledTitleStyle(); + } + + if (UtilValidate.isNotEmpty(style)) { + writer.append(" class=\""); + writer.append(style); + writer.append("\""); + } + */ + } + + public void renderImage(Appendable writer, Map context, Image image) throws IOException { + // open tag + writer.append(""); + } +} diff --git a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuRendererImage.java b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuRendererImage.java index d0a51c65b4..f2231dedad 100644 --- a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuRendererImage.java +++ b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuRendererImage.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * 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.widget.renderer.html; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.entity.Delegator; -import org.ofbiz.entity.GenericEntityException; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.widget.content.WidgetContentWorker; -import org.ofbiz.widget.model.ModelMenuItem; - -/** - * Widget Library - HTML Menu Renderer implementation - */ - -public class HtmlMenuRendererImage extends HtmlMenuRenderer { - - protected HtmlMenuRendererImage() {} - - public HtmlMenuRendererImage(HttpServletRequest request, HttpServletResponse response) { - super(request, response); - } - - - public String buildDivStr(ModelMenuItem menuItem, Map context) throws IOException { - - StringBuilder imgStr = new StringBuilder(""); - return imgStr.toString(); - } - -} +/******************************************************************************* + * 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.widget.renderer.html; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.Delegator; +import org.ofbiz.entity.GenericEntityException; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.widget.content.WidgetContentWorker; +import org.ofbiz.widget.model.ModelMenuItem; + +/** + * Widget Library - HTML Menu Renderer implementation + */ + +public class HtmlMenuRendererImage extends HtmlMenuRenderer { + + protected HtmlMenuRendererImage() {} + + public HtmlMenuRendererImage(HttpServletRequest request, HttpServletResponse response) { + super(request, response); + } + + + public String buildDivStr(ModelMenuItem menuItem, Map context) throws IOException { + + StringBuilder imgStr = new StringBuilder(""); + return imgStr.toString(); + } + +} diff --git a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuWrapper.java b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuWrapper.java index 54cb8d5abc..6d145cf618 100644 --- a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuWrapper.java +++ b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuWrapper.java @@ -1,252 +1,252 @@ -/******************************************************************************* - * 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.widget.renderer.html; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.xml.parsers.ParserConfigurationException; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.UtilGenerics; -import org.ofbiz.base.util.UtilHttp; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.widget.model.MenuFactory; -import org.ofbiz.widget.model.ModelMenu; -import org.ofbiz.widget.renderer.MenuStringRenderer; -import org.xml.sax.SAXException; - - -/** - * Widget Library - HTML Menu Wrapper class - makes it easy to do the setup and render of a menu - */ -public class HtmlMenuWrapper { - - public static final String module = HtmlMenuWrapper.class.getName(); - - protected String resourceName; - protected String menuName; - protected HttpServletRequest request; - protected HttpServletResponse response; - protected ModelMenu modelMenu; - protected MenuStringRenderer renderer; - protected Map context; - - protected HtmlMenuWrapper() {} - - public HtmlMenuWrapper(String resourceName, String menuName, HttpServletRequest request, HttpServletResponse response) - throws IOException, SAXException, ParserConfigurationException { - init(resourceName, menuName, request, response); - } - - public void init(String resourceName, String menuName, HttpServletRequest request, HttpServletResponse response) - throws IOException, SAXException, ParserConfigurationException { - this.resourceName = resourceName; - this.menuName = menuName; - this.request = request; - this.response = response; - - this.modelMenu = MenuFactory.getMenuFromWebappContext(resourceName, menuName, request); - - this.renderer = getMenuRenderer(); - - this.context = new HashMap(); - Map parameterMap = UtilHttp.getParameterMap(request); - context.put("parameters", parameterMap); - - HttpSession session = request.getSession(); - GenericValue userLogin = (GenericValue)session.getAttribute("userLogin"); - context.put("userLogin", userLogin); - - //make sure the locale is in the context - context.put("locale", UtilHttp.getLocale(request)); - - // if there was an error message, this is an error - if (UtilValidate.isNotEmpty(request.getAttribute("_ERROR_MESSAGE_"))) { - context.put("isError", Boolean.TRUE); - } else { - context.put("isError", Boolean.FALSE); - } - - // if a parameter was passed saying this is an error, it is an error - if ("true".equals(parameterMap.get("isError"))) { - context.put("isError", Boolean.TRUE); - } - } - - public MenuStringRenderer getMenuRenderer() { - return new HtmlMenuRenderer(request, response); - } - - public String renderMenuString() throws IOException { - HttpServletRequest req = ((HtmlMenuRenderer)renderer).request; - ServletContext ctx = (ServletContext) req.getAttribute("servletContext"); - if (ctx == null) { - if (Debug.infoOn()) Debug.logInfo("in renderMenuString, ctx is null(0)" , ""); - } - - Writer writer = new StringWriter(); - modelMenu.renderMenuString(writer, context, renderer); - - HttpServletRequest req2 = ((HtmlMenuRenderer)renderer).request; - ServletContext ctx2 = (ServletContext) req2.getAttribute("servletContext"); - if (ctx2 == null) { - if (Debug.infoOn()) Debug.logInfo("in renderMenuString, ctx is null(2)" , ""); - } - - return writer.toString(); - } - - /** - * Tells the menu library whether this is a response to an error or not. - * Defaults on initialization according to the presense of an errorMessage - * in the request or if an isError parameter was passed to the page with - * the value "true". If true then the prefilled values will come from the - * parameters Map instead of the value Map. - */ - public void setIsError(boolean isError) { - this.context.put("isError", Boolean.valueOf(isError)); - } - - public boolean getIsError() { - Boolean isErrorBoolean = (Boolean) this.context.get("isError"); - if (isErrorBoolean == null) { - return false; - } else { - return isErrorBoolean.booleanValue(); - } - } - - public void setMenuOverrideName(String menuName) { - this.context.put("menuName", menuName); - } - - public void putInContext(String name, Object value) { - this.context.put(name, value); - } - - public void putInContext(String menuItemName, String valueName, Object value) { - Map valueMap = UtilGenerics.toMap(context.get(menuItemName)); - if (valueMap == null) { - valueMap = new HashMap(); - context.put(menuItemName, valueMap); - } - valueMap.put(valueName, value); - } - - public Object getFromContext(String name) { - return this.context.get(name); - } - - public Object getFromContext(String menuItemName, String valueName) { - Map valueMap = UtilGenerics.toMap(context.get(menuItemName)); - if (valueMap == null) { - valueMap = new HashMap(); - context.put(menuItemName, valueMap); - } - return valueMap.get(valueName); - } - - public ModelMenu getModelMenu() { - return modelMenu; - } - - public MenuStringRenderer getRenderer() { - return renderer; - } - - public void setRenderer(MenuStringRenderer renderer) { - this.renderer = renderer; - } - - public void setRequest(HttpServletRequest request) { - this.request = request; - ((HtmlMenuRenderer)renderer).setRequest(request); - } - - public void setResponse(HttpServletResponse response) { - this.response = response; - ((HtmlMenuRenderer)renderer).setResponse(response); - } - - public HttpServletRequest getRequest() { - return ((HtmlMenuRenderer)renderer).request; - } - - public HttpServletResponse getResponse() { - return ((HtmlMenuRenderer)renderer).response; - } - - public static HtmlMenuWrapper getMenuWrapper(HttpServletRequest request, HttpServletResponse response, HttpSession session, String menuDefFile, String menuName, String menuWrapperClassName) { - - HtmlMenuWrapper menuWrapper = null; - - String menuSig = menuDefFile + "__" + menuName; - if (session != null) { - menuWrapper = (HtmlMenuWrapper)session.getAttribute(menuSig); - } - - if (menuWrapper == null) { - try { - Class cls = Class.forName("org.ofbiz.widget.html." + menuWrapperClassName); - menuWrapper = (HtmlMenuWrapper)cls.newInstance(); - menuWrapper.init(menuDefFile, menuName, request, response); - } catch (InstantiationException e) { - throw new RuntimeException(e.getMessage()); - } catch (IllegalAccessException e2) { - throw new RuntimeException(e2.getMessage()); - } catch (ClassNotFoundException e3) { - throw new RuntimeException("Class not found:" + e3.getMessage()); - } catch (IOException e4) { - throw new RuntimeException(e4.getMessage()); - } catch (SAXException e5) { - throw new RuntimeException(e5.getMessage()); - } catch (ParserConfigurationException e6) { - throw new RuntimeException(e6.getMessage()); - } - } else { - menuWrapper.setRequest(request); - menuWrapper.setResponse(response); - Map parameterMap = UtilHttp.getParameterMap(request); - menuWrapper.setParameters(parameterMap); - - GenericValue userLogin = (GenericValue)session.getAttribute("userLogin"); - menuWrapper.putInContext("userLogin", userLogin); - - } - - if (session != null) { - session.setAttribute(menuSig, menuWrapper); - } - return menuWrapper; - } - - public void setParameters(Map paramMap) { - context.put("parameters", paramMap); - } - -} +/******************************************************************************* + * 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.widget.renderer.html; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.xml.parsers.ParserConfigurationException; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.UtilGenerics; +import org.ofbiz.base.util.UtilHttp; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.widget.model.MenuFactory; +import org.ofbiz.widget.model.ModelMenu; +import org.ofbiz.widget.renderer.MenuStringRenderer; +import org.xml.sax.SAXException; + + +/** + * Widget Library - HTML Menu Wrapper class - makes it easy to do the setup and render of a menu + */ +public class HtmlMenuWrapper { + + public static final String module = HtmlMenuWrapper.class.getName(); + + protected String resourceName; + protected String menuName; + protected HttpServletRequest request; + protected HttpServletResponse response; + protected ModelMenu modelMenu; + protected MenuStringRenderer renderer; + protected Map context; + + protected HtmlMenuWrapper() {} + + public HtmlMenuWrapper(String resourceName, String menuName, HttpServletRequest request, HttpServletResponse response) + throws IOException, SAXException, ParserConfigurationException { + init(resourceName, menuName, request, response); + } + + public void init(String resourceName, String menuName, HttpServletRequest request, HttpServletResponse response) + throws IOException, SAXException, ParserConfigurationException { + this.resourceName = resourceName; + this.menuName = menuName; + this.request = request; + this.response = response; + + this.modelMenu = MenuFactory.getMenuFromWebappContext(resourceName, menuName, request); + + this.renderer = getMenuRenderer(); + + this.context = new HashMap(); + Map parameterMap = UtilHttp.getParameterMap(request); + context.put("parameters", parameterMap); + + HttpSession session = request.getSession(); + GenericValue userLogin = (GenericValue)session.getAttribute("userLogin"); + context.put("userLogin", userLogin); + + //make sure the locale is in the context + context.put("locale", UtilHttp.getLocale(request)); + + // if there was an error message, this is an error + if (UtilValidate.isNotEmpty(request.getAttribute("_ERROR_MESSAGE_"))) { + context.put("isError", Boolean.TRUE); + } else { + context.put("isError", Boolean.FALSE); + } + + // if a parameter was passed saying this is an error, it is an error + if ("true".equals(parameterMap.get("isError"))) { + context.put("isError", Boolean.TRUE); + } + } + + public MenuStringRenderer getMenuRenderer() { + return new HtmlMenuRenderer(request, response); + } + + public String renderMenuString() throws IOException { + HttpServletRequest req = ((HtmlMenuRenderer)renderer).request; + ServletContext ctx = (ServletContext) req.getAttribute("servletContext"); + if (ctx == null) { + if (Debug.infoOn()) Debug.logInfo("in renderMenuString, ctx is null(0)" , ""); + } + + Writer writer = new StringWriter(); + modelMenu.renderMenuString(writer, context, renderer); + + HttpServletRequest req2 = ((HtmlMenuRenderer)renderer).request; + ServletContext ctx2 = (ServletContext) req2.getAttribute("servletContext"); + if (ctx2 == null) { + if (Debug.infoOn()) Debug.logInfo("in renderMenuString, ctx is null(2)" , ""); + } + + return writer.toString(); + } + + /** + * Tells the menu library whether this is a response to an error or not. + * Defaults on initialization according to the presense of an errorMessage + * in the request or if an isError parameter was passed to the page with + * the value "true". If true then the prefilled values will come from the + * parameters Map instead of the value Map. + */ + public void setIsError(boolean isError) { + this.context.put("isError", Boolean.valueOf(isError)); + } + + public boolean getIsError() { + Boolean isErrorBoolean = (Boolean) this.context.get("isError"); + if (isErrorBoolean == null) { + return false; + } else { + return isErrorBoolean.booleanValue(); + } + } + + public void setMenuOverrideName(String menuName) { + this.context.put("menuName", menuName); + } + + public void putInContext(String name, Object value) { + this.context.put(name, value); + } + + public void putInContext(String menuItemName, String valueName, Object value) { + Map valueMap = UtilGenerics.toMap(context.get(menuItemName)); + if (valueMap == null) { + valueMap = new HashMap(); + context.put(menuItemName, valueMap); + } + valueMap.put(valueName, value); + } + + public Object getFromContext(String name) { + return this.context.get(name); + } + + public Object getFromContext(String menuItemName, String valueName) { + Map valueMap = UtilGenerics.toMap(context.get(menuItemName)); + if (valueMap == null) { + valueMap = new HashMap(); + context.put(menuItemName, valueMap); + } + return valueMap.get(valueName); + } + + public ModelMenu getModelMenu() { + return modelMenu; + } + + public MenuStringRenderer getRenderer() { + return renderer; + } + + public void setRenderer(MenuStringRenderer renderer) { + this.renderer = renderer; + } + + public void setRequest(HttpServletRequest request) { + this.request = request; + ((HtmlMenuRenderer)renderer).setRequest(request); + } + + public void setResponse(HttpServletResponse response) { + this.response = response; + ((HtmlMenuRenderer)renderer).setResponse(response); + } + + public HttpServletRequest getRequest() { + return ((HtmlMenuRenderer)renderer).request; + } + + public HttpServletResponse getResponse() { + return ((HtmlMenuRenderer)renderer).response; + } + + public static HtmlMenuWrapper getMenuWrapper(HttpServletRequest request, HttpServletResponse response, HttpSession session, String menuDefFile, String menuName, String menuWrapperClassName) { + + HtmlMenuWrapper menuWrapper = null; + + String menuSig = menuDefFile + "__" + menuName; + if (session != null) { + menuWrapper = (HtmlMenuWrapper)session.getAttribute(menuSig); + } + + if (menuWrapper == null) { + try { + Class cls = Class.forName("org.ofbiz.widget.html." + menuWrapperClassName); + menuWrapper = (HtmlMenuWrapper)cls.newInstance(); + menuWrapper.init(menuDefFile, menuName, request, response); + } catch (InstantiationException e) { + throw new RuntimeException(e.getMessage()); + } catch (IllegalAccessException e2) { + throw new RuntimeException(e2.getMessage()); + } catch (ClassNotFoundException e3) { + throw new RuntimeException("Class not found:" + e3.getMessage()); + } catch (IOException e4) { + throw new RuntimeException(e4.getMessage()); + } catch (SAXException e5) { + throw new RuntimeException(e5.getMessage()); + } catch (ParserConfigurationException e6) { + throw new RuntimeException(e6.getMessage()); + } + } else { + menuWrapper.setRequest(request); + menuWrapper.setResponse(response); + Map parameterMap = UtilHttp.getParameterMap(request); + menuWrapper.setParameters(parameterMap); + + GenericValue userLogin = (GenericValue)session.getAttribute("userLogin"); + menuWrapper.putInContext("userLogin", userLogin); + + } + + if (session != null) { + session.setAttribute(menuSig, menuWrapper); + } + return menuWrapper; + } + + public void setParameters(Map paramMap) { + context.put("parameters", paramMap); + } + +} diff --git a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuWrapperImage.java b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuWrapperImage.java index c41f2ac4f5..bed4c7f33f 100644 --- a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuWrapperImage.java +++ b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlMenuWrapperImage.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * 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.widget.renderer.html; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.parsers.ParserConfigurationException; - -import org.ofbiz.entity.Delegator; -import org.ofbiz.entity.GenericEntityException; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.entity.util.EntityQuery; -import org.ofbiz.widget.model.ModelMenuItem; -import org.ofbiz.widget.renderer.MenuStringRenderer; -import org.xml.sax.SAXException; - -/** - * Widget Library - HTML Menu Wrapper class - makes it easy to do the setup and render of a menu - */ -public class HtmlMenuWrapperImage extends HtmlMenuWrapper { - - public static final String module = HtmlMenuWrapperImage.class.getName(); - - protected HtmlMenuWrapperImage() {} - - public HtmlMenuWrapperImage(String resourceName, String menuName, HttpServletRequest request, HttpServletResponse response) - throws IOException, SAXException, ParserConfigurationException { - super(resourceName, menuName, request, response); - } - - @Override - public MenuStringRenderer getMenuRenderer() { - return new HtmlMenuRendererImage(request, response); - } - - @Override - public void init(String resourceName, String menuName, HttpServletRequest request, HttpServletResponse response) - throws IOException, SAXException, ParserConfigurationException { - - super.init(resourceName, menuName, request, response); - //String pubPt = (String)request.getAttribute("pubPt"); - //if (Debug.infoOn()) Debug.logInfo("in init, pubPt:" + pubPt, module); - Map dummyMap = new HashMap(); - Delegator delegator = (Delegator)request.getAttribute("delegator"); - //if (Debug.infoOn()) Debug.logInfo("in init, delegator:" + delegator, module); - try { - for (ModelMenuItem menuItem : modelMenu.getMenuItemList()) { - String contentId = menuItem.getAssociatedContentId(dummyMap); - //if (Debug.infoOn()) Debug.logInfo("in init, contentId:" + contentId, module); - GenericValue webSitePublishPoint = EntityQuery.use(delegator).from("WebSitePublishPoint").where("contentId", contentId).cache().queryOne(); - String menuItemName = menuItem.getName(); - //if (Debug.infoOn()) Debug.logInfo("in init, menuItemName:" + menuItemName, module); - //if (Debug.infoOn()) Debug.logInfo("in init, webSitePublishPoint:" + webSitePublishPoint, module); - putInContext(menuItemName, "WebSitePublishPoint", webSitePublishPoint); - } - } catch (GenericEntityException e) { - return; - } - } -} +/******************************************************************************* + * 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.widget.renderer.html; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; + +import org.ofbiz.entity.Delegator; +import org.ofbiz.entity.GenericEntityException; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.entity.util.EntityQuery; +import org.ofbiz.widget.model.ModelMenuItem; +import org.ofbiz.widget.renderer.MenuStringRenderer; +import org.xml.sax.SAXException; + +/** + * Widget Library - HTML Menu Wrapper class - makes it easy to do the setup and render of a menu + */ +public class HtmlMenuWrapperImage extends HtmlMenuWrapper { + + public static final String module = HtmlMenuWrapperImage.class.getName(); + + protected HtmlMenuWrapperImage() {} + + public HtmlMenuWrapperImage(String resourceName, String menuName, HttpServletRequest request, HttpServletResponse response) + throws IOException, SAXException, ParserConfigurationException { + super(resourceName, menuName, request, response); + } + + @Override + public MenuStringRenderer getMenuRenderer() { + return new HtmlMenuRendererImage(request, response); + } + + @Override + public void init(String resourceName, String menuName, HttpServletRequest request, HttpServletResponse response) + throws IOException, SAXException, ParserConfigurationException { + + super.init(resourceName, menuName, request, response); + //String pubPt = (String)request.getAttribute("pubPt"); + //if (Debug.infoOn()) Debug.logInfo("in init, pubPt:" + pubPt, module); + Map dummyMap = new HashMap(); + Delegator delegator = (Delegator)request.getAttribute("delegator"); + //if (Debug.infoOn()) Debug.logInfo("in init, delegator:" + delegator, module); + try { + for (ModelMenuItem menuItem : modelMenu.getMenuItemList()) { + String contentId = menuItem.getAssociatedContentId(dummyMap); + //if (Debug.infoOn()) Debug.logInfo("in init, contentId:" + contentId, module); + GenericValue webSitePublishPoint = EntityQuery.use(delegator).from("WebSitePublishPoint").where("contentId", contentId).cache().queryOne(); + String menuItemName = menuItem.getName(); + //if (Debug.infoOn()) Debug.logInfo("in init, menuItemName:" + menuItemName, module); + //if (Debug.infoOn()) Debug.logInfo("in init, webSitePublishPoint:" + webSitePublishPoint, module); + putInContext(menuItemName, "WebSitePublishPoint", webSitePublishPoint); + } + } catch (GenericEntityException e) { + return; + } + } +} diff --git a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlScreenRenderer.java b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlScreenRenderer.java index 845f0db66c..759a3d1f47 100644 --- a/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlScreenRenderer.java +++ b/framework/widget/src/org/ofbiz/widget/renderer/html/HtmlScreenRenderer.java @@ -1,948 +1,948 @@ -/******************************************************************************* - * 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.widget.renderer.html; - -import java.io.IOException; -import java.math.BigDecimal; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.GeneralException; -import org.ofbiz.base.util.UtilFormatOut; -import org.ofbiz.base.util.UtilGenerics; -import org.ofbiz.base.util.UtilHttp; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.entity.Delegator; -import org.ofbiz.entity.GenericValue; -import org.ofbiz.service.LocalDispatcher; -import org.ofbiz.webapp.control.RequestHandler; -import org.ofbiz.webapp.taglib.ContentUrlTag; -import org.ofbiz.widget.WidgetWorker; -import org.ofbiz.widget.content.WidgetContentWorker; -import org.ofbiz.widget.content.WidgetDataResourceWorker; -import org.ofbiz.widget.model.ModelForm; -import org.ofbiz.widget.model.ModelMenu; -import org.ofbiz.widget.model.ModelScreenWidget; -import org.ofbiz.widget.model.ModelScreenWidget.ColumnContainer; -import org.ofbiz.widget.model.ModelScreenWidget.Container; -import org.ofbiz.widget.model.ModelScreenWidget.Content; -import org.ofbiz.widget.model.ModelScreenWidget.Form; -import org.ofbiz.widget.model.ModelScreenWidget.HorizontalSeparator; -import org.ofbiz.widget.model.ModelScreenWidget.Label; -import org.ofbiz.widget.model.ModelScreenWidget.Menu; -import org.ofbiz.widget.model.ModelScreenWidget.PortalPage; -import org.ofbiz.widget.model.ModelScreenWidget.ScreenImage; -import org.ofbiz.widget.model.ModelScreenWidget.ScreenLink; -import org.ofbiz.widget.model.ModelScreenWidget.Screenlet; -import org.ofbiz.widget.model.ModelScreenWidget.Section; -import org.ofbiz.widget.model.ModelScreenWidget.SubContent; -import org.ofbiz.widget.model.ModelWidget; -import org.ofbiz.widget.renderer.FormStringRenderer; -import org.ofbiz.widget.renderer.MenuStringRenderer; -import org.ofbiz.widget.renderer.Paginator; -import org.ofbiz.widget.renderer.ScreenStringRenderer; - -/** - * Widget Library - HTML Form Renderer implementation - * @deprecated Use MacroScreenRenderer. - */ -public class HtmlScreenRenderer extends HtmlWidgetRenderer implements ScreenStringRenderer { - - public static final String module = HtmlScreenRenderer.class.getName(); - protected int elementId = 999; - - public HtmlScreenRenderer() {} - - protected String getNextElementId() { - elementId++; - return "hsr" + elementId; - } - - public String getRendererName() { - return "html"; - } - - public void renderScreenBegin(Appendable writer, Map context) throws IOException { - writer.append(""); - appendWhitespace(writer); - } - - public void renderScreenEnd(Appendable writer, Map context) throws IOException { - } - - public void renderSectionBegin(Appendable writer, Map context, Section section) throws IOException { - if (section.isMainSection()) { - this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context); - } - renderBeginningBoundaryComment(writer, section.isMainSection()?"Screen":"Section Widget", section); - } - - public void renderSectionEnd(Appendable writer, Map context, Section section) throws IOException { - renderEndingBoundaryComment(writer, section.isMainSection()?"Screen":"Section Widget", section); - } - - public void renderContainerBegin(Appendable writer, Map context, Container container) throws IOException { - String containerId = container.getId(context); - String autoUpdateTarget = container.getAutoUpdateTargetExdr(context); - HttpServletRequest request = (HttpServletRequest) context.get("request"); - if (UtilValidate.isNotEmpty(autoUpdateTarget) && UtilHttp.isJavaScriptEnabled(request)) { - if (UtilValidate.isEmpty(containerId)) { - containerId = getNextElementId(); - } - HttpServletResponse response = (HttpServletResponse) context.get("response"); - ServletContext ctx = (ServletContext) request.getAttribute("servletContext"); - RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_"); - - writer.append(""); - appendWhitespace(writer); - } - writer.append(""); - appendWhitespace(writer); - } - public void renderContainerEnd(Appendable writer, Map context, Container container) throws IOException { - writer.append(""); - appendWhitespace(writer); - } - - public void renderHorizontalSeparator(Appendable writer, Map context, HorizontalSeparator separator) throws IOException { - writer.append(""); - appendWhitespace(writer); - } - - public void renderScreenletBegin(Appendable writer, Map context, boolean collapsed, Screenlet screenlet) throws IOException { - HttpServletRequest request = (HttpServletRequest) context.get("request"); - HttpServletResponse response = (HttpServletResponse) context.get("response"); - boolean javaScriptEnabled = UtilHttp.isJavaScriptEnabled(request); - Menu tabMenu = screenlet.getTabMenu(); - if (tabMenu != null) { - tabMenu.renderWidgetString(writer, context, this); - } - writer.append("
"); - appendWhitespace(writer); - - String title = screenlet.getTitle(context); - Menu navMenu = screenlet.getNavigationMenu(); - Form navForm = screenlet.getNavigationForm(); - String collapsibleAreaId = null; - if (UtilValidate.isNotEmpty(title) || navMenu != null || navForm != null || screenlet.collapsible()) { - writer.append("
"); - appendWhitespace(writer); - writer.append("
    "); - appendWhitespace(writer); - if (UtilValidate.isNotEmpty(title)) { - writer.append("
  • "); - writer.append(title); - writer.append("
  • "); - appendWhitespace(writer); - } - if (screenlet.collapsible()) { - collapsibleAreaId = this.getNextElementId(); - String expandToolTip = null; - String collapseToolTip = null; - Map uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap")); - Map paramMap = UtilGenerics.checkMap(context.get("requestParameters")); - Map requestParameters = new HashMap(paramMap); - if (uiLabelMap != null) { - expandToolTip = (String) uiLabelMap.get("CommonExpand"); - collapseToolTip = (String) uiLabelMap.get("CommonCollapse"); - } - writer.append("
  •  
  • "); - appendWhitespace(writer); - } - if (!collapsed) { - if (navMenu != null) { - MenuStringRenderer savedRenderer = (MenuStringRenderer) context.get("menuStringRenderer"); - MenuStringRenderer renderer = new ScreenletMenuRenderer(request, response); - context.put("menuStringRenderer", renderer); - navMenu.renderWidgetString(writer, context, this); - context.put("menuStringRenderer", savedRenderer); - } else if (navForm != null) { - renderScreenletPaginateMenu(writer, context, navForm); - } - } - writer.append("
"); - appendWhitespace(writer); - writer.append("
"); - appendWhitespace(writer); - writer.append("
"); - appendWhitespace(writer); - writer.append(""); - appendWhitespace(writer); - } - } - - private int getActualPageSize(Map context) { - Integer value = (Integer) context.get("actualPageSize"); - return value != null ? value.intValue() : (getHighIndex(context) - getLowIndex(context)); - } - - private int getHighIndex(Map context) { - Integer value = (Integer) context.get("highIndex"); - return value != null ? value.intValue() : 0; - } - - private int getListSize(Map context) { - Integer value = (Integer) context.get("listSize"); - return value != null ? value.intValue() : 0; - } - - private int getLowIndex(Map context) { - Integer value = (Integer) context.get("lowIndex"); - return value != null ? value.intValue() : 0; - } - - protected void renderScreenletPaginateMenu(Appendable writer, Map context, Form form) throws IOException { - HttpServletResponse response = (HttpServletResponse) context.get("response"); - HttpServletRequest request = (HttpServletRequest) context.get("request"); - ModelForm modelForm; - try { - modelForm = form.getModelForm(context); - } catch (Exception e) { - throw new IOException(e); - } - modelForm.runFormActions(context); - Paginator.preparePager(modelForm, context); - String targetService = modelForm.getPaginateTarget(context); - if (targetService == null) { - targetService = "${targetService}"; - } - - // get the parametrized pagination index and size fields - int paginatorNumber = WidgetWorker.getPaginatorNumber(context); - String viewIndexParam = modelForm.getMultiPaginateIndexField(context); - String viewSizeParam = modelForm.getMultiPaginateSizeField(context); - - int viewIndex = Paginator.getViewIndex(modelForm, context); - int viewSize = Paginator.getViewSize(modelForm, context); - int listSize = getListSize(context); - - int lowIndex = getLowIndex(context); - int highIndex = getHighIndex(context); - int actualPageSize = getActualPageSize(context); - - // if this is all there seems to be (if listSize < 0, then size is unknown) - if (actualPageSize >= listSize && listSize >= 0) return; - - // needed for the "Page" and "rows" labels - Map uiLabelMap = UtilGenerics.cast(context.get("uiLabelMap")); - String ofLabel = ""; - if (uiLabelMap == null) { - Debug.logWarning("Could not find uiLabelMap in context", module); - } else { - ofLabel = uiLabelMap.get("CommonOf"); - ofLabel = ofLabel.toLowerCase(); - } - - // for legacy support, the viewSizeParam is VIEW_SIZE and viewIndexParam is VIEW_INDEX when the fields are "viewSize" and "viewIndex" - if (viewIndexParam.equals("viewIndex" + "_" + paginatorNumber)) viewIndexParam = "VIEW_INDEX" + "_" + paginatorNumber; - if (viewSizeParam.equals("viewSize" + "_" + paginatorNumber)) viewSizeParam = "VIEW_SIZE" + "_" + paginatorNumber; - - ServletContext ctx = (ServletContext) request.getAttribute("servletContext"); - RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_"); - - Map inputFields = UtilGenerics.toMap(context.get("requestParameters")); - // strip out any multi form fields if the form is of type multi - if (modelForm.getType().equals("multi")) { - inputFields = UtilHttp.removeMultiFormParameters(inputFields); - } - String queryString = UtilHttp.urlEncodeArgs(inputFields); - // strip legacy viewIndex/viewSize params from the query string - queryString = UtilHttp.stripViewParamsFromQueryString(queryString, "" + paginatorNumber); - // strip parametrized index/size params from the query string - HashSet paramNames = new HashSet(); - paramNames.add(viewIndexParam); - paramNames.add(viewSizeParam); - queryString = UtilHttp.stripNamedParamsFromQueryString(queryString, paramNames); - - String anchor = ""; - String paginateAnchor = modelForm.getPaginateTargetAnchor(); - if (paginateAnchor != null) anchor = "#" + paginateAnchor; - - // preparing the link text, so that later in the code we can reuse this and just add the viewIndex - StringBuilder prepLinkTextBuffer = new StringBuilder(targetService); - if (prepLinkTextBuffer.indexOf("?") < 0) { - prepLinkTextBuffer.append("?"); - } else if (prepLinkTextBuffer.indexOf("?", prepLinkTextBuffer.length() - 1) > 0) { - prepLinkTextBuffer.append("&"); - } - if (!UtilValidate.isEmpty(queryString) && !queryString.equals("null")) { - prepLinkTextBuffer.append(queryString).append("&"); - } - prepLinkTextBuffer.append(viewSizeParam).append("=").append(viewSize).append("&").append(viewIndexParam).append("="); - String prepLinkText = prepLinkTextBuffer.toString(); - - String linkText; - - appendWhitespace(writer); - // The current screenlet title bar navigation syling requires rendering - // these links in reverse order - // Last button - writer.append("
  • ").append(modelForm.getPaginateLastLabel(context)).append(""); - } else { - // disabled button - writer.append(" disabled\">").append(modelForm.getPaginateLastLabel(context)); - } - writer.append("
  • "); - appendWhitespace(writer); - // Next button - writer.append("
  • ").append(modelForm.getPaginateNextLabel(context)).append(""); - } else { - // disabled button - writer.append(" disabled\">").append(modelForm.getPaginateNextLabel(context)); - } - writer.append("
  • "); - appendWhitespace(writer); - if (listSize > 0) { - writer.append("
  • "); - writer.append(Integer.toString(lowIndex + 1)).append(" - ").append(Integer.toString(lowIndex + actualPageSize)).append(" ").append(ofLabel).append(" ").append(Integer.toString(listSize)); - writer.append("
  • "); - appendWhitespace(writer); - } - // Previous button - writer.append("
  • 0) { - writer.append("\">").append(modelForm.getPaginatePreviousLabel(context)).append(""); - } else { - // disabled button - writer.append(" disabled\">").append(modelForm.getPaginatePreviousLabel(context)); - } - writer.append("
  • "); - appendWhitespace(writer); - // First button - writer.append("
  • 0) { - writer.append("\">").append(modelForm.getPaginateFirstLabel(context)).append(""); - } else { - writer.append(" disabled\">").append(modelForm.getPaginateFirstLabel(context)); - } - writer.append("
  • "); - appendWhitespace(writer); - } - - public void renderScreenletSubWidget(Appendable writer, Map context, ModelScreenWidget subWidget, Screenlet screenlet) throws GeneralException, IOException { - if (subWidget.equals(screenlet.getNavigationForm())) { - HttpServletRequest request = (HttpServletRequest) context.get("request"); - HttpServletResponse response = (HttpServletResponse) context.get("response"); - if (request != null && response != null) { - Map globalCtx = UtilGenerics.checkMap(context.get("globalContext")); - globalCtx.put("NO_PAGINATOR", true); - FormStringRenderer savedRenderer = (FormStringRenderer) context.get("formStringRenderer"); - HtmlFormRenderer renderer = new HtmlFormRenderer(request, response); - renderer.setRenderPagination(false); - context.put("formStringRenderer", renderer); - subWidget.renderWidgetString(writer, context, this); - context.put("formStringRenderer", savedRenderer); - } - } else { - subWidget.renderWidgetString(writer, context, this); - } - } - - public void renderScreenletEnd(Appendable writer, Map context, Screenlet screenlet) throws IOException { - writer.append("
    "); - appendWhitespace(writer); - writer.append(""); - appendWhitespace(writer); - } - - public static class ScreenletMenuRenderer extends HtmlMenuRenderer { - public ScreenletMenuRenderer(HttpServletRequest request, HttpServletResponse response) { - super(request, response); - } - @Override - public void renderMenuOpen(Appendable writer, Map context, ModelMenu modelMenu) {} - @Override - public void renderMenuClose(Appendable writer, Map context, ModelMenu modelMenu) {} - } - - public void renderLabel(Appendable writer, Map context, Label label) throws IOException { - String labelText = label.getText(context); - if (UtilValidate.isEmpty(labelText)) { - // nothing to render - return; - } - // open tag - String style = label.getStyle(context); - String id = label.getId(context); - if (UtilValidate.isNotEmpty(style) || UtilValidate.isNotEmpty(id)) { - writer.append(""); - - // the text - writer.append(labelText); - - // close tag - writer.append(""); - - } else { - writer.append(labelText); - } - - appendWhitespace(writer); - } - - public void renderLink(Appendable writer, Map context, ScreenLink link) throws IOException { - HttpServletResponse response = (HttpServletResponse) context.get("response"); - HttpServletRequest request = (HttpServletRequest) context.get("request"); - - String targetWindow = link.getTargetWindow(context); - String target = link.getTarget(context); - - String uniqueItemName = link.getModelScreen().getName() + "_LF_" + UtilMisc.addToBigDecimalInMap(context, "screenUniqueItemIndex", BigDecimal.ONE); - - String linkType = WidgetWorker.determineAutoLinkType(link.getLinkType(), target, link.getUrlMode(), request); - if ("hidden-form".equals(linkType)) { - writer.append("
    "); - - for (Map.Entry parameter: link.getParameterMap(context).entrySet()) { - writer.append(""); - } - - writer.append(""); - } - - writer.append(""); - - // the text - ScreenImage img = link.getImage(); - if (img == null) { - writer.append(link.getText(context)); - } else { - renderImage(writer, context, img); - } - - // close tag - writer.append(""); - - appendWhitespace(writer); - } - - public void renderImage(Appendable writer, Map context, ScreenImage image) throws IOException { - // open tag - String src = image.getSrc(context); - if (UtilValidate.isEmpty(src)) { - return; - } - writer.append("image.getAlt(context);"); - - appendWhitespace(writer); - } - - public void renderContentBegin(Appendable writer, Map context, Content content) throws IOException { - String editRequest = content.getEditRequest(context); - String editContainerStyle = content.getEditContainerStyle(context); - String enableEditName = content.getEnableEditName(context); - String enableEditValue = (String)context.get(enableEditName); - - if (Debug.verboseOn()) Debug.logVerbose("directEditRequest:" + editRequest, module); - - if (UtilValidate.isNotEmpty(editRequest) && "true".equals(enableEditValue)) { - writer.append(" "); - appendWhitespace(writer); - } - } - - public void renderContentBody(Appendable writer, Map context, Content content) throws IOException { - Locale locale = UtilMisc.ensureLocale(context.get("locale")); - //Boolean nullThruDatesOnly = Boolean.valueOf(false); - String mimeTypeId = "text/html"; - String expandedContentId = content.getContentId(context); - String expandedDataResourceId = content.getDataResourceId(context); - String renderedContent = null; - LocalDispatcher dispatcher = (LocalDispatcher) context.get("dispatcher"); - Delegator delegator = (Delegator) context.get("delegator"); - - // make a new map for content rendering; so our current map does not get clobbered - Map contentContext = new HashMap(); - contentContext.putAll(context); - String dataResourceId = (String)contentContext.get("dataResourceId"); - if (Debug.verboseOn()) Debug.logVerbose("expandedContentId:" + expandedContentId, module); - - try { - if (UtilValidate.isNotEmpty(dataResourceId)) { - if (WidgetDataResourceWorker.dataresourceWorker != null) { - renderedContent = WidgetDataResourceWorker.dataresourceWorker.renderDataResourceAsTextExt(delegator, dataResourceId, contentContext, locale, mimeTypeId, false); - } else { - Debug.logError("Not rendering content, WidgetDataResourceWorker.dataresourceWorker not found.", module); - } - } else if (UtilValidate.isNotEmpty(expandedContentId)) { - if (WidgetContentWorker.contentWorker != null) { - renderedContent = WidgetContentWorker.contentWorker.renderContentAsTextExt(dispatcher, delegator, expandedContentId, contentContext, locale, mimeTypeId, true); - } else { - Debug.logError("Not rendering content, WidgetContentWorker.contentWorker not found.", module); - } - } else if (UtilValidate.isNotEmpty(expandedDataResourceId)) { - if (WidgetDataResourceWorker.dataresourceWorker != null) { - renderedContent = WidgetDataResourceWorker.dataresourceWorker.renderDataResourceAsTextExt(delegator, expandedDataResourceId, contentContext, locale, mimeTypeId, false); - } else { - Debug.logError("Not rendering content, WidgetDataResourceWorker.dataresourceWorker not found.", module); - } - } - if (UtilValidate.isEmpty(renderedContent)) { - String editRequest = content.getEditRequest(context); - if (UtilValidate.isNotEmpty(editRequest)) { - if (WidgetContentWorker.contentWorker != null) { - WidgetContentWorker.contentWorker.renderContentAsTextExt(dispatcher, delegator, "NOCONTENTFOUND", writer, contentContext, locale, mimeTypeId, true); - } else { - Debug.logError("Not rendering content, WidgetContentWorker.contentWorker not found.", module); - } - } - } else { - if (content.xmlEscape()) { - renderedContent = UtilFormatOut.encodeXmlValue(renderedContent); - } - - writer.append(renderedContent); - } - - } catch (GeneralException e) { - String errMsg = "Error rendering included content with id [" + expandedContentId + "] : " + e.toString(); - Debug.logError(e, errMsg, module); - //throw new RuntimeException(errMsg); - } catch (IOException e2) { - String errMsg = "Error rendering included content with id [" + expandedContentId + "] : " + e2.toString(); - Debug.logError(e2, errMsg, module); - //throw new RuntimeException(errMsg); - } - } - - public void renderContentEnd(Appendable writer, Map context, Content content) throws IOException { - - //Debug.logInfo("renderContentEnd, context:" + context, module); - String expandedContentId = content.getContentId(context); - String editMode = "Edit"; - String editRequest = content.getEditRequest(context); - String editContainerStyle = content.getEditContainerStyle(context); - String enableEditName = content.getEnableEditName(context); - String enableEditValue = (String)context.get(enableEditName); - if (editRequest != null && editRequest.toUpperCase().indexOf("IMAGE") > 0) { - editMode += " Image"; - } - //String editRequestWithParams = editRequest + "?contentId=${currentValue.contentId}&drDataResourceId=${currentValue.drDataResourceId}&directEditRequest=${directEditRequest}&indirectEditRequest=${indirectEditRequest}&caContentIdTo=${currentValue.caContentIdTo}&caFromDate=${currentValue.caFromDate}&caContentAssocTypeId=${currentValue.caContentAssocTypeId}"; - - if (UtilValidate.isNotEmpty(editRequest) && "true".equals(enableEditValue)) { - HttpServletResponse response = (HttpServletResponse) context.get("response"); - HttpServletRequest request = (HttpServletRequest) context.get("request"); - if (request != null && response != null) { - if (editRequest.indexOf("?") < 0) editRequest += "?"; - else editRequest += "&"; - editRequest += "contentId=" + expandedContentId; - ServletContext ctx = (ServletContext) request.getAttribute("servletContext"); - RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_"); - writer.append("").append(editMode).append(""); - } - if (UtilValidate.isNotEmpty(editContainerStyle)) { - writer.append(""); - } - appendWhitespace(writer); - } - } - - public void renderContentFrame(Appendable writer, Map context, Content content) throws IOException { - - - HttpServletRequest request = (HttpServletRequest) context.get("request"); - HttpServletResponse response = (HttpServletResponse) context.get("response"); - if (request != null && response != null) { - ServletContext ctx = (ServletContext) request.getAttribute("servletContext"); - RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_"); - String dataResourceId = content.getDataResourceId(context); -// String urlString = "/content/control/ViewSimpleContent?dataResourceId=" + dataResourceId; - String urlString = "/ViewSimpleContent?dataResourceId=" + dataResourceId; - - writer.append("