use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.
the class JSDatabaseManager method js_getDataSetByQuery.
/**
* Performs a sql query with a query builder object.
* Will throw an exception if anything did go wrong when executing the query.
*
* @sample
* // use the query from a foundset and add a condition
* /** @type {QBSelect<db:/example_data/orders>} */
* var q = foundset.getQuery()
* q.where.add(q.joins.orders_to_order_details.columns.discount.eq(2))
* var maxReturnedRows = 10;//useful to limit number of rows
* var ds = databaseManager.getDataSetByQuery(q, true, maxReturnedRows);
*
* // query: select PK from example.book_nodes where parent = 111 and(note_date is null or note_date > now)
* var query = datasources.db.example_data.book_nodes.createSelect().result.addPk().root
* query.where.add(query.columns.parent_id.eq(111))
* .add(query.or
* .add(query.columns.note_date.isNull)
* .add(query.columns.note_date.gt(new Date())))
* databaseManager.getDataSetByQuery(q, true, max_returned_rows)
*
* @param query QBSelect query.
* @param useTableFilters use table filters (default true).
* @param max_returned_rows The maximum number of rows returned by the query.
*
* @return The JSDataSet containing the results of the query.
*/
public JSDataSet js_getDataSetByQuery(QBSelect query, Boolean useTableFilters, Number max_returned_rows) throws ServoyException {
int _max_returned_rows = Utils.getAsInteger(max_returned_rows);
checkAuthorized();
String serverName = DataSourceUtils.getDataSourceServerName(query.getDataSource());
if (serverName == null)
throw new RuntimeException(new ServoyException(ServoyException.InternalCodes.SERVER_NOT_FOUND, new Object[] { query.getDataSource() }));
QuerySelect select = query.build();
if (!validateQueryArguments(select)) {
return new JSDataSet(application);
}
try {
return new JSDataSet(application, ((FoundSetManager) application.getFoundSetManager()).getDataSetByQuery(serverName, select, !Boolean.FALSE.equals(useTableFilters), _max_returned_rows));
} catch (ServoyException e) {
throw new RuntimeException(e);
}
}
use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.
the class JSDatabaseManager method addTableFilterParamInternal.
private boolean addTableFilterParamInternal(String serverName, String tableName, String dataprovider, String operator, Object value, String filterName) throws ServoyException {
checkAuthorized();
try {
if (value instanceof Wrapper) {
value = ((Wrapper) value).unwrap();
}
IServer server = application.getSolution().getServer(serverName);
if (server == null) {
application.reportJSError("Table filter not applied to unknown server '" + serverName + "', tableName = '" + tableName + "', dataprovider = '" + dataprovider + "', operator = '" + operator + "', value = '" + value + "', filterName = '" + filterName + "'", null);
return false;
}
ITable table = null;
if (tableName != null) {
table = server.getTable(tableName);
if (table == null) {
application.reportJSError("Table filter not applied to unknown table: serverName = '" + serverName + "', tableName = '" + tableName + "', dataprovider = '" + dataprovider + "', operator = '" + operator + "', value = '" + value + "', filterName = '" + filterName + "'", null);
return false;
}
}
// else table remains null: apply to all tables with that column
DataproviderTableFilterdefinition dataproviderTableFilterdefinition = application.getFoundSetManager().createDataproviderTableFilterdefinition(table, dataprovider, operator, value);
if (dataproviderTableFilterdefinition == null) {
application.reportJSError("Table filter not created, column not found in table or operator invalid, filterName = '" + filterName + "', serverName = '" + serverName + "', table = '" + table + "', dataprovider = '" + dataprovider + "', operator = '" + operator + "'", null);
return false;
}
return (((FoundSetManager) application.getFoundSetManager()).addTableFilterParam(filterName, serverName, table, dataproviderTableFilterdefinition));
} catch (Exception ex) {
Debug.error(ex);
}
return false;
}
use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.
the class J2DBClient method testClientRegistered.
/**
* @see com.servoy.j2db.ClientState#testClientRegistered(Object)
*/
@Override
public boolean testClientRegistered(Object exception) {
Object ex = exception;
while (ex instanceof Exception && !(ex instanceof ServoyException)) {
ex = ((Exception) ex).getCause();
}
if (isConnected() && ex instanceof ServoyException && (((ServoyException) ex).getErrorCode() == ServoyException.InternalCodes.CLIENT_NOT_REGISTERED || ((ServoyException) ex).getErrorCode() == ServoyException.InternalCodes.INVALID_RMI_SERVER_CONNECTION)) {
if (rmiFactoryFactory != null) {
if (!reconnecting) {
Debug.error("Test exception, calling disconnect in thread: " + Thread.currentThread().getName(), (Exception) exception);
rmiFactoryFactory.disconnect();
return false;
}
} else {
reconnectedToServer();
}
disconnectedFromServer();
return false;
}
return isConnected();
}
use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.
the class ViewFoundSet method doSave.
int doSave(ViewRecord record) {
int retCode = ISaveConstants.STOPPED;
List<ViewRecord> toSave = new ArrayList<>();
if (record == null) {
toSave.addAll(editedRecords);
} else {
if (record.isEditing())
toSave.add(record);
}
if (toSave.size() > 0) {
ArrayList<ViewRecord> processedRecords = new ArrayList<ViewRecord>();
try {
boolean previousRefresh = refresh;
String serverName = DataSourceUtils.getDataSourceServerName(select.getTable().getDataSource());
String transaction_id = manager.getTransactionID(serverName);
HashMap<SQLStatement, ViewRecord> statementToRecord = new HashMap<>();
List<SQLStatement> statements = new ArrayList<>();
for (ViewRecord rec : toSave) {
Map<String, Object> changes = rec.getChanges();
// directly just remove it from the edited records if we try to save it.
editedRecords.remove(rec);
if (changes == null)
continue;
Map<BaseQueryTable, Map<QueryColumn, Object>> tableToChanges = new IdentityHashMap<>();
columnNames.forEach((selectValue, name) -> {
if (changes.containsKey(name)) {
QueryColumn realColumn = select.getRealColumn(selectValue).orElseThrow(() -> {
RuntimeException ex = new RuntimeException("Can't save " + rec + " for changed values " + changes + " because table for column '" + name + "' cannot be found");
rec.setLastException(ex);
if (!failedRecords.contains(rec))
failedRecords.add(rec);
return ex;
});
BaseQueryTable table = realColumn.getTable();
Map<QueryColumn, Object> map = tableToChanges.get(table);
if (map == null) {
map = new HashMap<>();
tableToChanges.put(table, map);
}
map.put(realColumn, rec.getValue(name));
}
});
tableToChanges.forEach((table, changesMap) -> {
List<IQuerySelectValue> pkColumns = pkColumnsForTable.get(table);
if (pkColumns == null) {
RuntimeException ex = new RuntimeException("Can't save " + rec + " for changed values " + changes + " because there are no pk's found for table with changes " + table.getAlias() != null ? table.getAlias() : table.getName());
rec.setLastException(ex);
if (!failedRecords.contains(rec))
failedRecords.add(rec);
throw ex;
}
int counter = 0;
Object[] pk = new Object[pkColumns.size()];
QueryUpdate update = new QueryUpdate(table);
IQuerySelectValue[] queryPks = null;
try {
RowManager rowManager = manager.getRowManager(table.getDataSource());
if (rowManager != null) {
queryPks = getOrderedPkColumns(pkColumns, rowManager.getSQLSheet().getPKColumnDataProvidersAsArray());
}
} catch (Exception ex) {
Debug.error(ex);
}
if (queryPks == null)
queryPks = pkColumns.toArray(new IQuerySelectValue[0]);
for (IQuerySelectValue pkColumn : queryPks) {
Object pkValue = rec.getValue(columnNames.get(pkColumn));
update.addCondition(new CompareCondition(IBaseSQLCondition.EQUALS_OPERATOR, pkColumn, pkValue));
pk[counter++] = pkValue;
}
IDataSet pks = new BufferedDataSet();
pks.addRow(pk);
counter = 0;
String[] changedColumns = new String[changes.size()];
for (Entry<QueryColumn, Object> entry : changesMap.entrySet()) {
QueryColumn column = entry.getKey();
update.addValue(column, entry.getValue());
changedColumns[counter++] = column.getName();
}
SQLStatement statement = new SQLStatement(ISQLActionTypes.UPDATE_ACTION, serverName, table.getName(), pks, transaction_id, update, manager.getTableFilterParams(serverName, update));
statement.setChangedColumns(changedColumns);
statement.setExpectedUpdateCount(1);
statements.add(statement);
statementToRecord.put(statement, rec);
});
JSRecordMarkers validateObject = validate(rec);
if (validateObject != null && validateObject.isHasErrors()) {
Object[] genericExceptions = validateObject.getGenericExceptions();
if (genericExceptions.length > 0) {
rec.setLastException((Exception) genericExceptions[0]);
}
if (!failedRecords.contains(rec)) {
failedRecords.add(rec);
retCode = ISaveConstants.SAVE_FAILED;
}
}
if (!failedRecords.contains(rec)) {
processedRecords.add(rec);
}
}
if (// if this is a save all call we don't save if we have failed records
toSave.size() > 1 && failedRecords.isEmpty() || // if this is a single record save, we just check if it is failed or not
toSave.size() == 1 && !failedRecords.contains(record)) {
Object[] updateResult = manager.getApplication().getDataServer().performUpdates(manager.getApplication().getClientID(), statements.toArray(new SQLStatement[statements.size()]));
for (int i = 0; i < updateResult.length; i++) {
// i of the updateResults should be the same for the statements;
ViewRecord rec = statementToRecord.remove(statements.get(i));
Object o = updateResult[i];
if (o instanceof Exception) {
// something went wrong
failedRecords.add(rec);
rec.setLastException((Exception) o);
retCode = ISaveConstants.SAVE_FAILED;
} else if (!statementToRecord.values().contains(rec) && !failedRecords.contains(rec)) {
rec.clearChanges();
}
}
for (SQLStatement statement : statements) {
manager.notifyDataChange(DataSourceUtils.createDBTableDataSource(statement.getServerName(), statement.getTableName()), statement.getPKsRow(0), ISQLActionTypes.UPDATE_ACTION, statement.getChangedColumns());
}
// do a load but only if there are listeners
if (previousRefresh && shouldRefresh() && foundSetEventListeners.size() > 0) {
loadAllRecordsImpl();
}
}
} catch (ServoyException | RemoteException e) {
Debug.error(e);
} finally {
if (!failedRecords.isEmpty()) {
processedRecords.stream().forEachOrdered(editedRecords::add);
}
}
}
return retCode;
}
use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.
the class JSSecurity method js_getUserGroups.
/**
* Get all the groups for given user UID.
*
* @sample
* //get all the users in the security settings (Returns a JSDataset)
* var dsUsers = security.getUsers()
*
* //loop through each user to get their group
* //The getValue call is (row,column) where column 1 == id and 2 == name
* for(var i=1 ; i<=dsUsers.getMaxRowIndex() ; i++)
* {
* //print to the output debugger tab: "user: " and the username
* application.output("user:" + dsUsers.getValue(i,2));
*
* //set p to the user group for the current user
* /** @type {JSDataSet} */
* var p = security.getUserGroups(dsUsers.getValue(i,1));
*
* for(k=1;k<=p.getMaxRowIndex();k++)
* {
* //print to the output debugger tab: "group" and the group(s)
* //the user belongs to
* application.output("group: " + p.getValue(k,2));
* }
* }
*
* @param userUID to retrieve the user groups
*
* @return dataset with groupnames
*/
public JSDataSet js_getUserGroups(Object userUID) throws ServoyException {
checkAuthorized();
if (userUID == null)
return null;
String n_userUID = normalizeUID(userUID);
try {
String[] groups = null;
if (n_userUID.equals(application.getUserUID())) {
groups = application.getClientInfo().getUserGroups();
}
if (groups == null) {
groups = application.getUserManager().getUserGroups(application.getClientID(), n_userUID.toString());
}
if (groups != null) {
List rows = new ArrayList();
for (String element : groups) {
// fetch the id.
int groupId = getGroupId(element);
rows.add(new Object[] { new Integer(groupId), element });
}
// $NON-NLS-1$ //$NON-NLS-2$
return new JSDataSet(application, new BufferedDataSet(new String[] { "group_id", "group_name" }, rows));
}
} catch (Exception e) {
Debug.error(e);
}
return new JSDataSet();
}
Aggregations