public static String copyWSASWar(IProgressMonitor monitor, String wsasHome)
      throws FileNotFoundException, IOException {
    String tempWarFile = null;
    String tempWarLocation = null;
    String tempUnzipLocation = null;
    try {
      if (new File(WSASCoreUtils.tempWSASDirectory()).isDirectory()) {
        tempWarLocation =
            WSASCoreUtils.addAnotherNodeToPath(
                WSASCoreUtils.tempWSASDirectory(), WSASCoreUIMessages.DIR_TEMPWAR);
        File tempWarLocationFile = new File(tempWarLocation);
        if (tempWarLocationFile.exists()) {
          FileUtils.deleteDirectories(tempWarLocationFile);
        }
        tempWarLocationFile.mkdirs();
        tempWarFile =
            WSASCoreUtils.addAnotherNodeToPath(tempWarLocation, WSASCoreUIMessages.FILE_WSAS_WAR);
        new File(tempWarFile).createNewFile();
        Properties properties = new Properties();
        //			properties.load(new FileInputStream(WSASCoreUtils.tempWSASWebappFileLocation()));
        //				if (properties.containsKey(WSASCoreUIMessages.PROPERTY_KEY_PATH)){
        if (ServerModel.getWsasServerPath() != null) {
          String wsasWarFile =
              WSASCoreUtils.addAnotherNodeToPath(
                  (ServerModel.getWsasServerPath() != null)
                      ? ServerModel.getWsasServerPath()
                      : properties.getProperty(WSASCoreUIMessages.PROPERTY_KEY_PATH),
                  WSASCoreUIMessages.FILE_WSAS_WAR);
          FileChannel srcChannel = new FileInputStream(wsasWarFile).getChannel();
          FileChannel dstChannel = new FileOutputStream(tempWarFile).getChannel();
          // Copy file contents from source to destination
          dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
          // Close the channels
          srcChannel.close();
          dstChannel.close();

          // unzip this into another foulder
          tempUnzipLocation =
              FileUtils.addAnotherNodeToPath(tempWarLocation, WSASCoreUIMessages.DIR_UNZIP);
          File tempUnzipLocationFile = new File(tempUnzipLocation);
          if (!tempUnzipLocationFile.exists()) {
            tempUnzipLocationFile.mkdirs();
          }
          unzipWSASWar(tempWarFile, tempUnzipLocation);
        }

      } else {
        // Throws an error message
      }
    } catch (FileNotFoundException e) {
      throw e;
    } catch (IOException e) {
      throw e;
    }

    return tempUnzipLocation;
  }
 public void openEditor(File file) {
   try {
     refreshDistProjects();
     OMElement documentElement = new StAXOMBuilder(new FileInputStream(file)).getDocumentElement();
     OMElement firstElement = documentElement.getFirstElement();
     String templateType = "template.sequence";
     if ("endpoint".equals(firstElement.getLocalName())) {
       templateType = "template.endpoint";
       String localName = firstElement.getFirstElement().getLocalName();
       if ("address".equals(localName)) {
         templateType = templateType + "-1";
       } else if ("wsdl".equals(localName)) {
         templateType = templateType + "-2";
       } else {
         templateType = templateType + "-0";
       }
     }
     IFile dbsFile =
         ResourcesPlugin.getWorkspace()
             .getRoot()
             .getFileForLocation(Path.fromOSString(file.getAbsolutePath()));
     String path = dbsFile.getParent().getFullPath() + "/";
     String source = FileUtils.getContentAsString(file);
     Openable openable = ESBGraphicalEditor.getOpenable();
     openable.editorOpen(file.getName(), templateType, path + "template_", source);
   } catch (Exception e) {
     log.error("Cannot open the editor", e);
   }
 }
  public static ESBArtifact getESBArtifactFromFile(
      IFile refactoredFile, String projectNatureFilter) {
    IProject esbProject = refactoredFile.getProject();
    try {
      esbProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());

      if (esbProject.isOpen() && esbProject.hasNature(projectNatureFilter)) {

        ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact();
        esbProjectArtifact.fromFile(esbProject.getFile("artifact.xml").getLocation().toFile());
        List<ESBArtifact> allESBArtifacts = esbProjectArtifact.getAllESBArtifacts();

        String originalFileRelativePath =
            FileUtils.getRelativePath(
                    esbProject.getLocation().toFile(), refactoredFile.getLocation().toFile())
                .replaceAll(Pattern.quote(File.separator), "/");

        for (ESBArtifact esbArtifact : allESBArtifacts) {
          if (esbArtifact.getFile().equals(originalFileRelativePath)) {
            return esbArtifact;
          }
        }
      }
    } catch (CoreException e) {
      log.error("Error while reading ESB Project", e);
    } catch (FactoryConfigurationError e) {
      log.error("Error while reading ESB Project", e);
    } catch (Exception e) {
      log.error("Error while reading ESB Project", e);
    }

    return null;
  }
 public void copyImportFile(IContainer importLocation, boolean isNewAritfact, String groupId)
     throws IOException {
   File importFile = getModel().getImportFile();
   File destFile = null;
   List<OMElement> selectedSeqList = ((TemplateModel) getModel()).getSelectedTempSequenceList();
   if (selectedSeqList != null && selectedSeqList.size() > 0) {
     for (OMElement element : selectedSeqList) {
       String name = element.getAttributeValue(new QName("name"));
       destFile = new File(importLocation.getLocation().toFile(), name + ".xml");
       FileUtils.createFile(destFile, element.toString());
       fileLst.add(destFile);
       if (isNewAritfact) {
         ESBArtifact artifact = new ESBArtifact();
         artifact.setName(name);
         artifact.setVersion(version);
         artifact.setType("synapse/template");
         artifact.setServerRole("EnterpriseServiceBus");
         artifact.setGroupId(groupId);
         artifact.setFile(
             FileUtils.getRelativePath(
                     importLocation.getProject().getLocation().toFile(),
                     new File(importLocation.getLocation().toFile(), name + ".xml"))
                 .replaceAll(Pattern.quote(File.separator), "/"));
         esbProjectArtifact.addESBArtifact(artifact);
       }
     }
   } else {
     destFile = new File(importLocation.getLocation().toFile(), importFile.getName());
     FileUtils.copy(importFile, destFile);
     fileLst.add(destFile);
     String name = importFile.getName().replaceAll(".xml$", "");
     if (isNewAritfact) {
       ESBArtifact artifact = new ESBArtifact();
       artifact.setName(name);
       artifact.setVersion(version);
       artifact.setType("synapse/template");
       artifact.setServerRole("EnterpriseServiceBus");
       artifact.setGroupId(groupId);
       artifact.setFile(
           FileUtils.getRelativePath(
                   importLocation.getProject().getLocation().toFile(),
                   new File(importLocation.getLocation().toFile(), name + ".xml"))
               .replaceAll(Pattern.quote(File.separator), "/"));
       esbProjectArtifact.addESBArtifact(artifact);
     }
   }
 }
  @Override
  protected File processTokenReplacement(Artifact artifact) {
    File file = artifact.getFile();
    if (file.exists()) {
      String fileContent;
      StringBuffer sb = new StringBuffer();
      try {
        fileContent =
            org.wso2.developerstudio.eclipse.utils.file.FileUtils.getContentAsString(file);
        // StringTokenizer st=new StringTokenizer(fileContent,
        // CAppMavenUtils.REPLACER_DEFAULT_DELIMETER);

        Properties mavenProperties = getProject().getModel().getProperties();
        // Check whether the content actually has tokens and Properties section should define them.
        // Otherwise skip.
        // By default there are 2 such properties. So size check is 2.
        /*if (st.countTokens()>1 && mavenProperties.size()>1) {
        	while (st.hasMoreTokens()) {
        		String nextToken = st.nextToken();
        		if (mavenProperties.containsKey(nextToken)) {
        			String originalToken = nextToken;
        			nextToken = (String) mavenProperties.get(nextToken);
        			getLog().info("Replacing the token: "+originalToken+" with value: "+nextToken);
        		}
        		sb.append(nextToken);
        	}
        }else{
        	sb.append(fileContent);
        }*/

        String newFileContent = replaceTokens(fileContent, mavenProperties);
        File tempFile = org.wso2.developerstudio.eclipse.utils.file.FileUtils.createTempFile();
        // org.wso2.developerstudio.eclipse.utils.file.FileUtils.writeContent(tempFile,
        // sb.toString());
        org.wso2.developerstudio.eclipse.utils.file.FileUtils.writeContent(
            tempFile, newFileContent);
        return tempFile;
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return file;
  }
 protected void copyResources(MavenProject project, File projectLocation, Artifact artifact)
     throws IOException {
   ITemporaryFileTag newTag =
       org.wso2.developerstudio.eclipse.utils.file.FileUtils.createNewTempTag();
   File sequenceArtifact = processTokenReplacement(artifact);
   if (sequenceArtifact == null) {
     sequenceArtifact = artifact.getFile();
   }
   FileUtils.copyFile(sequenceArtifact, new File(projectLocation, artifact.getFile().getName()));
   newTag.clearAndEnd();
 }
  public List<IResource> exportArtifact(IProject project) throws Exception {
    String projectPath = project.getLocation().toFile().toString();
    List<IResource> exportResources = new ArrayList<IResource>();
    clearTarget(project);
    IFile pomFile = project.getFile("pom.xml");

    if (pomFile.exists()) {
      MavenProject mavenProject = MavenUtils.getMavenProject(pomFile.getLocation().toFile());
      List<Plugin> plugins = mavenProject.getBuild().getPlugins();
      for (Plugin plugin : plugins) {
        if (plugin.getArtifactId().equals("maven-dataservice-plugin")
            && plugin.getGroupId().equals("org.wso2.maven")) {
          Xpp3Dom artifactNode = ((Xpp3Dom) plugin.getConfiguration()).getChild("artifact");
          String dbsFile = artifactNode.getValue();
          String[] pathArray = dbsFile.split("/");
          IFile dbsFileRef =
              project
                  .getFolder("src")
                  .getFolder("main")
                  .getFolder("dataservice")
                  .getFile(pathArray[pathArray.length - 1]);
          if (dbsFileRef.exists()) {
            exportResources.add((IResource) dbsFileRef);
          }
        }
      }
    } else {
      File[] dbsFiles =
          FileUtils.getAllMatchingFiles(
              project.getLocation().toString(), null, DBS_FILE_EXTENSION, new ArrayList<File>());
      for (File dbsFile : dbsFiles) {
        String filePath = dbsFile.toString();
        // excluded any files inside target dir
        if (!filePath
            .substring(projectPath.length())
            .startsWith(File.separator + "target" + File.separator)) {
          IFile dbsFileRef =
              ResourcesPlugin.getWorkspace()
                  .getRoot()
                  .getFileForLocation(Path.fromOSString(dbsFile.getAbsolutePath()));
          exportResources.add((IResource) dbsFileRef);
        }
      }
    }

    return exportResources;
  }
  public void publish(IProject project, IServer server, File serverHome, File deployLocation)
      throws Exception {
    if (project.hasNature("org.wso2.developerstudio.eclipse.distribution.project.nature")) {

      URL serverURL = CarbonServerManager.getServerURL(server);
      ICredentials serverCredentials = CarbonServerManager.getServerCredentials(server);
      File tempDir = FileUtils.createTempDirectory();
      CAppDeployer cappDeployer = new CAppDeployer();
      //	        File carFile = CAppUtils.generateCAR(tempDir.getPath(), project, false);
      CarExportHandler handler = new CarExportHandler();
      List<IResource> exportArtifact = handler.exportArtifact(project);
      cappDeployer.deployCApp(
          serverCredentials.getUsername(),
          serverCredentials.getPassword(),
          serverURL.toString(),
          ((IFile) exportArtifact.get(0)).getLocation().toFile());
    }
  }
  public void openEditor(File file) {
    try {
      refreshDistProjects();
      OMElement documentElement = new StAXOMBuilder(new FileInputStream(file)).getDocumentElement();
      String templateType = "";

      if (documentElement.getChildrenWithName(new QName("endpoint")) != null
          && documentElement.getChildrenWithName(new QName("endpoint")).hasNext()) {
        // Endpoint template.
        templateType = ArtifactType.TEMPLATE_ENDPOINT.getLiteral();
        OMElement endpoint =
            (OMElement) documentElement.getChildrenWithName(new QName("endpoint")).next();
        String localName = endpoint.getFirstElement().getLocalName();
        if ("address".equals(localName)) {
          // Address endpoint template.
          templateType = ArtifactType.TEMPLATE_ENDPOINT_ADDRESS.getLiteral();
        } else if ("wsdl".equals(localName)) {
          // WSDL endpoint template.
          templateType = ArtifactType.TEMPLATE_ENDPOINT_WSDL.getLiteral();
        } else if ("http".equals(localName)) {
          // HTTP endpoint template.
          templateType = ArtifactType.TEMPLATE_ENDPOINT_HTTP.getLiteral();
        } else {
          // Default endpoint template.
          templateType = ArtifactType.TEMPLATE_ENDPOINT_DEFAULT.getLiteral();
        }
      } else {
        // Sequence template.
        templateType = ArtifactType.TEMPLATE_SEQUENCE.getLiteral();
      }

      IFile dbsFile =
          ResourcesPlugin.getWorkspace()
              .getRoot()
              .getFileForLocation(Path.fromOSString(file.getAbsolutePath()));
      String path = dbsFile.getParent().getFullPath() + "/";
      String source = FileUtils.getContentAsString(file);
      Openable openable = ESBGraphicalEditor.getOpenable();
      openable.editorOpen(file.getName(), templateType, path, source);
    } catch (Exception e) {
      log.error("Cannot open the editor", e);
    }
  }
 public static String[] getServerLibraryPaths(IServer server) throws Exception {
   String[] result = null;
   if (server != null) {
     IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
     HashMap<String, Object> operationParameters = new HashMap<String, Object>();
     operationParameters.put(
         ICarbonOperationManager.PARAMETER_TYPE,
         ICarbonOperationManager.OPERATION_GET_LIBRARY_PATHS);
     Object r =
         wsasServerManager.executeOperationOnServer(
             server, operationParameters); // getWSDLConversionResultUrl(resourceFile);
     if (r instanceof String[]) {
       result = (String[]) r;
       IPath serverLocation = getServerHome(server);
       for (int i = 0; i < result.length; i++) {
         result[i] = FileUtils.addAnotherNodeToPath(serverLocation.toOSString(), result[i]);
       }
     }
   }
   return result;
 }
  public List<IResource> exportArtifact(IProject project) throws Exception {
    List<IResource> exportResources = new ArrayList<IResource>();
    List<String> exportedPackageList = new ArrayList<String>();
    List<String> importededPackageList = new ArrayList<String>();

    ArchiveManipulator archiveManipulator = new ArchiveManipulator();
    NullProgressMonitor nullProgressMonitor = new NullProgressMonitor();
    BundlesDataInfo bundleData = new BundlesDataInfo();
    IFile bundleDataFile = project.getFile("bundles-data.xml");
    File tempProject = createTempProject();
    File libResources = createTempDir(tempProject, "lib_resources");
    MavenProject mavenProject =
        MavenUtils.getMavenProject(project.getFile("pom.xml").getLocation().toFile());

    if (bundleDataFile.exists()) {
      bundleData.deserialize(bundleDataFile);

      for (String lib : bundleData.getExportedPackageListsFromJar().keySet()) {
        IFile JarFile = project.getFile(lib);
        if (JarFile.exists()) {
          archiveManipulator.extract(JarFile.getLocation().toFile(), libResources);
          exportedPackageList.addAll(bundleData.getExportedPackageListsFromJar().get(lib));
        }
      }
      for (IProject lib : bundleData.getExportedPackageListsFromProject().keySet()) {
        if (lib.isOpen()) {
          lib.build(IncrementalProjectBuilder.FULL_BUILD, nullProgressMonitor);
          IJavaProject javaLibProject = JavaCore.create(lib);
          for (IPackageFragment pkg : javaLibProject.getPackageFragments()) {
            if (pkg.getKind() == IPackageFragmentRoot.K_SOURCE) {
              if (pkg.hasChildren()) {
                exportedPackageList.add(pkg.getElementName());
              }
            }
          }

          IPath outPutPath = getOutputPath(javaLibProject);
          // get resource location
          IPath resources = getResourcePath(lib);

          FileUtils.copyDirectoryContents(outPutPath.toFile(), libResources);
          if (resources.toFile().exists()) {
            FileUtils.copyDirectoryContents(resources.toFile(), libResources);
          }
        }
      }
      getPackages(exportedPackageList, mavenProject, "Export-Package");
      getPackages(importededPackageList, mavenProject, "Import-Package");
      BundleManifest manifest = new BundleManifest();
      manifest.setBundleName(project.getName());
      manifest.setBundleSymbolicName(project.getName());
      if (null != mavenProject.getModel().getDescription()
          && !"".equals(mavenProject.getModel().getDescription())) {
        manifest.setBundleDescription(mavenProject.getModel().getDescription());
      } else {
        manifest.setBundleDescription(project.getName());
      }
      if (null != mavenProject.getModel().getVersion()
          && !"".equals(mavenProject.getDescription())) {
        manifest.setBundleVersion(mavenProject.getModel().getVersion());
      } else {
        manifest.setBundleVersion("1.0.0");
      }
      if (null != bundleData.getFragmentHost() && !"".equals(bundleData.getFragmentHost())) {
        manifest.setFragmentHost(bundleData.getFragmentHost());
      }
      manifest.setExportPackagesList(exportedPackageList);
      if (importededPackageList.size() > 0) {
        manifest.setImportPackagesList(importededPackageList);
        manifest.setDynamicImports(false);
      }
      File metaInfDir = new File(libResources, "META-INF");
      if (!metaInfDir.exists()) metaInfDir.mkdir();
      File manifestFile = new File(metaInfDir, "MANIFEST.MF");
      FileUtils.createFile(manifestFile, manifest.toString());

      File tmpArchive = new File(tempProject, project.getName().concat(".jar"));
      archiveManipulator.archiveDir(tmpArchive.toString(), libResources.toString());

      IFile libArchive = getTargetArchive(project, "jar");
      FileUtils.copy(tmpArchive, libArchive.getLocation().toFile());
      exportResources.add((IResource) libArchive);

      // cleaning temp project
      // if(!org.apache.commons.io.FileUtils.deleteQuietly(tempProject.getLocation().toFile())){
      // tempProject.delete(true, getProgressMonitor());
    }

    TempFileUtils.cleanUp();
    return exportResources;
  }
  public boolean createFiles(EObject endpoint, String name, String fileURI1, String fileURI2) {
    /*		Resource diagram;
    String basePath = "platform:/resource/" + currentProject.getName()
    		+ "/" + COMPLEX_ENDPOINT_RESOURCE_DIR  + "/";*/
    IProject currentProject = getActiveProject();
    /*		IFile file = currentProject.getFile(COMPLEX_ENDPOINT_RESOURCE_DIR + "/"
    + fileURI1);*/

    IFile fileTobeOpened = null;
    // if (!file.exists()) {
    try {
      IFolder iFolder = currentProject.getFolder(SYNAPSE_CONFIG_DIR + "/complex-endpoints/");
      if (!iFolder.exists()) {
        iFolder.create(IResource.NONE, true, null);
      }
      fileTobeOpened =
          iFolder.getFile(
              name
                  + ".xml"); // currentProject.getFile(SYNAPSE_CONFIG_DIR + "/complex-endpoints/" +
                             // name + ".xml");

      if (fileTobeOpened.exists()) {
        OpenEditorUtils oeUtils = new OpenEditorUtils();
        oeUtils.openSeparateEditor(fileTobeOpened);
      } else {
        String path = fileTobeOpened.getParent().getFullPath() + "/";
        ArtifactTemplate complexEndpointArtifactTemplate = null;
        ArtifactTemplate[] endpointTemplates = getEndpointTemplates();
        if (endpoint instanceof FailoverEndPoint) {
          complexEndpointArtifactTemplate = endpointTemplates[4];
        } else if (endpoint instanceof LoadBalanceEndPoint) {
          complexEndpointArtifactTemplate = endpointTemplates[5];
        } else if (endpoint instanceof RecipientListEndPoint) {
          complexEndpointArtifactTemplate = endpointTemplates[6];
        }
        fileTobeOpened.create(
            complexEndpointArtifactTemplate.getTemplateDataStream(),
            true,
            new NullProgressMonitor());
        String source =
            org.wso2.developerstudio.eclipse.utils.file.FileUtils.getContentAsString(
                complexEndpointArtifactTemplate.getTemplateDataStream());
        source = source.replaceAll("\\{", "<").replaceAll("\\}", ">");
        source = StringUtils.replace(source, "<ep.name>", name);
        source = MessageFormat.format(source, name);
        Openable openable = ESBGraphicalEditor.getOpenable();
        openable.editorOpen(
            fileTobeOpened.getName(), ArtifactType.ENDPOINT.getLiteral(), path, source);
      }
    } catch (Exception e) {
      log.error("Cannot open file " + fileTobeOpened, e);
      return false;
    }
    String path = fileTobeOpened.getParent().getFullPath() + "/";

    /*			diagram = EsbDiagramEditorUtil.createResource(
    URI.createURI(basePath + fileURI1),
    URI.createURI(basePath + fileURI2),
    new NullProgressMonitor(), "complex_endpoint", name, null);*/
    /*			String source;
    try {
    	source = FileUtils.readFileToString(fileTobeOpened.getLocation().toFile());
    	Openable openable = ESBGraphicalEditor.getOpenable();
    	openable.editorOpen(fileTobeOpened.getName(), ArtifactType.COMPLEX_ENDPOINT.getLiteral(), path, source);
    } catch (IOException e1) {
    	log.error("Error while reading the file : "+fileTobeOpened, e1);
    	return false;
    } catch (Exception e) {
    	log.error("Error while opening the file : "+fileTobeOpened, e);
    	return false;
    }	*/
    /*			try {
    	EsbDiagramEditorUtil.openDiagram(diagram);

    } catch (PartInitException e) {
    	log.error("Cannot init editor", e);
    }*/
    return true;
    // }

    /*		else {
    	IWorkbenchPage page = PlatformUI.getWorkbench()
    			.getActiveWorkbenchWindow().getActivePage();
    	IEditorDescriptor desc = PlatformUI.getWorkbench()
    			.getEditorRegistry().getDefaultEditor(file.getName());
    	try {
    		page.openEditor(new FileEditorInput(file), desc.getId());
    	} catch (PartInitException e) {
    		log.error("Cannot init editor", e);
    	}
    	return true;
    }*/
  }
  private boolean createSequenceArtifact(TemplateModel sequenceModel) throws Exception {
    boolean isNewArtifact = true;
    IContainer location =
        project.getFolder(
            "src"
                + File.separator
                + "main"
                + File.separator
                + "synapse-config"
                + File.separator
                + "templates");
    esbProjectArtifact = new ESBProjectArtifact();
    esbProjectArtifact.fromFile(project.getFile("artifact.xml").getLocation().toFile());
    File pomfile = project.getFile("pom.xml").getLocation().toFile();
    getModel().getMavenInfo().setPackageName("synapse/template");
    if (!pomfile.exists()) {
      createPOM(pomfile);
    }

    updatePom();
    project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
    String groupId = getMavenGroupId(pomfile);
    groupId += ".template";

    if (getModel().getSelectedOption().equals("import.template")) {
      IFile sequence = location.getFile(new Path(getModel().getImportFile().getName()));
      if (sequence.exists()) {
        if (!MessageDialog.openQuestion(
            getShell(), "WARNING", "Do you like to override exsiting project in the workspace")) {
          return false;
        }
        isNewArtifact = false;
      }
      copyImportFile(location, isNewArtifact, groupId);
    } else {
      String templateContent = "";
      String template = "";
      ArtifactTemplate selectedTemplate = templateModel.getSelectedTemplate();
      templateContent = FileUtils.getContentAsString(selectedTemplate.getTemplateDataStream());

      if (selectedTemplate.getName().equals("Address Endpoint Template")) {
        template = createEPTemplate(templateContent, "Address Endpoint Template");
      } else if (selectedTemplate.getName().equals("WSDL Endpoint Template")) {
        template = createEPTemplate(templateContent, "WSDL Endpoint Template");
      } else if (selectedTemplate.getName().equals("Default Endpoint Template")) {
        template = createEPTemplate(templateContent, "Default Endpoint Template");
      } else if (selectedTemplate.getName().equals("Sequence Template")) {
        template = createEPTemplate(templateContent, "Sequence Template");
      } else if (selectedTemplate.getName().equals("HTTP Endpoint Template")) {
        template = createEPTemplate(templateContent, "HTTP Endpoint Template");
      } else {
        template = createEPTemplate(templateContent, "");
      }

      File destFile =
          new File(location.getLocation().toFile(), sequenceModel.getTemplateName() + ".xml");
      FileUtils.createFile(destFile, template);
      fileLst.add(destFile);
      ESBArtifact artifact = new ESBArtifact();
      artifact.setName(sequenceModel.getTemplateName());
      artifact.setVersion(version);
      if ("Sequence Template".equals(selectedTemplate.getName())) {
        artifact.setType("synapse/sequenceTemplate");
      } else {
        artifact.setType("synapse/endpointTemplate");
      }
      artifact.setServerRole("EnterpriseServiceBus");
      artifact.setGroupId(groupId);
      artifact.setFile(
          FileUtils.getRelativePath(
                  project.getLocation().toFile(),
                  new File(
                      location.getLocation().toFile(), sequenceModel.getTemplateName() + ".xml"))
              .replaceAll(Pattern.quote(File.separator), "/"));
      esbProjectArtifact.addESBArtifact(artifact);
    }
    esbProjectArtifact.toFile();
    project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
    return true;
  }
  public List<IResource> exportArtifact(IProject project) {
    List<IResource> exportResources = new ArrayList<IResource>();
    if (!project.isOpen()) {
      return exportResources;
    }

    try {
      ArchiveManipulator archiveManipulator = new ArchiveManipulator();
      NullProgressMonitor nullProgressMonitor = new NullProgressMonitor();
      // cleaning target directory
      clearTarget(project);
      project.build(IncrementalProjectBuilder.FULL_BUILD, nullProgressMonitor);
      IJavaProject javaProject = JavaCore.create(project);

      List<String> exportPac = getExportPackages(javaProject);
      BundleManifest manifest = new BundleManifest();
      manifest.setBundleName(project.getName());
      manifest.setBundleSymbolicName(project.getName());
      manifest.setBundleDescription(project.getName());
      manifest.setBundleVersion("2.0");
      manifest.setExportPackagesList(exportPac);
      // IPath outPutPath = javaProject.getOutputLocation();
      IPath outPutPath =
          ResourcesPlugin.getWorkspace()
              .getRoot()
              .getFolder(javaProject.getOutputLocation())
              .getLocation();
      // Let's create a temp project
      IProject tempProject =
          ResourcesPlugin.getWorkspace().getRoot().getProject(".temp" + System.currentTimeMillis());
      tempProject.create(nullProgressMonitor);
      tempProject.open(nullProgressMonitor);
      tempProject.setHidden(true);
      org.eclipse.osgi.storagemanager.StorageManager manager =
          new StorageManager(tempProject.getLocation().toFile(), "false");

      File validatorResource = manager.createTempFile("validator_resources");
      validatorResource.delete();
      validatorResource.mkdir();
      FileUtils.copyDirectoryContents(outPutPath.toFile(), validatorResource); // copy binaries

      /////////////////////// Create the Bundle*********************************

      File metainfPath = new File(validatorResource, "META-INF");
      metainfPath.mkdir();
      File manifestFile = new File(metainfPath, "MANIFEST.MF");
      FileUtils.createFile(manifestFile, manifest.toString());
      File tmpArchive =
          new File(tempProject.getLocation().toFile(), project.getName().concat(".jar"));
      archiveManipulator.archiveDir(tmpArchive.toString(), validatorResource.toString());
      IFolder binaries = project.getFolder("target");
      if (!binaries.exists()) {
        binaries.create(true, true, nullProgressMonitor);
        binaries.setHidden(true);
      }
      IFile serviceArchive =
          project.getFile("target" + File.separator + project.getName().concat(".jar"));
      FileUtils.copy(tmpArchive, serviceArchive.getLocation().toFile());
      exportResources.add((IResource) serviceArchive);
      // cleaning temp project
      tempProject.delete(true, nullProgressMonitor);

    } catch (Exception e) {
      e.printStackTrace();
    }
    return exportResources;
  }