@Override public Object executeServiceModule( HttpServletRequest request, HttpServletResponse response, Object input, String module, Map<Object, Object> executionContext) throws IOException { logger.debug("entering: executeServiceModule()"); // $NON-NLS-1$ logger.debug("module=" + module); // $NON-NLS-1$ if (module == null) { throw new IOException("Mobile module cannot be null"); } Module mobileModule = retrieveModule(this.repository, module, null, this.rootPaths); byte[] result = mobileModule.getContent(); result = preprocessContent(result, getResource(repository, mobileModule.getPath())); response.getWriter().print(new String(result)); response.getWriter().flush(); logger.debug("exiting: executeServiceModule()"); return result; }
/** * Create connection from the data-source selected at this view * * @return * @throws SQLException */ public static Connection getConnectionFromSelectedDatasource() throws SQLException { String datasourceName = CommonIDEParameters.get(SELECTED_DATASOURCE_NAME); DataSource dataSource = null; if ((datasourceName == null) || datasourceName.equals(DEFAULT_DATASOURCE_NAME)) { logger.debug("No selected datasource found. Make use of the default one"); dataSource = DataSourceFacade.getInstance().getDataSource(CommonIDEParameters.getRequest()); if (dataSource != null) { Connection connection = dataSource.getConnection(); return connection; } logger.error("Trying to use the default datasource, but it is null"); } else { logger.debug(String.format("Selected datasource found %s", datasourceName)); dataSource = DataSourceFacade.getInstance() .getNamedDataSource(CommonIDEParameters.getRequest(), datasourceName); if (dataSource != null) { Connection connection = dataSource.getConnection(); return connection; } logger.error( String.format( "Selected datasource found %s, but the datasource itself is null", datasourceName)); } return null; }
@Override public void executeUpdate(List<String> knownFiles, List<String> errors) throws Exception { if (knownFiles.size() == 0) { return; } try { Connection connection = dataSource.getConnection(); DatabaseMetaData databaseMetaData = getMetaData(connection); String productName = connection.getMetaData().getDatabaseProductName(); IDialectSpecifier dialectSpecifier = DBUtils.getDialectSpecifier(productName); try { for (Iterator<String> iterator = knownFiles.iterator(); iterator.hasNext(); ) { String dsDefinition = iterator.next(); try { if (dsDefinition.endsWith(EXTENSION_TABLE)) { executeTableUpdate(connection, databaseMetaData, dialectSpecifier, dsDefinition); } else if (dsDefinition.endsWith(EXTENSION_VIEW)) { executeViewUpdate(connection, databaseMetaData, dialectSpecifier, dsDefinition); } } catch (Exception e) { logger.error(e.getMessage(), e); errors.add(e.getMessage()); } } } finally { if (connection != null) { connection.close(); } } } catch (SQLException e) { logger.error(e.getMessage(), e); } }
private void executeViewCreateOrReplace(Connection connection, JsonObject dsDefinitionObject) throws SQLException { StringBuilder sql = new StringBuilder(); String viewName = dsDefinitionObject.get(VIEW_NAME).getAsString().toUpperCase(); String query = dsDefinitionObject.get(QUERY).getAsString(); String sqlExpression = null; ResultSet rs = connection.getMetaData().getTables(null, null, viewName, new String[] {TABLE, VIEW}); if (rs.next()) { sql.append(DROP_VIEW + viewName); sqlExpression = sql.toString(); try { logger.info(sqlExpression); executeUpdateSQL(connection, sqlExpression); } catch (SQLException e) { logger.error(sqlExpression); logger.error(e.getMessage(), e); } } sql = new StringBuilder(); sql.append(CREATE_VIEW + viewName + AS + query); sqlExpression = sql.toString(); try { logger.info(sqlExpression); executeUpdateSQL(connection, sqlExpression); } catch (SQLException e) { logger.error(sqlExpression); throw new SQLException(sqlExpression, e); } }
public MobileExecutor(IRepository repository, String... rootPaths) { super(); logger.debug("entering: constructor()"); this.repository = repository; this.rootPaths = rootPaths; if ((this.rootPaths == null) || (this.rootPaths.length == 0)) { this.rootPaths = new String[] {null, null}; } logger.debug("exiting: constructor()"); }
private void executeTableCreate( Connection connection, IDialectSpecifier dialectSpecifier, JsonObject dsDefinitionObject) throws SQLException { StringBuilder sql = new StringBuilder(); String tableName = dsDefinitionObject.get(TABLE_NAME).getAsString(); sql.append(CREATE_TABLE + tableName + " ("); // $NON-NLS-1$ JsonArray columns = dsDefinitionObject.get(COLUMNS).getAsJsonArray(); int i = 0; for (JsonElement jsonElement : columns) { if (jsonElement instanceof JsonObject) { if (i > 0 && i < columns.size()) { sql.append(", "); // $NON-NLS-1$ } JsonObject jsonObject = (JsonObject) jsonElement; String name = jsonObject.get(COLUMN_NAME).getAsString(); String type = dbUtils.specifyDataType(connection, jsonObject.get(COLUMN_TYPE).getAsString()); String length = jsonObject.get(COLUMN_LENGTH).getAsString(); boolean notNull = jsonObject.get(COLUMN_NOT_NULL).getAsBoolean(); boolean primaryKey = jsonObject.get(COLUMN_PRIMARY_KEY).getAsBoolean(); String defaultValue = jsonObject.get(COLUMN_DEFAULT_VALUE).getAsString(); sql.append(name + " " + type); // $NON-NLS-1$ if (DBSupportedTypesMap.VARCHAR.equals(type) || DBSupportedTypesMap.CHAR.equals(type)) { sql.append("(" + length + ") "); // $NON-NLS-1$ //$NON-NLS-2$ } else { sql.append(" "); // $NON-NLS-1$ } if (notNull) { sql.append(NOT_NULL); } if (primaryKey) { sql.append(PRIMARY_KEY); } if (defaultValue != null && !"".equals(defaultValue)) { // $NON-NLS-1$ sql.append(DEFAULT + defaultValue + " "); // $NON-NLS-1$ } } i++; } sql.append(")"); // $NON-NLS-1$ String sqlExpression = sql.toString(); try { logger.info(sqlExpression); executeUpdateSQL(connection, sqlExpression); } catch (SQLException e) { logger.error(sqlExpression); throw new SQLException(sqlExpression, e); } }
protected static final String readFile(IFile file) throws ContentProviderException { try { BufferedReader in = null; if (file.getClass() .getCanonicalName() .equals("org.eclipse.dirigible.ide.workspace.impl.File")) { in = new BufferedReader(new InputStreamReader(file.getContents())); } else { IResource resource = getFromRepository(file); in = new BufferedReader( new InputStreamReader(new ByteArrayInputStream(resource.getContent()))); } StringBuilder builder = new StringBuilder(); String line = null; while ((line = in.readLine()) != null) { builder.append(line); builder.append("\n"); // $NON-NLS-1$ } return builder.toString(); } catch (Exception ex) { LOGGER.error(CANNOT_READ_FILE_CONTENTS, ex); throw new ContentProviderException(CANNOT_READ_FILE_CONTENTS, ex); } }
/** * Return the constructed zip in servlet response * * @param response * @param tmpFile * @param request */ private void sendZip(HttpServletRequest request, HttpServletResponse response, byte[] content) { String fileName = null; fileName = defaultFileName(request) + ".zip"; response.setContentType("application/zip"); // $NON-NLS-1$ response.setHeader( "Content-Disposition", "attachment;filename=\"" //$NON-NLS-1$ //$NON-NLS-2$ + fileName + "\""); //$NON-NLS-1$ try { BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); ByteArrayInputStream fis = new ByteArrayInputStream(content); int len; byte[] buf = new byte[1024]; while ((len = fis.read(buf)) > 0) { bos.write(buf, 0, len); } bos.close(); fis.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } }
public class CustomResourceChangeListener implements IResourceChangeListener { private static final Logger logger = Logger.getLogger(CustomResourceChangeListener.class.getName()); private StructuredViewer viewer; private ICustomResourceChangeListenerCallback callbackObject; public CustomResourceChangeListener( StructuredViewer viewer, ICustomResourceChangeListenerCallback callbackObject) { super(); this.viewer = viewer; this.callbackObject = callbackObject; } @Override public void resourceChanged(IResourceChangeEvent event) { final Display display = Display.getCurrent(); UISession uiSession = RWT.getUISession(display); uiSession.exec( new Runnable() { @Override public void run() { if (!viewer.getControl().isDisposed()) { try { callbackObject.callback(); } catch (Exception e) { logger.error(e.getMessage()); } } } }); } }
public class GetStartedStartup implements IStartup { private static final Logger logger = Logger.getLogger(GetStartedStartup.class); @Override public void earlyStartup() { Display.getDefault() .asyncExec( new Runnable() { @Override public void run() { if (CommonParameters.get("git") != null) { // starting for git import - skip get started return; } // enable/disable get started wizard if (WorkspaceLocator.getWorkspace().getRoot().getProjects().length == 0) { GetStartedProjectHandler projectHandler = new GetStartedProjectHandler(); try { projectHandler.execute(null); } catch (ExecutionException e) { logger.error(e.getMessage()); } } } }); } }
private void populateMetaData(DataSource dataSource) { Connection connection = null; try { try { connection = dataSource.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); CommonParameters.set( CommonParameters.DATABASE_PRODUCT_NAME, metaData.getDatabaseProductName()); CommonParameters.set( CommonParameters.DATABASE_PRODUCT_VERSION, metaData.getDatabaseProductVersion()); CommonParameters.set( CommonParameters.DATABASE_MINOR_VERSION, metaData.getDatabaseMinorVersion() + EMPTY); CommonParameters.set( CommonParameters.DATABASE_MAJOR_VERSION, metaData.getDatabaseMajorVersion() + EMPTY); CommonParameters.set(CommonParameters.DATABASE_DRIVER_NAME, metaData.getDriverName()); CommonParameters.set( CommonParameters.DATABASE_DRIVER_MINOR_VERSION, metaData.getDriverMinorVersion() + EMPTY); CommonParameters.set( CommonParameters.DATABASE_DRIVER_MAJOR_VERSION, metaData.getDriverMajorVersion() + EMPTY); CommonParameters.set( CommonParameters.DATABASE_CONNECTION_CLASS_NAME, connection.getClass().getCanonicalName()); } finally { if (connection != null) { connection.close(); } } } catch (SQLException e) { logger.error(e.getMessage(), e); } }
static { try { // ProxyUtils.setProxySettings(); deleteTempDirectories(); } catch (IOException e) { logger.error(e.getMessage(), e); } }
@Override public void stop() { try { messageHub.unsubscribe(client, topic); MessageListenerManager.getInstance().unregisterProcessor(this); } catch (EMessagingException e) { logger.error(e.getMessage(), e); } }
protected static final void writeFile(IFile file, byte[] content) throws ContentProviderException { try { if (file.getClass() .getCanonicalName() .equals("org.eclipse.dirigible.ide.workspace.impl.File")) { file.setContents(new ByteArrayInputStream(content), false, false, null); } else { IResource resource = getFromRepository(file); resource.setContent(content); } } catch (CoreException ex) { LOGGER.error(CANNOT_SAVE_FILE_CONTENTS, ex); throw new ContentProviderException(CANNOT_SAVE_FILE_CONTENTS, ex); } catch (IOException e) { LOGGER.error(CANNOT_SAVE_FILE_CONTENTS, e); throw new ContentProviderException(CANNOT_SAVE_FILE_CONTENTS, e); } }
/** * Extract the Dirigible project as a zip from the repository. * * @param request * @return */ private byte[] getContentFromRepository(HttpServletRequest request) { byte[] zippedContent = null; try { IRepository repository = getRepository(request); zippedContent = repository.exportZip(getDefaultPathForExport(), true); } catch (IOException e) { logger.error(e.getMessage(), e); } return zippedContent; }
public IValidationStatus validateTemplate() { if ((getTemplateLocation() == null) || EMPTY_STRING.equals(getTemplateLocation())) { return ValidationStatus.createError(TEMPLATE_LOCATION_IS_EMPTY); } InputStream in; try { in = getInputStreamByTemplateLocation(getTemplateLocation()); } catch (IOException e) { logger.error(e.getMessage(), e); return ValidationStatus.createError(e.getMessage()); } if (in == null) { logger.error(String.format(COULD_NOT_OPEN_INPUT_STREAM_FOR, getTemplateLocation())); return ValidationStatus.createError( String.format(COULD_NOT_OPEN_INPUT_STREAM_FOR, getTemplateLocation())); } return ValidationStatus.createOk(); }
@Override protected void doExecution(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String module = request.getPathInfo(); JavaExecutor executor = createExecutor(request); Map<Object, Object> executionContext = new HashMap<Object, Object>(); try { Object result = executor.executeServiceModule(request, response, module, executionContext); if (result != null) { logger.error(result.toString()); response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, result.toString()); } } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
protected String getExportFilePrefix() { StringBuilder buff = new StringBuilder(); buff.append(IRepositoryPaths.REGISTRY).append(UNDERSCORE); try { buff.append(java.net.InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { logger.error(e.getMessage(), e); buff.append(UNKNOWN_HOST); } return buff.toString(); }
private WrappedDataSource createLocal() { localDataSource = (DataSource) System.getProperties().get(LOCAL_DB_NAME); if (localDataSource == null) { localDataSource = new EmbeddedDataSource(); ((EmbeddedDataSource) localDataSource).setDatabaseName(LOCAL_DB_NAME); ((EmbeddedDataSource) localDataSource).setCreateDatabase(LOCAL_DB_ACTION); System.getProperties().put(LOCAL_DB_NAME, localDataSource); } logger.warn(EMBEDDED_DATA_SOURCE_IS_USED); WrappedDataSource wrappedDataSource = new WrappedDataSource(localDataSource); return wrappedDataSource; }
private Object evaluate(final String function, final Object... arguments) { final String script = buildFunctionCall(function, arguments); for (int i = 0; i < EVALUATE_ATTEMPTS; i++) { try { return browser.evaluate(script); } catch (final Exception ex) { logger.debug(ex.getMessage(), ex); } } throw new IllegalStateException(SCRIPT_EVALUATION_FAILED + script); }
@Override public void start(Listener listener) { this.listener = listener; this.client = listener.getParams().get(PARAM_CLIENT); this.topic = listener.getParams().get(PARAM_TOPIC); try { messageHub.subscribe(client, topic); MessageListenerManager.getInstance().registerProcessor(this); } catch (EMessagingException e) { logger.error(e.getMessage(), e); } }
@Override public void init() throws ServletException { super.init(); String eclipseLauncherProperty = System.getProperty("osgi.syspath"); logger.debug("osgi.syspath: " + eclipseLauncherProperty); if (eclipseLauncherProperty == null) { eclipseLauncherProperty = System.getProperty("user.dir"); logger.debug("user.dir: " + eclipseLauncherProperty); } eclipseLauncherProperty = eclipseLauncherProperty.replace("/./", "/"); libDirectory = new File(eclipseLauncherProperty); if (libDirectory.exists() && (libDirectory.getParentFile() != null) && libDirectory.getParentFile().exists()) { libDirectory = libDirectory.getParentFile(); } try { getClasspath(); } catch (IOException e) { throw new ServletException(e); } }
public class MessageListenerEventProcessor implements IListenerEventProcessor { private static final String PARAM_CLIENT = "client"; private static final String PARAM_TOPIC = "topic"; private static final String PARAM_MESSAGE = "message"; private static final Logger logger = Logger.getLogger(MessageListenerEventProcessor.class); private String client; private String topic; private Listener listener; private MessageHub messageHub; public MessageListenerEventProcessor() { this.messageHub = new MessageHub(DataSourceFacade.getInstance().getDataSource(null), null); } @Override public void start(Listener listener) { this.listener = listener; this.client = listener.getParams().get(PARAM_CLIENT); this.topic = listener.getParams().get(PARAM_TOPIC); try { messageHub.subscribe(client, topic); MessageListenerManager.getInstance().registerProcessor(this); } catch (EMessagingException e) { logger.error(e.getMessage(), e); } } @Override public void stop() { try { messageHub.unsubscribe(client, topic); MessageListenerManager.getInstance().unregisterProcessor(this); } catch (EMessagingException e) { logger.error(e.getMessage(), e); } } public void processMessages() throws EMessagingException { for (MessageDefinition messageDefinition : messageHub.receive(client)) { Map<Object, Object> executionContext = new HashMap<Object, Object>(); executionContext.put(PARAM_MESSAGE, messageDefinition); ListenerProcessor.executeByEngineType(listener.getModule(), executionContext, listener); } } }
public class LogProgressMonitor implements IProgressMonitor { private static final Logger logger = Logger.getLogger(LogProgressMonitor.class); boolean cancelled; @Override public void beginTask(String name, int totalWork) { logger.info(String.format("beginTask: %s, %d ", name, totalWork)); } @Override public void done() { logger.info("done."); } @Override public void internalWorked(double work) { logger.info(String.format("internalWorked: %d ", work)); } @Override public boolean isCanceled() { return this.cancelled; } @Override public void setCanceled(boolean value) { this.cancelled = value; } @Override public void setTaskName(String name) { // TODO Auto-generated method stub } @Override public void subTask(String name) { logger.info(String.format("subTask: %s ", name)); } @Override public void worked(int work) { logger.info(String.format("worked: %d ", work)); } }
private void createTableColumns() { if (getTableName() == null) { return; } try { Connection connection = null; try { connection = DataSourceFacade.getInstance() .getDataSource(CommonParameters.getRequest()) .getConnection(); List<TableColumn> availableTableColumns = new ArrayList<TableColumn>(); ResultSet primaryKeys = DBUtils.getPrimaryKeys(connection, getTableName()); while (primaryKeys.next()) { String columnName = primaryKeys.getString("COLUMN_NAME"); // $NON-NLS-1$ TableColumn tableColumn = new TableColumn(columnName, 0, true, true); availableTableColumns.add(tableColumn); } ResultSet columns = DBUtils.getColumns(connection, getTableName()); while (columns.next()) { // columns String columnName = columns.getString("COLUMN_NAME"); // $NON-NLS-1$ int columnType = columns.getInt("DATA_TYPE"); // $NON-NLS-1$ TableColumn tableColumn = new TableColumn(columnName, columnType, false, true); if (!exists(availableTableColumns, tableColumn)) { availableTableColumns.add(tableColumn); } } setTableColumns(availableTableColumns.toArray(new TableColumn[] {})); } finally { if (connection != null) { connection.close(); } } } catch (Exception e) { logger.error(ERROR_ON_LOADING_TABLE_COLUMNS_FROM_DATABASE_FOR_GENERATION, e); } }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!PermissionsUtils.isUserInRole(request, IRoles.ROLE_OPERATOR)) { String err = String.format(PermissionsUtils.PERMISSION_ERR, "Export"); logger.debug(err); throw new ServletException(err); } // put guid in the session request.getSession().setAttribute(GUID, createGUID()); // $NON-NLS-1$ byte[] zippedContent = getContentFromRepository(request); sendZip(request, response, zippedContent); }
@SuppressWarnings("rawtypes") public void run() { IStructuredSelection selection = (IStructuredSelection) viewer.getSelection(); TreeParent parent = null; for (Iterator nextSelection = selection.iterator(); nextSelection.hasNext(); ) { Object obj = nextSelection.next(); if (TreeObject.class.isInstance(obj)) { if (((TreeObject) obj).getTableDefinition() != null) { TableDefinition tableDefinition = ((TreeObject) obj).getTableDefinition(); boolean confirm = MessageDialog.openConfirm( viewer.getControl().getShell(), DELETE_TABLE, String.format( WARNING_THIS_ACTION_WILL_DELETE_THE_TABLE_AND_ALL_OF_ITS_CONTENT_CONTINUE, tableDefinition.getTableName())); if (!confirm) { continue; } parent = ((TreeObject) obj).getParent(); IDatabaseConnectionFactory connectionFactory = parent.getConnectionFactory(); try { deleteTable(tableDefinition, connectionFactory); } catch (SQLException e) { showMessage(String.format(FAILED_TO_DELETE_TABLE_S, tableDefinition.getTableName())); logger.error(e.getMessage(), e); } } } } if (parent != null) { RefreshViewAction refresh = new RefreshViewAction(viewer, parent.getChildren()[0]); refresh.run(); } }
public class JavaServlet extends AbstractScriptingServlet { private static final long serialVersionUID = -2029496922201773270L; private static final Logger logger = Logger.getLogger(JavaServlet.class); private File libDirectory; private static String classpath; @Override public void init() throws ServletException { super.init(); String eclipseLauncherProperty = System.getProperty("osgi.syspath"); logger.debug("osgi.syspath: " + eclipseLauncherProperty); if (eclipseLauncherProperty == null) { eclipseLauncherProperty = System.getProperty("user.dir"); logger.debug("user.dir: " + eclipseLauncherProperty); } eclipseLauncherProperty = eclipseLauncherProperty.replace("/./", "/"); libDirectory = new File(eclipseLauncherProperty); if (libDirectory.exists() && (libDirectory.getParentFile() != null) && libDirectory.getParentFile().exists()) { libDirectory = libDirectory.getParentFile(); } try { getClasspath(); } catch (IOException e) { throw new ServletException(e); } } @Override protected void doExecution(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String module = request.getPathInfo(); JavaExecutor executor = createExecutor(request); Map<Object, Object> executionContext = new HashMap<Object, Object>(); try { Object result = executor.executeServiceModule(request, response, module, executionContext); if (result != null) { logger.error(result.toString()); response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, result.toString()); } } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } private String getClasspath() throws IOException { synchronized (JavaServlet.class) { if (classpath == null) { if (this.libDirectory != null) { classpath = ClassFileManager.getJars(this.libDirectory); } else { try { classpath = ClassFileManager.getJars(new File(Platform.getInstallLocation().getURL().toURI())); } catch (URISyntaxException e) { throw new IOException(e); } } } } return classpath; } public JavaExecutor createExecutor(HttpServletRequest request) throws IOException { JavaExecutor executor = new JavaExecutor( getRepository(request), getClasspath(), getScriptingRegistryPath(request), REGISTRY_SCRIPTING_DEPLOY_PATH); return executor; } }
/** Action that will trigger opening of Table Definition editor. */ public class DeleteTableAction extends Action { private static final String DROP_TABLE = "DROP TABLE "; // $NON-NLS-1$ private static final String DATABASE_VIEW = Messages.DeleteTableAction_DATABASE_VIEW; private static final String FAILED_TO_DELETE_TABLE_S = Messages.DeleteTableAction_FAILED_TO_DELETE_TABLE_S; private static final Logger logger = Logger.getLogger(DeleteTableAction.class); private static final String WARNING_THIS_ACTION_WILL_DELETE_THE_TABLE_AND_ALL_OF_ITS_CONTENT_CONTINUE = Messages .DeleteTableAction_WARNING_THIS_ACTION_WILL_DELETE_THE_TABLE_AND_ALL_OF_ITS_CONTENT_CONTINUE; private static final String WILL_DELETE_THE_TABLE_AND_ITS_CONTENT = Messages.DeleteTableAction_WILL_DELETE_THE_TABLE_AND_ITS_CONTENT; private static final String DELETE_TABLE = Messages.DeleteTableAction_DELETE_TABLE; private static final long serialVersionUID = 3872859942737870851L; private TreeViewer viewer; public DeleteTableAction(TreeViewer viewer) { this.viewer = viewer; setText(DELETE_TABLE); setToolTipText(WILL_DELETE_THE_TABLE_AND_ITS_CONTENT); } @SuppressWarnings("rawtypes") public void run() { IStructuredSelection selection = (IStructuredSelection) viewer.getSelection(); TreeParent parent = null; for (Iterator nextSelection = selection.iterator(); nextSelection.hasNext(); ) { Object obj = nextSelection.next(); if (TreeObject.class.isInstance(obj)) { if (((TreeObject) obj).getTableDefinition() != null) { TableDefinition tableDefinition = ((TreeObject) obj).getTableDefinition(); boolean confirm = MessageDialog.openConfirm( viewer.getControl().getShell(), DELETE_TABLE, String.format( WARNING_THIS_ACTION_WILL_DELETE_THE_TABLE_AND_ALL_OF_ITS_CONTENT_CONTINUE, tableDefinition.getTableName())); if (!confirm) { continue; } parent = ((TreeObject) obj).getParent(); IDatabaseConnectionFactory connectionFactory = parent.getConnectionFactory(); try { deleteTable(tableDefinition, connectionFactory); } catch (SQLException e) { showMessage(String.format(FAILED_TO_DELETE_TABLE_S, tableDefinition.getTableName())); logger.error(e.getMessage(), e); } } } } if (parent != null) { RefreshViewAction refresh = new RefreshViewAction(viewer, parent.getChildren()[0]); refresh.run(); } } protected void showMessage(String message) { MessageDialog.openError(viewer.getControl().getShell(), DATABASE_VIEW, message); } private void deleteTable( TableDefinition tableDefinition, IDatabaseConnectionFactory connectionFactory) throws SQLException { Connection connection = connectionFactory.getDatabaseConnection(); try { Statement createStatement = connection.createStatement(); String name = tableDefinition.getFqn(); createStatement.execute(DROP_TABLE + name); } finally { if (connection != null) { connection.close(); } } } }
@SuppressWarnings("unused") public class EditorWidget extends AbstractTextEditorWidget { private static final long serialVersionUID = -8881201238299386468L; private static final Logger logger = Logger.getLogger(EditorWidget.class); private static final String SCRIPT_EVALUATION_FAILED = Messages.EditorWidget_SCRIPT_EVALUATION_FAILED; private static final int EVALUATE_ATTEMPTS = 15; private static final String EDITOR_URL = "/orion/editor.html"; // $NON-NLS-1$ private Browser browser; private String text; private IEditorWidgetListener listener; private String mode; private boolean loaded; private boolean disabledForReadOnly; private boolean readOnly; private boolean breakpointsEnabled; private int row; private static Map<String, String> ORION_MODES = new HashMap<String, String>(); static { ORION_MODES.put("javascript", "application/javascript"); ORION_MODES.put("html", "text/html"); ORION_MODES.put("css", "text/css"); ORION_MODES.put("json", "application/json"); ORION_MODES.put("menu", "application/json"); ORION_MODES.put("java", "text/x-java-source"); ORION_MODES.put("xml", "application/xml"); ORION_MODES.put("yaml", "text/x-yaml"); } public EditorWidget(final Composite parent) { this(parent, false); } @SuppressWarnings("serial") public EditorWidget(final Composite parent, final boolean javaScriptEditor) { super(parent, SWT.NONE); super.setLayout(new FillLayout()); browser = new Browser(this, SWT.NONE); browser.setUrl(CommonParameters.getContextPath() + EDITOR_URL); browser.addProgressListener( new ProgressListener() { @Override public void completed(final ProgressEvent event) { loaded = true; updateWidgetContents(); if (javaScriptEditor && DebugModelFacade.getDebugModel() != null) { final DebugSessionModel session = DebugModelFacade.getDebugModel().getActiveSession(); if (session != null && session.getCurrentLineBreak() != null) { final String filePath = session.getCurrentLineBreak().getBreakpoint().getFullPath(); final String path = CommonUtils.formatToRuntimePath( ICommonConstants.ARTIFACT_TYPE.SCRIPTING_SERVICES, filePath); final int[] breakpoints = DebugModelFacade.getDebugModel().getBreakpointsMetadata().getBreakpoints(path); loadBreakpoints(breakpoints); } } } @Override public void changed(final ProgressEvent event) { // } }); // DO NOT REMOVE THIS new BrowserFunction(browser, "saveCalled") { // $NON-NLS-1$ @Override public Object function(final Object[] arguments) { if (listener != null) { listener.save(); } return null; } }; // DO NOT REMOVE THIS new BrowserFunction(browser, "dirtyChanged") { // $NON-NLS-1$ @Override public Object function(final Object[] arguments) { if (listener != null) { listener.dirtyStateChanged((Boolean) arguments[0]); } return null; } }; // DO NOT REMOVE THIS new BrowserFunction(browser, "setBreakpoint") { // $NON-NLS-1$ @Override public Object function(final Object[] arguments) { if ((listener != null) && (arguments[0] != null) && (arguments[0] instanceof Number)) { listener.setBreakpoint(((Number) arguments[0]).intValue()); } return null; } }; // DO NOT REMOVE THIS new BrowserFunction(browser, "clearBreakpoint") { // $NON-NLS-1$ @Override public Object function(final Object[] arguments) { if ((listener != null) && (arguments[0] != null) && (arguments[0] instanceof Number)) { listener.clearBreakpoint(((Number) arguments[0]).intValue()); } return null; } }; } public void setListener(final IEditorWidgetListener listener) { this.listener = listener; } @Override public void setText( final String text, final EditorMode mode, final boolean readOnly, final boolean breakpointsEnabled, final int row) { this.text = text; this.mode = mode.getName(); String orionMode = ORION_MODES.get(this.mode); if (orionMode != null) { this.mode = orionMode; } this.readOnly = readOnly; this.breakpointsEnabled = breakpointsEnabled; this.row = row; if (loaded) { updateWidgetContents(); } } @Override public String getText() { return (String) browser.evaluate("return getText();"); // $NON-NLS-1$ } public void setDirty(final boolean dirty) { execute("setDirty", dirty); // $NON-NLS-1$ } public void setDebugRow(final int row) { execute("setDebugRow", row); // $NON-NLS-1$ } public void loadBreakpoints(final int[] breakpoints) { for (final int breakpoint : breakpoints) { execute("loadBreakpoint", breakpoint); // $NON-NLS-1$ } } private void updateWidgetContents() { evaluate("setText", text, mode, readOnly, breakpointsEnabled, row); // $NON-NLS-1$ } public void setMode(final String mode) { evaluate("setMode", mode); // $NON-NLS-1$ } public void setReadOnly(final boolean readOnly) { if (disabledForReadOnly) { execute("setReadOnly", false); // $NON-NLS-1$ return; } execute("setReadOnly", readOnly); // $NON-NLS-1$ } public void setBreakpointsEnabled(final boolean status) { evaluate("setBreakpointsEnabled", status); // $NON-NLS-1$ } private void execute(final String function, final Object... arguments) { browser.execute(buildFunctionCall(function, arguments)); } private Object evaluate(final String function, final Object... arguments) { final String script = buildFunctionCall(function, arguments); for (int i = 0; i < EVALUATE_ATTEMPTS; i++) { try { return browser.evaluate(script); } catch (final Exception ex) { logger.debug(ex.getMessage(), ex); } } throw new IllegalStateException(SCRIPT_EVALUATION_FAILED + script); } private String buildFunctionCall(final String function, final Object... arguments) { final StringBuilder call = new StringBuilder(); call.append(function).append('('); if (arguments != null) { for (final Object argument : arguments) { String strArg = null; if (argument instanceof String) { strArg = prepareStringArgument((String) argument); } else { strArg = String.valueOf(argument); } call.append(strArg).append(","); // $NON-NLS-1$ } if (arguments.length > 0) { call.deleteCharAt(call.length() - 1); } } call.append(')'); return call.toString(); } private String prepareStringArgument(final String argument) { return "'" + StringEscapeUtils.escapeJavaScript(argument) + "'"; // $NON-NLS-1$ //$NON-NLS-2$ } }