public void setTemplate(TemplateType type, InputStream inputStream) throws CoreException {
   File template = getTemplate(type);
   if (template != null) {
     if (!template.exists()) {
       try {
         File file = new File(template.getParent());
         file.mkdirs();
         template.createNewFile();
         FileOutputStream fos = new FileOutputStream(template);
         FileUtil.copy(inputStream, fos);
         fos.close();
       } catch (Exception e) {
         BonitaStudioLog.error(e);
       }
     } else {
       try {
         template.delete();
         template.createNewFile();
         FileOutputStream fos = new FileOutputStream(template);
         FileUtil.copy(inputStream, fos);
         fos.close();
       } catch (Exception e) {
         BonitaStudioLog.error(e);
       }
     }
   } else {
     throw new CoreException(Status.CANCEL_STATUS);
   }
 }
 private Instance getConnectorConfiguration(Model model, StringToExpressionConverter converter) {
   final Instance configuration =
       model.newInstance("connectorconfiguration.ConnectorConfiguration");
   configuration.set("definitionId", getDefinitionId());
   configuration.set("version", getDefinitionVersion());
   final Map<String, Object> additionalInputs = definitionMapper.getAdditionalInputs(inputs);
   final Map<String, Object> allInput = new HashMap<String, Object>(inputs);
   allInput.putAll(additionalInputs);
   for (Entry<String, Object> input : allInput.entrySet()) {
     final String parameterKeyFor = getParameterKeyFor(input.getKey());
     if (parameterKeyFor != null) {
       final Instance parameter = model.newInstance("connectorconfiguration.ConnectorParameter");
       parameter.set("key", parameterKeyFor);
       parameter.set(
           "expression",
           getParameterExpressionFor(
               model,
               parameterKeyFor,
               converter,
               definitionMapper.transformParameterValue(parameterKeyFor, input.getValue(), inputs),
               getReturnType(parameterKeyFor)));
       configuration.add("parameters", parameter);
     } else {
       if (BonitaStudioLog.isLoggable(IStatus.OK)) {
         BonitaStudioLog.debug(
             input.getKey() + " not mapped for " + getDefinitionId(), BarImporterPlugin.PLUGIN_ID);
       }
     }
   }
   return configuration;
 }
  protected void addArchiveDescriptor(
      IRepositoryStore<IRepositoryFileStore> sourceStore, List<IResource> resourcesToExport) {
    IFile descFile = sourceStore.getResource().getFile(DESCRIPTOR_FILE);
    if (descFile.exists()) {
      try {
        descFile.delete(true, Repository.NULL_PROGRESS_MONITOR);
      } catch (CoreException e) {
        BonitaStudioLog.error(e);
      }
    }

    final Properties properties = new Properties();
    properties.put(VERSION, ProductVersion.CURRENT_VERSION);
    properties.put(TYPE, getArchiveType());
    FileOutputStream out = null;
    try {
      out = new FileOutputStream(descFile.getLocation().toFile());
      properties.store(out, null);
      resourcesToExport.add(descFile);
      cleanAfterExport.add(descFile);
    } catch (Exception e) {
      BonitaStudioLog.error(e);
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          BonitaStudioLog.error(e);
        }
      }
      sourceStore.refresh();
    }
  }
 /* (non-Javadoc)
  * @see org.eclipse.jface.wizard.Wizard#performFinish()
  */
 @Override
 public boolean performFinish() {
   try {
     IStatus status = page.finish();
     if (status.getSeverity() == IStatus.CANCEL) {
       return false;
     }
     if (statusContainsError(status)) {
       String message = status.getMessage();
       if (message == null || message.isEmpty()) {
         message = Messages.exportErrorOccuredMsg;
       }
       new BonitaErrorDialog(
               Display.getDefault().getActiveShell(),
               Messages.exportErrorOccured,
               message,
               status,
               IStatus.ERROR)
           .open();
     } else {
       MessageDialog.openInformation(
           Display.getDefault().getActiveShell(),
           Messages.exportSuccessTitle,
           Messages.exportSuccessMsg);
     }
     return !statusContainsError(status);
   } catch (InvocationTargetException e) {
     BonitaStudioLog.error(e);
   } catch (InterruptedException e) {
     BonitaStudioLog.error(e);
   }
   return false;
 }
  protected void addProcessImage(
      final BusinessArchiveBuilder builder, final AbstractProcess process) throws CoreException {
    if (PlatformUI.isWorkbenchRunning()) {
      final String processName = process.getName() + "_" + process.getVersion();
      final String path = processName + ".png"; // $NON-NLS-1$

      try {
        Diagram diagram = ModelHelper.getDiagramFor(ModelHelper.getMainProcess(process));
        if (diagram == null) {
          return; // DON'T ADD IMAGE, DON'T THROW EXCEPTION FOR TESTS PURPUSES
        }
        final ResourceSet resourceSet = new ResourceSetImpl();
        final TransactionalEditingDomain editingDomain =
            CustomDiagramEditingDomainFactory.getInstance().createEditingDomain(resourceSet);
        final Resource resource = resourceSet.createResource(diagram.eResource().getURI());
        try {
          resource.load(resourceSet.getLoadOptions());
        } catch (final IOException e1) {
          BonitaStudioLog.error(e1);
        }
        diagram = (Diagram) resource.getEObject(diagram.eResource().getURIFragment(diagram));
        final CopyToImageUtilEx copyToImageUtil = new CopyToImageUtilEx();
        byte[] imageBytes = null;
        try {
          imageBytes =
              copyToImageUtil.copyToImageByteArray(
                  diagram,
                  process,
                  ImageFileFormat.PNG,
                  Repository.NULL_PROGRESS_MONITOR,
                  new PreferencesHint("exportToImage"),
                  true);
        } catch (final Exception e) {
          BonitaStudioLog.error(e);
          return;
        } finally {
          editingDomain.dispose();
        }
        if (imageBytes != null) {
          try {
            builder.addExternalResource(new BarResource(path, imageBytes));
          } catch (final Exception e) {
            BonitaStudioLog.log("Process image file generation has failed"); // $NON-NLS-1$
          }
        }
      } catch (final Exception e) {
        BonitaStudioLog.error(e);
      }
    }
  }
 private Instance getParameterExpressionFor(
     Model model,
     String input,
     StringToExpressionConverter converter,
     Object value,
     String returnType) {
   if (value instanceof String || value instanceof Boolean || value instanceof Number) {
     String type = definitionMapper.getExpectedExpresstionType(input, value);
     if (type == null) {
       return converter.parse(value.toString(), returnType, true);
     } else {
       return converter.parse(value.toString(), returnType, true, type);
     }
   } else if (value instanceof List) {
     List<Object> listValue = (List<Object>) value;
     if (!listValue.isEmpty()) {
       Instance expression = null;
       Object row = listValue.get(0);
       if (row instanceof List) {
         expression = model.newInstance("expression.TableExpression");
         addRow(model, converter, expression, row);
         for (int i = 1; i < listValue.size(); i++) {
           row = listValue.get(i);
           addRow(model, converter, expression, row);
         }
       } else {
         expression = model.newInstance("expression.ListExpression");
         for (int i = 0; i < listValue.size(); i++) {
           Object v = listValue.get(i);
           expression.add(
               "expressions", converter.parse(v.toString(), String.class.getName(), false));
         }
       }
       return expression;
     }
   } else {
     if (BonitaStudioLog.isLoggable(IStatus.OK)) {
       String valueString = "null";
       if (value != null) {
         valueString = value.toString();
       }
       BonitaStudioLog.debug(
           input + " value " + valueString + " cannot be transform to an expression",
           BarImporterPlugin.PLUGIN_ID);
     }
   }
   return null;
 }
  protected void editData() {
    final IStructuredSelection selection = (IStructuredSelection) dataTableViewer.getSelection();
    if (onlyOneElementSelected(selection)) {
      final Data selectedData = (Data) selection.getFirstElement();
      if (selectedData.eContainer() == null) {
        final AbstractProcess parentProcess = ModelHelper.getParentProcess(eObject);
        BonitaStudioLog.error(
            "Investigation trace for issue BS-11552:\n"
                + "The context was not initialized.\n "
                + "Please report the issue with details and attached impacted process.\n"
                + "data: "
                + (selectedData != null ? selectedData.getName() : "null data")
                + "\n"
                + "From diagram:"
                + (parentProcess != null ? parentProcess.getName() : "No process found."),
            DataPlugin.PLUGIN_ID);
      }

      final DataWizard wizard =
          new DataWizard(
              getEditingDomain(),
              selectedData,
              getDataFeature(),
              getDataFeatureToCheckUniqueID(),
              getShowAutoGenerateForm());
      wizard.setIsPageFlowContext(isPageFlowContext());
      wizard.setIsOverviewContext(isOverViewContext());
      new CustomWizardDialog(
              Display.getDefault().getActiveShell(), wizard, IDialogConstants.OK_LABEL)
          .open();
      dataTableViewer.refresh();
    }
  }
  @SuppressWarnings("unchecked")
  protected void moveData(final IStructuredSelection structuredSelection) {
    final MoveDataWizard moveDataWizard = new MoveDataWizard((DataAware) getEObject());
    if (new WizardDialog(Display.getDefault().getActiveShell(), moveDataWizard).open()
        == Dialog.OK) {
      final DataAware dataAware = moveDataWizard.getSelectedDataAwareElement();
      try {
        final MoveDataCommand cmd =
            new MoveDataCommand(
                getEditingDomain(),
                (DataAware) getEObject(),
                structuredSelection.toList(),
                dataAware);
        OperationHistoryFactory.getOperationHistory().execute(cmd, null, null);

        if (!(cmd.getCommandResult().getStatus().getSeverity() == Status.OK)) {
          final List<Object> data = (List<Object>) cmd.getCommandResult().getReturnValue();
          String dataNames = "";
          for (final Object d : data) {
            dataNames = dataNames + ((Element) d).getName() + ",";
          }
          dataNames = dataNames.substring(0, dataNames.length() - 1);
          MessageDialog.openWarning(
              Display.getDefault().getActiveShell(),
              Messages.PromoteDataWarningTitle,
              Messages.bind(Messages.PromoteDataWarningMessage, dataNames));
        }

      } catch (final ExecutionException e1) {
        BonitaStudioLog.error(e1);
      }
      refresh();
    }
  }
    /* (non-Javadoc)
     * @see org.eclipse.ui.actions.CompoundContributionItem#getContributionItems()
     */
    @Override
    protected IContributionItem[] getContributionItems() {
      final List<IContributionItem> res = new ArrayList<IContributionItem>();
      IRepository repository = RepositoryManager.getInstance().getCurrentRepository();
      diagramSotre =
          (DiagramRepositoryStore) repository.getRepositoryStore(DiagramRepositoryStore.class);
      try {
        for (AbstractProcess process : diagramSotre.getAllProcesses()) {
          if (process.getName().equals(subprocessName)) {
            Map<String, String> params = new HashMap<String, String>();
            params.put(OpenSpecificProcessCommand.PARAMETER_PROCESS_NAME, process.getName());
            params.put(OpenSpecificProcessCommand.PARAMETER_PROCESS_VERSION, process.getVersion());
            CommandContributionItemParameter param =
                new CommandContributionItemParameter(
                    PlatformUI.getWorkbench().getActiveWorkbenchWindow(),
                    null,
                    OpenSpecificProcessCommand.ID,
                    CommandContributionItem.STYLE_PUSH);
            param.parameters = params;
            param.label = process.getVersion();
            param.visibleEnabled = true;
            param.commandId = OpenSpecificProcessCommand.ID;
            CommandContributionItem commandContributionItem = new CommandContributionItem(param);
            commandContributionItem.setVisible(true);
            res.add(commandContributionItem);
          }
        }

      } catch (Exception ex) {
        BonitaStudioLog.error(ex);
      }
      return res.toArray(new IContributionItem[res.size()]);
    }
  @SuppressWarnings("static-access")
  public void testDownloadDefaultTemplate() {
    LookAndFeelPropertySection tester = new LookAndFeelPropertySection();
    ResourceType t = ApplicationResourceFileStore.ResourceType.PROCESS_TEMPLATE;
    final String fileName = "process.html";
    assertNotNull(
        "ResourceType PORCESS_TEMPLATE not exist anymore, but this test is based on it", t);

    tester.downloadDefaultTemplate(
        t,
        ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getAbsolutePath()
            + File.separatorChar
            + fileName);
    final File createdFile =
        new File(
            ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getAbsolutePath()
                + File.separatorChar
                + fileName);
    assertNotNull("File " + fileName + " is asked to be downloaded but is not", createdFile);

    try {
      @SuppressWarnings("unused")
      FileInputStream fromIn = new FileInputStream(createdFile);
    } catch (FileNotFoundException e) {
      BonitaStudioLog.log(e.getMessage());
      fail("File " + fileName + " were not present in the destination folder");
    }
    createdFile.delete();
  }
 public <T extends IRepositoryStore<? extends IRepositoryFileStore>> T getRepositoryStore(
     final Class<T> storeClass) {
   try {
     jobManager.join(
         WorkspaceInitializationJob.WORKSPACE_INIT_FAMILY, Repository.NULL_PROGRESS_MONITOR);
   } catch (OperationCanceledException | InterruptedException e) {
     BonitaStudioLog.error("Synchronization failed", e);
   }
   return repositoryManagerInstance.getRepositoryStore(storeClass);
 }
 public DesignProcessDefinitionBuilder getProcessDefinitionBuilder() {
   for (final IConfigurationElement element :
       BonitaStudioExtensionRegistryManager.getInstance()
           .getConfigurationElements(PROCESS_DEFINITION_EXPORTER_ID)) {
     try {
       return (DesignProcessDefinitionBuilder) element.createExecutableExtension("class");
     } catch (final CoreException e) {
       BonitaStudioLog.error(e, EnginePlugin.PLUGIN_ID);
     }
   }
   return new DesignProcessDefinitionBuilder();
 }
 public void execute() {
   try {
     File root = ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile();
     File destFile = new File(root, "studio.properties");
     if (!destFile.exists()) {
       URL url = ApplicationPlugin.getDefault().getBundle().getResource("/studio.properties");
       File propertyFile = new File(FileLocator.toFileURL(url).getFile());
       PlatformUtil.copyResource(root, propertyFile, new NullProgressMonitor());
     }
   } catch (Exception e) {
     BonitaStudioLog.error(e);
   }
 }
 public List<BARResourcesProvider> getBARResourcesProvider() {
   final List<BARResourcesProvider> res = new ArrayList<BARResourcesProvider>();
   final IConfigurationElement[] extensions =
       BonitaStudioExtensionRegistryManager.getInstance()
           .getConfigurationElements(BAR_RESOURCE_PROVIDERS_EXTENSION_POINT);
   for (final IConfigurationElement extension : extensions) {
     try {
       res.add(
           extensionContextInjectionFactory.make(
               extension, "providerClass", BARResourcesProvider.class));
     } catch (final Exception ex) {
       BonitaStudioLog.error(ex);
     }
   }
   return res;
 }
 /* (non-Javadoc)
  * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
  */
 public void selectionChanged(IWorkbenchPart part, ISelection selection) {
   if (part != null
       && part.getClass() != null
       && part.getClass().getName() != null
       && part.getClass().getName().startsWith("org.bonitasoft")) {
     if (!isBonitaEditorActive) {
       try {
         //	PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(BonitaModelingPropertiesView.VIEW_ID);
       } catch (Exception ex) {
         BonitaStudioLog.error(ex);
       }
     }
     isBonitaEditorActive = true;
   } else {
     isBonitaEditorActive = false;
   }
 }
 @BonitaAPI
 public static void importXSD(String filePath) {
   File file = new File(filePath);
   XSDRepositoryStore xsdStore =
       (XSDRepositoryStore)
           RepositoryManager.getInstance().getRepositoryStore(XSDRepositoryStore.class);
   IRepositoryFileStore fileStore = xsdStore.createRepositoryFileStore(file.getName());
   Resource resource =
       new XSDResourceFactoryImpl().createResource(URI.createFileURI(file.getAbsolutePath()));
   try {
     resource.load(Collections.EMPTY_MAP);
   } catch (IOException e1) {
     BonitaStudioLog.error(e1);
   }
   if (!resource.getContents().isEmpty()) {
     XSDSchema content = (XSDSchema) resource.getContents().get(0);
     fileStore.save(content);
   }
 }
 /*
  * (non-Javadoc)
  * @see org.bonitasoft.studio.common.repository.provider.
  * IBOSArchiveFileStoreProvider#getFileStoreForConfiguration(org.bonitasoft.
  * studio.model.process. AbstractProcess,
  * org.bonitasoft.studio.model.configuration.Configuration)
  */
 @Override
 public Set<IRepositoryFileStore> getFileStoreForConfiguration(
     final AbstractProcess process, final Configuration configuration) {
   final Set<IRepositoryFileStore> result = new HashSet<IRepositoryFileStore>();
   final List<FormMapping> allFormMappings =
       getAllItemsOfType(process, ProcessPackage.Literals.FORM_MAPPING);
   for (final WebPageFileStore fStore :
       transform(filter(allFormMappings, withInternalType()), formMappingToFileStore())) {
     if (fStore != null) {
       result.add(fStore);
       try {
         result.addAll(getRelatedFileStore(fStore));
       } catch (final BarResourceCreationException | IOException e) {
         BonitaStudioLog.error("Failed to retrieve related form resources", e);
       }
     }
   }
   return result;
 }
  public Connector5Descriptor(Instance connectorInstance) {
    this.uuid = connectorInstance.getUuid();
    this.name = connectorInstance.get(NAME);
    this.connectorId = connectorInstance.get(CONNECTOR_ID);
    this.documentation = connectorInstance.get(DOCUMENTATION);
    this.event = connectorInstance.get(EVENT);
    this.ignoreErrors = connectorInstance.get(ERROR_HANDLE);
    final List<Instance> parameters = connectorInstance.get(PARAMETERS);
    for (Instance parameter : parameters) {
      String key = parameter.get(PARAMETER_KEY);
      Object value = parameter.get(PARAMETER_VALUE);
      inputs.put(key, value);
    }
    final List<Instance> outputMapping = connectorInstance.get(OUTPUTS);
    for (Instance output : outputMapping) {
      try {
        Instance data = output.get(OUTPUT_DATA);
        String value = output.get(OUTPUT_EXPRESSION);
        if (data != null) {
          outputs.put((String) data.get("name"), value);
        } else {
          Instance container = connectorInstance.getContainer();
          if (container.instanceOf("form.Widget")) {
            String id = "field_" + container.get("name");
            outputs.put(id, value);
          }
        }
      } catch (IllegalArgumentException e) {
        BonitaStudioLog.warning(
            "The connector "
                + connectorId
                + "/"
                + name
                + " doesn't provide the expected feature for outputs.",
            BarImporterPlugin.PLUGIN_ID);
      }
    }
    definitionMapper =
        ConnectorIdToDefinitionMapping.getInstance().getDefinitionMapper(connectorId);

    this.containerType = connectorInstance.getContainer().getType().getEClass();
  }
 public Configuration getConfiguration(final AbstractProcess process, String configurationId) {
   Configuration configuration = null;
   final ProcessConfigurationRepositoryStore processConfStore =
       RepositoryManager.getInstance()
           .getRepositoryStore(ProcessConfigurationRepositoryStore.class);
   if (configurationId == null) {
     configurationId =
         ConfigurationPlugin.getDefault()
             .getPreferenceStore()
             .getString(ConfigurationPreferenceConstants.DEFAULT_CONFIGURATION);
   }
   if (configurationId.equals(ConfigurationPreferenceConstants.LOCAL_CONFIGURAITON)) {
     final String id = ModelHelper.getEObjectID(process);
     IRepositoryFileStore file = processConfStore.getChild(id + ".conf");
     if (file == null) {
       file = processConfStore.createRepositoryFileStore(id + ".conf");
       configuration = ConfigurationFactory.eINSTANCE.createConfiguration();
       configuration.setName(configurationId);
       configuration.setVersion(ModelVersion.CURRENT_VERSION);
       file.save(configuration);
     }
     try {
       configuration = (Configuration) file.getContent();
     } catch (final ReadFileStoreException e) {
       BonitaStudioLog.error("Failed to read process configuration", e);
     }
   } else {
     for (final Configuration conf : process.getConfigurations()) {
       if (configurationId.equals(conf.getName())) {
         configuration = conf;
       }
     }
   }
   if (configuration == null) {
     configuration = ConfigurationFactory.eINSTANCE.createConfiguration();
     configuration.setName(configurationId);
     configuration.setVersion(ModelVersion.CURRENT_VERSION);
   }
   // Synchronize configuration with definition
   new ConfigurationSynchronizer(process, configuration).synchronize();
   return configuration;
 }
  protected BARResourcesProvider getBARApplicationResourcesProvider() {
    BARResourcesProvider result = null;
    int maxPriority = -1;
    final IConfigurationElement[] extensions =
        BonitaStudioExtensionRegistryManager.getInstance()
            .getConfigurationElements(BAR_APPLICATION_RESOURCE_PROVIDERS_EXTENSION_POINT);
    for (final IConfigurationElement extension : extensions) {

      try {
        final int p = Integer.parseInt(extension.getAttribute("priority"));
        if (p >= maxPriority) {

          result = (BARResourcesProvider) extension.createExecutableExtension("providerClass");
          maxPriority = p;
        }
      } catch (final Exception ex) {
        BonitaStudioLog.error(ex);
      }
    }
    return result;
  }
  protected Properties loadProperties(final String path) {
    FileInputStream fis = null;
    Properties p = null;
    try {
      fis = new FileInputStream(path);
      p = new Properties();
      p.load(fis);
    } catch (final Exception e) {
      BonitaStudioLog.error(e);
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (final IOException e1) {

        }
      }
    }

    return p;
  }
  @Override
  public void dispose(
      IUndoContext context, boolean flushUndo, boolean flushRedo, boolean flushContext) {
    // dispose of any limit that was set for the context if it is not to be
    // used again.
    if (context instanceof EditingDomainUndoContext) {
      EditingDomainUndoContext editingDomainContext = (EditingDomainUndoContext) context;
      EditingDomain editingDomain = editingDomainContext.getEditingDomain();
      if (PlatformUI.isWorkbenchRunning()
          && PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null
          && PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() != null
          && PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()
              != null) {

        IEditorReference[] editorReferences =
            PlatformUI.getWorkbench()
                .getActiveWorkbenchWindow()
                .getActivePage()
                .getEditorReferences();
        for (IEditorReference editorRef : editorReferences) {
          try {
            IWorkbenchPart part = editorRef.getPart(false);
            if (part instanceof DiagramEditor) {
              DiagramEditor editor = (DiagramEditor) part;
              if (editor.getEditingDomain() != null
                  && editor.getEditingDomain().equals(editingDomain)) {
                return; // do not dispose if the editing domain
                // is else
              }
            }
          } catch (Exception e) {
            BonitaStudioLog.error(e);
          }
        }
      }
    }
    defaultOperationHistory.dispose(context, flushUndo, flushRedo, flushContext);
  }
 protected void addDefinitionPropertiesFile(
     List<IResource> resourcesToExport, final IRepositoryStore store, ConnectorDefinition def) {
   final DefinitionResourceProvider messageProvider =
       DefinitionResourceProvider.getInstance(store, getBundle());
   List<File> propertiesFile = messageProvider.getExistingLocalesResource(def);
   for (File propertyFile : propertiesFile) {
     String newFilename = propertyFile.getName();
     try {
       IFile f = store.getResource().getFile(newFilename);
       if (!f.exists()) {
         FileInputStream fis = new FileInputStream(propertyFile);
         f.create(fis, true, Repository.NULL_PROGRESS_MONITOR);
         fis.close();
         cleanAfterExport.add(f);
       }
       if (!resourcesToExport.contains(f)) {
         resourcesToExport.add(f);
       }
     } catch (Exception e) {
       BonitaStudioLog.error(e);
     }
   }
 }
  protected void addDefinitionIcons(
      List<IResource> resourcesToExport, final IRepositoryStore store, ConnectorDefinition def) {
    if (def.getIcon() != null) {
      IFile iconFile = store.getResource().getFile(Path.fromOSString(def.getIcon()));
      if (iconFile != null && iconFile.exists()) {
        resourcesToExport.add(iconFile);
      } else {
        URL url =
            ConnectorPlugin.getDefault()
                .getBundle()
                .getResource(ConnectorDefRepositoryStore.STORE_NAME + "/" + def.getIcon());
        if (url != null) {
          try {
            IFile f = store.getResource().getFile(def.getIcon());
            if (!f.exists()) {
              InputStream is = url.openStream();
              f.create(is, true, Repository.NULL_PROGRESS_MONITOR);
              if (!resourcesToExport.contains(f)) {
                resourcesToExport.add(f);
              }
              cleanAfterExport.add(f);
              is.close();
            }

          } catch (Exception e) {
            BonitaStudioLog.error(e);
          }
        }
      }
    }

    for (Category c : def.getCategory()) {
      if (c.getIcon() != null) {
        IFile iconFile = store.getResource().getFile(Path.fromOSString(c.getIcon()));
        if (iconFile != null && iconFile.exists()) {
          if (!resourcesToExport.contains(iconFile)) {
            resourcesToExport.add(iconFile);
          }
        } else {
          URL url =
              ConnectorPlugin.getDefault()
                  .getBundle()
                  .getResource(ConnectorDefRepositoryStore.STORE_NAME + "/" + c.getIcon());
          if (url != null) {
            try {
              IFile f = store.getResource().getFile(c.getIcon());
              if (!f.exists()) {
                InputStream is = url.openStream();
                f.create(is, true, Repository.NULL_PROGRESS_MONITOR);
                if (!resourcesToExport.contains(f)) {
                  resourcesToExport.add(f);
                }
                cleanAfterExport.add(f);
                is.close();
              }
            } catch (Exception e) {
              BonitaStudioLog.error(e);
            }
          }
        }
      }
    }
  }
  public BusinessArchive createBusinessArchive(
      final AbstractProcess process,
      final Configuration configuration,
      final Set<EObject> excludedObject,
      final boolean addProcessImage)
      throws Exception {

    checkArgument(configuration != null);
    BonitaStudioLog.info(
        "Building bar for process " + process.getName() + " (" + process.getVersion() + " )...",
        EnginePlugin.PLUGIN_ID);
    final DesignProcessDefinitionBuilder procBuilder = getProcessDefinitionBuilder();
    procBuilder.seteObjectNotExported(excludedObject);
    final DesignProcessDefinition def = procBuilder.createDefinition(process);

    if (def == null) {
      throw new Exception(Messages.cantDeployEmptyPool);
    }

    final BusinessArchiveBuilder builder = new BusinessArchiveBuilder().createNewBusinessArchive();
    builder.setProcessDefinition(def);

    builder.setParameters(getParameterMapFromConfiguration(configuration));
    final byte[] content = new ActorMappingExporter().toByteArray(configuration);
    if (content != null) {
      builder.setActorMapping(content);
    }

    for (final BARResourcesProvider resourceProvider : getBARResourcesProvider()) {
      resourceProvider.addResourcesForConfiguration(
          builder, process, configuration, excludedObject);
    }

    // Add forms resources
    final BARResourcesProvider provider = getBARApplicationResourcesProvider();
    if (provider != null) {
      provider.addResourcesForConfiguration(builder, process, configuration, excludedObject);
    }

    if (!(process instanceof SubProcessEvent)) {
      if (addProcessImage) {
        Display.getDefault()
            .syncExec(
                new Runnable() {

                  @Override
                  public void run() {
                    try {
                      addProcessImage(builder, process);
                    } catch (final CoreException e) {
                      BonitaStudioLog.error(e);
                    }
                  }
                });
      }
    }

    final BusinessArchive archive = builder.done();
    BonitaStudioLog.info(
        "Build complete for process " + process.getName() + " (" + process.getVersion() + " ).",
        EnginePlugin.PLUGIN_ID);
    return archive;
  }
  protected IStatus addDependencies(ConnectorImplementation impl, IFolder classpathFolder)
      throws CoreException {
    final IDefinitionRepositoryStore store = (IDefinitionRepositoryStore) getDefinitionStore();
    final DependencyRepositoryStore depStore =
        (DependencyRepositoryStore)
            RepositoryManager.getInstance().getRepositoryStore(DependencyRepositoryStore.class);
    final DefinitionResourceProvider resourceProvider =
        DefinitionResourceProvider.getInstance(getDefinitionStore(), getBundle());

    ConnectorDefinition def =
        store.getDefinition(impl.getDefinitionId(), impl.getDefinitionVersion());
    for (String jarName : def.getJarDependency()) {
      if (ignoredLibs.contains(jarName)) {
        continue;
      }
      IRepositoryFileStore file = depStore.getChild(jarName);
      if (file != null) {
        if (file.getResource().exists()) {
          if (!classpathFolder.getFile(file.getName()).exists()) {
            try {
              file.getResource()
                  .copy(
                      classpathFolder.getFullPath().append(file.getName()),
                      true,
                      Repository.NULL_PROGRESS_MONITOR);
            } catch (CoreException e) {
              BonitaStudioLog.error(e);
            }
          }
        }
      } else { // Search in provided jars
        InputStream is = resourceProvider.getDependencyInputStream(jarName);
        if (is != null) {
          IFile jarFile = classpathFolder.getFile(jarName);
          if (!jarFile.exists()) {
            jarFile.create(is, true, Repository.NULL_PROGRESS_MONITOR);
          }
        } else {
          return ValidationStatus.error(Messages.bind(Messages.implementationDepNotFound, jarName));
        }
      }
    }
    for (String jarName : impl.getJarDependencies().getJarDependency()) {
      if (ignoredLibs.contains(jarName)) {
        continue;
      }
      IRepositoryFileStore file = depStore.getChild(jarName);
      if (file != null) {
        if (file.getResource().exists()) {
          if (!classpathFolder.getFile(file.getName()).exists()) {
            try {
              file.getResource()
                  .copy(
                      classpathFolder.getFullPath().append(file.getName()),
                      true,
                      Repository.NULL_PROGRESS_MONITOR);
            } catch (CoreException e) {
              BonitaStudioLog.error(e);
            }
          }
        }
      } else { // Search in provided jars
        InputStream is = resourceProvider.getDependencyInputStream(jarName);
        if (is != null) {
          IFile jarFile = classpathFolder.getFile(jarName);
          if (!jarFile.exists()) {
            jarFile.create(is, true, Repository.NULL_PROGRESS_MONITOR);
          }
        } else {
          return ValidationStatus.error(Messages.bind(Messages.implementationDepNotFound, jarName));
        }
      }
    }
    return Status.OK_STATUS;
  }
  public IStatus run(IProgressMonitor progressMonitor) {
    progressMonitor.beginTask(Messages.exporting, IProgressMonitor.UNKNOWN);
    IStatus status = Status.OK_STATUS;
    try {
      ignoredLibs.add(
          NamingUtils.toConnectorImplementationFilename(
                  impl.getImplementationId(), impl.getImplementationVersion(), false)
              + ".jar");
      cleanAfterExport = new ArrayList<IResource>();
      final SourceRepositoryStore sourceStore = getSourceStore();
      final IRepositoryStore implStore = getImplementationStore();

      List<IResource> resourcesToExport = new ArrayList<IResource>();
      IFolder classpathFolder = implStore.getResource().getFolder(CLASSPATH_DIR);
      if (classpathFolder.exists()) {
        classpathFolder.delete(true, Repository.NULL_PROGRESS_MONITOR);
      }

      classpathFolder.create(true, true, Repository.NULL_PROGRESS_MONITOR);
      resourcesToExport.add(classpathFolder);
      cleanAfterExport.add(classpathFolder);

      status =
          addImplementationJar(impl, classpathFolder, sourceStore, implStore, resourcesToExport);
      if (status.getSeverity() != IStatus.OK) {
        return status;
      }
      addArchiveDescriptor(sourceStore, resourcesToExport);

      if (addDependencies) {
        status = addDependencies(impl, classpathFolder);
        if (status.getSeverity() != IStatus.OK) {
          return status;
        }
      }

      addConnectorImplementation(impl, resourcesToExport, includeSources);
      addConnectorDefinition(impl, resourcesToExport);

      final ArchiveFileExportOperation operation =
          new ArchiveFileExportOperation(null, resourcesToExport, destPath);
      operation.setUseCompression(true);
      operation.setUseTarFormat(false);
      operation.setCreateLeadupStructure(false);
      operation.run(progressMonitor);
      if (!operation.getStatus().isOK()) {
        return operation.getStatus();
      }
    } catch (CoreException e) {
      BonitaStudioLog.error(e);
      return ValidationStatus.error(e.getMessage(), e);
    } catch (InvocationTargetException e) {
      BonitaStudioLog.error(e);
      return ValidationStatus.error(e.getMessage(), e);
    } catch (InterruptedException e) {
      BonitaStudioLog.error(e);
      return ValidationStatus.error(e.getMessage(), e);
    } catch (FileNotFoundException e) {
      BonitaStudioLog.error(e);
      return ValidationStatus.error(e.getMessage(), e);
    } finally {
      if (implBackup != null) {
        final IRepositoryStore store = getImplementationStore();
        String fileName = NamingUtils.getEResourceFileName(implBackup, true);
        if (fileName == null) {
          fileName =
              NamingUtils.toConnectorImplementationFilename(
                  implBackup.getImplementationId(), implBackup.getImplementationVersion(), true);
        }
        IRepositoryFileStore implFile = store.getChild(fileName);
        if (implFile != null) {
          implFile.save(implBackup);
        } else {
          return ValidationStatus.error(fileName + " not found in repository");
        }
      }

      for (IResource r : cleanAfterExport) {
        if (r.exists()) {
          try {
            r.delete(true, Repository.NULL_PROGRESS_MONITOR);
          } catch (CoreException e) {
            BonitaStudioLog.error(e);
          }
        }
      }
    }

    return status;
  }
  /* (non-Javadoc)
   * @see org.eclipse.jface.wizard.Wizard#performFinish()
   */
  @Override
  public boolean performFinish() {
    final TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(container);
    Data workingCopy = page.getWorkingCopy();
    setDatasourceId(workingCopy, dataContainmentFeature);
    if (editMode) {
      AbstractProcess process = ModelHelper.getParentProcess(container);
      CompoundCommand cc = new CompoundCommand();
      final RefactorDataOperation op =
          new RefactorDataOperation(BonitaGroovyRefactoringAction.REFACTOR_OPERATION);
      op.setCompoundCommand(cc);
      op.setEditingDomain(editingDomain);
      op.setContainer(process);
      op.setNewData(workingCopy);
      op.setOldData(originalData);
      op.updateReferencesInScripts();
      final boolean switchingDataeClass = !originalData.eClass().equals(workingCopy.eClass());
      op.setUpdateDataReferences(switchingDataeClass);
      if (op.isCanExecute()) {
        try {

          getContainer().run(true, false, op);

        } catch (InvocationTargetException e) {
          BonitaStudioLog.error(e);
        } catch (InterruptedException e) {
          BonitaStudioLog.error(e);
        }

        if (switchingDataeClass) {
          List<?> dataList = (List<?>) container.eGet(dataContainmentFeature);
          int index = dataList.indexOf(originalData);
          cc.append(
              RemoveCommand.create(editingDomain, container, dataContainmentFeature, originalData));
          cc.append(
              AddCommand.create(
                  editingDomain, container, dataContainmentFeature, workingCopy, index));
        } else {
          for (EStructuralFeature feature : originalData.eClass().getEAllStructuralFeatures()) {
            cc.append(
                SetCommand.create(editingDomain, originalData, feature, workingCopy.eGet(feature)));
          }
        }

        editingDomain.getCommandStack().execute(cc);
      } else {
        cc.dispose();
      }
    } else {
      editingDomain
          .getCommandStack()
          .execute(
              AddCommand.create(editingDomain, container, dataContainmentFeature, workingCopy));
    }
    try {
      RepositoryManager.getInstance()
          .getCurrentRepository()
          .getProject()
          .build(
              IncrementalProjectBuilder.FULL_BUILD,
              XtextProjectHelper.BUILDER_ID,
              Collections.EMPTY_MAP,
              null);
    } catch (CoreException e) {
      BonitaStudioLog.error(e, DataPlugin.PLUGIN_ID);
    }

    return true;
  }
  @Override
  public List<ICompletionProposal> computeCompletionProposals(
      final ContentAssistInvocationContext context, final IProgressMonitor monitor) {
    final List<ICompletionProposal> list = new ArrayList<ICompletionProposal>();
    boolean extendContext = false;
    try {
      if (context instanceof JavaContentAssistInvocationContext) {
        final ITextViewer viewer = context.getViewer();
        final List<ScriptVariable> scriptVariables = getScriptVariables(viewer);
        if (scriptVariables.isEmpty()) {
          return list;
        }
        final CompletionContext coreContext =
            ((JavaContentAssistInvocationContext) context).getCoreContext();
        if (coreContext != null && !coreContext.isExtended()) {
          // must use reflection to set the fields
          ReflectionUtils.setPrivateField(
              InternalCompletionContext.class, "isExtended", coreContext, true);
          extendContext = true;
        }
        final ICompilationUnit unit =
            ((JavaContentAssistInvocationContext) context).getCompilationUnit();
        if (unit instanceof GroovyCompilationUnit) {
          if (((GroovyCompilationUnit) unit).getModuleNode() == null) {
            return Collections.emptyList();
          }
          final ContentAssistContext assistContext =
              new GroovyCompletionProposalComputer()
                  .createContentAssistContext(
                      (GroovyCompilationUnit) unit,
                      context.getInvocationOffset(),
                      context.getDocument());
          CharSequence prefix = null;
          try {
            prefix = context.computeIdentifierPrefix();
          } catch (final BadLocationException e) {
            BonitaStudioLog.error(e);
          }

          if (assistContext != null && assistContext.completionNode instanceof VariableExpression) {
            try {
              final VariableExpression expr = (VariableExpression) assistContext.completionNode;
              if (scriptVariables != null) {
                for (final ScriptVariable f : scriptVariables) {
                  if (expr.getName().equals(f.getName())) {
                    final IType type = javaProject.findType(f.getType());
                    if (type == null) {
                      return list;
                    }
                    for (final IMethod m : type.getMethods()) {
                      if (m.getElementName().startsWith(prefix.toString())) {
                        final GroovyCompletionProposal proposal =
                            new GroovyCompletionProposal(
                                CompletionProposal.METHOD_REF, context.getInvocationOffset());
                        proposal.setName(m.getElementName().toCharArray());
                        proposal.setCompletion(
                            m.getElementName().substring(prefix.length()).toCharArray());
                        proposal.setFlags(m.getFlags());

                        if (prefix.length() == m.getElementName().length()) {
                          proposal.setReplaceRange(
                              context.getInvocationOffset(), context.getInvocationOffset());
                          proposal.setReceiverRange(0, 0);
                        } else {
                          proposal.setReplaceRange(
                              context.getInvocationOffset() - prefix.length(),
                              context.getInvocationOffset());
                          proposal.setReceiverRange(prefix.length(), prefix.length());
                        }

                        final char[][] parametersArray =
                            new char[m.getParameterNames().length][256];
                        final List<Parameter> parameters = new ArrayList<Parameter>();
                        for (int i = 0; i < m.getParameterNames().length; i++) {
                          parametersArray[i] = m.getParameterNames()[i].toCharArray();
                          parameters.add(
                              new Parameter(
                                  ClassHelper.make(
                                      Signature.getSignatureSimpleName(m.getParameterTypes()[i])),
                                  m.getParameterNames()[i]));
                        }

                        final ClassNode classNode =
                            ClassHelper.make(m.getDeclaringType().getFullyQualifiedName());
                        proposal.setDeclarationSignature(
                            ProposalUtils.createTypeSignature(classNode));
                        proposal.setParameterNames(parametersArray);
                        if (m.getDeclaringType().getFullyQualifiedName().equals(f.getType())) {
                          proposal.setRelevance(100);
                        }

                        final MethodNode methodNode =
                            new MethodNode(
                                m.getElementName(),
                                m.getFlags(),
                                ClassHelper.make(
                                    Signature.getSignatureSimpleName(m.getReturnType())),
                                parameters.toArray(new Parameter[parameters.size()]),
                                new ClassNode[0],
                                null);
                        final char[] methodSignature =
                            ProposalUtils.createMethodSignature(methodNode);
                        proposal.setSignature(methodSignature);

                        final GroovyJavaGuessingCompletionProposal groovyProposal =
                            GroovyJavaGuessingCompletionProposal.createProposal(
                                proposal,
                                (JavaContentAssistInvocationContext) context,
                                true,
                                "Groovy",
                                ProposalFormattingOptions.newFromOptions());
                        if (groovyProposal != null) {
                          list.add(groovyProposal);
                        }
                      }
                    }
                  }
                }
              }
            } catch (final JavaModelException e) {
              BonitaStudioLog.error(e);
            }
          }
        }

        return list;
      }
    } finally {
      final CompletionContext coreContext =
          ((JavaContentAssistInvocationContext) context).getCoreContext();
      if (extendContext && coreContext != null && coreContext.isExtended()) {
        // must use reflection to set the fields
        ReflectionUtils.setPrivateField(
            InternalCompletionContext.class, "isExtended", coreContext, false);
      }
    }

    return Collections.emptyList();
  }