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());
                  }
                }
              }
            });
  }
}
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 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));
  }
}
/** 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();
      }
    }
  }
}
Example #6
0
@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$
  }
}
/** Database Viewer represents the structure of the tenant specific schema */
public class DatabaseViewer extends ViewPart
    implements IDatabaseConnectionFactory, ISelectionChangedListener {

  private static final Logger logger = Logger.getLogger(DatabaseViewer.class);

  private static final String SELECTED_DATASOURCE_NAME = "SELECTED_DATASOURCE_NAME";

  static final String DEFAULT_DATASOURCE_NAME = "Default";

  private static final String DATABASE_VIEW = Messages.DatabaseViewer_DATABASE_VIEW;

  /** The ID of the view as specified by the extension. */
  public static final String ID =
      "org.eclipse.dirigible.ide.db.viewer.views.DatabaseViewer"; //$NON-NLS-1$

  protected TreeViewer viewer;

  @SuppressWarnings("unused")
  private DrillDownAdapter drillDownAdapter;

  protected Action viewTableContentAction;
  private Action deleteAction;
  private Action exportDataAction;
  private Action doubleClickAction;
  private boolean isOperator;

  private ShowTableDefinitionAction showTableDefinitionAction;

  protected RefreshViewAction refreshViewAction;

  class NameSorter extends ViewerSorter {
    private static final long serialVersionUID = -7067479902071396325L;
  }

  /** The constructor. */
  public DatabaseViewer() {
    isOperator = CommonIDEParameters.isUserInRole(IRoles.ROLE_OPERATOR);
  }

  /** This is a callback that will allow us to create the viewer and initialize it. */
  @Override
  @SuppressWarnings("unused")
  public void createPartControl(Composite parent) {

    parent.setLayout(new GridLayout());
    DatabaseViewerToolBar databaseViewerToolBar = new DatabaseViewerToolBar();
    databaseViewerToolBar.addSelectionChangedListener(this);
    databaseViewerToolBar.createToolBar(parent, getSite().getShell());

    PatternFilter filter = new PatternFilter();
    FilteredTree tree =
        new FilteredTree(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL, filter, true);
    viewer = tree.getViewer();
    DrillDownAdapter drillDownAdapter = new DrillDownAdapter(viewer);
    viewer.setContentProvider(initContentProvider());
    viewer.setLabelProvider(new DatabaseViewLabelProvider(this));
    viewer.setSorter(new NameSorter());
    viewer.setInput(getViewSite());

    // Create the help context id for the viewer's control
    // PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(),
    // "org.eclipse.dirigible.ide.db.viewer.views.DatabaseViewer");

    makeActions();
    hookContextMenu();
    hookDoubleClickAction();
    contributeToActionBars();
  }

  protected IContentProvider initContentProvider() {
    return new DatabaseViewContentProvider(this);
  }

  protected IFilter getSchemaFilter(Connection connection) throws SQLException {
    return null;
  }

  private void hookContextMenu() {
    MenuManager menuMgr = new MenuManager("#PopupMenu"); // $NON-NLS-1$
    menuMgr.setRemoveAllWhenShown(true);
    menuMgr.addMenuListener(
        new IMenuListener() {
          private static final long serialVersionUID = -4330735691305481160L;

          @Override
          public void menuAboutToShow(IMenuManager manager) {
            DatabaseViewer.this.fillContextMenu(manager);
          }
        });
    Menu menu = menuMgr.createContextMenu(viewer.getControl());
    viewer.getControl().setMenu(menu);
    getSite().registerContextMenu(menuMgr, viewer);
  }

  private void contributeToActionBars() {
    IActionBars bars = getViewSite().getActionBars();
    fillLocalPullDown(bars.getMenuManager());
    fillLocalToolBar(bars.getToolBarManager());
  }

  private void fillLocalPullDown(IMenuManager manager) {
    manager.add(showTableDefinitionAction);
    manager.add(viewTableContentAction);
    manager.add(exportDataAction);
    manager.add(new Separator());
    if (isOperator) {
      manager.add(deleteAction);
    }
    manager.add(new Separator());
    manager.add(refreshViewAction);
  }

  private void fillContextMenu(IMenuManager manager) {
    ISelection selection = viewer.getSelection();
    Object obj = ((IStructuredSelection) selection).getFirstElement();
    if (!TreeParent.class.isInstance(obj)) {
      if (TreeObject.class.isInstance(obj)) {
        TreeObject tObject = (TreeObject) obj;
        List<Capability> capabilities = tObject.getTableDefinition().getCapabilities();
        if ((capabilities != null) && !capabilities.isEmpty()) {
          if (capabilities.contains(Capability.ShowTableDefinition)) {
            manager.add(showTableDefinitionAction);
          }
          if (capabilities.contains(Capability.ViewTableContent)) {
            manager.add(viewTableContentAction);
          }
          if (capabilities.contains(Capability.ExportData)) {
            manager.add(exportDataAction);
          }
          if (!manager.isEmpty()) {
            manager.add(new Separator());
          }
          if (isOperator && capabilities.contains(Capability.Delete)) {
            manager.add(deleteAction);
          }
          if (!manager.isEmpty()) {
            manager.add(new Separator());
          }
        }
      }
    }
    manager.add(refreshViewAction);
    // Other plug-ins can contribute there actions here
    manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
  }

  private void fillLocalToolBar(IToolBarManager manager) {
    manager.add(showTableDefinitionAction);
    manager.add(viewTableContentAction);
    manager.add(exportDataAction);
    manager.add(new Separator());
    if (isOperator) {
      manager.add(deleteAction);
    }
    manager.add(new Separator());
    manager.add(refreshViewAction);
  }

  private void makeActions() {
    createRefreshAction();
    createExportDataAction();
    createViewTableContentAction();
    createShowTableDefinitionAction();
    if (isOperator) {
      deleteAction = new DeleteTableAction(viewer);
    }
    doubleClickAction = new ShowTableDefinitionAction(viewer);
  }

  protected void createRefreshAction() {
    refreshViewAction = new RefreshViewAction(viewer);
  }

  protected void createViewTableContentAction() {
    viewTableContentAction =
        new ViewTableContentAction(
            viewer, "org.eclipse.dirigible.ide.db.viewer.views.SQLConsole"); // $NON-NLS-1$
  }

  protected void createShowTableDefinitionAction() {
    showTableDefinitionAction = new ShowTableDefinitionAction(viewer);
  }

  protected void createExportDataAction() {
    exportDataAction = new ExportDataAction(viewer);
  }

  private void hookDoubleClickAction() {
    viewer.addDoubleClickListener(
        new IDoubleClickListener() {
          @Override
          public void doubleClick(DoubleClickEvent event) {
            doubleClickAction.run();
          }
        });
  }

  protected void showMessage(String message) {
    MessageDialog.openInformation(viewer.getControl().getShell(), DATABASE_VIEW, message);
  }

  /** Passing the focus request to the viewer's control. */
  @Override
  public void setFocus() {
    viewer.getControl().setFocus();
  }

  @Override
  public Connection getDatabaseConnection() throws SQLException {
    return getConnectionFromSelectedDatasource();
  }

  public static String getSelectedDatasourceName() throws SQLException {
    return CommonIDEParameters.get(SELECTED_DATASOURCE_NAME);
  }

  /**
   * 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;
  }

  boolean showSchemes() {
    return false;
  }

  @Override
  public void selectionChanged(SelectionChangedEvent event) {
    if (event.getSource() instanceof DatabaseViewerToolBar) {
      String datasourceName =
          (String) ((IStructuredSelection) event.getSelection()).getFirstElement();
      CommonIDEParameters.set(SELECTED_DATASOURCE_NAME, datasourceName);
      viewer.setContentProvider(initContentProvider());
      viewer.refresh();
    }
  }
}
public class ToolBarMenuViewProvider {

  private static final Logger logger = Logger.getLogger(ToolBarMenuViewProvider.class);

  private static final String EMPTY = ""; // $NON-NLS-1$
  private static final String SAVE = Messages.WorkspaceExplorerView_SAVE;
  private static final String SAVE_ALL = Messages.WorkspaceExplorerView_SAVE_ALL;
  private static final String NEW = Messages.WorkspaceExplorerView_NEW;

  private static final String PUBLISH_TOOL_TIP_TEXT = Messages.WorkspaceExplorerView_PUBLISH;
  private static final String ACTIVATE_TOOL_TIP_TEXT = Messages.WorkspaceExplorerView_ACTIVATE;

  private static final String PUBLISH_FAILED = Messages.WorkspaceExplorerView_PUBLISH_FAILED;
  private static final String ACTIVATION_FAILED = Messages.WorkspaceExplorerView_ACTIVATION_FAILED;

  private static final Image SAVE_ICON =
      ImageUtils.createImage(
          ImageUtils.getIconURL(
              "org.eclipse.dirigible.ide.workspace.ui",
              "/resources/icons/",
              "save.png")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  private static final Image SAVE_ALL_ICON =
      ImageUtils.createImage(
          ImageUtils.getIconURL(
              "org.eclipse.dirigible.ide.workspace.ui",
              "/resources/icons/",
              "save_all.png")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

  private static final Image PUBLISH_ICON =
      ImageUtils.createImage(
          ImageUtils.getIconURL(
              "org.eclipse.dirigible.ide.publish.ui",
              "/resources/icons/",
              "publish.png")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  private static final Image ACTIVATE_ICON =
      ImageUtils.createImage(
          ImageUtils.getIconURL(
              "org.eclipse.dirigible.ide.publish.ui",
              "/resources/icons/",
              "activate.png")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

  public static void createToolBarMenu(Composite parent, Shell shell) {
    if (CommonIDEParameters.isRAP()) {
      int style = SWT.FLAT | SWT.WRAP | SWT.RIGHT | SWT.BORDER | SWT.SHADOW_OUT;

      final ToolBar toolBar = new ToolBar(parent, style);

      if (CommonIDEParameters.isSandboxEnabled()) {
        createActivateToolItem(toolBar, shell);
        createSeparator(toolBar);
      }

      createPublishToolItem(toolBar, shell);

      createSeparator(toolBar);

      createSaveToolItem(toolBar);

      createSeparator(toolBar);

      createSaveAllToolItem(toolBar);

      createSeparator(toolBar);

      createNewToolItem(parent, toolBar);
    }
  }

  private static ToolItem createSeparator(final ToolBar toolBar) {
    return new ToolItem(toolBar, SWT.SEPARATOR);
  }

  private static ToolItem createActivateToolItem(final ToolBar toolBar, final Shell shell) {
    ToolItem toolItem = createToolItem(toolBar, EMPTY, ACTIVATE_TOOL_TIP_TEXT, ACTIVATE_ICON);
    toolItem.addSelectionListener(
        new SelectionListener() {
          private static final long serialVersionUID = 2364528684607846153L;

          @Override
          public void widgetSelected(SelectionEvent e) {
            StatusLineManagerUtil.getDefaultStatusLineManager().removeAll();
            try {
              activate();
            } catch (Exception ex) {
              logger.error(ex.getMessage(), ex);
              StatusLineManagerUtil.setErrorMessage(ex.getMessage());
              MessageDialog.openError(shell, PUBLISH_FAILED, ex.getMessage());
            }

            WebViewerView.refreshWebViewerViewIfVisible();
          }

          @Override
          public void widgetDefaultSelected(SelectionEvent e) {
            //
          }
        });
    return toolItem;
  }

  private static ToolItem createPublishToolItem(final ToolBar toolBar, final Shell shell) {
    ToolItem toolItem = createToolItem(toolBar, EMPTY, PUBLISH_TOOL_TIP_TEXT, PUBLISH_ICON);
    toolItem.addSelectionListener(
        new SelectionListener() {
          private static final long serialVersionUID = 3334607710375924130L;

          @Override
          public void widgetSelected(SelectionEvent e) {
            StatusLineManagerUtil.getDefaultStatusLineManager().removeAll();
            try {
              publish();
            } catch (Exception ex) {
              logger.error(ex.getMessage(), ex);
              StatusLineManagerUtil.setErrorMessage(ex.getMessage());
              MessageDialog.openError(shell, ACTIVATION_FAILED, ex.getMessage());
            }

            WebViewerView.refreshWebViewerViewIfVisible();
          }

          @Override
          public void widgetDefaultSelected(SelectionEvent e) {
            //
          }
        });
    return toolItem;
  }

  private static ToolItem createNewToolItem(Composite parent, final ToolBar toolBar) {
    final Menu menu = NewMenuItemViewProvider.createMenu(parent);

    final ToolItem toolItem = createToolItem(toolBar, NEW, NEW, null, SWT.DROP_DOWN);
    toolItem.addSelectionListener(
        new SelectionListener() {
          private static final long serialVersionUID = -2281618627759204367L;

          @Override
          public void widgetSelected(SelectionEvent e) {
            if (e.detail == SWT.ARROW) {
              Rectangle rect = toolItem.getBounds();
              Point pt = new Point(rect.x, rect.y + rect.height);
              pt = toolBar.toDisplay(pt);
              menu.setLocation(pt.x, pt.y);
              menu.setVisible(true);
            }
          }

          @Override
          public void widgetDefaultSelected(SelectionEvent e) {
            //

          }
        });

    return toolItem;
  }

  private static ToolItem createSaveToolItem(final ToolBar toolBar) {
    ToolItem toolItem = createToolItem(toolBar, EMPTY, SAVE, SAVE_ICON);
    toolItem.addSelectionListener(
        new SelectionListener() {
          private static final long serialVersionUID = -8381124396267155406L;

          @Override
          public void widgetSelected(SelectionEvent e) {
            IWorkbench workbench = PlatformUI.getWorkbench();
            IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
            IPageListener saveAction = (IPageListener) ActionFactory.SAVE.create(window);
            saveAction.pageActivated(window.getActivePage());
            ((IWorkbenchAction) saveAction).run();
          }

          @Override
          public void widgetDefaultSelected(SelectionEvent e) {
            //
          }
        });
    return toolItem;
  }

  private static ToolItem createSaveAllToolItem(final ToolBar toolBar) {
    ToolItem toolItem = createToolItem(toolBar, EMPTY, SAVE_ALL, SAVE_ALL_ICON);
    toolItem.addSelectionListener(
        new SelectionListener() {
          private static final long serialVersionUID = 6845514748708051108L;

          @Override
          public void widgetSelected(SelectionEvent e) {
            IWorkbench workbench = PlatformUI.getWorkbench();
            IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
            ActionFactory.SAVE_ALL.create(window).run();
          }

          @Override
          public void widgetDefaultSelected(SelectionEvent e) {
            //
          }
        });
    return toolItem;
  }

  private static ToolItem createToolItem(
      ToolBar toolBar, String text, String toolTipText, Image image) {
    return createToolItem(toolBar, text, toolTipText, image, SWT.PUSH);
  }

  private static ToolItem createToolItem(
      ToolBar toolBar, String text, String toolTipText, Image image, int style) {
    ToolItem toolItem = new ToolItem(toolBar, style);
    toolItem.setText(text);
    toolItem.setToolTipText(toolTipText);
    toolItem.setImage(image);
    return toolItem;
  }

  private static void publish() throws PublishException {
    for (IProject project : PublishManager.getProjects(getSelection())) {
      PublishManager.publishProject(project);
    }
  }

  private static void activate() throws PublishException {
    for (IProject project : PublishManager.getProjects(getSelection())) {
      PublishManager.activateProject(project);
    }
  }

  private static ISelection getSelection() {
    IWorkbench workbench = PlatformUI.getWorkbench();
    IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
    ISelectionService selectionService = workbenchWindow.getSelectionService();
    ISelection selection = selectionService.getSelection();
    return selection;
  }
}
public class JavascriptServiceTemplateModel extends GenerationModel {

  private static final String ERROR_ON_LOADING_TABLE_COLUMNS_FROM_DATABASE_FOR_GENERATION =
      Messages
          .JavascriptServiceTemplateModel_ERROR_ON_LOADING_TABLE_COLUMNS_FROM_DATABASE_FOR_GENERATION;

  private static final String TARGET_LOCATION_IS_NOT_ALLOWED =
      Messages.JavascriptServiceTemplateModel_TARGET_LOCATION_IS_NOT_ALLOWED;

  private static final Logger logger = Logger.getLogger(JavascriptServiceTemplateModel.class);

  private String tableName;

  private String tableType;

  private TableColumn[] tableColumns;

  private boolean columnsInit = false;

  public String getTableName() {
    return tableName;
  }

  public void setTableName(String tableName) {
    this.tableName = tableName;
  }

  public String getTableType() {
    return tableType;
  }

  public void setTableType(String tableType) {
    this.tableType = tableType;
  }

  public TableColumn[] getTableColumns() {
    if (!columnsInit) {
      createTableColumns();
    }
    return tableColumns; // NOPMD
  }

  public void setTableColumns(TableColumn[] tableColumns) {
    this.tableColumns = tableColumns;
    columnsInit = true;
  }

  @Override
  public IValidationStatus validate() {
    IValidationStatus locationStatus = validateLocation();
    if (locationStatus.hasErrors()) {
      return locationStatus;
    }
    IValidationStatus templateStatus = validateTemplate();
    if (locationStatus.hasErrors()) {
      return locationStatus;
    }
    // if (!validateTableName()) {
    // return false;
    // }
    return ValidationStatus.getValidationStatus(locationStatus, templateStatus);
  }

  public IValidationStatus validateLocation() {
    IValidationStatus status;
    try {
      status = validateLocationGeneric();
      if (status.hasErrors()) {
        return status;
      }
      IPath location = new Path(getTargetLocation()).append(getFileName());
      // TODO - more precise test for the location ../WebContent/...
      if (location.toString().indexOf(ICommonConstants.ARTIFACT_TYPE.SCRIPTING_SERVICES) == -1) {
        return ValidationStatus.createError(TARGET_LOCATION_IS_NOT_ALLOWED);
      }
    } catch (Exception e) {
      // temp workaround due to another bug - context menu is not context
      // aware => target location and name are null (in the first page of
      // the wizard)
      return ValidationStatus.createError(""); // $NON-NLS-1$
    }
    return status;
  }

  public boolean validateTableName() {
    return tableName != null;
  }

  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);
    }
  }

  private boolean exists(List<TableColumn> availableTableColumns, TableColumn tableColumn) {
    if (getTableName() == null) {
      return false;
    }
    for (TableColumn tableColumn2 : availableTableColumns) {
      TableColumn tableColumnX = tableColumn2;
      if (tableColumnX.getName().equals(tableColumn.getName())) {
        tableColumnX.setType(tableColumn.getType());
        return true;
      }
    }
    return false;
  }
}
public class DefaultContentProvider implements IContentProvider, IExecutableExtension {

  private static final String CANNOT_SAVE_FILE_CONTENTS =
      Messages.DefaultContentProvider_CANNOT_SAVE_FILE_CONTENTS;
  private static final String CANNOT_READ_FILE_CONTENTS =
      Messages.DefaultContentProvider_CANNOT_READ_FILE_CONTENTS;
  private static final String WE_SHOULD_NEVER_GET_HERE =
      Messages.DefaultContentProvider_WE_SHOULD_NEVER_GET_HERE;
  private static final Logger LOGGER = Logger.getLogger(DefaultContentProvider.class);

  @Override
  public String getContent(IEditorInput input) throws ContentProviderException {
    if (input instanceof IFileEditorInput) {
      IFileEditorInput fileInput = (IFileEditorInput) input;
      return readFile(fileInput.getFile());
    }
    if (input instanceof ContentEditorInput) {
      ContentEditorInput contentInput = (ContentEditorInput) input;
      return new String(contentInput.getContent());
    }
    throw new IllegalStateException(WE_SHOULD_NEVER_GET_HERE);
  }

  @Override
  public void save(IProgressMonitor monitor, IEditorInput input, String content, boolean overwrite)
      throws ContentProviderException {
    if (input instanceof IFileEditorInput) {
      IFileEditorInput fileInput = (IFileEditorInput) input;
      writeFile(fileInput.getFile(), content.getBytes());
      //			activateIfNeeded();
    }
  }

  //	private void activateIfNeeded() {
  //		ResourcesPlugin.getWorkspace().notifyAll();
  //	}

  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);
    }
  }

  private static IResource getFromRepository(IFile file) {
    IRepository repository = RepositoryFacade.getInstance().getRepository();

    String resourcePath =
        IRepositoryPaths.DB_DIRIGIBLE_USERS
            + CommonIDEParameters.getUserName()
            + IRepositoryPaths.SEPARATOR
            + IRepositoryPaths.WORKSPACE_FOLDER_NAME
            + file.getFullPath();
    IResource resource = repository.getResource(resourcePath);
    return resource;
  }

  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);
    }
  }

  @Override
  public void setInitializationData(IConfigurationElement config, String propertyName, Object data)
      throws CoreException {
    //
  }
}
/** Exports the current content of the Registry */
public class ContentExporterServlet extends ContentBaseServlet {

  private static final long serialVersionUID = 5798183051027211544L;

  private static final Logger logger = Logger.getLogger(ContentExporterServlet.class);

  private static final String GUID = "guid"; // $NON-NLS-1$
  private static final String DEFAULT_PATH_FOR_EXPORT = IRepositoryPaths.REGISTRY_DEPLOY_PATH;
  private static final String EMPTY = ""; // $NON-NLS-1$
  private static final String DATE_FORMAT = "yyyyMMdd-HHmmss"; // $NON-NLS-1$

  static final String UNKNOWN_HOST = "unknown_host";

  static final String UNDERSCORE = "_"; // $NON-NLS-1$

  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();
  }

  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

  /** @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);
  }

  /**
   * 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);
    }
  }

  private String defaultFileName(HttpServletRequest request) {
    String fileName;
    String guid = EMPTY.equals(getGUID(request)) ? EMPTY : getGUID(request);
    fileName = getExportFilePrefix() + UNDERSCORE + guid;
    return fileName;
  }

  /**
   * 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;
  }

  protected String getDefaultPathForExport() {
    return DEFAULT_PATH_FOR_EXPORT;
  }

  /**
   * Create guid. Currently timestamp.
   *
   * @return
   */
  private String createGUID() {
    // SimpleDateFormat sdfDate = new
    // SimpleDateFormat("yyyy.MM.dd.HH.mm.ss.SSS");
    SimpleDateFormat sdfDate = new SimpleDateFormat(DATE_FORMAT);
    Date now = new Date();
    String strDate = sdfDate.format(now);
    return strDate;
  }

  private String getGUID(HttpServletRequest request) {
    return (String) request.getSession().getAttribute(GUID);
  }
}
public class JGitConnector {

  private static final String INVALID_USERNAME_AND_PASSWORD =
      Messages.JGitConnector_INVALID_USERNAME_AND_PASSWORD;

  public static final String TEMP_DIRECTORY_PREFIX = "org.eclipse.dirigible.jgit."; // $NON-NLS-1$

  private static final String REFS_HEADS_MASTER = "refs/heads/master"; // $NON-NLS-1$
  private static final String MERGE = "merge"; // $NON-NLS-1$
  private static final String MASTER = "master"; // $NON-NLS-1$
  private static final String BRANCH = "branch"; // $NON-NLS-1$
  public static final String ADD_ALL_FILE_PATTERN = "."; // $NON-NLS-1$

  private static final Logger logger = Logger.getLogger(JGitConnector.class);

  static {
    try {
      // ProxyUtils.setProxySettings();
      deleteTempDirectories();
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
    }
  }

  private static void deleteTempDirectories() throws IOException {
    File file = GitFileUtils.createTempDirectory("DeleteDirectory");
    File tempDirectory = file.getParentFile();
    for (File temp : tempDirectory.listFiles()) {
      if (temp.isDirectory() && temp.getName().startsWith(TEMP_DIRECTORY_PREFIX)) {
        GitFileUtils.deleteDirectory(temp);
      }
    }
    GitFileUtils.deleteDirectory(file);
  }

  /**
   * Gets org.eclipse.jgit.lib.Repository object for existing Git Repository.
   *
   * @param repositoryPath the path to an existing Git Repository
   * @return {@link org.eclipse.jgit.lib.Repository} object
   * @throws IOException
   */
  public static Repository getRepository(String repositoryPath) throws IOException {
    RepositoryBuilder repositoryBuilder = new RepositoryBuilder();
    repositoryBuilder.findGitDir(new File(repositoryPath));
    Repository repository = repositoryBuilder.build();
    repository.getConfig().setString(BRANCH, MASTER, MERGE, REFS_HEADS_MASTER);
    return repository;
  }

  /**
   * Clones git remote repository to the file system.
   *
   * @param gitDirectory where the remote repository will be cloned
   * @param repositoryURI repository's URI example: https://qwerty.com/xyz/abc.git
   * @throws InvalidRemoteException
   * @throws TransportException
   * @throws GitAPIException
   */
  public static void cloneRepository(File gitDirectory, String repositoryURI)
      throws InvalidRemoteException, TransportException, GitAPIException {
    cloneRepository(gitDirectory, repositoryURI, null, null);
  }

  /**
   * Clones secured git remote repository to the file system.
   *
   * @param gitDirectory where the remote repository will be cloned
   * @param repositoryURI repository's URI example: https://qwerty.com/xyz/abc.git
   * @param username the username used for authentication
   * @param password the password used for authentication
   * @throws InvalidRemoteException
   * @throws TransportException
   * @throws GitAPIException
   */
  public static void cloneRepository(
      File gitDirectory, String repositoryURI, String username, String password)
      throws InvalidRemoteException, TransportException, GitAPIException {
    try {
      CloneCommand cloneCommand = Git.cloneRepository();
      cloneCommand.setURI(repositoryURI);
      if (!StringUtils.isEmptyOrNull(username) && !StringUtils.isEmptyOrNull(password)) {
        cloneCommand.setCredentialsProvider(
            new UsernamePasswordCredentialsProvider(username, password));
      }
      cloneCommand.setRemote(Constants.DEFAULT_REMOTE_NAME);
      cloneCommand.setDirectory(gitDirectory);
      cloneCommand.call();
    } catch (NullPointerException e) {
      throw new TransportException(INVALID_USERNAME_AND_PASSWORD);
    }
  }

  private final Git git;
  private Repository repository;

  public JGitConnector(Repository repository) throws IOException {
    this.repository = repository;
    this.git = new Git(repository);
  }

  /**
   * Adds content from file(s) to the staging index
   *
   * @param filePattern File to add content from. Example: "." includes all files. If "dir/subdir/"
   *     is directory then "dir/subdir" all files from the directory recursively
   * @throws IOException
   * @throws NoFilepatternException
   * @throws GitAPIException
   */
  public void add(String filePattern) throws IOException, NoFilepatternException, GitAPIException {
    AddCommand addCommand = git.add();
    addCommand.addFilepattern(filePattern);
    addCommand.call();
  }

  /**
   * Adds changes to the staging index. Then makes commit.
   *
   * @param message the commit message
   * @param name the name of the committer used for the commit
   * @param email the email of the committer used for the commit
   * @param all if set to true, command will automatically stages files that have been modified and
   *     deleted, but new files not known by the repository are not affected. This corresponds to
   *     the parameter -a on the command line.
   * @throws NoHeadException
   * @throws NoMessageException
   * @throws UnmergedPathsException
   * @throws ConcurrentRefUpdateException
   * @throws WrongRepositoryStateException
   * @throws GitAPIException
   * @throws IOException
   */
  public void commit(String message, String name, String email, boolean all)
      throws NoHeadException, NoMessageException, UnmergedPathsException,
          ConcurrentRefUpdateException, WrongRepositoryStateException, GitAPIException,
          IOException {
    CommitCommand commitCommand = git.commit();
    commitCommand.setMessage(message);
    commitCommand.setCommitter(name, email);
    commitCommand.setAuthor(name, email);
    commitCommand.setAll(all);
    commitCommand.call();
  }

  /**
   * Creates new branch from a particular start point
   *
   * @param name the branch name
   * @param startPoint valid tree-ish object example: "5c15e8", "master", "HEAD",
   *     "21d5a96070353d01c0f30bc0559ab4de4f5e3ca0"
   * @throws RefAlreadyExistsException
   * @throws RefNotFoundException
   * @throws InvalidRefNameException
   * @throws GitAPIException
   */
  public void createBranch(String name, String startPoint)
      throws RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException,
          GitAPIException {
    repository.getConfig().setString(BRANCH, name, MERGE, REFS_HEADS_MASTER);
    CreateBranchCommand createBranchCommand = git.branchCreate();
    createBranchCommand.setName(name);
    createBranchCommand.setStartPoint(startPoint);
    createBranchCommand.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
    createBranchCommand.call();
  }

  /**
   * Checkout to a valid tree-ish object example: "5c15e8", "master", "HEAD",
   * "21d5a96070353d01c0f30bc0559ab4de4f5e3ca0"
   *
   * @param name the tree-ish object
   * @return {@link org.eclipse.jgit.lib.Ref} object
   * @throws RefAlreadyExistsException
   * @throws RefNotFoundException
   * @throws InvalidRefNameException
   * @throws CheckoutConflictException
   * @throws GitAPIException
   */
  public Ref checkout(String name)
      throws RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException,
          CheckoutConflictException, GitAPIException {
    CheckoutCommand checkoutCommand = git.checkout();
    checkoutCommand.setName(name);
    return checkoutCommand.call();
  }

  /**
   * Hard reset the repository. Makes the working directory and staging index content to exactly
   * match the Git repository.
   *
   * @throws CheckoutConflictException
   * @throws GitAPIException
   */
  public void hardReset() throws CheckoutConflictException, GitAPIException {
    ResetCommand resetCommand = git.reset();
    resetCommand.setMode(ResetType.HARD);
    resetCommand.call();
  }

  /**
   * Fetches from a remote repository and tries to merge into the current branch.
   *
   * @throws WrongRepositoryStateException
   * @throws InvalidConfigurationException
   * @throws DetachedHeadException
   * @throws InvalidRemoteException
   * @throws CanceledException
   * @throws RefNotFoundException
   * @throws NoHeadException
   * @throws TransportException
   * @throws GitAPIException
   */
  public void pull()
      throws WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException,
          InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException,
          TransportException, GitAPIException {
    PullCommand pullCommand = git.pull();
    pullCommand.call();
  }

  /**
   * Pushes the committed changes to the remote repository.
   *
   * @param username for the remote repository
   * @param password for the remote repository
   * @throws InvalidRemoteException
   * @throws TransportException
   * @throws GitAPIException
   */
  public void push(String username, String password)
      throws InvalidRemoteException, TransportException, GitAPIException {
    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
    pushCommand.call();
  }

  /**
   * Tries to rebase the selected branch on top of the current one.
   *
   * @param name the branch to rebase
   * @throws NoHeadException
   * @throws WrongRepositoryStateException
   * @throws GitAPIException
   */
  public void rebase(String name)
      throws NoHeadException, WrongRepositoryStateException, GitAPIException {
    RebaseCommand rebaseCommand = git.rebase();
    rebaseCommand.setOperation(Operation.BEGIN);
    rebaseCommand.setUpstream(name);
    rebaseCommand.call();
  }

  /**
   * Get the current status of the Git repository.
   *
   * @return {@link org.eclipse.jgit.api.Status} object
   * @throws NoWorkTreeException
   * @throws GitAPIException
   */
  public Status status() throws NoWorkTreeException, GitAPIException {
    return git.status().call();
  }

  /**
   * Returns the SHA of the last commit on the specified branch.
   *
   * @param branch the name of the specified branch
   * @return SHA example: "21d5a96070353d01c0f30bc0559ab4de4f5e3ca0"
   * @throws RefAlreadyExistsException
   * @throws RefNotFoundException
   * @throws InvalidRefNameException
   * @throws CheckoutConflictException
   * @throws GitAPIException
   */
  public String getLastSHAForBranch(String branch)
      throws RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException,
          CheckoutConflictException, GitAPIException {
    return checkout(branch).getLeaf().getObjectId().getName();
  }
}
public class DatabaseUpdater extends AbstractDataUpdater {

  private static final String DASH = " - "; // $NON-NLS-1$
  private static final String AUTOMATIC_DROP_COLUMN_NOT_SUPPORTED =
      Messages.getString("DatabaseUpdater.AUTOMATIC_DROP_COLUMN_NOT_SUPPORTED"); // $NON-NLS-1$
  private static final String AS = " AS "; // $NON-NLS-1$
  private static final String CREATE_VIEW = "CREATE VIEW "; // $NON-NLS-1$
  private static final String DROP_VIEW = "DROP VIEW "; // $NON-NLS-1$
  private static final String QUERY = "query"; // $NON-NLS-1$
  private static final String CANNOT_BE_CHANGED_TO =
      Messages.getString("DatabaseUpdater.CANNOT_BE_CHANGED_TO"); // $NON-NLS-1$
  private static final String TYPE2 = Messages.getString("DatabaseUpdater.TYPE2"); // $NON-NLS-1$
  private static final String ADDING_PRIMARY_KEY_COLUMN =
      Messages.getString("DatabaseUpdater.ADDING_PRIMARY_KEY_COLUMN"); // $NON-NLS-1$
  private static final String ADDING_NOT_NULL_COLUMN =
      Messages.getString("DatabaseUpdater.ADDING_NOT_NULL_COLUMN"); // $NON-NLS-1$
  private static final String AND_COLUMN =
      Messages.getString("DatabaseUpdater.AND_COLUMN"); // $NON-NLS-1$
  private static final String INCOMPATIBLE_CHANGE_OF_TABLE =
      Messages.getString("DatabaseUpdater.INCOMPATIBLE_CHANGE_OF_TABLE"); // $NON-NLS-1$
  private static final String ADD = "ADD "; // $NON-NLS-1$
  private static final String ALTER_TABLE = "ALTER TABLE "; // $NON-NLS-1$
  private static final String COLUMN_DEFAULT_VALUE = "defaultValue"; // $NON-NLS-1$
  private static final String COLUMN_PRIMARY_KEY = "primaryKey"; // $NON-NLS-1$
  private static final String COLUMN_NOT_NULL = "notNull"; // $NON-NLS-1$
  private static final String COLUMN_LENGTH = "length"; // $NON-NLS-1$
  private static final String COLUMN_TYPE = "type"; // $NON-NLS-1$
  private static final String COLUMN_NAME = "name"; // $NON-NLS-1$
  private static final String COLUMNS = "columns"; // $NON-NLS-1$
  private static final String CREATE_TABLE = "CREATE TABLE "; // $NON-NLS-1$
  private static final String VIEW_NAME = "viewName"; // $NON-NLS-1$
  private static final String VIEW = "VIEW"; // $NON-NLS-1$
  private static final String TABLE = "TABLE"; // $NON-NLS-1$
  private static final String TABLE_NAME = "tableName"; // $NON-NLS-1$
  private static final String DEFAULT = "DEFAULT "; // $NON-NLS-1$
  private static final String PRIMARY_KEY = "PRIMARY KEY "; // $NON-NLS-1$
  private static final String NOT_NULL = "NOT NULL "; // $NON-NLS-1$

  private static final Logger logger = Logger.getLogger(DatabaseUpdater.class);

  public static final String EXTENSION_TABLE = ".table"; // $NON-NLS-1$
  public static final String EXTENSION_VIEW = ".view"; // $NON-NLS-1$
  public static final String REGISTRY_DATA_STRUCTURES_DEFAULT =
      ICommonConstants.DATA_CONTENT_REGISTRY_PUBLISH_LOCATION;

  private IRepository repository;
  private DataSource dataSource;
  private String location;
  private DBUtils dbUtils;

  public DatabaseUpdater(IRepository repository, DataSource dataSource, String location) {
    this.repository = repository;
    this.dataSource = dataSource;
    this.location = location;
    this.dbUtils = new DBUtils(dataSource);
  }

  @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);
    }
  }

  @Override
  public void executeUpdate(
      List<String> knownFiles, HttpServletRequest request, List<String> errors) throws Exception {
    executeUpdate(knownFiles, errors);
  }

  private void executeTableUpdate(
      Connection connection,
      DatabaseMetaData databaseMetaData,
      IDialectSpecifier dialectSpecifier,
      String dsDefinition)
      throws SQLException, IOException {
    JsonObject dsDefinitionObject = parseTable(dsDefinition);
    String tableName = dsDefinitionObject.get(TABLE_NAME).getAsString();
    tableName = tableName.toUpperCase();
    ResultSet rs = null;
    try {
      rs = databaseMetaData.getTables(null, null, tableName, new String[] {TABLE, VIEW});
      if (rs.next()) {
        // String retrievedTableName = rs.getString(3);
        executeTableUpdate(connection, dialectSpecifier, dsDefinitionObject);
      } else {
        executeTableCreate(connection, dialectSpecifier, dsDefinitionObject);
      }
    } finally {
      if (rs != null) {
        rs.close();
      }
    }
  }

  private DatabaseMetaData getMetaData(Connection connection) throws SQLException {
    // get the database metadata
    DatabaseMetaData databaseMetaData = connection.getMetaData();
    return databaseMetaData;
  }

  private void executeViewUpdate(
      Connection connection,
      DatabaseMetaData databaseMetaData,
      IDialectSpecifier dialectSpecifier,
      String dsDefinition)
      throws SQLException, IOException {
    JsonObject dsDefinitionObject = parseView(dsDefinition);
    String viewName = dsDefinitionObject.get(VIEW_NAME).getAsString();
    viewName = viewName.toUpperCase();
    executeViewCreateOrReplace(connection, dsDefinitionObject);
  }

  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);
    }
  }

  private void executeUpdateSQL(Connection connection, String sql) throws SQLException {
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    preparedStatement.executeUpdate();
  }

  private void executeTableUpdate(
      Connection connection, IDialectSpecifier dialectSpecifier, JsonObject dsDefinitionObject)
      throws SQLException {
    StringBuilder sql = new StringBuilder();
    String tableName = dsDefinitionObject.get(TABLE_NAME).getAsString().toUpperCase();

    Map<String, String> columnDefinitions = new HashMap<String, String>();
    ResultSet rsColumns =
        connection.getMetaData().getColumns(null, null, tableName, "%"); // $NON-NLS-1$
    while (rsColumns.next()) {
      String typeName = DBSupportedTypesMap.getTypeName(rsColumns.getInt(5));
      columnDefinitions.put(rsColumns.getString(4).toUpperCase(), typeName);
    }

    sql.append(ALTER_TABLE + tableName + " "); // $NON-NLS-1$

    JsonArray columns = dsDefinitionObject.get(COLUMNS).getAsJsonArray();
    int i = 0;
    StringBuffer addSql = new StringBuffer();
    addSql.append(dialectSpecifier.getAlterAddOpen());

    for (JsonElement jsonElement : columns) {

      if (jsonElement instanceof JsonObject) {
        JsonObject jsonObject = (JsonObject) jsonElement;
        String name = jsonObject.get(COLUMN_NAME).getAsString().toUpperCase();
        String type =
            dbUtils.specifyDataType(
                connection, jsonObject.get(COLUMN_TYPE).getAsString().toUpperCase());
        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();

        if (!columnDefinitions.containsKey(name)) {
          if (i > 0) {
            addSql.append(", "); // $NON-NLS-1$
          }
          addSql.append(name + " " + type); // $NON-NLS-1$
          if (DBSupportedTypesMap.VARCHAR.equals(type) || DBSupportedTypesMap.CHAR.equals(type)) {
            addSql.append("(" + length + ") "); // $NON-NLS-1$ //$NON-NLS-2$
          } else {
            addSql.append(" "); // $NON-NLS-1$
          }
          if (notNull) {
            // sql.append("NOT NULL ");
            throw new SQLException(
                INCOMPATIBLE_CHANGE_OF_TABLE
                    + tableName
                    + AND_COLUMN
                    + name
                    + ADDING_NOT_NULL_COLUMN);
          }
          if (primaryKey) {
            // sql.append("PRIMARY KEY ");
            throw new SQLException(
                INCOMPATIBLE_CHANGE_OF_TABLE
                    + tableName
                    + AND_COLUMN
                    + name
                    + ADDING_PRIMARY_KEY_COLUMN);
          }
          if (defaultValue != null && !"".equals(defaultValue)) { // $NON-NLS-1$
            sql.append(DEFAULT + defaultValue + " "); // $NON-NLS-1$
          }
          i++;
        } else if (!columnDefinitions.get(name).equals(type)) {
          throw new SQLException(
              INCOMPATIBLE_CHANGE_OF_TABLE
                  + tableName
                  + AND_COLUMN
                  + name
                  + TYPE2
                  + columnDefinitions.get(name)
                  + CANNOT_BE_CHANGED_TO
                  + type);
        }
      }
    }

    // TODO Derby does not support multiple ADD in a single statement!

    if (i > 0) {
      addSql.append(dialectSpecifier.getAlterAddClose());
      sql.append(addSql.toString());
    }

    if (columnDefinitions.size() > columns.size()) {
      throw new SQLException(
          INCOMPATIBLE_CHANGE_OF_TABLE + tableName + DASH + AUTOMATIC_DROP_COLUMN_NOT_SUPPORTED);
    }

    if (i > 0) {
      String sqlExpression = sql.toString();
      try {
        logger.info(sqlExpression);
        executeUpdateSQL(connection, sqlExpression);
      } catch (SQLException e) {
        logger.error(sqlExpression);
        throw new SQLException(sqlExpression, e);
      }
    }
  }

  private JsonObject parseTable(String dsDefinition) throws IOException {
    // {
    // "tableName":"table_name",
    // "columns":
    // [
    // {
    // "name":"id",
    // "type":"INTEGER",
    // "length":"0",
    // "notNull":"true",
    // "primaryKey":"true"
    // },
    // {
    // "name":"text",
    // "type":"VARCHAR",
    // "length":"32",
    // "notNull":"false",
    // "primaryKey":"false"
    // },
    // ]
    // }
    IRepository repository = this.repository;
    //		# 177
    //		IResource resource = repository.getResource(this.location + dsDefinition);
    IResource resource = repository.getResource(dsDefinition);

    String content = new String(resource.getContent());
    JsonParser parser = new JsonParser();
    JsonObject dsDefinitionObject = (JsonObject) parser.parse(content);

    // TODO validate the parsed content has the right structure

    return dsDefinitionObject;
  }

  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);
    }
  }

  private JsonObject parseView(String dsDefinition) throws IOException {
    // {
    // "viewName":"view_name",
    // "query":"SELECT * FROM table_name"
    // }
    IRepository repository = this.repository;
    IResource resource = repository.getResource(this.location + dsDefinition);
    String content = new String(resource.getContent());
    JsonParser parser = new JsonParser();
    JsonObject dsDefinitionObject = (JsonObject) parser.parse(content);

    // TODO validate the parsed content has the right structure

    return dsDefinitionObject;
  }

  @Override
  public void enumerateKnownFiles(ICollection collection, List<String> dsDefinitions)
      throws IOException {
    if (collection.exists()) {
      List<IResource> resources = collection.getResources();
      for (Iterator<IResource> iterator = resources.iterator(); iterator.hasNext(); ) {
        IResource resource = iterator.next();
        if (resource != null && resource.getName() != null) {
          if (resource.getName().endsWith(EXTENSION_TABLE)
              || resource.getName().endsWith(EXTENSION_VIEW)) {
            //						# 177
            //						String fullPath = collection.getPath().substring(
            //								this.location.length())
            //								+ IRepository.SEPARATOR + resource.getName();
            String fullPath = resource.getPath();
            dsDefinitions.add(fullPath);
          }
        }
      }

      List<ICollection> collections = collection.getCollections();
      for (Iterator<ICollection> iterator = collections.iterator(); iterator.hasNext(); ) {
        ICollection subCollection = iterator.next();
        enumerateKnownFiles(subCollection, dsDefinitions);
      }
    }
  }

  @Override
  public IRepository getRepository() {
    return this.repository;
  }

  @Override
  public String getLocation() {
    return this.location;
  }
}
Example #14
0
public abstract class GenerationModel {

  private static final String EMPTY_STRING = ""; // $NON-NLS-1$

  private static final String COULD_NOT_OPEN_INPUT_STREAM_FOR =
      Messages.GenerationModel_COULD_NOT_OPEN_INPUT_STREAM_FOR;

  private static final String TEMPLATE_LOCATION_IS_EMPTY =
      Messages.GenerationModel_TEMPLATE_LOCATION_IS_EMPTY;

  private static final String RESOURCE_ALREADY_EXISTS_IN_THE_WORKSPACE =
      Messages.GenerationModel_RESOURCE_ALREADY_EXISTS_IN_THE_WORKSPACE;

  private static final String NAME_IS_NOT_VALID_FOR_A_RESOURCE_OF_THE_GIVEN_TYPE_S =
      Messages.GenerationModel_NAME_IS_NOT_VALID_FOR_A_RESOURCE_OF_THE_GIVEN_TYPE_S;

  private static final String PATH_IS_NOT_VALID_FOR_A_RESOURCE_OF_THE_GIVEN_TYPE_S =
      Messages.GenerationModel_PATH_IS_NOT_VALID_FOR_A_RESOURCE_OF_THE_GIVEN_TYPE_S;

  private static final Logger logger = Logger.getLogger(GenerationModel.class);

  private IResource sourceResource;

  // private String targetLocation;

  private String targetContainer;

  private String packageName;

  private String fileName;

  private TemplateType template;

  private Class<?> templateClassLoader;

  public IResource getSourceResource() {
    return sourceResource;
  }

  public void setSourceResource(IResource sourceResource) {
    this.sourceResource = sourceResource;
  }

  public String getTargetLocation() {
    // return targetLocation;
    if (this.targetContainer == null) {
      return null;
    }
    if (getPackageName() == null) {
      return this.targetContainer;
    }
    return this.targetContainer + IRepository.SEPARATOR + getPackageName();
  }

  // public void setTargetLocation(String targetLocation) {
  // this.targetLocation = targetLocation;
  // }

  public String getTargetContainer() {
    return targetContainer;
  }

  public void setTargetContainer(String targetContainer) {
    this.targetContainer = targetContainer;
  }

  public String getPackageName() {
    return this.packageName;
  }

  public void setPackageName(String packageName) {
    if ((this.packageName != null)
        && (this.packageName.length() > 1)
        && this.packageName.startsWith(IRepository.SEPARATOR)) {
      this.packageName = this.packageName.substring(1);
    }
    this.packageName = packageName;
  }

  public String getFileName() {
    return fileName;
  }

  public void setFileName(String fileName) {
    this.fileName = fileName;
  }

  public String getTemplateLocation() {
    if (template != null) {
      return template.getLocation();
    }
    return null;
  }

  public String[] getTemplateNames() {
    if (template != null) {
      return template.getSourceNames();
    }
    return null;
  }

  public String[] getTemplateLocations() {
    if (template != null) {
      return template.getSourceLocations();
    }
    return null;
  }

  public boolean[] getTemplateGenerates() {
    if (template != null) {
      return template.getSourceGenerates();
    }
    return null;
  }

  public String[] getTemplateRenamings() {
    if (template != null) {
      return template.getSourceRenamings();
    }
    return null;
  }

  public String getTemplateExtension() {
    if (template != null) {
      return template.getExtension();
    }
    return null;
  }

  public TemplateType getTemplate() {
    return template;
  }

  public void setTemplate(TemplateType template) {
    this.template = template;
  }

  public IValidationStatus validateLocationGeneric() {
    IWorkspace workspace = WorkspaceLocator.getWorkspace();
    return validateLocationGeneric(workspace);
  }

  public IValidationStatus validateLocationGeneric(IWorkspace workspace) {

    IStatus folderLocationValidation =
        workspace.validatePath(getTargetLocation(), IResource.FOLDER);
    IStatus projectLocationValidation =
        workspace.validatePath(getTargetLocation(), IResource.PROJECT);
    if (!folderLocationValidation.isOK() && !projectLocationValidation.isOK()) {
      return ValidationStatus.createError(PATH_IS_NOT_VALID_FOR_A_RESOURCE_OF_THE_GIVEN_TYPE_S);
    }

    if (getTargetLocation().contains(ICommonConstants.ARTIFACT_TYPE.SCRIPTING_SERVICES)) {

      if (isValidScriptingServiceFileName(getFileName())) {
        IWorkspaceRoot root = workspace.getRoot();
        if (isResourceExist(root)) {
          IResource res = extractResource(root);
          return ValidationStatus.createError(
              String.format(
                  RESOURCE_ALREADY_EXISTS_IN_THE_WORKSPACE, res.getFullPath().toString()));
        }
        return ValidationStatus.createOk();
      }
      return ValidationStatus.createError(NAME_IS_NOT_VALID_FOR_A_RESOURCE_OF_THE_GIVEN_TYPE_S);
    }

    IStatus nameValidation = workspace.validateName(getFileName(), IResource.FILE);
    if (!nameValidation.isOK()) {
      return ValidationStatus.createError(NAME_IS_NOT_VALID_FOR_A_RESOURCE_OF_THE_GIVEN_TYPE_S);
    }
    IWorkspaceRoot root = workspace.getRoot();
    if (isResourceExist(root)) {
      IPath location = new Path(getTargetLocation()).append(getFileName());
      return ValidationStatus.createError(
          String.format(RESOURCE_ALREADY_EXISTS_IN_THE_WORKSPACE, location.toString()));
    }
    return ValidationStatus.createOk();
  }

  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();
  }

  public static InputStream getInputStreamByTemplateLocation(String location) throws IOException {
    InputStream in = null;
    IRepository repository = RepositoryFacade.getInstance().getRepository();
    org.eclipse.dirigible.repository.api.IResource resource = repository.getResource(location);
    if (resource != null) {
      in = new ByteArrayInputStream(resource.getContent());
    }

    return in;
  }

  protected abstract IValidationStatus validate();

  public String getFileNameNoExtension() {
    return CommonUtils.getFileNameNoExtension(fileName);
  }

  public String getProjectName() {
    StringBuilder result = new StringBuilder();
    if (getTargetContainer() == null) {
      return null;
    }
    IPath location = new Path(getTargetContainer());
    // if (location.segmentCount() > 2) {
    // for (int i = 0; i < location.segmentCount(); i++) {
    // if (i == 1) {
    // continue;
    // }
    // result.append(location.segment(i) + ICommonConstants.SEPARATOR);
    // }
    // result.delete(result.length() - ICommonConstants.SEPARATOR.length(), result.length());
    // } else {
    result.append(location.segment(0));
    // }
    return result.toString();
  }

  public Class<?> getTemplateClassLoader() {
    return templateClassLoader;
  }

  public void setTemplateClassLoader(Class<?> templateClassLoader) {
    this.templateClassLoader = templateClassLoader;
  }

  private boolean isValidScriptingServiceFileName(String fileName) {

    String scriptingServicefileRegExPattern =
        "([a-zA-Z_0-9]+)+([\\.]){0,1}(([a-zA-Z0-9]*)*)"; //$NON-NLS-1$
    if (Pattern.matches(scriptingServicefileRegExPattern, fileName)) {
      return true;
    }
    return false;
  }

  private boolean isResourceExist(IWorkspaceRoot root) {
    IResource resource = extractResource(root);
    if (resource != null) {
      return true;
    }
    return false;
  }

  private IResource extractResource(IWorkspaceRoot root) {
    IPath location = new Path(getTargetLocation()).append(getFileName());
    IResource resource = root.findMember(location.toString());
    return resource;
  }
}
/** DataSource Facade utility class for IDE */
public class DataSourceFacade {

  private static final String EMPTY = "";

  private static final String EMBEDDED_DATA_SOURCE_IS_USED =
      Messages.DataSourceFacade_EMBEDDED_DATA_SOURCE_IS_USED;

  private static final String LOCAL_DB_ACTION = "create"; // $NON-NLS-1$
  private static final String LOCAL_DB_NAME = "derby"; // $NON-NLS-1$

  private static final String DATASOURCE_DEFAULT = "DEFAULT_DATASOURCE"; // $NON-NLS-1$

  public static final Logger logger = Logger.getLogger(DataSourceFacade.class.getCanonicalName());

  private static DataSource localDataSource;

  private static DataSourceFacade instance;

  private WrappedDataSource dataSource;

  public static DataSourceFacade getInstance() {
    if (instance == null) {
      instance = new DataSourceFacade();
    }
    return instance;
  }

  public DataSource getDataSource() {
    if (dataSource == null) {
      dataSource = getFromSession();
      if (dataSource == null) {
        dataSource = createLocal();
      }
      populateMetaData(dataSource);
    }
    return dataSource;
  }

  private WrappedDataSource getFromSession() {
    DataSource dataSource = null;
    dataSource = (DataSource) CommonParameters.getObject(DATASOURCE_DEFAULT);
    if (dataSource != null) {
      WrappedDataSource wrappedDataSource = new WrappedDataSource(dataSource);
      return wrappedDataSource;
    }
    return null;
  }

  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 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);
    }
  }
}
Example #16
0
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;
  }
}
Example #17
0
public class MobileExecutor extends AbstractScriptExecutor {

  private static final Logger logger = Logger.getLogger(MobileExecutor.class);

  private IRepository repository;
  private String[] rootPaths;

  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()");
  }

  @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;
  }

  protected byte[] preprocessContent(byte[] rawContent, IEntity entity) throws IOException {
    return rawContent;
  }

  protected byte[] buildResourceData(
      final IEntity entity, final HttpServletRequest request, final HttpServletResponse response)
      throws IOException {
    byte[] data = new byte[] {};
    data = readResourceData((IResource) entity);
    return data;
  }

  protected byte[] readResourceData(IResource resource) throws IOException {
    return resource.getContent();
  }

  protected void beforeExecution(
      HttpServletRequest request, HttpServletResponse response, String module, Context context) {}

  @Override
  protected void registerDefaultVariable(Object scope, String name, Object value) {
    //
  }

  @Override
  protected String getModuleType(String path) {
    return ICommonConstants.ARTIFACT_TYPE.MOBILE_APPLICATIONS;
  }
}