Professional Documents
Culture Documents
*************************************************************************
* The contents of this file are subject to the Openbravo Public License
* Version 1.1 (the "License"), being the Mozilla Public License
* Version 1.1 with a permitted attribution clause; you may not use this
* file except in compliance with the License. You may obtain a copy of
* the License at http://www.openbravo.com/legal/license.html
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
* The Original Code is Openbravo ERP.
* The Initial Developer of the Original Code is Openbravo SLU
* All portions are Copyright (C) 2010-2018 Openbravo SLU
* All Rights Reserved.
* Contributor(s): ______________________________________.
************************************************************************
*/
package org.openbravo.client.application.window;
import com.onbarcode.barcode.AbstractBarcode;
import com.onbarcode.barcode.EAN128;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.openbravo.model.ad.utility.Image;
import org.openbravo.model.common.enterprise.Organization;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.criterion.Restrictions;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.Scriptable;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.base.model.Property;
import org.openbravo.base.model.domaintype.PrimitiveDomainType;
import org.openbravo.base.provider.OBProvider;
import org.openbravo.base.secureApp.VariablesSecureApp;
import org.openbravo.base.structure.BaseOBObject;
import org.openbravo.client.application.ApplicationConstants;
import org.openbravo.client.application.DynamicExpressionParser;
import org.openbravo.client.application.Note;
import org.openbravo.client.application.window.servlet.CalloutHttpServletResponse;
import org.openbravo.client.application.window.servlet.CalloutServletConfig;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.client.kernel.KernelUtils;
import org.openbravo.client.kernel.RequestContext;
import org.openbravo.client.kernel.reference.EnumUIDefinition;
import org.openbravo.client.kernel.reference.ForeignKeyUIDefinition;
import org.openbravo.client.kernel.reference.UIDefinition;
import org.openbravo.client.kernel.reference.UIDefinitionController;
import org.openbravo.dal.core.DalUtil;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.security.SecurityChecker;
import org.openbravo.dal.service.OBCriteria;
import org.openbravo.dal.service.OBDal;
import org.openbravo.dal.service.OBDao;
import org.openbravo.dal.service.OBQuery;
import org.openbravo.data.Sqlc;
import org.openbravo.erpCommon.ad_callouts.CalloutConstants;
import org.openbravo.erpCommon.ad_callouts.CalloutInformationProvider;
import org.openbravo.erpCommon.ad_callouts.HttpServletCalloutInformationProvider;
import org.openbravo.erpCommon.ad_callouts.SimpleCallout;
import org.openbravo.erpCommon.ad_callouts.SimpleCalloutInformationProvider;
import org.openbravo.erpCommon.utility.MimeTypeUtil;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.model.ad.datamodel.Column;
import org.openbravo.model.ad.domain.ReferencedTable;
import org.openbravo.model.ad.ui.AuxiliaryInput;
import org.openbravo.model.ad.ui.Field;
import org.openbravo.model.ad.ui.Tab;
import org.openbravo.model.ad.ui.Window;
import org.openbravo.model.ad.utility.Attachment;
import org.openbravo.service.db.DalConnectionProvider;
import org.openbravo.service.json.JsonConstants;
import org.openbravo.service.json.JsonToDataConverter;
import org.openbravo.service.json.JsonUtils;
/**
* This class computes all the required information in Openbravo 3 forms.
* Basically, this can be summarized in the following actions:
*
* Computation of all required column information (including combo values)
*
* Computation of auxiliary input values
*
* Execution of callouts
*
* Insertion of all relevant data in the session
*
* Format: in the request and session the values are always formatted in classic
* mode. The ui definition computes jsonobjects which contain a value as well as
* a classicValue, the latter is placed in the request/session for subsequent
* callout computations.
*/
public class FormInitializationComponent extends BaseActionHandler {
private static final Logger log =
Logger.getLogger(FormInitializationComponent.class);
@Inject
private ApplicationDictionaryCachedStructures adcs;
private static final int MAX_CALLOUT_CALLS = 50;
@Inject
private ApplicationDictionaryCachedStructures cachedStructures;
@Inject
@Any
private Instance<FICExtension> ficExtensions;
@Override
protected JSONObject execute(Map<String, Object> parameters, String content)
{
OBContext.setAdminMode(true);
long iniTime = System.currentTimeMillis();
String mode = null, tabId = null, rowId = null;
try {
// Execution mode. It can be:
// - NEW: used when the user clicks on the "New record" button
// - EDIT: used when the user opens a record in form view
// - CHANGE: used when the user changes a field which should fire
callouts or
// comboreloads
// - SETSESSION: used when the user calls a process
mode = readParameter(parameters, "MODE");
// ID of the parent record
String parentId = readParameter(parameters, "PARENT_ID");
// The ID of the tab
tabId = readParameter(parameters, "TAB_ID");
// The ID of the record. Only relevant on EDIT, CHANGE and
SETSESSION modes
rowId = readParameter(parameters, "ROW_ID");
// The column changed by the user. Only relevant on CHANGE mode
String changedColumn = readParameter(parameters,
"CHANGED_COLUMN");
Tab tab = getTab(tabId);
BaseOBObject row = null;
BaseOBObject parentRecord = null;
Map<String, JSONObject> columnValues = new HashMap<String,
JSONObject>();
List<String> allColumns = new ArrayList<String>();
List<String> calloutsToCall = new ArrayList<String>();
List<String> lastfieldChanged = new ArrayList<String>();
List<String> changeEventCols = new ArrayList<String>();
Map<String, List<String>> columnsInValidation = new
HashMap<String, List<String>>();
List<JSONObject> calloutMessages = new ArrayList<JSONObject>();
List<String> jsExcuteCode = new ArrayList<String>();
Map<String, Object> hiddenInputs = new HashMap<String, Object>();
convertedJson.put(property.getName(), jsonValue);
if (property.isId()) {
// Execution of callouts
long t6 = System.currentTimeMillis();
List<String> changedCols = executeCallouts(mode, tab,
columnValues, changedColumn, calloutsToCall,
lastfieldChanged, calloutMessages, changeEventCols,
jsExcuteCode, hiddenInputs,
overwrittenAuxiliaryInputs);
if (changedCols.size() > 0) {
RequestContext.get().setRequestParameter("donotaddcurrentelement", "true");
subsequentComboReload(tab, columnValues, changedCols,
columnsInValidation);
}
// Attachment information
long t7 = System.currentTimeMillis();
List<JSONObject> attachments = new ArrayList<JSONObject>();
int attachmentCount = 0;
if (jsContent.has("MULTIPLE_ROW_IDS")) {
attachmentCount = computeAttachmentCount(tab,
convertJSONArray(jsContent.getJSONArray("MULTIPLE_ROW_IDS")), true);
} else {
attachmentCount = computeAttachmentCount(tab,
Arrays.asList(rowId), false);
}
// Notes information
long t8 = System.currentTimeMillis();
int noteCount = computeNoteCount(tab, rowId);
OBContext.restorePreviousMode();
}
return null;
}
byte[] barcodeImage=null;
try {
barcode.setData("(01)90614141004365(17)100629(3201)000374(30)02(10)57432");
//barcode.setData("(00)350123451234567894(21)01234567");
// log.warn(randomNumber+"randomNumber..............");
barcode.setShowText(true);
barcode.drawBarcode("D:/barcode/barcode-upca.jpg");
// barcode.drawBarcode("D:/barcode/barcode-upca.jpg");
log.warn(barcode.drawBarcodeToBytes()+"barcode in
bytes"+barcode.getBarcodeInfo());
barcodeImage=barcode.drawBarcodeToBytes();
// JPEG format columnValues.inpbarcodeImage=
// *
{value:barcode.drawBarcode(),classicValue:barcode.drawBarcode()};
// *
//columnValues.inpbarcodeImage."C:\\upca.gif"lassicValue=barcode.drawBarcode();
log.warn(barcode.getData()+"barcode
data"+barcode.drawBarcode("D:/barcode/barcode-upca.jpg"));
//jsContent.put("inpbarcodeImage",barcode.drawBarcode());
// sendBarcodeToDb(barcode.drawBarcodeToBytes(),orgId);
}
catch (Exception e) {
log.warn(e.toString()+"exception");
// throw new ServletException(e);
}
return barcodeImage ;
}
log.warn("imageWidthValue"+vars.getStringParameter("imageWidthValue"));
log.warn("imageHeightValue"+vars.getStringParameter("imageHeightValue"));
log.warn("imageSizeAction"+vars.getStringParameter("imageSizeAction"));
log.warn("imageId"+vars.getStringParameter("imageId"));
log.warn("parentObjectId"+vars.getStringParameter("parentObjectId"));
log.warn("inpadOrgId"+vars.getStringParameter("inpadOrgId"));
log.warn("inpTabId"+vars.getStringParameter("inpTabId"));
log.warn("inpColumnName"+vars.getStringParameter("inpColumnName"));
log.warn("Command"+vars.getStringParameter("Command"));*/
OBContext.setAdminMode(true);
try {
// Check access to record...
String tabId = "180";
log.warn("inpTabId"+tabId);
OBContext.getOBContext().getEntityAccessChecker().checkWritableAccess(entity);
if (mimeType.contains("svg+xml")) {
// Vector images do not have width nor height
imageSizeAction = "N";
sizeOld = new Long[] { 0L, 0L };
sizeNew = new Long[] { 0L, 0L };
} else {
// Bitmap images need to manage width and height
String paramWidth = null;
int newWidth = paramWidth == null || paramWidth.isEmpty() ?
0 : Integer
.parseInt(paramWidth);
if (imageSizeAction.equals("ALLOWED") ||
imageSizeAction.equals("ALLOWED_MINIMUM")
|| imageSizeAction.equals("ALLOWED_MAXIMUM")
|| imageSizeAction.equals("RECOMMENDED")
|| imageSizeAction.equals("RECOMMENDED_MINIMUM")
|| imageSizeAction.equals("RECOMMENDED_MAXIMUM")) {
sizeOld = new Long[] { (long) newWidth, (long)
newHeight };
sizeNew = Utility.computeImageSize(bytea);
} else if (imageSizeAction.equals("RESIZE_NOASPECTRATIO"))
{
sizeOld = Utility.computeImageSize(bytea);
bytea = Utility.resizeImageByte(bytea, newWidth,
newHeight, false, false);
sizeNew = Utility.computeImageSize(bytea);
} else if (imageSizeAction.equals("RESIZE_ASPECTRATIO")) {
sizeOld = Utility.computeImageSize(bytea);
bytea = Utility.resizeImageByte(bytea, newWidth,
newHeight, true, true);
sizeNew = Utility.computeImageSize(bytea);
} else if (imageSizeAction.equals("RESIZE_ASPECTRATIONL"))
{
sizeOld = Utility.computeImageSize(bytea);
bytea = Utility.resizeImageByte(bytea, newWidth,
newHeight, true, false);
sizeNew = Utility.computeImageSize(bytea);
} else {
sizeOld = Utility.computeImageSize(bytea);
sizeNew = sizeOld;
}
}
imageId = image.getId();
log.warn("image id in form init"+imageId);
}
// response.setContentType("text/html; charset=UTF-8");
// PrintWriter writer = response.getWriter();
//writeRedirectOB3(writer, selectorId, imageId,
imageSizeAction, sizeOld, sizeNew, null);
} catch (Exception ex) {
// log4j.error("Error uploading image", ex);
///response.setContentType("text/html; charset=UTF-8");
//PrintWriter writer = response.getWriter();
/**
* Get JSONObject list with data of the attachments in given tab and records
*
* @param tab tab to take attachments
* @param recordIds list of record IDs where taken attachments
* @param doExists flag to not return the actual count just 1 or 0
* @return count of attachment found for the given records.
*/
private int computeAttachmentCount(Tab tab, List<String> recordIds, boolean
doExists) {
String tableId = tab.getTable().getId();
OBCriteria<Attachment> attachmentFiles =
OBDao.getFilteredCriteria(Attachment.class,
Restrictions.eq("table.id", tableId),
Restrictions.in("record", recordIds));
// do not filter by the attachment's organization
// if the user has access to the record where the file its attached, it
has
// access to all its
// attachments
attachmentFiles.setFilterOnReadableOrganization(false);
if (doExists) {
// We only want to know if there is at least 1 attachment. Limit
the query to 1
// record and
// return the size of the result.
attachmentFiles.setMaxResults(1);
return attachmentFiles.list().size();
}
return attachmentFiles.count();
}
jsonColumnValues.put(OBViewFieldHandler.getFieldColumnName(field, null),
columnValues.get(inpColName));
log.warn(jsonColumnValues.toString()
+"jsonColumnValues");
}
////// condition for barcode writting into field
//String
str=jsonColumnValues.getJSONObject("barcode_image").getString("value");
// log.warn(str+"barcode data"+str);
/*String orgId1="E46CEA107E1B4B4EA594503A7D49ADF1";
try {
byte[] barcode= getBarcodeDataAndSendToDb(orgId1);
String selectorId = "isc_OBImageSelector_0";
OBContext.setAdminMode(true);
try {
// Check access to record...
String tabId = "180";
log.warn("inpTabId"+tabId);
String tableId =
adcs.getTab(tabId).getTable().getId();
Entity entity =
ModelProvider.getInstance().getEntityByTableId(tableId);
OBContext.getOBContext().getEntityAccessChecker().checkWritableAccess(entity);
//MimeTypeUtil.getInstance().getMimeTypeName(bytea);
log.warn("imageSizeAction"+imageSizeAction);
String imageId;
Long[] sizeOld;
Long[] sizeNew;
if (!mimeType.contains("image")
|| (!mimeType.contains("jpeg") && !
mimeType.contains("png")
&& !mimeType.contains("gif") &&
!mimeType.contains("bmp") && !mimeType
.contains("svg+xml"))) {
imageId = "";
imageSizeAction = "WRONGFORMAT";
sizeOld = new Long[] { 0L, 0L };
sizeNew = new Long[] { 0L, 0L };
} else {
if (mimeType.contains("svg+xml")) {
// Vector images do not have width
nor height
imageSizeAction = "N";
sizeOld = new Long[] { 0L, 0L };
sizeNew = new Long[] { 0L, 0L };
} else {
// Bitmap images need to manage
width and height
String paramWidth = null;
int newWidth = paramWidth == null
|| paramWidth.isEmpty() ? 0 : Integer
.parseInt(paramWidth);
//vars.getStringParameter("imageHeightValue");
int newHeight = paramHeight == null
|| paramHeight.isEmpty() ? 0 : Integer
.parseInt(paramHeight);
if
(imageSizeAction.equals("ALLOWED") || imageSizeAction.equals("ALLOWED_MINIMUM")
||
imageSizeAction.equals("ALLOWED_MAXIMUM")
||
imageSizeAction.equals("RECOMMENDED")
||
imageSizeAction.equals("RECOMMENDED_MINIMUM")
||
imageSizeAction.equals("RECOMMENDED_MAXIMUM")) {
sizeOld = new Long[] { (long)
newWidth, (long) newHeight };
sizeNew =
Utility.computeImageSize(bytea);
} else if
(imageSizeAction.equals("RESIZE_NOASPECTRATIO")) {
sizeOld =
Utility.computeImageSize(bytea);
bytea =
Utility.resizeImageByte(bytea, newWidth, newHeight, false, false);
sizeNew =
Utility.computeImageSize(bytea);
} else if
(imageSizeAction.equals("RESIZE_ASPECTRATIO")) {
sizeOld =
Utility.computeImageSize(bytea);
bytea =
Utility.resizeImageByte(bytea, newWidth, newHeight, true, true);
sizeNew =
Utility.computeImageSize(bytea);
} else if
(imageSizeAction.equals("RESIZE_ASPECTRATIONL")) {
sizeOld =
Utility.computeImageSize(bytea);
bytea =
Utility.resizeImageByte(bytea, newWidth, newHeight, true, false);
sizeNew =
Utility.computeImageSize(bytea);
} else {
sizeOld =
Utility.computeImageSize(bytea);
sizeNew = sizeOld;
}
//vars.getStringParameter("inpadOrgId");
Organization org =
OBDal.getInstance().get(Organization.class, orgId);
image.setOrganization(org);
image.setBindaryData(bytea);
image.setActive(true);
image.setName("Image");
image.setWidth(sizeNew[0]);
image.setHeight(sizeNew[1]);
image.setMimetype(mimeType);
OBDal.getInstance().save(image);
OBDal.getInstance().flush();
imageId = image.getId();
JSONObject obj1=new
JSONObject();
obj1.put("value",imageId);
obj1.put("classicValue",imageId);
jsonColumnValues.put("barcode_image",obj1) ;
log.warn("image id in form
init"+imageId);
}
// response.setContentType("text/html;
charset=UTF-8");
// PrintWriter writer =
response.getWriter();
//writeRedirectOB3(writer, selectorId,
imageId, imageSizeAction, sizeOld, sizeNew, null);
} catch (Exception ex) {
// log4j.error("Error uploading image",
ex);
///response.setContentType("text/html;
charset=UTF-8");
//PrintWriter writer =
response.getWriter();
//w//riteRedirectOB3(writer,
selectorId, "", "ERROR_UPLOADING", new Long[] { 0L, 0L },
// new Long[] { 0L, 0L },
ex.getMessage());
} finally {
OBContext.restorePreviousMode();
}
*/
/* }
catch (Exception e) {
// log.warn(e.toString()+"exception");
// throw new ServletException(e);
}
//jsonColumnValues.barcode_image.clssicValue=barcode.
drawBarcode();
}
finalObject.put("columnValues", jsonColumnValues);
}*/
JSONObject jsonAuxiliaryInputValues = new JSONObject();
for (AuxiliaryInput auxIn : getAuxiliaryInputList(tab.getId())) {
jsonAuxiliaryInputValues.put(auxIn.getName(),
columnValues.get("inp" +
Sqlc.TransformaNombreColumna(auxIn.getName())));
}
finalObject.put("auxiliaryInputValues",
jsonAuxiliaryInputValues);
finalObject.put("overwrittenAuxiliaryInputs", new
JSONArray(overwrittenAuxiliaryInputs));
if (mode.equals("NEW") || mode.equals("EDIT") ||
mode.equals("SETSESSION")) {
// We also include information related to validation
dependencies
// and we add the columns which have a callout
finalObject.put("sessionAttributes", sessionAttributes);
finalObject.put("dynamicCols", new
JSONArray(changeEventCols));
}
finalObject.put("noteCount", noteCount);
}
if (attachments.size() > 0) {
finalObject.put("attachments", new JSONArray(attachments));
}
finalObject.put("attachmentCount", attachmentCount);
finalObject.put("attachmentExists", attachmentCount > 0);
if (!jsExcuteCode.isEmpty()) {
finalObject.put("jscode", new JSONArray(jsExcuteCode));
}
log.debug(finalObject.toString(1));
return finalObject;
} catch (JSONException e) {
log.error("Error while generating the final JSON object: ", e);
return null;
}
}
RequestContext.get().setRequestParameter("donotaddcurrentelement", "true");
}
log.warn("computeColumnValues - forceComboReload: " +
forceComboReload);
HashMap<String, Field> columnsOfFields = new HashMap<String, Field>();
for (Field field : getADFieldList(tab.getId())) {
if (field.getColumn() == null) {
continue;
}
checkNamingCollisionWithAuxiliaryInput(tab, col);
Field field = columnsOfFields.get(col);
try {
String columnId = field.getColumn().getId();
final Property prop =
KernelUtils.getInstance().getPropertyFromColumn(field.getColumn());
UIDefinition uiDef =
UIDefinitionController.getInstance().getUIDefinition(columnId);
String value = null;
if (mode.equals("NEW")) {
// On NEW mode, the values are computed through the
UIDefinition (the defaults
// will be
// used)
if (field.getProperty() != null && !
field.getProperty().isEmpty()) {
// if the column is a property we try to
compute the property value, if value is
// not
// found null is passed. Refer issue
// https://issues.openbravo.com/view.php?
id=25754
Object propertyValue =
DalUtil.getValueFromPath(parentRecord, field.getProperty());
if (propertyValue != null) {
JSONObject jsonObject = new JSONObject();
if (propertyValue instanceof
BaseOBObject) {
jsonObject.put("value",
((BaseOBObject) propertyValue).getId());
jsonObject.put("classicValue",
((BaseOBObject) propertyValue).getId());
ArrayList<JSONObject> comboEntries
= new ArrayList<JSONObject>();
JSONObject entries = new
JSONObject();
entries.put("id", ((BaseOBObject)
propertyValue).getId());
entries.put("_identifier",
((BaseOBObject) propertyValue).getIdentifier());
comboEntries.add(entries);
jsonObject.put("entries", new
JSONArray(comboEntries));
} else {
jsonObject.put("value",
propertyValue.toString());
jsonObject.put("classicValue",
propertyValue.toString());
log.warn(
"value" +
propertyValue.toString() + "classicValue" + propertyValue.toString());
}
value = jsonObject.toString();
}
} else {
if (field.getColumn().isLinkToParentColumn() &&
parentRecord != null
&&
referencedEntityIsParent(parentRecord, field)) {
// If the column is link to the parent
tab, we set its value as the parent id
RequestContext.get().setRequestParameter("inp" +
Sqlc.TransformaNombreColumna(col),
parentId);
value = uiDef.getFieldProperties(field,
true);
} else if
(field.getColumn().getDBColumnName().equalsIgnoreCase("IsActive")) {
// The Active column is always set to
'true' on new records
RequestContext.get().setRequestParameter("inp" +
Sqlc.TransformaNombreColumna(col), "Y");
value = uiDef.getFieldProperties(field,
true);
} else {
// Else, the default is used
if
(isNotActiveOrVisibleAndNotNeeded(field, visibleProperties)) {
// If the column is not currently
visible, and its not mandatory, we don't need
// to
// compute the combo.
// If a column is mandatory then
the combo needs to be computed, because the
// selected
// value can depend on the
computation if there is no default value
log.warn("Not calculating combo in
" + mode + " mode for column " + col);
value =
uiDef.getFieldPropertiesWithoutCombo(field, false);
} else {
if (isNotActiveOrVisible(field,
visibleProperties)) {
log.warn("Only first combo
record in " + mode + " mode for column " + col);
value =
uiDef.getFieldPropertiesFirstRecord(field, false);
} else {
value =
uiDef.getFieldProperties(field, false);
}
}
}
}
} else if (mode.equals("EDIT")
|| (mode.equals("CHANGE") && (forceComboReload
|| changeEventCols.contains(changedColumn)))) {
// On EDIT mode, the values are computed through the
UIDefinition (the values
// have been
// previously set in the RequestContext)
// This is also done this way on CHANGE mode where a
combo reload is needed
if (isNotActiveOrVisibleAndNotNeeded(field,
visibleProperties)) {
// If the column is not currently visible, and
its not mandatory, we don't need
// to
// compute the combo.
// If a column is mandatory then the combo
needs to be computed, because the
// selected
// value can depend on the computation if there
is no default value
log.warn("field: " + field + " -
getFieldPropertiesWithoutCombo: hasVisibleProperties: "
+ (visibleProperties != null) + ",
&contains: "
+ (visibleProperties != null
&&
visibleProperties.contains("inp" + Sqlc.TransformaNombreColumna(col)))
+ ", isDisplayed=" +
field.isDisplayed() + ", isShowInGridView="
+ field.isShowInGridView() + ",
isShownInStatusBar=" + field.isShowInGridView()
+ ", hasDefaultValue=" +
(field.getColumn().getDefaultValue() != null)
+ ", isMandatory=" +
field.getColumn().isMandatory());
uiDef.getFieldPropertiesWithoutCombo(field,
true);
} else {
log.warn("field: " + field + " -
getFieldProperties: hasVisibleProperties: "
+ (visibleProperties != null) + ",
&contains: "
+ (visibleProperties != null
&&
visibleProperties.contains("inp" + Sqlc.TransformaNombreColumna(col)))
+ ", isDisplayed=" +
field.isDisplayed() + ", isShowInGridView="
+ field.isShowInGridView() + ",
isShownInStatusBar=" + field.isShowInGridView()
+ ", hasDefaultValue=" +
(field.getColumn().getDefaultValue() != null)
+ ", isMandatory=" +
field.getColumn().isMandatory());
if (isNotActiveOrVisible(field,
visibleProperties)) {
log.debug("Only first combo record in " +
mode + " mode for column " + col);
value =
uiDef.getFieldPropertiesFirstRecord(field, true);
} else {
value = uiDef.getFieldProperties(field,
true);
}
}
} else if (mode.equals("CHANGE") ||
mode.equals("SETSESSION")) {
// On CHANGE and SETSESSION mode, the values are read
from the request
JSONObject jsCol = new JSONObject();
String colName = "inp" +
Sqlc.TransformaNombreColumna(col);
Object jsonValue = null;
if (jsContent.has(colName)) {
jsonValue = jsContent.get(colName);
} else if
(jsContent.has(field.getColumn().getDBColumnName())) {
// Special case related to the primary key
column, which is sent with its
// dbcolumnname
// instead of the "inp" name
jsonValue =
jsContent.get(field.getColumn().getDBColumnName());
}
if (prop.isPrimitive()) {
if (JSONObject.NULL.equals(jsonValue)) {
jsonValue = null;
}
if (jsonValue instanceof String) {
jsCol.put("value",
uiDef.createFromClassicString((String) jsonValue));
jsCol.put("classicValue", jsonValue);
} else {
jsCol.put("value", jsonValue);
jsCol.put("classicValue",
uiDef.convertToClassicString(jsonValue));
}
value = jsCol.toString();
} else {
jsCol.put("value", jsonValue);
jsCol.put("classicValue", jsonValue);
log.warn(jsonValue+"value and classic value");
value = jsCol.toString();
log.warn(value+"value and classic value");
}
}
JSONObject jsonobject = null;
if (value != null) {
jsonobject = new JSONObject(value);
if (mode.equals("CHANGE")) {
String oldValue = RequestContext.get()
.getRequestParameter("inp" +
Sqlc.TransformaNombreColumna(col));
String newValue =
jsonobject.has("classicValue") ? jsonobject.getString("classicValue")
: (jsonobject.has("value") ?
jsonobject.getString("value") : null);
if (newValue == null ||
newValue.equals("null")) {
newValue = "";
}
if (oldValue == null ||
oldValue.equals("null")) {
oldValue = "";
}
if (!oldValue.equals(newValue)) {
changedCols.add(field.getColumn().getDBColumnName());
}
}
if (field.getColumn().isStoredInSession() ||
field.getColumn().isKeyColumn()) {
setSessionValue(
tab.getWindow().getId() + "|"
+ field.getColumn().getDBColumnName().toUpperCase(),
log.warn(overwrittenAuxiliaryInputs.contains(auxIn.getName())+"ama");
// Don't compute the auxiliary inputs that have been
overwritten by callouts
if (overwrittenAuxiliaryInputs.contains(auxIn.getName())) {
continue;
}
}
columnValues.put("inp" +
Sqlc.TransformaNombreColumna(auxIn.getName()), jsonObj);
log.warn(jsonObj.toString() + "inside compute auxiiary input");
RequestContext.get().setRequestParameter("inp" +
Sqlc.TransformaNombreColumna(auxIn.getName()),
value == null || value.equals("null") ? null :
value.toString());
ModelProvider.getInstance().getEntityByTableName(parentTab.getTable().getDBTableNam
e()).getName(),
parentId);
}
if (parentTab != null && parentRecord != null) {
setSessionValues(parentRecord, parentTab);
}
return parentRecord;
}
boolean tableBasedTable =
ApplicationConstants.TABLEBASEDTABLE.equals(tab.getTable().getDataOriginType());
RequestContext.get().setRequestParameter(inpColName, value);
}
} catch (Exception e) {
log.error("Couldn't read column value from the
request for column " + inpColName, e);
}
}
}
try {
if (currentValue != null && !
currentValue.toString().equals("null")) {
if (currentValue instanceof BaseOBObject) {
if (prop.getReferencedProperty() != null) {
currentValue = ((BaseOBObject)
currentValue).get(prop.getReferencedProperty().getName());
} else {
currentValue = ((BaseOBObject)
currentValue).getId();
}
} else {
currentValue =
UIDefinitionController.getInstance().getUIDefinition(prop.getColumnId())
.convertToClassicString(currentValue);
}
if (currentValue != null && currentValue.equals("null")) {
currentValue = null;
}
log.warn(Sqlc.TransformaNombreColumna(columnName)+"column
name in curr value");
if (currentValue == null) {
if (Sqlc.TransformaNombreColumna(columnName) ==
"barcode_image")
{
/*
* UPCA barcode = new UPCA();
*
*
* // UPC-A Valid data char set: 0, 1, 2, 3, 4,
5, 6, 7, 8, 9 (Digits)
*
* // UPC-A Valid data length: 11 digits only,
excluding the last checksum digit
*
* barcode.setData("01234567890");
*
* // for UPC-A with supplement data (2 or 5
digits)
*
*
* barcode.drawBarcode("C:\\upca.gif"); //
Generate UPCA barcode & encode into
* // JPEG format columnValues.inpbarcodeImage=
// *
*
{value:barcode.drawBarcode(),classicValue:barcode.drawBarcode()}; // *
*
//columnValues.inpbarcodeImage."C:\\upca.gif"lassicValue=barcode.drawBarcode(
* );
currentValue=barcode.drawBarcode("C:\\upca.gif");
*/
}
RequestContext.get().setRequestParameter("inp" +
Sqlc.TransformaNombreColumna(columnName), null);
} else {
RequestContext.get().setRequestParameter("inp" +
Sqlc.TransformaNombreColumna(columnName),
currentValue.toString());
}
} else {
RequestContext.get().setRequestParameter("inp" +
Sqlc.TransformaNombreColumna(columnName), null);
}
} catch (Exception ignore) {
String msg = "Could not get value for column: " + columnName + "
- tab: " + tab;
if (obj != null) {
msg += " - row: " + obj.getId();
}
log.error(msg, ignore);
}
}
try {
String fieldId = null;
if (field.getProperty() != null && !
field.getProperty().isEmpty()) {
fieldId = "inp" + "_propertyField_" +
Sqlc.TransformaNombreColumna(field.getName()).replace(" ", "")
+ "_" + field.getColumn().getDBColumnName();
} else {
fieldId = "inp" +
Sqlc.TransformaNombreColumna(field.getColumn().getDBColumnName());
}
RequestContext.get().setRequestParameter(fieldId,
jsonObj.has("classicValue") &&
jsonObj.get("classicValue") != null
&& !
jsonObj.getString("classicValue").equals("null") ?
jsonObj.getString("classicValue")
: null);
} catch (JSONException e) {
log.error("Couldn't read JSON parameter for column " +
field.getColumn().getDBColumnName());
}
}
private HashMap<String, Field> buildInpField(List<Field> fields) {
HashMap<String, Field> inpFields = new HashMap<String, Field>();
for (Field field : fields) {
if (field.getColumn() == null) {
continue;
}
inpFields.put("inp" +
Sqlc.TransformaNombreColumna(field.getColumn().getDBColumnName()), field);
}
return inpFields;
}
// In CHANGE mode, we will add the initial callout call for the changed
column,
// if there is
// one
if (mode.equals("CHANGE")) {
if (changedColumn != null) {
for (Column col : getADColumnList(tab.getTable().getId()))
{
if (("inp" +
Sqlc.TransformaNombreColumna(col.getDBColumnName())).equals(changedColumn)) {
if (col.getCallout() != null) {
// The column has a callout. We will add
the callout to the callout list
addCalloutToList(col, calloutsToCall,
lastfieldChanged);
}
}
}
}
}
Object calloutObject;
boolean isCalloutInitialized = false;
if (calloutInstances.get(calloutClassName) != null) {
calloutObject =
calloutInstances.get(calloutClassName);
isCalloutInitialized = true;
} else {
calloutObject =
calloutClass.getDeclaredConstructor().newInstance();
calloutInstances.put(calloutClassName,
calloutObject);
}
RequestContext.get().setRequestParameter("inpLastFieldChanged",
lastFieldChanged);
RequestContext.get().setRequestParameter("inpOB3UIMode",
"Y");
CalloutServletConfig config = new
CalloutServletConfig(calloutClassName,
RequestContext.getServletContext());
CalloutInformationProvider calloutResponseManager = null;
calloutResponseManager = new
SimpleCalloutInformationProvider(result);
} else {
// We then execute the callout
HttpServlet calloutInstance = (HttpServlet)
calloutObject;
CalloutHttpServletResponse fakeResponse = new
CalloutHttpServletResponse(request.getResponse());
if (isCalloutInitialized) {
Method doPost =
calloutClass.getMethod("doPost", HttpServletRequest.class,
HttpServletResponse.class);
doPost.setAccessible(true);
doPost.invoke(calloutInstance,
request.getRequest(), fakeResponse);
} else {
calloutInstance.init(config);
calloutInstance.service(request.getRequest(),
fakeResponse);
}
String calloutResponse =
fakeResponse.getOutputFromWriter();
// Now we parse the callout response and modify the
stored values of the columns
// modified
// by the callout
ArrayList<NativeArray> returnedArray = new
ArrayList<NativeArray>();
String calloutNameJS =
parseCalloutResponse(calloutResponse, returnedArray);
if (calloutNameJS != null && calloutNameJS != "") {
calledCallouts.add(calloutNameJS);
}
calloutResponseManager = new
HttpServletCalloutInformationProvider(returnedArray);
}
managesUpdatedValuesForCallout(columnValues, tab,
calloutsToCall, lastfieldChangedList, messages,
dynamicCols, jsExecuteCode, hiddenInputs,
overwrittenAuxiliaryInputs, changedCols, inpFields,
calloutClassName, request,
calloutResponseManager);
lastCalledCallout = calloutClassName;
lastFieldOfLastCalloutCalled = lastFieldChanged;
} catch (Exception e) {
throw new OBException("Couldn't execute callout (class " +
calloutClassName + ")", e);
}
}
if (calledCallouts.size() == MAX_CALLOUT_CALLS) {
log.warn("Warning: maximum number of callout calls reached");
}
return changedCols;
RequestContext.get().getVariablesSecureApp().getLanguage()));
message.put("severity", "TYPE_ERROR");
messages.add(message);
log.warn("Callout " + calloutClassName
+ " returned EXECUTE command which
is no longer supported, it should be fixed. Window-tab: "
+ tab.getWindow().getName() + " - "
+ tab.getName());
}
}
} else {
if (name.startsWith("inp")) {
boolean changed = false;
if (inpFields.containsKey(name)) {
Column col = inpFields.get(name).getColumn();
if (col != null) {
String colId = "inp" +
Sqlc.TransformaNombreColumna(col.getDBColumnName());
if
(calloutInformationProvider.isComboData(element)) {
// Combo data
calloutInformationProvider.manageComboData(columnValues, dynamicCols,
changedCols,
request, element, col,
colId);
// When managing combos, it is not
taken into account if the column value has
// changed, so 'changed' is always
true.
changed = true;
} else {
// Normal data
Object el =
calloutInformationProvider.getCurrentElementValue(element);
String oldValue =
request.getRequestParameter(colId);
// We set the new value in the
request, so that the JSONObject is computed
// with the new value
UIDefinition uiDef =
UIDefinitionController.getInstance().getUIDefinition(col.getId());
if (el instanceof String || !
(uiDef.getDomainType() instanceof PrimitiveDomainType)) {
request.setRequestParameter(colId, uiDef.convertToClassicString(el));
}
String jsonStr =
uiDef.getFieldProperties(inpFields.get(name), true);
JSONObject jsonobj = new
JSONObject(jsonStr);
if (el == null && (uiDef instanceof
ForeignKeyUIDefinition
|| uiDef instanceof
EnumUIDefinition)) {
// Special case for null
values for combos: we must clean the combo values
jsonobj.put(CalloutConstants.VALUE, "");
jsonobj.put(CalloutConstants.CLASSIC_VALUE, "");
changedCols.add(col.getDBColumnName());
}
request.setRequestParameter(colId,
jsonobj.getString(CalloutConstants.CLASSIC_VALUE));
}
} else {
log.warn(
"Column value
didn't change. We do not attempt to execute any additional callout");
}
}
if (changed && col.getCallout() != null)
{
// We need to fire this callout, as
the column value was changed
// but only if the callout we are
firing is different
if
(isShouldBeFired(calloutClassName, col)) {
addCalloutToList(col,
calloutsToCall, lastfieldChangedList);
}
}
}
} else {
for (AuxiliaryInput aux :
tab.getADAuxiliaryInputList()) {
if (name.equalsIgnoreCase("inp" +
Sqlc.TransformaNombreColumna(aux.getName()))) {
Object el =
calloutInformationProvider.getCurrentElementValue(element);
JSONObject obj = new JSONObject();
obj.put(CalloutConstants.VALUE,
el);
obj.put(CalloutConstants.CLASSIC_VALUE, el);
columnValues.put(name, obj);
log.warn(columnValues+"auxialory
input for loop");
// Add the auxiliary input to the
list of auxiliary inputs modified by
// callouts
/*
*
if(colmnValues.inpbarcodeImag.contains("barcode_image")&&columnValues.
*
inpbarcodeImageinpbarcodeImage.value.isEmpty())
*
* { UPCA barcode = new UPCA();
*
*
* UPC-A Valid data char set: 0, 1,
2, 3, 4, 5, 6, 7, 8, 9 (Digits)
*
* UPC-A Valid data length: 11
digits only, excluding the last checksum digit
*
* barcode.setData("01234567890");
*
* // for UPC-A with supplement
data (2 or 5 digits)
*
* barcode.setSupData("12"); //
supplement bar height vs bar height ratio
* barcode.setSupHeight(0.8f); //
space between barcode and supplement barcode
* (in pixel)
barcode.setSupSpace(15);
*
*
* // UPC-A Unit of Measure, pixel,
cm, or inch
*
*
barcode.setUom(IBarcode.UOM_PIXEL); // UPC-A barcode bar module width (X) in
* pixel barcode.setX(3f); // UPC-A
barcode bar module height (Y) in pixel
* barcode.setY(75f);
*
* // barcode image margins
barcode.setLeftMargin(0f);
* barcode.setRightMargin(0f);
barcode.setTopMargin(0f);
* barcode.setBottomMargin(0f);
*
* // barcode image resolution in
dpi barcode.setResolution(72);
*
* // disply barcode encoding data
below the barcode barcode.setShowText(true);
* // barcode encoding data font
style barcode.setTextFont(new Font("Arial", 0,
* 12)); // space between barcode
and barcode encoding data
* barcode.setTextMargin(6);
*
* // barcode displaying angle
barcode.setRotate(IBarcode.ROTATE_0);
*
*
*
barcode.drawBarcode("C:\\upca.gif"); // Generate UPCA barcode & encode into
* JPEG format
columnValues.inpbarcodeImage=
*
{value:barcode.drawBarcode(),classicValue:barcode.drawBarcode()};
*
//columnValues.inpbarcodeImage.classicValue=barcode.drawBarcode(); }
*/
if (!
overwrittenAuxiliaryInputs.contains(aux.getName())) {
overwrittenAuxiliaryInputs.add(aux.getName());
}
}
}
if (!columnValues.containsKey(name)) {
// This returned value wasn't found to be
either a column or an auxiliary
// input. We assume it is a hidden input,
which are used in places like
// selectors
Object el =
calloutInformationProvider.getCurrentElementValue(element);
if (el != null) {
if
(calloutInformationProvider.isComboData(element)) {
// In this case, we ignore
the value, as a hidden input cannot be an array
// of elements
} else {
hiddenInputs.put(name, el);
// We set the hidden fields
in the request, so that subsequent callouts
// can use them
request.setRequestParameter(name, el.toString());
}
}
}
}
}
}
element = calloutInformationProvider.getNextElement();
}
}
/**
* This callout should be fire only if the callout we are firing is
different.
*
* @param calloutClassName callout that is firing
* @return true if it is should be fired.
*/
private boolean isShouldBeFired(String calloutClassName, Column col) {
return !
calloutClassName.equals(col.getCallout().getADModelImplementationList().get(0).getJ
avaClassName());
}
return null;
}
return null;
}
Column c = field.getColumn();
String val = "";
if (c.getValidation() != null &&
c.getValidation().getValidationCode() != null) {
val += c.getValidation().getValidationCode();
}
if (c.getReference().getId().equals("18")) {
if (c.getReferenceSearchKey() != null) {
for (ReferencedTable t :
c.getReferenceSearchKey().getADReferencedTableList()) {
val += " AND " + t.getSQLWhereClause();
}
}
}
return val;