Search in sources :

Example 11 with ServoyException

use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.

the class FoundsetTypeSabloValue method browserUpdatesReceived.

public void browserUpdatesReceived(Object jsonValue, PropertyDescription pd, IBrowserConverterContext dataConverterContext) {
    PushToServerEnum pushToServer = BrowserConverterContext.getPushToServerValue(dataConverterContext);
    if (getFoundset() == null)
        return;
    try {
        if (jsonValue instanceof JSONArray) {
            JSONArray arr = (JSONArray) jsonValue;
            for (int i = 0; i < arr.length(); i++) {
                JSONObject update = (JSONObject) arr.get(i);
                // {newViewPort: {startIndex : startIndex, size : size}}
                if (update.has("newViewPort")) {
                    JSONObject newViewport = update.getJSONObject("newViewPort");
                    int requestID = update.getInt(ID_KEY);
                    viewPort.clearSendingInitialPreferredViewport();
                    viewPort.setBounds(newViewport.getInt(START_INDEX), newViewport.getInt(SIZE));
                    changeMonitor.requestIdHandled(requestID, true);
                }
                if (update.has(PREFERRED_VIEWPORT_SIZE)) {
                    viewPort.setPreferredViewportSize(update.getInt(PREFERRED_VIEWPORT_SIZE));
                    if (update.has(FoundsetPropertyTypeConfig.SEND_SELECTION_VIEWPORT_INITIALLY))
                        viewPort.setSendSelectionViewportInitially(update.getBoolean(FoundsetPropertyTypeConfig.SEND_SELECTION_VIEWPORT_INITIALLY));
                    if (update.has(INITIAL_SELECTION_VIEWPORT_CENTERED))
                        viewPort.setInitialSelectionViewportCentered(update.getBoolean(INITIAL_SELECTION_VIEWPORT_CENTERED));
                } else // {loadExtraRecords: negativeOrPositiveCount}
                if (update.has("loadExtraRecords")) {
                    int requestID = update.getInt(ID_KEY);
                    viewPort.clearSendingInitialPreferredViewport();
                    viewPort.loadExtraRecords(update.getInt("loadExtraRecords"));
                    changeMonitor.requestIdHandled(requestID, true);
                } else // {loadLessRecords: negativeOrPositiveCount}
                if (update.has("loadLessRecords")) {
                    int requestID = update.getInt(ID_KEY);
                    viewPort.clearSendingInitialPreferredViewport();
                    viewPort.loadLessRecords(update.getInt("loadLessRecords"));
                    changeMonitor.requestIdHandled(requestID, true);
                } else if (update.has("sort")) {
                    int requestID = update.getInt(ID_KEY);
                    JSONArray columns = update.getJSONArray("sort");
                    StringBuilder sort = new StringBuilder();
                    Map<String, String> dp = dataproviders.size() > 0 ? dataproviders : recordDataLinkedPropertyIDToColumnDP;
                    String dataProviderID = null;
                    boolean sortAscending = true;
                    for (int j = 0; j < columns.length(); j++) {
                        JSONObject sortColumn = columns.getJSONObject(j);
                        String name = sortColumn.getString("name");
                        if (dp.containsKey(name)) {
                            sort.append(dp.get(name));
                            sort.append(" " + sortColumn.getString("direction"));
                            if (dataProviderID == null) {
                                dataProviderID = dp.get(name);
                                sortAscending = "asc".equalsIgnoreCase(sortColumn.getString("direction"));
                            }
                            if (j < columns.length() - 1)
                                sort.append(",");
                        }
                    }
                    IWebFormUI formUI = getFormUI();
                    IWebFormController fc = (formUI != null ? formUI.getController() : null);
                    if (fc != null && fc.getForm().getOnSortCmdMethodID() > 0 && dataProviderID != null) {
                        // our api only supports one dataproviderid sort at a time
                        JSEvent event = new JSEvent();
                        event.setFormName(fc.getName());
                        fc.executeFunction(String.valueOf(fc.getForm().getOnSortCmdMethodID()), Utils.arrayMerge((new Object[] { dataProviderID, Boolean.valueOf(sortAscending), event }), // $NON-NLS-1$
                        Utils.parseJSExpressions(fc.getForm().getFlattenedMethodArguments("onSortCmdMethodID"))), true, null, false, // $NON-NLS-1$
                        "onSortCmdMethodID");
                    } else {
                        try {
                            String currentSort = foundset.getSort();
                            String newSort = sort.toString();
                            foundset.setSort(newSort);
                            if (// really a new sort
                            !Utils.equalObjects(currentSort, newSort) || // not sorted, send back to client
                            !Utils.equalObjects(foundset.getSort(), newSort)) {
                                changeMonitor.foundsetSortChanged();
                            }
                        } catch (ServoyException e) {
                            Debug.error("Cannot sort foundset by " + sort.toString(), e);
                        }
                    }
                    changeMonitor.requestIdHandled(requestID, true);
                } else // {newClientSelection: newSelectedIndexesArray}
                if (update.has("newClientSelection")) {
                    JSONArray jsonSelectedIndexes = update.getJSONArray("newClientSelection");
                    int[] newSelectedIndexes = new int[jsonSelectedIndexes.length()];
                    for (int j = newSelectedIndexes.length - 1; j >= 0; j--) {
                        newSelectedIndexes[j] = jsonSelectedIndexes.getInt(j);
                    }
                    // this !Arrays.equals check in conjunction with pause()/resume() is needed to avoid an effect on the client that server always sends back changed selection in which case
                    // if the user quickly changes selection multiple times and the connection is slow, selection will jump all over
                    // the place until it stabilizes correctly
                    getListSelectionListener().pause();
                    try {
                        if (newSelectedIndexes.length == 1) {
                            foundset.setSelectedIndex(newSelectedIndexes[0]);
                        } else {
                            foundset.setSelectedIndexes(newSelectedIndexes);
                        }
                    } finally {
                        getListSelectionListener().resume();
                        // if server denies the new selection as invalid and doesn't change selection, send it to the client so that it doesn't keep invalid selection
                        if (!Arrays.equals(foundset.getSelectedIndexes(), newSelectedIndexes)) {
                            changeMonitor.selectionChanged(false);
                        }
                    }
                } else // {newClientSelectionRequest: newSelectedIndexesArray}
                if (update.has("newClientSelectionRequest")) {
                    int requestID = update.getInt(ID_KEY);
                    JSONArray jsonSelectedIndexes = update.getJSONArray("newClientSelectionRequest");
                    int[] newSelectedIndexes = new int[jsonSelectedIndexes.length()];
                    for (int j = newSelectedIndexes.length - 1; j >= 0; j--) {
                        newSelectedIndexes[j] = jsonSelectedIndexes.getInt(j);
                    }
                    int[] oldSelection = foundset.getSelectedIndexes();
                    // this !Arrays.equals check in conjunction with pause()/resume() is needed to avoid an effect on the client that server always sends back changed selection in which case
                    // if the user quickly changes selection multiple times and the connection is slow, selection will jump all over
                    // the place until it stabilizes correctly
                    getListSelectionListener().pause();
                    try {
                        if (newSelectedIndexes.length == 1) {
                            foundset.setSelectedIndex(newSelectedIndexes[0]);
                        } else {
                            foundset.setSelectedIndexes(newSelectedIndexes);
                        }
                    } finally {
                        getListSelectionListener().resume();
                        if (!Arrays.equals(oldSelection, foundset.getSelectedIndexes())) {
                            // if the selection is changed, send it back to the client so that its model is also updated
                            changeMonitor.selectionChanged(false);
                            changeMonitor.requestIdHandled(requestID, true);
                        } else {
                            if (!Arrays.equals(oldSelection, newSelectedIndexes)) {
                                // it was supposed to change but the server did not allow it
                                changeMonitor.requestIdHandled(requestID, false);
                            } else
                                changeMonitor.requestIdHandled(requestID, true);
                        }
                    }
                } else if (update.has(ViewportDataChangeMonitor.VIEWPORT_CHANGED)) {
                    if (PushToServerEnum.allow.compareTo(pushToServer) <= 0) {
                        // {dataChanged: { ROW_ID_COL_KEY: rowIDValue, dataproviderName: value }}
                        JSONObject dataChangeJSON = (JSONObject) update.get(ViewportDataChangeMonitor.VIEWPORT_CHANGED);
                        String rowIDValue = dataChangeJSON.getString(ROW_ID_COL_KEY);
                        String dpKey = dataChangeJSON.getString(DATAPROVIDER_KEY);
                        String dataProviderName;
                        if (dataproviders.containsKey(dpKey)) {
                            dataProviderName = dataproviders.get(dpKey);
                        } else {
                            dataProviderName = recordDataLinkedPropertyIDToColumnDP.get(dpKey);
                        }
                        Object value = dataChangeJSON.get(VALUE_KEY);
                        if (foundset != null) {
                            Pair<String, Integer> splitHashAndIndex = splitPKHashAndIndex(rowIDValue);
                            int recordIndex = foundset.getRecordIndex(splitHashAndIndex.getLeft(), splitHashAndIndex.getRight().intValue());
                            if (recordIndex != -1) {
                                IRecordInternal record = foundset.getRecord(recordIndex);
                                // convert Dates where it's needed
                                // this should be enough for when only foundset dataproviders are used
                                PropertyDescription dataProviderPropDesc = getDataProviderPropertyDescription(dataProviderName);
                                ValueReference<Boolean> returnValueAdjustedIncommingValueForRow = new ValueReference<Boolean>(Boolean.FALSE);
                                value = JSONUtils.fromJSONUnwrapped(null, value, dataProviderPropDesc, dataConverterContext, returnValueAdjustedIncommingValueForRow);
                                try {
                                    if (record.startEditing()) {
                                        try {
                                            record.setValue(dataProviderName, value);
                                        } catch (IllegalArgumentException e) {
                                            // TODO handle the validaton errors.
                                            IWebFormUI formUI = getFormUI();
                                            formUI.getController().getApplication().reportError("Validation for " + dataProviderName + " for value: " + value + " failed.", e);
                                        }
                                    }
                                // else cannot start editing; finally block will deal with it (send old value back to client as new one can't be pushed)
                                } finally {
                                    // if server denies the new value as invalid and doesn't change it, send it to the client so that it doesn't keep invalid value; the same if for example a double was rounded to an int
                                    if (!Utils.equalObjects(record.getValue(dataProviderName), value) || returnValueAdjustedIncommingValueForRow.value.booleanValue()) {
                                        changeMonitor.recordsUpdated(recordIndex, recordIndex, foundset.getSize(), viewPort, Arrays.asList(new String[] { dataProviderName }));
                                    }
                                }
                            } else {
                                Debug.error("Cannot set foundset record (" + rowIDValue + ") dataprovider '" + dataProviderName + "' to value '" + value + ". Record not found.");
                            }
                        }
                    } else {
                        log.error("Property (" + pd + ") that doesn't define a suitable pushToServer value (allow/shallow/deep) tried to modify foundset dataprovider value serverside. Denying and sending back full viewport!");
                        changeMonitor.viewPortCompletelyChanged();
                    }
                }
            }
        }
    } catch (JSONException e) {
        Debug.error("Error when getting browser updates for property (" + this.toString() + ") for " + jsonValue, e);
    }
}
Also used : JSEvent(com.servoy.j2db.scripting.JSEvent) IRecordInternal(com.servoy.j2db.dataprocessing.IRecordInternal) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IWebFormController(com.servoy.j2db.server.ngclient.IWebFormController) ServoyException(com.servoy.j2db.util.ServoyException) PropertyDescription(org.sablo.specification.PropertyDescription) IWebFormUI(com.servoy.j2db.server.ngclient.IWebFormUI) JSONObject(org.json.JSONObject) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) JSONObject(org.json.JSONObject) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) PushToServerEnum(org.sablo.specification.WebObjectSpecification.PushToServerEnum) Map(java.util.Map) HashMap(java.util.HashMap) ValueReference(org.sablo.util.ValueReference)

Example 12 with ServoyException

use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.

the class FoundSet method createRecord.

// do real query for state
// is already synched by caller around the PksAndRecordsHolder instance
private Record createRecord(int row, int sz, IDataSet pks, SafeArrayList<IRecordInternal> cachedRecords) {
    // safety, SQL in limit
    int a_sizeHint = (sz > fsm.config.pkChunkSize()) ? fsm.config.pkChunkSize() : sz;
    if (Math.abs(row - lastRecordCreatedIndex) > 30 && cachedRecords.get(row - 1) == null && cachedRecords.get(row + 1) == null) {
        synchronized (pksAndRecords) {
            removeRecords(row, false, cachedRecords);
        }
    }
    lastRecordCreatedIndex = row;
    Record retval = null;
    try {
        int startRow = row;
        int sizeHint = a_sizeHint;
        if (row > 0) {
            if (cachedRecords.get(row - 1) == null) {
                if (cachedRecords.get(row + 1) != null) {
                    startRow = row - fsm.config.chunkSize();
                } else {
                    startRow = row - fsm.config.chunkSize() / 2;
                }
                startRow = Math.max(startRow, 0);
            }
        } else {
            sizeHint = ((cachedRecords.get(row + 1) != null || pks.getRowCount() == 1) ? 1 : a_sizeHint);
        }
        int oldSize = pks.getRowCount();
        List<Row> rows = rowManager.getRows(pks, startRow, sizeHint, false);
        // construct States
        for (int r = rows.size(); --r >= 0; ) {
            if (cachedRecords.get(startRow + r) == null) {
                Row rowData = rows.get(r);
                if (rowData != null) {
                    Record state = new Record(this, rowData);
                    cachedRecords.set(startRow + r, state);
                } else {
                    pks.removeRow(startRow + r);
                    cachedRecords.remove(startRow + r);
                }
            }
        }
        retval = (Record) cachedRecords.get(row);
        if (retval == null) {
            rows = rowManager.getRows(pks, row, 1, false);
            if (rows.size() == 1) {
                Row rowData = rows.get(0);
                if (rowData != null) {
                    Record state = new Record(this, rowData);
                    cachedRecords.set(row, state);
                    retval = state;
                }
            } else {
                if (row < pks.getRowCount()) {
                    pks.removeRow(row);
                    cachedRecords.remove(row);
                }
            }
        }
        int newSize = pks.getRowCount();
        if (oldSize != newSize) {
            fireDifference(oldSize, newSize, null);
        }
        synchronized (pksAndRecords) {
            removeRecords(row, true, cachedRecords);
        }
    } catch (ServoyException ex) {
        if (ex.getErrorCode() == ServoyException.InternalCodes.CLIENT_NOT_REGISTERED) {
            // $NON-NLS-1$
            fsm.getApplication().reportError(fsm.getApplication().getI18NMessage("servoy.foundSet.error.loadingRecord"), ex);
            throw new RuntimeException(ex);
        }
        retval = (Record) cachedRecords.get(row);
        if (retval == null) {
            // make empty row so that it wont be an infinite loop of record lookups!!
            Row data = rowManager.createNotYetExistInDBRowObject(sheet.getNewRowData(fsm.getApplication(), this), false);
            data.flagExistInDB();
            retval = new Record(this, data);
            cachedRecords.set(row, retval);
        }
        // $NON-NLS-1$
        fsm.getApplication().handleException(fsm.getApplication().getI18NMessage("servoy.foundSet.error.loadingRecord"), ex);
    }
    return retval;
}
Also used : IJSRecord(com.servoy.base.scripting.api.IJSRecord) ServoyException(com.servoy.j2db.util.ServoyException)

Example 13 with ServoyException

use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.

the class FoundSetManager method getDataSetByQuery.

public IDataSet getDataSetByQuery(IQueryBuilder query, boolean useTableFilters, int max_returned_rows) throws ServoyException {
    if (!application.haveRepositoryAccess()) {
        // no access to repository yet, have to log in first
        return null;
    }
    QBSelect select = (QBSelect) query;
    String serverName = getDataSourceServerName(select.getDataSource());
    if (serverName == null)
        throw new RuntimeException(new ServoyException(ServoyException.InternalCodes.SERVER_NOT_FOUND, new Object[] { select.getDataSource() }));
    return getDataSetByQuery(serverName, select.build(), useTableFilters, max_returned_rows);
}
Also used : QBSelect(com.servoy.j2db.querybuilder.impl.QBSelect) ServoyException(com.servoy.j2db.util.ServoyException)

Example 14 with ServoyException

use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.

the class FoundSetManager method insertToDataSource.

public Object[] insertToDataSource(String name, IDataSet dataSet, ColumnType[] columnTypes, WrappedObjectReference<String[]> pkNames, boolean create, boolean skipOnLoad, String server) throws ServoyException {
    if (name == null) {
        return null;
    }
    WrappedObjectReference<String[]> actualPkNames = pkNames;
    if (actualPkNames == null)
        actualPkNames = new WrappedObjectReference<String[]>(null);
    String dataSource = IServer.VIEW_SERVER.equals(server) ? DataSourceUtils.createViewDataSource(name) : DataSourceUtils.createInmemDataSource(name);
    // initial dataset to use, but can also be set later to a 0 row dataset that is created to match columnNames and columnTypes with an in-mem
    // table definition, if that is available and columns do not match with the initial dataset
    IDataSet fixedDataSet = dataSet;
    List<ColumnType> fixedColumnTypes;
    if (columnTypes == null) {
        ColumnType[] dataSetTypes = BufferedDataSetInternal.getColumnTypeInfo(dataSet);
        fixedColumnTypes = dataSetTypes == null ? null : asList(dataSetTypes);
    } else {
        fixedColumnTypes = asList(columnTypes);
    }
    // get column def from the first in-mem datasource found
    ServoyJSONObject columnsDef = null;
    Iterator<TableNode> tblIte = application.getFlattenedSolution().getTableNodes(dataSource);
    int onLoadMethodId = -1;
    while (tblIte.hasNext()) {
        TableNode tn = tblIte.next();
        if (columnsDef == null)
            columnsDef = tn.getColumns();
        if (onLoadMethodId == -1)
            onLoadMethodId = tn.getOnFoundSetLoadMethodID();
    }
    HashMap<String, ColumnInfoDef> columnInfoDefinitions = null;
    Set<Integer> columnsThatNeedToStringSerialize = null;
    if (columnsDef == null) {
        // if we have array columns, convert values using StringSerializer
        if (containsArrayType(fixedColumnTypes)) {
            columnsThatNeedToStringSerialize = new HashSet<>();
            for (int i = 0; i < fixedColumnTypes.size(); i++) {
                ColumnType columnType = fixedColumnTypes.get(i);
                if (columnType.getSqlType() == Types.ARRAY) {
                    fixedColumnTypes.set(i, ColumnType.getColumnType(IColumnTypes.TEXT));
                    columnsThatNeedToStringSerialize.add(Integer.valueOf(i));
                }
            }
        }
    } else {
        TableDef tableInfo = DatabaseUtils.deserializeTableInfo(columnsDef);
        // column names that are not SEQUENCE_AUTO_ENTER/DATABASE_IDENTITY from table node (columnsDef)
        List<String> inmemColumnNamesThatCanSetData = new ArrayList<>();
        // column types of columns that are not SEQUENCE_AUTO_ENTER/DATABASE_IDENTITY from table node (columnsDef)
        List<ColumnType> inmemColumnTypesForColumnsThatCanSetData = new ArrayList<>();
        // ALL column defs from design time table node (columnsDef)
        columnInfoDefinitions = new HashMap<String, ColumnInfoDef>();
        // pk/rowid column names from design time table node (columnsDef)
        List<String> inmemPKs = new ArrayList<>();
        for (int j = 0; j < tableInfo.columnInfoDefSet.size(); j++) {
            ColumnInfoDef cid = tableInfo.columnInfoDefSet.get(j);
            if (cid.autoEnterType != ColumnInfo.SEQUENCE_AUTO_ENTER || cid.autoEnterSubType != ColumnInfo.DATABASE_IDENTITY) {
                // we only support auto-enter for in-mem tables based on dbident (that is then handled by hsql)
                // that is why we only check for that here; for example, if one would define at design time a
                // uuid generator pk column on an in-mem table, that would not work; it would try to insert null into a non-nullable column
                inmemColumnNamesThatCanSetData.add(cid.name);
                inmemColumnTypesForColumnsThatCanSetData.add(cid.columnType);
            }
            if ((cid.flags & IBaseColumn.IDENT_COLUMNS) != 0) {
                inmemPKs.add(cid.name);
            }
            columnInfoDefinitions.put(cid.name, cid);
            // apply stringserializer on designed datasources
            if (JSONSerializerWrapper.STRING_SERIALIZER_NAME.equals(cid.converterName)) {
                if (columnsThatNeedToStringSerialize == null) {
                    columnsThatNeedToStringSerialize = new HashSet<>();
                }
                columnsThatNeedToStringSerialize.add(Integer.valueOf(j));
            }
        }
        if (actualPkNames.o == null && inmemPKs.size() > 0) {
            actualPkNames.o = inmemPKs.toArray(new String[inmemPKs.size()]);
        }
        if (!asList(dataSet.getColumnNames()).equals(inmemColumnNamesThatCanSetData) || !compareColumnTypes(fixedColumnTypes, inmemColumnTypesForColumnsThatCanSetData)) {
            if (dataSet.getColumnCount() > 0 && /*
													 * do not generate warning if this is just the initial load of a design time inmem table that adds 0 rows
													 * and doesn't care about columns
													 */
            !asList(dataSet.getColumnNames()).equals(inmemColumnNamesThatCanSetData)) {
                Debug.warn("Dataset column names definition does not match inmem table definition for datasource : " + dataSource + " columns of dataset: " + Arrays.toString(dataSet.getColumnNames()) + ", columns of in mem definition: " + inmemColumnNamesThatCanSetData);
            }
            if (fixedColumnTypes != null && !compareColumnTypes(fixedColumnTypes, inmemColumnTypesForColumnsThatCanSetData)) {
                Debug.warn("Dataset column types definition does not match inmem table definition for datasource : " + dataSource + " types of dataset: " + fixedColumnTypes + ", types of in mem definition: " + inmemColumnTypesForColumnsThatCanSetData);
            }
            fixedColumnTypes = inmemColumnTypesForColumnsThatCanSetData;
            fixedDataSet = BufferedDataSetInternal.createBufferedDataSet(inmemColumnNamesThatCanSetData.toArray(new String[inmemColumnNamesThatCanSetData.size()]), fixedColumnTypes.toArray(new ColumnType[fixedColumnTypes.size()]), new ArrayList<Object[]>(), false);
        }
    }
    // - in the else branch above (already defined at design time), columns that are not auto sequences or dbidents; see inmemColumnNames/inmemColumnTypes(which is at this point the same as fixedColumnTypes)
    if (fixedColumnTypes != null && dataSet.getRowCount() > 0 && dataSet.getRow(0).length != fixedColumnTypes.size()) {
        // $NON-NLS-1$
        throw new RepositoryException("Data set rows do not match column count");
    }
    if (columnsThatNeedToStringSerialize != null) {
        replaceValuesWithSerializedString(dataSet, columnsThatNeedToStringSerialize);
    }
    try {
        ITable table = IServer.VIEW_SERVER.equals(server) ? viewDataSources.get(dataSource) : inMemDataSources.get(dataSource);
        if (table == null && !create) {
            throw new RepositoryException("Appending to non-existing datasource: " + dataSource);
        }
        GlobalTransaction gt = getGlobalTransaction();
        String tid = null;
        String serverName = server == null ? (table == null ? IServer.INMEM_SERVER : table.getServerName()) : server;
        if (gt != null) {
            tid = gt.getTransactionID(serverName);
        }
        if (create && table != null) {
            // temp table was used before, delete all data in it
            FoundSet foundSet = (FoundSet) getSharedFoundSet(dataSource);
            foundSet.removeLastFound();
            try {
                QueryDelete delete = new QueryDelete(new QueryTable(table.getSQLName(), table.getDataSource(), table.getCatalog(), table.getSchema(), true));
                SQLStatement deleteStatement = new SQLStatement(ISQLActionTypes.DELETE_ACTION, table.getServerName(), table.getName(), null, tid, delete, null);
                application.getDataServer().performUpdates(application.getClientID(), new ISQLStatement[] { deleteStatement });
            } catch (Exception e) {
                Debug.log(e);
                table = null;
            }
            RowManager element = rowManagers.get(dataSource);
            if (element != null) {
                element.flushAllCachedRows();
            }
        }
        InsertResult insertResult = application.getDataServer().insertDataSet(application.getClientID(), fixedDataSet, dataSource, table == null ? IServer.INMEM_SERVER : table.getServerName(), table == null ? null : table.getName(), /* create temp table when null */
        tid, fixedColumnTypes == null ? null : fixedColumnTypes.toArray(new ColumnType[fixedColumnTypes.size()]), /* inferred from dataset when null */
        actualPkNames.o, columnInfoDefinitions);
        if (insertResult != null) {
            table = insertResult.getTable();
            // do we want to fix that somehow or the caller should just make sure it calls it with the correct column order?
            if (dataSet != fixedDataSet && dataSet.getRowCount() > 0) {
                insertResult = application.getDataServer().insertDataSet(application.getClientID(), dataSet, dataSource, table.getServerName(), table.getName(), tid, columnTypes, /* will be inferred by called method from dataset if null */
                actualPkNames.o, columnInfoDefinitions);
            }
            if (IServer.INMEM_SERVER.equals(serverName)) {
                inMemDataSources.put(dataSource, table);
            } else {
                viewDataSources.put(dataSource, table);
            }
            fireTableEvent(table);
            if (!skipOnLoad && dataSet.getRowCount() == 0 && onLoadMethodId > 0) {
                IFoundSetInternal sharedFoundSet = getSharedFoundSet(dataSource);
                executeFoundsetTriggerReturnFirst(sharedFoundSet.getTable(), new Object[] { DataSourceUtils.getInmemDataSourceName(dataSource) }, StaticContentSpecLoader.PROPERTY_ONFOUNDSETLOADMETHODID, false, (Scriptable) sharedFoundSet);
            }
            if (create) {
                // only refresh when it is a new full load, when adding data to an existing table, it is only applicable to the (shared) foundset
                refreshFoundSetsFromDB(dataSource, null, false);
            }
            return insertResult.getGeneratedPks();
        }
    } catch (RemoteException e) {
        throw new RepositoryException(e);
    }
    return null;
}
Also used : ColumnType(com.servoy.j2db.query.ColumnType) BaseColumnType(com.servoy.base.query.BaseColumnType) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) TableDef(com.servoy.j2db.util.xmlxport.TableDef) ColumnInfoDef(com.servoy.j2db.util.xmlxport.ColumnInfoDef) ITable(com.servoy.j2db.persistence.ITable) WrappedObjectReference(com.servoy.j2db.util.WrappedObjectReference) InsertResult(com.servoy.j2db.dataprocessing.IDataServer.InsertResult) QueryDelete(com.servoy.j2db.query.QueryDelete) RepositoryException(com.servoy.j2db.persistence.RepositoryException) BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryTable(com.servoy.j2db.query.QueryTable) ServoyException(com.servoy.j2db.util.ServoyException) JavaScriptException(org.mozilla.javascript.JavaScriptException) IOException(java.io.IOException) MarshallException(org.jabsorb.serializer.MarshallException) ApplicationException(com.servoy.j2db.ApplicationException) RemoteException(java.rmi.RemoteException) RepositoryException(com.servoy.j2db.persistence.RepositoryException) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) TableNode(com.servoy.j2db.persistence.TableNode) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) RemoteException(java.rmi.RemoteException)

Example 15 with ServoyException

use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.

the class FoundSetManager method createDataSourceFromQuery.

public String createDataSourceFromQuery(String name, String serverName, ISQLSelect sqlSelect, boolean useTableFilters, int maxNumberOfRowsToRetrieve, int[] types, String[] pkNames) throws ServoyException {
    if (name == null) {
        return null;
    }
    try {
        String queryTid = getTransactionID(serverName);
        String dataSource = DataSourceUtils.createInmemDataSource(name);
        ITable table = inMemDataSources.get(dataSource);
        GlobalTransaction gt = getGlobalTransaction();
        String targetTid = null;
        String targetServerName = table == null ? IServer.INMEM_SERVER : table.getServerName();
        if (gt != null) {
            targetTid = gt.getTransactionID(targetServerName);
        }
        if (table != null) {
            // temp table was used before, delete all data in it
            FoundSet foundSet = (FoundSet) getSharedFoundSet(dataSource);
            foundSet.removeLastFound();
            try {
                QueryDelete delete = new QueryDelete(new QueryTable(table.getSQLName(), table.getDataSource(), table.getCatalog(), table.getSchema(), true));
                SQLStatement deleteStatement = new SQLStatement(ISQLActionTypes.DELETE_ACTION, table.getServerName(), table.getName(), null, targetTid, delete, null);
                application.getDataServer().performUpdates(application.getClientID(), new ISQLStatement[] { deleteStatement });
            } catch (Exception e) {
                Debug.log(e);
                table = null;
            }
        }
        table = application.getDataServer().insertQueryResult(application.getClientID(), serverName, queryTid, sqlSelect, useTableFilters ? getTableFilterParams(serverName, sqlSelect) : null, false, 0, maxNumberOfRowsToRetrieve, IDataServer.CUSTOM_QUERY, dataSource, table == null ? IServer.INMEM_SERVER : table.getServerName(), table == null ? null : table.getName(), /* create temp table when null */
        targetTid, ColumnType.getColumnTypes(types), pkNames);
        if (table != null) {
            inMemDataSources.put(dataSource, table);
            fireTableEvent(table);
            refreshFoundSetsFromDB(dataSource, null, false);
            return dataSource;
        }
    } catch (RemoteException e) {
        throw new RepositoryException(e);
    }
    return null;
}
Also used : QueryDelete(com.servoy.j2db.query.QueryDelete) ITable(com.servoy.j2db.persistence.ITable) RepositoryException(com.servoy.j2db.persistence.RepositoryException) RemoteException(java.rmi.RemoteException) BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryTable(com.servoy.j2db.query.QueryTable) ServoyException(com.servoy.j2db.util.ServoyException) JavaScriptException(org.mozilla.javascript.JavaScriptException) IOException(java.io.IOException) MarshallException(org.jabsorb.serializer.MarshallException) ApplicationException(com.servoy.j2db.ApplicationException) RemoteException(java.rmi.RemoteException) RepositoryException(com.servoy.j2db.persistence.RepositoryException)

Aggregations

ServoyException (com.servoy.j2db.util.ServoyException)58 RepositoryException (com.servoy.j2db.persistence.RepositoryException)31 ApplicationException (com.servoy.j2db.ApplicationException)25 RemoteException (java.rmi.RemoteException)25 ArrayList (java.util.ArrayList)16 ITable (com.servoy.j2db.persistence.ITable)14 QuerySelect (com.servoy.j2db.query.QuerySelect)13 BaseQueryTable (com.servoy.base.query.BaseQueryTable)11 QueryTable (com.servoy.j2db.query.QueryTable)10 ServoyJSONObject (com.servoy.j2db.util.ServoyJSONObject)10 IOException (java.io.IOException)9 SQLException (java.sql.SQLException)9 JavaScriptException (org.mozilla.javascript.JavaScriptException)9 Column (com.servoy.j2db.persistence.Column)8 Table (com.servoy.j2db.persistence.Table)8 IBaseColumn (com.servoy.base.persistence.IBaseColumn)7 QueryColumn (com.servoy.j2db.query.QueryColumn)7 HashMap (java.util.HashMap)7 MarshallException (org.jabsorb.serializer.MarshallException)7 NativeObject (org.mozilla.javascript.NativeObject)7