Search in sources :

Example 11 with ApplicationException

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

the class JSApplication method js_executeProgram.

/**
 * Execute a program and returns output. Specify the cmd as you would do in a console.
 *
 * @sample
 * // For Windows systems:
 * // Runs a binary located in the user's home directory. The application will run in the current working
 * // directory, which in general is the one where Servoy was started from.
 * application.executeProgram("c:\\Users\\myself\\myapp.exe", ["arg1", "arg2", "arg3"]);
 * // The same as above, but run the application in the user's home directory.
 * application.executeProgram("c:\\Users\\myself\\myapp.exe", ["arg1", "arg2", "arg3"], null, "c:\\Users\\myself\\");
 * // The same as above, but also set an environment variable for the called program.
 * application.executeProgram("c:\\Users\\myself\\myapp.exe", ["arg1", "arg2", "arg3"], ["MY_ENV_VAR=something"], "c:\\Users\\myself\\");
 * // For non-Windows systems:
 * application.executeProgram("/home/myself/myapp", ["arg1", "arg2", "arg3"]);
 * application.executeProgram("/home/myself/myapp", ["arg1", "arg2", "arg3"], null, "/home/myself/");
 * application.executeProgram("/home/myself/myapp", ["arg1", "arg2", "arg3"], ["MY_ENV_VAR=something"], "/home/myself/");
 * // Open a file with the default application associated with it. (on Windows)
 * application.executeProgram("rundll32.exe", ["url.dll,FileProtocolHandler", "filename"]);
 * // Open a file with the default application associated with it. (on Linux)
 * application.executeProgram("xdg-open", ["filename"]);
 * // Open a file with the default application associated with it. (on MacOS)
 * application.executeProgram("open", ["filename"]);
 * // Open a file with a specific application (on MacOS).
 * application.executeProgram("open", ["-a", "OpenOffice.org.app", "filename.doc"]);
 *
 * @param program (fullpath) of the program to execute
 * @param params an array of strings as program arguments
 * @param environmentVars array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.
 * @param startDir the working directory of the subprocess, or null if the subprocess should inherit the working directory of the current process.
 * @return The output generated by the program execution.
 * @throws ApplicationException
 */
public String js_executeProgram(String program, String[] params, String[] environmentVars, String startDir) throws ApplicationException {
    StringBuilder output = new StringBuilder();
    try {
        // startDir can be null or any string
        File _startDir = (startDir == null ? null : new File(startDir));
        String[] commandWithParams = Utils.arrayJoin(new String[] { program }, params);
        Process myProcess = Runtime.getRuntime().exec(commandWithParams, environmentVars, _startDir);
        BufferedReader in = new BufferedReader(new InputStreamReader(myProcess.getInputStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
            output.append(line);
            output.append("\n");
        }
        in.close();
        // clear any error
        setLastErrorCode(0);
    } catch (Exception e) {
        setLastErrorCode(ServoyException.EXECUTE_PROGRAM_FAILED);
        // throw new ApplicationException(ServoyException.EXECUTE_PROGRAM_FAILED, e);
        ApplicationException applicationException = new ApplicationException(ServoyException.EXECUTE_PROGRAM_FAILED, e);
        JavaScriptException javaScriptException = new JavaScriptException(applicationException, "", 0);
        throw javaScriptException;
    }
    return output.toString();
}
Also used : ApplicationException(com.servoy.j2db.ApplicationException) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) File(java.io.File) ApplicationException(com.servoy.j2db.ApplicationException) ExitScriptException(com.servoy.j2db.ExitScriptException) ServoyException(com.servoy.j2db.util.ServoyException) JavaScriptException(org.mozilla.javascript.JavaScriptException) JavaScriptException(org.mozilla.javascript.JavaScriptException)

Example 12 with ApplicationException

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

the class RuntimeWindow method showObject.

public void showObject(Object form) throws ServoyException {
    String f = null;
    if (form instanceof BasicFormController) {
        f = ((BasicFormController) form).getName();
    } else if (form instanceof FormScope) {
        f = ((FormScope) form).getFormController().getName();
    } else if (form instanceof FormController.JSForm) {
        f = ((FormController.JSForm) form).getFormPanel().getName();
    } else if (form instanceof String) {
        f = (String) form;
    } else if (form instanceof JSForm) {
        f = ((JSForm) form).getName();
    }
    if (f != null) {
        Form frm = application.getFlattenedSolution().getForm(f);
        IBasicFormManager fm = application.getFormManager();
        if (frm == null && fm.isPossibleForm(f))
            frm = fm.getPossibleForm(f);
        if (!application.getFlattenedSolution().formCanBeInstantiated(frm)) {
            // abstract form
            throw new ApplicationException(ServoyException.ABSTRACT_FORM, new Object[] { f });
        }
        show(f);
    }
}
Also used : ApplicationException(com.servoy.j2db.ApplicationException) JSForm(com.servoy.j2db.scripting.solutionmodel.JSForm) Form(com.servoy.j2db.persistence.Form) JSForm(com.servoy.j2db.scripting.solutionmodel.JSForm) IBasicFormManager(com.servoy.j2db.IBasicFormManager) BasicFormController(com.servoy.j2db.BasicFormController)

Example 13 with ApplicationException

use of com.servoy.j2db.ApplicationException 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;
    }
}
Also used : IFoundSetInternal(com.servoy.j2db.dataprocessing.IFoundSetInternal) FoundSet(com.servoy.j2db.dataprocessing.FoundSet) ISwingFoundSet(com.servoy.j2db.dataprocessing.ISwingFoundSet) IDisplay(com.servoy.j2db.dataprocessing.IDisplay) Point(java.awt.Point) FindState(com.servoy.j2db.dataprocessing.FindState) ApplicationException(com.servoy.j2db.ApplicationException) EventObject(java.util.EventObject) IDisplayData(com.servoy.j2db.dataprocessing.IDisplayData) IFormatScriptComponent(com.servoy.j2db.ui.scripting.IFormatScriptComponent) ParseException(java.text.ParseException) IScriptableProvider(com.servoy.j2db.scripting.IScriptableProvider) IDelegate(com.servoy.j2db.util.IDelegate)

Example 14 with ApplicationException

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

the class RecordItemModel method setValue.

/**
 * @param obj
 * @param dataProviderID
 * @param prevValue
 */
public void setValue(Component component, String dataProviderID, Object value) {
    Object obj = value;
    String compDpid = getDataProviderID(component);
    boolean ownComponentsValue = compDpid != null && dataProviderID.endsWith(compDpid);
    Object prevValue = null;
    if (ownComponentsValue && component instanceof IResolveObject) {
        obj = ((IResolveObject) component).resolveRealValue(obj);
    }
    if (component instanceof IDisplayData) {
        obj = Utils.removeJavascripLinkFromDisplay((IDisplayData) component, new Object[] { obj });
    }
    WebForm webForm = component.findParent(WebForm.class);
    IRecordInternal record = (IRecordInternal) RecordItemModel.this.getObject();
    // use UI converter to convert from UI value to record value
    if (!(record instanceof FindState)) {
        obj = ComponentFormat.applyUIConverterFromObject(component, obj, dataProviderID, webForm.getController().getApplication().getFoundSetManager());
    }
    FormScope fs = webForm.getController().getFormScope();
    try {
        Pair<String, String> scope = ScopesUtils.getVariableScope(dataProviderID);
        if (scope.getLeft() != null) {
            if (record == null) {
                webForm.getController().getApplication().getScriptEngine().getSolutionScope().getScopesScope().getGlobalScope(scope.getLeft()).put(scope.getRight(), obj);
            } else {
                // does an additional fire in foundset!
                prevValue = record.getParentFoundSet().setDataProviderValue(dataProviderID, obj);
            }
        } else if (fs.has(dataProviderID, fs)) {
            prevValue = fs.get(dataProviderID);
            fs.put(dataProviderID, obj);
        } else {
            if (record != null && record.startEditing()) {
                try {
                    prevValue = record.getValue(dataProviderID);
                    record.setValue(dataProviderID, obj);
                } catch (IllegalArgumentException e) {
                    Debug.trace(e);
                    ((WebClientSession) Session.get()).getWebClient().handleException(null, new ApplicationException(ServoyException.INVALID_INPUT, e));
                    Object stateValue = record.getValue(dataProviderID);
                    if (!Utils.equalObjects(prevValue, stateValue)) {
                        // reset display to changed value in validator method
                        obj = stateValue;
                    }
                    if (ownComponentsValue) {
                        ((IDisplayData) component).setValueValid(false, prevValue);
                    }
                    return;
                }
                if (ownComponentsValue && record instanceof FindState && component instanceof IScriptableProvider && ((IScriptableProvider) component).getScriptObject() instanceof IFormatScriptComponent && ((IFormatScriptComponent) ((IScriptableProvider) component).getScriptObject()).getComponentFormat() != null) {
                    ((FindState) record).setFormat(dataProviderID, ((IFormatScriptComponent) ((IScriptableProvider) component).getScriptObject()).getComponentFormat().parsedFormat);
                }
            }
        }
        // then dont call notify
        if (ownComponentsValue) {
            ((IDisplayData) component).notifyLastNewValueWasChange(prevValue, obj);
        }
    } finally {
        // then touch the lastInvalidValue
        if (ownComponentsValue) {
            if (((IDisplayData) component).isValueValid()) {
                lastInvalidValue = NONE;
            } else {
                lastInvalidValue = obj;
            }
        }
    }
    return;
}
Also used : IRecordInternal(com.servoy.j2db.dataprocessing.IRecordInternal) WebForm(com.servoy.j2db.server.headlessclient.WebForm) FormScope(com.servoy.j2db.scripting.FormScope) FindState(com.servoy.j2db.dataprocessing.FindState) ApplicationException(com.servoy.j2db.ApplicationException) IDisplayData(com.servoy.j2db.dataprocessing.IDisplayData) IFormatScriptComponent(com.servoy.j2db.ui.scripting.IFormatScriptComponent) IScriptableProvider(com.servoy.j2db.scripting.IScriptableProvider)

Example 15 with ApplicationException

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

the class FoundSet method deleteRecord.

private void deleteRecord(IRecordInternal state, int row, boolean partOfBiggerDelete) throws ServoyException {
    if (sheet.getTable() == null) {
        return;
    }
    if (!hasAccess(IRepository.DELETE) && (state == null || state.existInDataSource())) {
        throw new ApplicationException(ServoyException.NO_DELETE_ACCESS, new Object[] { sheet.getTable().getName() });
    }
    if (state != null && !(state instanceof PrototypeState) && !findMode) {
        if (!fsm.getRowManager(fsm.getDataSource(sheet.getTable())).addRowToDeleteSet(state.getPKHashKey())) {
            // already being deleted in recursion
            return;
        }
        if (!partOfBiggerDelete) {
            try {
                // see EditRecordList.stopEditing
                if (state.existInDataSource() && !executeFoundsetTriggerBreakOnFalse(new Object[] { state }, PROPERTY_ONDELETEMETHODID, true)) {
                    // trigger returned false
                    // $NON-NLS-1$
                    Debug.log("Delete not granted for the table " + getTable());
                    throw new ApplicationException(ServoyException.DELETE_NOT_GRANTED);
                }
            } catch (DataException e) {
                // trigger threw exception
                state.getRawData().setLastException(e);
                getFoundSetManager().getEditRecordList().markRecordAsFailed(state);
                // $NON-NLS-1$ //$NON-NLS-2$
                Debug.log("Delete not granted for the table " + getTable() + ", pre-delete trigger threw exception");
                throw new ApplicationException(ServoyException.DELETE_NOT_GRANTED);
            }
            // check for related data
            FlattenedSolution flattenedSolution = fsm.getApplication().getFlattenedSolution();
            Iterator<Relation> it = flattenedSolution.getRelations(sheet.getTable(), true, false);
            while (it.hasNext()) {
                Relation rel = it.next();
                if (Relation.isValid(rel, flattenedSolution) && !rel.getAllowParentDeleteWhenHavingRelatedRecords() && !rel.isExactPKRef(fsm.getApplication().getFlattenedSolution()) && !rel.isGlobal()) {
                    IFoundSetInternal set = state.getRelatedFoundSet(rel.getName());
                    if (set != null && set.getSize() > 0) {
                        fsm.getApplication().reportJSError("Delete not granted due to AllowParentDeleteWhenHavingRelatedRecords size: " + set.getSize() + " from record with PK: " + state.getPKHashKey() + " index in foundset: " + row + " blocked by relation: " + rel.getName(), null);
                        throw new ApplicationException(ServoyException.NO_PARENT_DELETE_WITH_RELATED_RECORDS, new Object[] { rel.getName() }).setContext(this.toString());
                    }
                }
            }
            // so only delete related data if the record is already in the db
            if (state.existInDataSource()) {
                // delete the related data
                it = flattenedSolution.getRelations(sheet.getTable(), true, false);
                while (it.hasNext()) {
                    Relation rel = it.next();
                    if (// if completely global never delete do cascade delete
                    Relation.isValid(rel, flattenedSolution) && rel.getDeleteRelatedRecords() && !rel.isGlobal()) {
                        IFoundSetInternal set = state.getRelatedFoundSet(rel.getName());
                        if (set != null) {
                            Debug.trace(// $NON-NLS-1$//$NON-NLS-2$
                            "******************************* delete related set size: " + set.getSize() + " from record with PK: " + state.getPKHashKey() + " index in foundset: " + // $NON-NLS-1$
                            row);
                            set.deleteAllInternal();
                        }
                    }
                }
            }
        }
        if (state.existInDataSource()) {
            Row data = state.getRawData();
            rowManager.deleteRow(this, data, hasAccess(IRepository.TRACKING), partOfBiggerDelete);
            executeFoundsetTrigger(new Object[] { state }, PROPERTY_ONAFTERDELETEMETHODID, false);
            GlobalTransaction gt = fsm.getGlobalTransaction();
            if (gt != null) {
                gt.addDeletedRecord(state);
            }
            // really remove the state from the edited records, can't be saved at all anymore after delete.
            fsm.getEditRecordList().removeEditedRecord(state);
        } else {
            rowManager.clearRow(state.getRawData());
        }
    }
    if (!(state instanceof PrototypeState)) {
        removeRecordInternalEx(state, row);
        // delete the row data so it won't be updated by other foundsets also having records to this rowdata.
        if (state != null && state.getRawData() != null) {
            state.getRawData().flagExistInDB();
        }
    }
}
Also used : Relation(com.servoy.j2db.persistence.Relation) ApplicationException(com.servoy.j2db.ApplicationException) FlattenedSolution(com.servoy.j2db.FlattenedSolution)

Aggregations

ApplicationException (com.servoy.j2db.ApplicationException)22 ServoyException (com.servoy.j2db.util.ServoyException)12 RepositoryException (com.servoy.j2db.persistence.RepositoryException)5 Relation (com.servoy.j2db.persistence.Relation)4 Table (com.servoy.j2db.persistence.Table)4 BasicFormController (com.servoy.j2db.BasicFormController)3 IBasicFormManager (com.servoy.j2db.IBasicFormManager)3 Column (com.servoy.j2db.persistence.Column)3 Form (com.servoy.j2db.persistence.Form)3 ITable (com.servoy.j2db.persistence.ITable)3 QuerySelect (com.servoy.j2db.query.QuerySelect)3 RemoteException (java.rmi.RemoteException)3 ArrayList (java.util.ArrayList)3 JavaScriptException (org.mozilla.javascript.JavaScriptException)3 ScriptableObject (org.mozilla.javascript.ScriptableObject)3 IBaseColumn (com.servoy.base.persistence.IBaseColumn)2 BaseQueryTable (com.servoy.base.query.BaseQueryTable)2 ExitScriptException (com.servoy.j2db.ExitScriptException)2 FindState (com.servoy.j2db.dataprocessing.FindState)2 IDisplayData (com.servoy.j2db.dataprocessing.IDisplayData)2