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, String[] pkNames, boolean create, boolean skipOnLoad, String server) throws ServoyException {
if (name == null) {
return null;
}
String dataSource = IServer.VIEW_SERVER.equals(server) ? DataSourceUtils.createViewDataSource(name) : DataSourceUtils.createInmemDataSource(name);
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;
boolean[] rowsToStringserialize = null;
if (columnsDef == null) {
// if we have array columns, convert values using StringSerializer
if (containsArrayType(fixedColumnTypes)) {
rowsToStringserialize = new boolean[fixedColumnTypes.size()];
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));
rowsToStringserialize[i] = true;
}
}
}
} else {
TableDef tableInfo = DatabaseUtils.deserializeTableInfo(columnsDef);
columnInfoDefinitions = new HashMap<String, ColumnInfoDef>();
List<String> inmemColumnNames = new ArrayList<>();
List<String> inmemPKs = new ArrayList<>();
List<ColumnType> inmemColumnTypes = 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) {
inmemColumnNames.add(cid.name);
inmemColumnTypes.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 (rowsToStringserialize == null) {
rowsToStringserialize = new boolean[fixedColumnTypes.size()];
}
rowsToStringserialize[j] = true;
}
}
if (pkNames == null && inmemPKs.size() > 0) {
pkNames = inmemPKs.toArray(new String[inmemPKs.size()]);
}
if (!asList(dataSet.getColumnNames()).equals(inmemColumnNames) || !compareColumnTypes(fixedColumnTypes, inmemColumnTypes)) {
if (dataSet.getColumnCount() > 0 && !asList(dataSet.getColumnNames()).equals(inmemColumnNames)) {
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: " + inmemColumnNames);
}
if (fixedColumnTypes != null && !compareColumnTypes(fixedColumnTypes, inmemColumnTypes)) {
Debug.warn("Dataset column types definition does not match inmem table definition for datasource : " + dataSource + " types of dataset: " + fixedColumnTypes + ", types of in mem definition: " + inmemColumnTypes);
}
fixedColumnTypes = inmemColumnTypes;
fixedDataSet = BufferedDataSetInternal.createBufferedDataSet(inmemColumnNames.toArray(new String[inmemColumnNames.size()]), fixedColumnTypes.toArray(new ColumnType[fixedColumnTypes.size()]), new ArrayList<Object[]>(), false);
}
}
// - in the else branch above (already defined in the table node), columns that are not auto sequences or dbidents; see inmemColumnNames/inmemColumnTypes(which is at this point the same as fixedColumnTypes)
if (dataSet.getRowCount() > 0 && dataSet.getRow(0).length != fixedColumnTypes.size()) {
// $NON-NLS-1$
throw new RepositoryException("Data set rows do not match column count");
}
if (rowsToStringserialize != null) {
replaceValuesWithSerializedString(dataSet, rowsToStringserialize);
}
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 */
pkNames, columnInfoDefinitions);
if (insertResult != null) {
table = insertResult.getTable();
// then call insertDataSet again so the data is inserted with the columns defined in the the dataset.
if (dataSet != fixedDataSet && dataSet.getRowCount() > 0) {
insertResult = application.getDataServer().insertDataSet(application.getClientID(), dataSet, dataSource, table.getServerName(), table.getName(), tid, fixedColumnTypes == null ? null : fixedColumnTypes.toArray(new ColumnType[fixedColumnTypes.size()]), /* inferred from dataset when null */
pkNames, columnInfoDefinitions);
}
if (IServer.INMEM_SERVER.equals(serverName)) {
inMemDataSources.put(dataSource, table);
} else {
viewDataSources.put(dataSource, table);
}
fireTableEvent(table);
if (!skipOnLoad && fixedDataSet.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;
}
use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.
the class DebugUtils method errorToDebugger.
public static void errorToDebugger(IExecutingEnviroment engine, String message, Object errorDetail) {
Object detail = errorDetail;
if (engine instanceof RemoteDebugScriptEngine) {
DBGPDebugger debugger = ((RemoteDebugScriptEngine) engine).getDebugger();
if (debugger != null) {
RhinoException rhinoException = null;
if (detail instanceof Exception) {
Throwable exception = (Exception) detail;
while (exception != null) {
if (exception instanceof RhinoException) {
rhinoException = (RhinoException) exception;
break;
}
exception = exception.getCause();
}
}
String msg = message;
if (rhinoException != null) {
if (msg == null) {
msg = rhinoException.getLocalizedMessage();
} else
msg += '\n' + rhinoException.getLocalizedMessage();
msg += '\n' + rhinoException.getScriptStackTrace();
} else if (detail instanceof Exception) {
Object e = ((Exception) detail).getCause();
if (e != null) {
detail = e;
}
String stackTrace = null;
ByteArrayOutputStream bos = null;
PrintStream ps = null;
try {
bos = new ByteArrayOutputStream();
ps = new PrintStream(bos);
((Exception) detail).printStackTrace(ps);
ps.flush();
bos.flush();
stackTrace = bos.toString();
} catch (Exception ex) {
Debug.error(ex);
} finally {
if (ps != null)
ps.close();
if (bos != null) {
try {
bos.close();
} catch (Exception ex) {
Debug.error(ex);
}
}
}
if (stackTrace == null)
stackTrace = detail.toString();
msg += "\n > " + stackTrace;
if (detail instanceof ServoyException && ((ServoyException) detail).getScriptStackTrace() != null) {
msg += '\n' + ((ServoyException) detail).getScriptStackTrace();
}
} else if (detail != null) {
msg += "\n" + detail;
String scriptstack = Debug.getScriptStacktraceFromContext(msg);
if (scriptstack != null)
msg += "\n" + scriptstack;
} else {
String scriptstack = Debug.getScriptStacktraceFromContext(msg);
if (scriptstack != null)
msg += "\n" + scriptstack;
}
debugger.outputStdErr(msg.toString() + '\n');
}
}
}
use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.
the class WebForm method print.
// public void print(boolean showDialogs, boolean printCurrentRecordOnly, boolean showPrinterSelectDialog, int zoomFactor, PrinterJob printerJob)
// {
// print(showDialogs, printCurrentRecordOnly, showPrinterSelectDialog, printerJob);
// }
/**
* @see com.servoy.j2db.IFormUIInternal#print(boolean, boolean, boolean, java.awt.print.PrinterJob)
*/
public void print(boolean showDialogs, boolean printCurrentRecordOnly, boolean showPrinterSelectDialog, PrinterJob printerJob) {
IFoundSetInternal fs = formController.getFoundSet();
try {
if (printCurrentRecordOnly) {
fs = fs.copyCurrentRecordFoundSet();
}
} catch (ServoyException e1) {
Debug.error(e1);
}
IApplication application = formController.getApplication();
ByteArrayOutputStream baos = null;
MainPage page = null;
if (printerJob == null) {
page = (MainPage) findPage();
if (page == null) {
IMainContainer tmp = ((FormManager) application.getFormManager()).getCurrentContainer();
if (tmp instanceof MainPage)
page = (MainPage) tmp;
}
// if "page" is still null then there is no wicket front-end for this client - so printing is not intended to reach the client; print on the server instead
// (can happen for batch processors for example)
}
if (page != null) {
baos = new ByteArrayOutputStream();
StreamPrintServiceFactory[] factories = null;
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
ClassLoader savedClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(((PluginManager) application.getPluginManager()).getClassLoader());
// $NON-NLS-1$
factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, "application/pdf");
if (factories == null || factories.length == 0) {
// $NON-NLS-1$
Debug.error("No suitable pdf printer found");
return;
}
} finally {
Thread.currentThread().setContextClassLoader(savedClassLoader);
}
try {
FormPreviewPanel fpp = new FormPreviewPanel(application, formController, fs);
// AWT stuff happens here, so execute it in the AWT Event Thread - else exceptions can occur
// for example in JEditorPane while getting the preferred size & stuff
processFppInAWTEventQueue(fpp, application);
StreamPrintService sps = factories[0].getPrintService(baos);
Doc doc = new SimpleDoc(fpp.getPageable(), flavor, null);
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
sps.createPrintJob().print(doc, pras);
fpp.destroy();
} catch (Exception ex) {
// $NON-NLS-1$
application.reportError(application.getI18NMessage("servoy.formPanel.error.printDocument"), ex);
}
// $NON-NLS-1$
String contentType = "application/pdf";
// BTW, "application/octet-stream" works for all browsers, but it is not that accurate
if (// if it's not batch processor/jsp, because if it is, then getClientInfo() gives NullPointerException
application.getApplicationType() != IApplication.HEADLESS_CLIENT) {
ClientInfo info = Session.get().getClientInfo();
if (info instanceof WebClientInfo) {
String userAgent = ((WebClientInfo) info).getProperties().getNavigatorUserAgent();
if (// $NON-NLS-1$
userAgent != null && userAgent.toLowerCase().contains("safari")) {
// $NON-NLS-1$
contentType = "application/octet-stream";
}
}
}
// $NON-NLS-1$ //$NON-NLS-2$
String url = page.serveResource(formController.getName() + ".pdf", baos.toByteArray(), contentType, "attachment");
// $NON-NLS-1$
page.setShowURLCMD(url, "_self", null, 0, false);
} else {
try {
FormPreviewPanel fpp = new FormPreviewPanel(application, formController, fs);
// AWT stuff happens here, so execute it in the AWT Event Thread - else exceptions can occur
// for example in JEditorPane while getting the preferred size & stuff
processFppInAWTEventQueue(fpp, application);
PrintPreview.startPrinting(application, fpp.getPageable(), printerJob, formController.getPreferredPrinterName(), false, true);
fpp.destroy();
} catch (Exception ex) {
// $NON-NLS-1$
application.reportError(application.getI18NMessage("servoy.formPanel.error.printDocument"), ex);
}
}
}
use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.
the class ValuelistPropTest method fillTestSolution.
@Override
protected void fillTestSolution() throws ServoyException {
try {
ValueList vl = solution.createNewValueList(validator, "myVl1");
vl.setCustomValues("1\n2\n3");
vl = solution.createNewValueList(validator, "myVl2");
vl.setCustomValues("11\n22\n33");
Form form = solution.createNewForm(validator, null, "test", "mem:test", false, new Dimension(600, 400));
form.setNavigatorID(-1);
form.createNewPart(IBaseSMPart.BODY, 5);
form.createNewWebComponent("myCustomComponent", "my-component");
} catch (JSONException e) {
e.printStackTrace();
throw new ServoyException();
}
}
use of com.servoy.j2db.util.ServoyException in project servoy-client by Servoy.
the class AbstractSolutionTest method buildSolution.
@Before
public void buildSolution() throws Exception {
TestNGClient.initSettings();
Types.getTypesInstance().registerTypes();
final File f = new File(NGClient.class.getProtectionDomain().getCodeSource().getLocation().getPath());
IPackageReader[] servicesReaders = null;
IPackageReader[] componentsReaders = null;
InMemPackageReader inMemPackageReader = getTestComponents();
if (f.isFile() && f.getName().startsWith("servoy_ngclient") && f.getName().endsWith(".jar")) {
// it is running from bundles/jars
ZipFile zipFile = new ZipFile(f);
componentsReaders = inMemPackageReader != null ? new IPackageReader[] { new ZipPackageReader(zipFile, "war/servoycore/"), new ZipPackageReader(zipFile, "war/servoydefault/"), inMemPackageReader } : new IPackageReader[] { new ZipPackageReader(zipFile, "war/servoycore/"), new ZipPackageReader(zipFile, "war/servoydefault/") };
servicesReaders = new IPackageReader[] { new ZipPackageReader(zipFile, "war/servoyservices/") };
} else {
// it is running from sources/projects
File ngClientProjDir = f;
if (!new File(ngClientProjDir, "/war/servoycore/").exists()) {
ngClientProjDir = ngClientProjDir.getParentFile();
}
componentsReaders = getReaders(new File[] { new File(ngClientProjDir.getAbsoluteFile() + "/war/servoycore/"), new File(ngClientProjDir.getAbsoluteFile() + "/war/servoydefault/") }, // in eclipse we .. out of bin, in jenkins we .. out of @dot
inMemPackageReader);
servicesReaders = getReaders(new File[] { new File(ngClientProjDir.getAbsoluteFile(), "/war/servoyservices/") }, null);
}
WebComponentSpecProvider.init(componentsReaders, DefaultComponentPropertiesProvider.instance);
WebServiceSpecProvider.init(servicesReaders);
final TestRepository tr = new TestRepository();
try {
ApplicationServerRegistry.setApplicationServerSingleton(new TestApplicationServer(tr));
UUID uuid = UUID.randomUUID();
final RootObjectMetaData metadata = tr.createRootObjectMetaData(tr.getElementIdForUUID(uuid), uuid, "Test", IRepository.SOLUTIONS, 1, 1);
solution = (Solution) tr.createRootObject(metadata);
tr.cacheRootObject(solution);
solution.setChangeHandler(new ChangeHandler(tr));
fillTestSolution();
HttpSession testHttpsession = new TestHttpsession();
endpoint = new NGClientEndpoint() {
// for testing onstart of the NGClientEndpoint should not run
@Override
public void onStart() {
}
@Override
protected HttpSession getHttpSession(Session session) {
return testHttpsession;
}
};
NGClientWebsocketSession session = new NGClientWebsocketSession(new WebsocketSessionKey(testHttpsession.getId(), 1)) {
@Override
public void init(Map<String, List<String>> requestParams) throws Exception {
// override default init, shouldnt make another client.
}
@Override
protected IEventDispatcher createEventDispatcher() {
return new TestNGEventDispatcher(endpoint);
}
};
WebsocketSessionManager.addSession(session);
NGClientWebsocketSessionWindows windows = new NGClientWebsocketSessionWindows(session);
CurrentWindow.set(windows);
client = new TestNGClient(tr, session) {
@Override
public boolean loadSolutionsAndModules(SolutionMetaData solutionMetaData) {
boolean b = super.loadSolutionsAndModules(solutionMetaData);
IPersistIndex index = PersistIndexCache.getCachedIndex(solution);
solution.getChangeHandler().addIPersistListener((IItemChangeListener<IPersist>) index);
try {
setupData();
} catch (ServoyException e) {
e.printStackTrace();
}
return b;
}
};
J2DBGlobals.setServiceProvider(client);
client.setUseLoginSolution(false);
endpoint.start(new TestSession(), String.valueOf(session.getSessionKey().getClientnr()), "null", "42");
CurrentWindow.set(session.getWindows().iterator().next());
} catch (RepositoryException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
Aggregations