use of com.servoy.j2db.dataprocessing.FoundSet in project servoy-client by Servoy.
the class Utils method getScriptableString.
/**
* Returns a js/json string representation of the given {@link Scriptable}
* @param scriptable
* @param processed map to prevent loops in graph
* @return the scriptable as string
*/
private static CharSequence getScriptableString(Scriptable scriptable, Map<Scriptable, CharSequence> processed) {
Context.enter();
try {
if (scriptable instanceof Record || scriptable instanceof FoundSet)
return scriptable.toString();
if (scriptable instanceof XMLObject || scriptable instanceof NativeError)
return scriptable.toString();
CharSequence processedString = processed.get(scriptable);
if (processedString != null) {
return processedString;
}
if (processed.size() > 10)
return scriptable.toString();
if (// $NON-NLS-1$
scriptable instanceof NativeArray)
// $NON-NLS-1$
processed.put(scriptable, "Array[SelfRef]");
else
// $NON-NLS-1$
processed.put(scriptable, "Object[SelfRef]");
Object[] ids = scriptable.getIds();
if (ids != null && ids.length > 0) {
StringBuilder sb = new StringBuilder();
if (scriptable instanceof NativeArray)
sb.append('[');
else
sb.append('{');
for (Object object : ids) {
if (!(object instanceof Integer)) {
sb.append(object);
sb.append(':');
}
Object value = null;
if (object instanceof String) {
value = scriptable.get((String) object, scriptable);
} else if (object instanceof Number) {
value = scriptable.get(((Number) object).intValue(), scriptable);
}
if (!(value instanceof NativeJavaMethod)) {
if (value instanceof Scriptable) {
sb.append(getScriptableString((Scriptable) value, processed));
} else {
sb.append(value);
}
sb.append(',');
}
}
sb.setLength(sb.length() - 1);
if (scriptable instanceof NativeArray)
sb.append(']');
else
sb.append('}');
processed.put(scriptable, sb);
return sb;
}
Object defaultValue;
try {
defaultValue = scriptable.getDefaultValue(String.class);
} catch (Exception e) {
defaultValue = null;
}
if (defaultValue == null)
defaultValue = scriptable.toString();
processed.put(scriptable, defaultValue.toString());
return defaultValue.toString();
} finally {
Context.exit();
}
}
use of com.servoy.j2db.dataprocessing.FoundSet in project servoy-client by Servoy.
the class FixedJTable method changeSelection.
/**
* @see javax.swing.JTable#changeSelection(int, int, boolean, boolean)
*/
@Override
public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
if (cellEditor != null && getEditingRow() != rowIndex && !cellEditor.stopCellEditing()) {
// don't change selection if there is a celleditor hanging around.
return;
}
ListSelectionModel rsm = getSelectionModel();
boolean isSelected = false;
for (int index : getSelectedRows()) if (index == rowIndex)
isSelected = true;
if (!isSelected && rsm instanceof AlwaysRowSelectedSelectionModel && !((AlwaysRowSelectedSelectionModel) rsm).canChangeSelection())
return;
ListSelectionModel csm = getColumnModel().getSelectionModel();
// get the value so it will be loaded first.
TableModel model = getModel();
if (model instanceof FoundSet)
((FoundSet) model).getRecord(rowIndex);
changeSelectionModel(csm, columnIndex, toggle, extend, false, false);
changeSelectionModel(rsm, rowIndex, toggle, extend, rsm.getSelectionMode() != ListSelectionModel.SINGLE_SELECTION ? rsm.isSelectedIndex(rowIndex) : false, true);
// everything!
if (getAutoscrolls()) {
Rectangle cellRect = getCellRect(rowIndex, columnIndex, false);
if (cellRect != null) {
scrollRectToVisible(cellRect);
}
}
}
use of com.servoy.j2db.dataprocessing.FoundSet in project servoy-client by Servoy.
the class PartNode method process.
public List<DataRendererDefinition> process(FormPreviewPanel fpp, FoundSet fs, Table table, QuerySelect sqlString) throws Exception {
// Selection model must be in print mode to be able to set the selection to -1 . Otherwise is not allowed by the selectionModel
((ISwingFoundSet) fs).getSelectionModel().hideSelectionForPrinting();
// this is needed because we must keep sql the same in foundset during printing
FoundSet rootSet = (FoundSet) fs.copy(false);
foundSets.add(rootSet);
IApplication app = fpp.getApplication();
// retval
List<DataRendererDefinition> list = new ArrayList<DataRendererDefinition>();
if (part != null && (part.getPartType() == Part.LEADING_SUBSUMMARY || part.getPartType() == Part.TRAILING_SUBSUMMARY || isLeadingAndTrailingSubsummary)) {
QuerySelect newSQLString = AbstractBaseQuery.deepClone(sqlString);
IDataServer server = app.getDataServer();
// build the sql parts based on sort columns
ArrayList<IQuerySelectValue> selectCols = new ArrayList<IQuerySelectValue>();
ArrayList<QueryColumn> groupbyCols = new ArrayList<QueryColumn>();
ArrayList<QuerySort> sortbyCols = new ArrayList<QuerySort>();
for (SortColumn element : sortColumns) {
BaseQueryTable queryTable = sqlString.getTable();
Relation[] relations = element.getRelations();
if (relations != null) {
for (Relation relation : relations) {
ISQLTableJoin join = (ISQLTableJoin) sqlString.getJoin(queryTable, relation.getName());
if (join == null) {
// $NON-NLS-1$ //$NON-NLS-2$
Debug.log("Missing relation " + relation.getName() + " in join condition for form on table " + table.getName());
} else {
queryTable = join.getForeignTable();
}
}
}
Column column = (Column) element.getColumn();
QueryColumn queryColumn = column.queryColumn(queryTable);
selectCols.add(queryColumn);
groupbyCols.add(queryColumn);
sortbyCols.add(new QuerySort(queryColumn, element.getSortOrder() == SortColumn.ASCENDING, fs.getFoundSetManager().getSortOptions(column)));
}
// make sql
for (AggregateVariable ag : allAggregates) {
selectCols.add(new QueryAggregate(ag.getType(), new QueryColumn(newSQLString.getTable(), -1, ag.getColumnNameToAggregate(), ag.getDataProviderType(), ag.getLength(), 0, null, ag.getFlags()), ag.getName()));
}
newSQLString.setColumns(selectCols);
newSQLString.setGroupBy(groupbyCols);
ArrayList<IQuerySort> oldSort = newSQLString.getSorts();
// fix the sort (if columns not are selected of used in groupby they cannot be used in sort)
newSQLString.setSorts(sortbyCols);
FoundSetManager foundSetManager = ((FoundSetManager) app.getFoundSetManager());
String transaction_id = foundSetManager.getTransactionID(table.getServerName());
IDataSet data = server.performQuery(app.getClientID(), table.getServerName(), transaction_id, newSQLString, null, foundSetManager.getTableFilterParams(table.getServerName(), newSQLString), false, 0, foundSetManager.config.pkChunkSize() * 4, IDataServer.PRINT_QUERY);
// create a new FoundSet with 'data' and with right 'table', 'where','whereArgs'
SubSummaryFoundSet newSet = new SubSummaryFoundSet(app.getFoundSetManager(), rootSet, sortColumns, allAggregates, data, table);
// restore the sort for child body parts
newSQLString.setSorts(oldSort);
// make new where for use in sub queries
for (QuerySort sortbyCol : sortbyCols) {
QueryColumn sc = (QueryColumn) (sortbyCol).getColumn();
newSQLString.addCondition(SQLGenerator.CONDITION_SEARCH, new CompareCondition(IBaseSQLCondition.EQUALS_OPERATOR, sc, new Placeholder(new TablePlaceholderKey(sc.getTable(), '#' + sc.getName()))));
}
int count = newSet.getSize();
for (int ii = 0; ii < count; ii++) {
// make copy for setting sort column
QuerySelect newSQLStringCopy = AbstractBaseQuery.deepClone(newSQLString);
// handle the child first, this puts the rootset in the right state! for use of related(!) fields in the subsums
// THIS is EXTREMELY important for correct printing, see also SubSummaryFoundSet.queryForRelatedFoundSet
List<DataRendererDefinition> childRetval = null;
IFoundSetInternal curLeafFoundSet = null;
if (child != null) {
for (int i = 0; i < sortbyCols.size(); i++) {
QueryColumn sc = (QueryColumn) (sortbyCols.get(i)).getColumn();
TablePlaceholderKey placeholderKey = new TablePlaceholderKey(sc.getTable(), '#' + sc.getName());
if (!newSQLStringCopy.setPlaceholderValue(placeholderKey, data.getRow(ii)[i])) {
Debug.error(// $NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
new RuntimeException("Could not set placeholder " + placeholderKey + " in query " + newSQLStringCopy + "-- continuing"));
}
}
childRetval = child.process(fpp, rootSet, table, newSQLStringCopy);
curLeafFoundSet = child.getCurrentLeafFoundSet();
}
SubSummaryFoundSet.PrintState state = (SubSummaryFoundSet.PrintState) newSet.getRecord(ii);
state.setDelegate(curLeafFoundSet);
if (part.getPartType() == Part.LEADING_SUBSUMMARY) {
state.doAggregatesLookup();
list.add(new DataRendererDefinition(fpp, renderParent, part, renderer, state));
}
if (childRetval != null) {
list.addAll(childRetval);
}
if (isLeadingAndTrailingSubsummary) {
state.doAggregatesLookup();
list.add(new DataRendererDefinition(fpp, renderParent, second_part, second_renderer, state));
} else if (part.getPartType() == Part.TRAILING_SUBSUMMARY) {
state.doAggregatesLookup();
list.add(new DataRendererDefinition(fpp, renderParent, part, renderer, state));
}
}
} else // for handeling (virtual) body part
{
rootSet.browseAll(sqlString);
int count = app.getFoundSetManager().getFoundSetCount(rootSet);
for (int ii = 0; ii < count; ii++) {
currentLeafFoundSet = rootSet;
list.add(new DataRendererDefinition(fpp, renderParent, part, renderer, rootSet, ii));
}
}
return list;
}
use of com.servoy.j2db.dataprocessing.FoundSet in project servoy-client by Servoy.
the class CellAdapter method getCellEditorValue.
public Object getCellEditorValue() {
// test if currentEditing state isn't deleted already
if (currentEditingState == null || dataProviderID == null || (currentEditingState != null && currentEditingState.getParentFoundSet() == null))
return null;
Object comp = editor;
if ((comp instanceof IDisplay && ((IDisplay) comp).isReadOnly()) || gettingEditorValue) {
return currentEditingState.getValue(getDataProviderID());
}
try {
gettingEditorValue = true;
if (comp instanceof IDelegate<?>) {
comp = ((IDelegate<?>) comp).getDelegate();
}
// HACK:needed for commit value copied from other hack 'processfocus' in DataField
if (comp instanceof DataField && ((DataField) comp).isEditable()) {
DataField edit = (DataField) comp;
boolean needEntireState = edit.needEntireState();
try {
edit.setNeedEntireState(false);
int fb = edit.getFocusLostBehavior();
if (fb == JFormattedTextField.COMMIT || fb == JFormattedTextField.COMMIT_OR_REVERT) {
try {
edit.commitEdit();
// Give it a chance to reformat.
edit.setValueObject(edit.getValue());
} catch (ParseException pe) {
return null;
}
} else if (fb == JFormattedTextField.REVERT) {
edit.setValueObject(edit.getValue());
}
} finally {
edit.setNeedEntireState(needEntireState);
}
}
Object obj = null;
if (editor instanceof IDisplayData) {
IDisplayData displayData = (IDisplayData) editor;
obj = Utils.removeJavascripLinkFromDisplay(displayData, null);
if (!findMode) {
// use UI converter to convert from UI value to record value
obj = ComponentFormat.applyUIConverterFromObject(displayData, obj, dataProviderID, application.getFoundSetManager());
}
// if the editor is not enable or is readonly dont try to set any value.
if (!displayData.isEnabled() || displayData.isReadOnly())
return obj;
// this can happen when toggeling with readonly. case 233226 or 232188
if (!currentEditingState.isEditing() && !currentEditingState.startEditing())
return obj;
try {
if (// $NON-NLS-1$
currentEditingState != null && (obj == null || "".equals(obj)) && currentEditingState.getValue(dataProviderID) == null) {
return null;
}
} catch (IllegalArgumentException iae) {
Debug.error(iae);
}
Object oldVal = null;
if (currentEditingState instanceof FindState) {
if (displayData instanceof IScriptableProvider && ((IScriptableProvider) displayData).getScriptObject() instanceof IFormatScriptComponent && ((IFormatScriptComponent) ((IScriptableProvider) displayData).getScriptObject()).getComponentFormat() != null) {
((FindState) currentEditingState).setFormat(dataProviderID, ((IFormatScriptComponent) ((IScriptableProvider) displayData).getScriptObject()).getComponentFormat().parsedFormat);
}
try {
oldVal = currentEditingState.getValue(dataProviderID);
} catch (IllegalArgumentException iae) {
// $NON-NLS-1$
Debug.error("Error getting the previous value", iae);
oldVal = null;
}
currentEditingState.setValue(dataProviderID, obj);
if (!Utils.equalObjects(oldVal, obj)) {
// call notifyLastNewValue changed so that the onChangeEvent will be fired and called when attached.
displayData.notifyLastNewValueWasChange(oldVal, obj);
obj = dal.getValueObject(currentEditingState, dataProviderID);
}
} else {
if (!displayData.isValueValid() && Utils.equalObjects(lastInvalidValue, obj)) {
// already validated
return obj;
}
try {
adjusting = true;
try {
oldVal = currentEditingState.getValue(dataProviderID);
} catch (IllegalArgumentException iae) {
// $NON-NLS-1$
Debug.error("Error getting the previous value", iae);
}
try {
if (oldVal == Scriptable.NOT_FOUND && dal.getFormScope().has(dataProviderID, dal.getFormScope())) {
oldVal = dal.getFormScope().get(dataProviderID);
dal.getFormScope().put(dataProviderID, obj);
IFoundSetInternal foundset = currentEditingState.getParentFoundSet();
if (foundset instanceof FoundSet)
((FoundSet) foundset).fireFoundSetChanged();
} else
currentEditingState.setValue(dataProviderID, obj);
} catch (IllegalArgumentException e) {
Debug.trace(e);
displayData.setValueValid(false, oldVal);
application.handleException(null, new ApplicationException(ServoyException.INVALID_INPUT, e));
Object stateValue = null;
try {
stateValue = dal.getValueObject(currentEditingState, dataProviderID);
} catch (IllegalArgumentException iae) {
Debug.error(iae);
}
Object displayValue;
if (Utils.equalObjects(oldVal, stateValue)) {
// reset display to typed value
displayValue = obj;
} else {
// reset display to changed value in validator method
displayValue = stateValue;
}
convertAndSetValue(displayData, displayValue);
return displayValue;
}
if (!Utils.equalObjects(oldVal, obj)) {
fireModificationEvent(currentEditingState);
displayData.notifyLastNewValueWasChange(oldVal, obj);
obj = dal.getValueObject(currentEditingState, dataProviderID);
// we also want to reset the value in the current display if changed by script
convertAndSetValue(displayData, obj);
} else if (!displayData.isValueValid()) {
displayData.notifyLastNewValueWasChange(null, obj);
} else {
displayData.setValueValid(true, null);
}
} finally {
adjusting = false;
if (displayData.isValueValid()) {
lastInvalidValue = NONE;
} else {
lastInvalidValue = obj;
}
}
}
}
return obj;
} finally {
gettingEditorValue = false;
}
}
use of com.servoy.j2db.dataprocessing.FoundSet in project servoy-client by Servoy.
the class FoundsetTest method foundsetViewportAllRecordDeleted.
@Test
public void foundsetViewportAllRecordDeleted() throws JSONException, ServoyException {
IWebFormController form = (IWebFormController) client.getFormManager().showFormInCurrentContainer("test");
Assert.assertNotNull(form);
WebFormComponent wc = form.getFormUI().getWebComponent("mycustombean");
FoundsetTypeSabloValue rawPropertyValue = (FoundsetTypeSabloValue) wc.getRawPropertyValue("myfoundset");
BrowserConverterContext allowBrowserConverterContext = new BrowserConverterContext(wc, PushToServerEnum.allow);
FoundsetTypeViewport viewPort = rawPropertyValue.getViewPort();
FoundSet foundset = (FoundSet) form.getFormModel();
viewPort.setBounds(5, 5);
foundset.setSelectedIndex(6);
StringWriter stringWriter = new StringWriter();
JSONWriter jsonWriter = new JSONWriter(stringWriter);
// just to clear changed flags
rawPropertyValue.toJSON(jsonWriter, new DataConversion(), allowBrowserConverterContext);
// create an empty separate foundset from the same datasource
FoundSet sepEmpFs = (FoundSet) client.getFoundSetManager().getNewFoundSet("mem:test");
foundset.js_loadRecords(sepEmpFs);
stringWriter = new StringWriter();
jsonWriter = new JSONWriter(stringWriter);
rawPropertyValue.changesToJSON(jsonWriter, new DataConversion(), allowBrowserConverterContext);
JSONAssert.assertEquals("{\"upd_serverSize\":0,\"upd_selectedRowIndexes\":[],\"upd_viewPort\":{\"startIndex\":0,\"size\":0,\"upd_rows\":[{\"startIndex\":0,\"endIndex\":4,\"type\":2}]}}", stringWriter.toString(), true);
}
Aggregations