Search in sources :

Example 21 with ServoyException

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

the class FoundSetManager method validateRecord.

@SuppressWarnings("nls")
@Override
public JSRecordMarkers validateRecord(IRecordInternal record, Object state) {
    if (record == null)
        return null;
    // always reset the validation object
    record.setRecordMarkers(null);
    // first check for a validation entity method
    ITable table = record.getParentFoundSet().getTable();
    JSRecordMarkers recordMarkers = new JSRecordMarkers(record, application, state);
    Object[] args = new Object[] { record, recordMarkers, state };
    Scriptable scope = record.getParentFoundSet() instanceof Scriptable ? (Scriptable) record.getParentFoundSet() : null;
    try {
        executeFoundsetTrigger(table, args, StaticContentSpecLoader.PROPERTY_ONVALIDATEMETHODID, true, scope);
    } catch (ServoyException e) {
        recordMarkers.addGenericException(e);
    }
    if (record.existInDataSource()) {
        try {
            // if the first returns false it will stop the rest (inline with what we had)
            if (!executeFoundsetTriggerBreakOnFalse(table, args, StaticContentSpecLoader.PROPERTY_ONUPDATEMETHODID, true, scope)) {
                recordMarkers.setOnBeforeUpdateFailed();
            }
        } catch (ServoyException e) {
            recordMarkers.addGenericException(e);
        }
    } else {
        try {
            // if the first returns false it will stop the rest (inline with what we had)
            if (!executeFoundsetTriggerBreakOnFalse(table, args, StaticContentSpecLoader.PROPERTY_ONINSERTMETHODID, true, scope)) {
                recordMarkers.setOnBeforeInsertFailed();
            }
        } catch (ServoyException e) {
            recordMarkers.addGenericException(e);
        }
    }
    // check for null and length and validators
    SQLSheet sqlSheet = record.getParentFoundSet().getSQLSheet();
    record.getParentFoundSet().getTable().getColumns().forEach(column -> {
        // null
        Object rawValue = record instanceof ViewRecord ? record.getValue(column.getDataProviderID()) : record.getRawData().getRawValue(column.getDataProviderID());
        if (isNullColumnValidatorEnabled() && !column.getAllowNull() && column.getDatabaseDefaultValue() == null && (rawValue == null || ("".equals(rawValue) && Column.mapToDefaultType(column.getType()) == IColumnTypes.TEXT))) {
            recordMarkers.report("i18n:servoy.record.error.null.not.allowed", column.getDataProviderID(), ILogLevel.ERROR, state, new Object[] { column.getDataProviderID() });
            // this would result normally in an Record.exception so for now also set that
            if (!(record instanceof ViewRecord)) {
                record.getRawData().setLastException(new DataException("Column " + column.getDataProviderID() + " can't be null", ServoyException.DATA_INTEGRITY_VIOLATION));
            }
        }
        // validators only for changed columns (based on the raw, "unconverted" value)
        Object oldRawValue = record instanceof ViewRecord ? ((ViewRecord) record).getOldVaue(column.getDataProviderID()) : record.existInDataSource() ? record.getRawData().getOldRawValue(column.getDataProviderID()) : null;
        if (!(rawValue instanceof DbIdentValue) && !Utils.equalObjects(rawValue, oldRawValue)) {
            // the length check
            int valueLen = Column.getObjectSize(rawValue, column.getType());
            if (// insufficient space to save value
            valueLen > 0 && column.getLength() > 0 && valueLen > column.getLength()) {
                recordMarkers.report("i18n:servoy.record.error.columnSizeTooSmall", column.getDataProviderID(), ILogLevel.ERROR, state, new Object[] { column.getDataProviderID(), Integer.valueOf(column.getLength()), rawValue });
            }
            if (// for ViewRecords this is null, we don't have the actual sheet here for the underlying column
            sqlSheet != null) {
                Pair<String, Map<String, String>> validatorInfo = sqlSheet.getColumnValidatorInfo(sqlSheet.getColumnIndex(column.getDataProviderID()));
                if (validatorInfo != null) {
                    IColumnValidator validator = columnValidatorManager.getValidator(validatorInfo.getLeft());
                    if (validator == null) {
                        Debug.error("Column '" + column.getDataProviderID() + "' does have column validator  information, but either the validator '" + validatorInfo.getLeft() + "'  is not available, is the validator installed? (default default_validators.jar in the plugins) or the validator information is incorrect.");
                        recordMarkers.report("i18n:servoy.error.validatorNotFound", column.getDataProviderID(), ILogLevel.ERROR, state, new Object[] { validatorInfo.getLeft() });
                    } else {
                        try {
                            if (validator instanceof IColumnValidator2) {
                                ((IColumnValidator2) validator).validate(validatorInfo.getRight(), rawValue, column.getDataProviderID(), recordMarkers, state);
                            } else {
                                validator.validate(validatorInfo.getRight(), rawValue);
                            }
                        } catch (IllegalArgumentException e) {
                            recordMarkers.report("i18n:servoy.record.error.validation", column.getDataProviderID(), ILogLevel.ERROR, state, new Object[] { column.getDataProviderID(), rawValue, e.getMessage() });
                        }
                    }
                }
            }
        }
    });
    if (recordMarkers.isInvalid()) {
        record.setRecordMarkers(recordMarkers);
        return recordMarkers;
    }
    return null;
}
Also used : Scriptable(org.mozilla.javascript.Scriptable) ServoyException(com.servoy.j2db.util.ServoyException) DbIdentValue(com.servoy.j2db.dataprocessing.ValueFactory.DbIdentValue) ITable(com.servoy.j2db.persistence.ITable) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 22 with ServoyException

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

the class JSDatabaseManager method js_getFoundSetDataProviderAsArray.

/**
 * This method is deprecated, use databaseManager.convertToDataSet(foundset, pkNames) instead.
 *
 * @sample
 * var dataSet = databaseManager.convertToDataSet(foundset,['order_id']);
 *
 * @deprecated As of release 6.0, replaced by {@link #convertToDataSet(Object[])}.
 *
 * @param foundset The foundset
 * @param dataprovider The dataprovider for the values of the array.
 *
 * @return An Array with the column values.
 */
@Deprecated
public Object[] js_getFoundSetDataProviderAsArray(Object foundset, String dataprovider) throws ServoyException {
    checkAuthorized();
    if (foundset instanceof FoundSet && ((FoundSet) foundset).getSQLSheet().getTable() != null) {
        FoundSet fs = (FoundSet) foundset;
        FoundSetManager fsm = (FoundSetManager) application.getFoundSetManager();
        SQLSheet sheet = fs.getSQLSheet();
        Column column = sheet.getTable().getColumn(dataprovider);
        if (column != null) {
            IDataSet dataSet = null;
            if ((fs.hadMoreRows() || fs.getSize() > fsm.config.pkChunkSize()) && !fsm.getEditRecordList().hasEditedRecords(fs)) {
                // large foundset, query the column in 1 go
                QuerySelect sqlSelect = AbstractBaseQuery.deepClone(fs.getQuerySelectForReading());
                ArrayList<IQuerySelectValue> cols = new ArrayList<IQuerySelectValue>(1);
                cols.add(column.queryColumn(sqlSelect.getTable()));
                sqlSelect.setColumns(cols);
                SQLStatement trackingInfo = null;
                if (fsm.getEditRecordList().hasAccess(sheet.getTable(), IRepository.TRACKING_VIEWS)) {
                    trackingInfo = new SQLStatement(ISQLActionTypes.SELECT_ACTION, sheet.getServerName(), sheet.getTable().getName(), null, null);
                    trackingInfo.setTrackingData(new String[] { column.getSQLName() }, new Object[][] {}, new Object[][] {}, fsm.getApplication().getUserUID(), fsm.getTrackingInfo(), fsm.getApplication().getClientID());
                }
                try {
                    dataSet = fsm.getDataServer().performQuery(fsm.getApplication().getClientID(), sheet.getServerName(), fsm.getTransactionID(sheet), sqlSelect, null, fsm.getTableFilterParams(sheet.getServerName(), sqlSelect), false, 0, -1, IDataServer.FOUNDSET_LOAD_QUERY, trackingInfo);
                } catch (RemoteException e) {
                    Debug.error(e);
                    return new Object[0];
                } catch (ServoyException e) {
                    Debug.error(e);
                    return new Object[0];
                }
            } else {
                // small foundset or there are edited records
                List<Column> pks = fs.getSQLSheet().getTable().getRowIdentColumns();
                if (// if is pk optimize
                pks.size() == 1 && pks.get(0).equals(column)) {
                    PksAndRecordsHolder pksAndRecordsCopy;
                    PKDataSet pkds;
                    boolean queryForMore;
                    int rowCount;
                    synchronized (fs.getPksAndRecords()) {
                        pksAndRecordsCopy = fs.getPksAndRecords().shallowCopy();
                        pkds = pksAndRecordsCopy.getPks();
                        queryForMore = pkds == null || pkds.hadMoreRows();
                        rowCount = pkds == null ? 0 : pkds.getRowCount();
                    }
                    if (queryForMore) {
                        fs.queryForMorePKs(pksAndRecordsCopy, rowCount, -1, true);
                    }
                    dataSet = pkds;
                }
            }
            if (dataSet != null) {
                Object[] retval = new Object[dataSet.getRowCount()];
                for (int i = 0; i < retval.length; i++) {
                    Object[] dataSetRow = dataSet.getRow(i);
                    if (dataSetRow == null) {
                        Debug.warn(// $NON-NLS-1$//$NON-NLS-2$
                        "js_getFoundSetDataProviderAsArray - null row at index: " + i + " when getting dataprovider: " + dataprovider + " from foundset: " + // $NON-NLS-1$
                        foundset);
                        retval[i] = null;
                    } else {
                        Object value = dataSetRow[0];
                        if (column.hasFlag(IBaseColumn.UUID_COLUMN)) {
                            // this is a UUID column, first convert to UUID (could be string or byte array (media)) - so we can get/use it as a valid uuid string
                            value = Utils.getAsUUID(value, false);
                        }
                        retval[i] = value;
                    }
                }
                return retval;
            }
        }
        // cannot het the data via a dataset, use the records (could be slow)
        List<Object> lst = new ArrayList<Object>();
        for (int i = 0; i < fs.getSize(); i++) {
            IRecordInternal r = fs.getRecord(i);
            Object value = r.getValue(dataprovider);
            if (value instanceof Date) {
                value = new Date(((Date) value).getTime());
            }
            lst.add(value);
        }
        return lst.toArray();
    }
    return new Object[0];
}
Also used : ArrayList(java.util.ArrayList) IJSFoundSet(com.servoy.base.scripting.api.IJSFoundSet) QuerySelect(com.servoy.j2db.query.QuerySelect) ServoyException(com.servoy.j2db.util.ServoyException) Date(java.util.Date) QueryColumn(com.servoy.j2db.query.QueryColumn) IBaseColumn(com.servoy.base.persistence.IBaseColumn) Column(com.servoy.j2db.persistence.Column) QBColumn(com.servoy.j2db.querybuilder.impl.QBColumn) NativeObject(org.mozilla.javascript.NativeObject) RemoteException(java.rmi.RemoteException) IQuerySelectValue(com.servoy.j2db.query.IQuerySelectValue)

Example 23 with ServoyException

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

the class JSDatabaseManager method js_getSQLParameters.

/**
 * Returns the internal SQL parameters, as an array, that are used to define the specified (related)foundset.
 * When the founset is in find mode, the arguments for the find conditions are included in the result.
 *
 * @sample var sqlParameterArray = databaseManager.getSQLParameters(foundset,false)
 *
 * @param foundsetOrQBSelect The JSFoundset or QBSelect to get the sql parameters for.
 * @param includeFilters include the parameters for the filters.
 *
 * @return An Array with the sql parameter values.
 */
public Object[] js_getSQLParameters(Object foundsetOrQBSelect, boolean includeFilters) throws ServoyException {
    checkAuthorized();
    if (foundsetOrQBSelect instanceof IFoundSetInternal && ((IFoundSetInternal) foundsetOrQBSelect).getTable() != null) {
        try {
            // TODO parameters from updates and cleanups
            QuerySet querySet = getQuerySet(((IFoundSetInternal) foundsetOrQBSelect).getCurrentStateQuery(true, false), includeFilters);
            Object[][] qsParams = querySet.getSelect().getParameters();
            if (qsParams == null || qsParams.length == 0) {
                return null;
            }
            return qsParams[0];
        } catch (Exception e) {
            Debug.error(e);
        }
    } else if (foundsetOrQBSelect instanceof QBSelect) {
        try {
            QuerySelect select = ((QBSelect) foundsetOrQBSelect).build();
            if (select.getColumns() == null) {
                // no columns, add pk
                // note that QBSelect.build() already returns a clone
                ITable table = application.getFoundSetManager().getTable(select.getTable().getDataSource());
                Iterator<Column> pkIt = ((Table) table).getRowIdentColumns().iterator();
                if (!pkIt.hasNext()) {
                    throw new RepositoryException(ServoyException.InternalCodes.PRIMARY_KEY_NOT_FOUND, new Object[] { table.getName() });
                }
                while (pkIt.hasNext()) {
                    Column c = pkIt.next();
                    select.addColumn(c.queryColumn(select.getTable()));
                }
            }
            QuerySet querySet = getQuerySet(select, includeFilters);
            Object[][] qsParams = querySet.getSelect().getParameters();
            if (qsParams == null || qsParams.length == 0) {
                return null;
            }
            return qsParams[0];
        } catch (RemoteException e) {
            Debug.error(e);
        }
    }
    return null;
}
Also used : BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryTable(com.servoy.j2db.query.QueryTable) ITable(com.servoy.j2db.persistence.ITable) Table(com.servoy.j2db.persistence.Table) QuerySet(com.servoy.j2db.persistence.QuerySet) RepositoryException(com.servoy.j2db.persistence.RepositoryException) QuerySelect(com.servoy.j2db.query.QuerySelect) ApplicationException(com.servoy.j2db.ApplicationException) RemoteException(java.rmi.RemoteException) SQLException(java.sql.SQLException) ServoyException(com.servoy.j2db.util.ServoyException) RepositoryException(com.servoy.j2db.persistence.RepositoryException) QBSelect(com.servoy.j2db.querybuilder.impl.QBSelect) QueryColumn(com.servoy.j2db.query.QueryColumn) IBaseColumn(com.servoy.base.persistence.IBaseColumn) Column(com.servoy.j2db.persistence.Column) QBColumn(com.servoy.j2db.querybuilder.impl.QBColumn) Iterator(java.util.Iterator) ITable(com.servoy.j2db.persistence.ITable) NativeObject(org.mozilla.javascript.NativeObject) RemoteException(java.rmi.RemoteException)

Example 24 with ServoyException

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

the class JSDatabaseManager method copyMatchingFields.

public boolean copyMatchingFields(Object src, IRecordInternal dest, boolean overwrite, Object[] names) throws ServoyException {
    checkAuthorized();
    if (dest.getParentFoundSet().getSQLSheet() == null) {
        return false;
    }
    List<Object> al = new ArrayList<Object>();
    if (names != null) {
        al = Arrays.asList(names);
    }
    try {
        SQLSheet destSheet = dest.getParentFoundSet().getSQLSheet();
        Table dest_table = destSheet.getTable();
        boolean wasEditing = dest.isEditing();
        Map<String, Method> getters = new HashMap<String, Method>();
        if (dest.startEditing()) {
            Iterator<Column> it = dest_table.getColumns().iterator();
            while (it.hasNext()) {
                Column c = it.next();
                ColumnInfo ci = c.getColumnInfo();
                if (ci != null && ci.isExcluded()) {
                    continue;
                }
                if (al.contains(c.getDataProviderID())) {
                    // skip, also if value in dest_rec is null
                    continue;
                }
                Object dval = dest.getValue(c.getDataProviderID());
                if (dval == null || (!dest_table.getRowIdentColumns().contains(c) && (overwrite || (al.size() > 0 && !al.contains(c.getDataProviderID()))))) {
                    if (src instanceof IRecordInternal) {
                        IRecordInternal src_rec = (IRecordInternal) src;
                        int index = src_rec.getParentFoundSet().getColumnIndex(c.getDataProviderID());
                        if (index != -1) {
                            Object sval = src_rec.getValue(c.getDataProviderID());
                            try {
                                int type = ((FoundSetManager) application.getFoundSetManager()).getConvertedTypeForColumn(c, false);
                                dest.setValue(c.getDataProviderID(), Column.getAsRightType(type, c.getFlags(), sval, c.getLength(), true, true));
                            } catch (Exception e) {
                                application.reportJSError("Could not copy matching field to " + dest_table.getName() + "." + c.getDataProviderID() + ". The value: '" + sval + "' does not match the type of the destination.", e);
                            }
                        }
                    } else if (src instanceof NativeObject) {
                        NativeObject no = ((NativeObject) src);
                        if (no.has(c.getDataProviderID(), no)) {
                            Object raw_val = no.get(c.getDataProviderID(), no);
                            Object val = c.getAsRightType(raw_val);
                            dest.setValue(c.getDataProviderID(), val);
                        }
                    } else if (src != null) {
                        Method m = getMethod(src, c.getDataProviderID(), getters);
                        if (m != null) {
                            Object raw_val = m.invoke(src, (Object[]) null);
                            Object val = c.getAsRightType(raw_val);
                            dest.setValue(c.getDataProviderID(), val);
                        }
                    }
                }
            }
            if (!wasEditing) {
                dest.stopEditing();
            }
            return true;
        }
    } catch (Exception e) {
        Debug.error(e);
    }
    return false;
}
Also used : BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryTable(com.servoy.j2db.query.QueryTable) ITable(com.servoy.j2db.persistence.ITable) Table(com.servoy.j2db.persistence.Table) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ColumnInfo(com.servoy.j2db.persistence.ColumnInfo) QueryString(com.servoy.j2db.persistence.QueryString) Method(java.lang.reflect.Method) ApplicationException(com.servoy.j2db.ApplicationException) RemoteException(java.rmi.RemoteException) SQLException(java.sql.SQLException) ServoyException(com.servoy.j2db.util.ServoyException) RepositoryException(com.servoy.j2db.persistence.RepositoryException) NativeObject(org.mozilla.javascript.NativeObject) QueryColumn(com.servoy.j2db.query.QueryColumn) IBaseColumn(com.servoy.base.persistence.IBaseColumn) Column(com.servoy.j2db.persistence.Column) QBColumn(com.servoy.j2db.querybuilder.impl.QBColumn) NativeObject(org.mozilla.javascript.NativeObject)

Example 25 with ServoyException

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

the class JSDatabaseManager method js_createDataSourceByQuery.

/**
 * Performs a query and saves the result in a datasource.
 * Will throw an exception if anything went wrong when executing the query.
 * Column types in the datasource are inferred from the query result or can be explicitly specified.
 *
 * A datasource can be reused if the data has the same signature (column names and types).
 * A new createDataSourceByQuery() call will clear the datasource contents from a previous call and insert the current data.
 *
 * @sample
 * // select customer data for order 1234
 * var q = datasources.db.example_data.customers.createSelect()
 * q.result.add(q.columns.customer_id).add(q.columns.city).add(q.columns.country);
 * q.where.add(q.joins.customers_to_orders.columns.orderid.eq(1234));
 * var uri = databaseManager.createDataSourceByQuery('mydata', q, true, 999, null, ['customer_id']);
 * //var uri = databaseManager.createDataSourceByQuery('mydata', q, true, 999, [JSColumn.TEXT, JSColumn.TEXT, JSColumn.TEXT], ['customer_id']);
 *
 * // the uri can be used to create a form using solution model
 * var myForm = solutionModel.newForm('newForm', uri, 'myStyleName', false, 800, 600);
 * myForm.newTextField('city', 140, 20, 140,20);
 *
 * // the uri can be used to acces a foundset directly
 * var fs = databaseManager.getFoundSet(uri);
 * fs.loadAllRecords();
 *
 * @param name Data source name
 * @param query The query builder to be executed.
 * @param useTableFilters use table filters (default true).
 * @param max_returned_rows The maximum number of rows returned by the query.
 * @param types The column types, when null the types are inferred from the query.
 * @param pkNames array of pk names, when null a hidden pk-column will be added
 *
 * @return datasource containing the results of the query or null if the parameters are wrong.
 */
public String js_createDataSourceByQuery(String name, QBSelect query, Boolean useTableFilters, Number max_returned_rows, int[] types, String[] pkNames) 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 null;
    }
    try {
        return ((FoundSetManager) application.getFoundSetManager()).createDataSourceFromQuery(name, serverName, select, !Boolean.FALSE.equals(useTableFilters), _max_returned_rows, types, pkNames);
    } catch (ServoyException e) {
        throw new RuntimeException(e);
    }
}
Also used : QueryString(com.servoy.j2db.persistence.QueryString) QuerySelect(com.servoy.j2db.query.QuerySelect) ServoyException(com.servoy.j2db.util.ServoyException)

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