public static String getTempJarPath(IModule module) throws CoreException {
    try {
      File tempFolder =
          File.createTempFile(
              "tempFolderForJavaAppJar", //$NON-NLS-1$
              null);
      tempFolder.delete();
      tempFolder.mkdirs();

      if (!tempFolder.exists()) {
        throw CloudErrorUtil.toCoreException(
            NLS.bind(
                Messages.JavaCloudFoundryArchiver_ERROR_CREATE_TEMP_DIR, tempFolder.getPath()));
      }

      File targetFile = new File(tempFolder, module.getName() + ".jar"); // $NON-NLS-1$
      targetFile.deleteOnExit();

      String path = new Path(targetFile.getAbsolutePath()).toString();

      return path;

    } catch (IOException io) {
      CloudErrorUtil.toCoreException(io);
    }
    return null;
  }
 protected void handleApplicationDeploymentFailure(String errorMessage) throws CoreException {
   if (errorMessage == null) {
     errorMessage = Messages.JavaCloudFoundryArchiver_ERROR_CREATE_PACKAGED_FILE;
   }
   throw CloudErrorUtil.toCoreException(
       errorMessage
           + " - " //$NON-NLS-1$
           + appModule.getDeployedApplicationName()
           + ". Unable to package application for deployment."); //$NON-NLS-1$
 }
  protected CFServiceInstance createCloudService(String name, String label, String plan)
      throws CoreException {
    CFServiceInstance toCreate = getCloudServiceToCreate(name, label, plan);

    if (toCreate == null) {
      throw CloudErrorUtil.toCoreException(
          "Unable to create service : " + label + ". Service does not exist in the Cloud space.");
    }

    createService(toCreate);
    return toCreate;
  }
  /**
   * Returns non-null Cloud application module mapped to the first module in the list of modules. If
   * the cloud module module does not exist for the given module, it will attempt to create it. To
   * avoid re-creating a cloud application module that may have been deleted, restrict invoking this
   * method to only operations that start, restart, or update an application. Should not be called
   * when deleting an application.
   *
   * @param local WST modules representing app to be deployed.
   * @return non-null Cloud Application module mapped to the given WST module.
   * @throws CoreException if no modules specified or mapped cloud application module cannot be
   *     resolved.
   */
  protected CloudFoundryApplicationModule getOrCreateCloudApplicationModule(IModule[] modules)
      throws CoreException {

    IModule module = modules[0];

    CloudFoundryServer cloudServer = getBehaviour().getCloudFoundryServer();

    CloudFoundryApplicationModule appModule = cloudServer.getCloudModule(module);

    if (appModule == null) {
      throw CloudErrorUtil.toCoreException(
          NLS.bind(INTERNAL_ERROR_NO_MAPPED_CLOUD_MODULE, modules[0].getId()));
    }

    return appModule;
  }
  public ApplicationArchive getApplicationArchive(IProgressMonitor monitor) throws CoreException {

    if (!initialized) {
      // Seems like initialize() wasn't invoked prior to this call
      throw CloudErrorUtil.toCoreException(
          Messages.JavaCloudFoundryArchiver_ERROR_ARCHIVER_NOT_INITIALIZED);
    }

    ApplicationArchive archive =
        JavaWebApplicationDelegate.getArchiveFromManifest(appModule, cloudServer);

    if (archive == null) {

      File packagedFile = null;

      IJavaProject javaProject = CloudFoundryProjectUtil.getJavaProject(appModule);

      if (javaProject == null) {
        handleApplicationDeploymentFailure(
            Messages.JavaCloudFoundryArchiver_ERROR_NO_JAVA_PROJ_RESOLVED);
      }

      JavaPackageFragmentRootHandler rootResolver =
          getPackageFragmentRootHandler(javaProject, monitor);

      IType mainType = rootResolver.getMainType(monitor);

      final IPackageFragmentRoot[] roots = rootResolver.getPackageFragmentRoots(monitor);

      if (roots == null || roots.length == 0) {
        handleApplicationDeploymentFailure(
            Messages.JavaCloudFoundryArchiver_ERROR_NO_PACKAGE_FRAG_ROOTS);
      }

      JarPackageData jarPackageData = getJarPackageData(roots, mainType, monitor);

      boolean isBoot = CloudFoundryProjectUtil.isSpringBoot(appModule);

      // Search for existing MANIFEST.MF
      IFile metaFile = getManifest(roots, javaProject);

      // Only use existing manifest files for non-Spring boot, as Spring
      // boot repackager will
      // generate it own manifest file.
      if (!isBoot && metaFile != null) {
        // If it is not a boot project, use a standard library jar
        // builder
        jarPackageData.setJarBuilder(getDefaultLibJarBuilder());

        jarPackageData.setManifestLocation(metaFile.getFullPath());
        jarPackageData.setSaveManifest(false);
        jarPackageData.setGenerateManifest(false);
        // Check manifest accessibility through the jar package data
        // API
        // to verify the packaging won't fail
        if (!jarPackageData.isManifestAccessible()) {
          handleApplicationDeploymentFailure(
              NLS.bind(
                  Messages.JavaCloudFoundryArchiver_ERROR_MANIFEST_NOT_ACCESSIBLE,
                  metaFile.getLocation().toString()));
        }

        InputStream inputStream = null;
        try {

          inputStream = new FileInputStream(metaFile.getLocation().toFile());
          Manifest manifest = new Manifest(inputStream);
          Attributes att = manifest.getMainAttributes();
          if (att.getValue("Main-Class") == null) { // $NON-NLS-1$
            handleApplicationDeploymentFailure(
                Messages.JavaCloudFoundryArchiver_ERROR_NO_MAIN_CLASS_IN_MANIFEST);
          }
        } catch (FileNotFoundException e) {
          handleApplicationDeploymentFailure(
              NLS.bind(
                  Messages.JavaCloudFoundryArchiver_ERROR_FAILED_READ_MANIFEST,
                  e.getLocalizedMessage()));

        } catch (IOException e) {
          handleApplicationDeploymentFailure(
              NLS.bind(
                  Messages.JavaCloudFoundryArchiver_ERROR_FAILED_READ_MANIFEST,
                  e.getLocalizedMessage()));

        } finally {

          if (inputStream != null) {
            try {
              inputStream.close();

            } catch (IOException io) {
              // Ignore
            }
          }
        }

      } else {
        // Otherwise generate a manifest file. Note that manifest files
        // are only generated in the temporary jar meant only for
        // deployment.
        // The associated Java project is no modified.
        jarPackageData.setGenerateManifest(true);

        // This ensures that folders in output folders appear at root
        // level
        // Example: src/main/resources, which is in the project's
        // classpath, contains non-Java templates folder and
        // has output folder target/classes. If not exporting output
        // folder,
        // templates will be packaged in the jar using this path:
        // resources/templates
        // This may cause problems with the application's dependencies
        // if they are looking for just /templates at top level of the
        // jar
        // If exporting output folders, templates folder will be
        // packaged at top level in the jar.
        jarPackageData.setExportOutputFolders(true);
      }

      try {
        packagedFile = packageApplication(jarPackageData, monitor);
      } catch (CoreException e) {
        handleApplicationDeploymentFailure(
            NLS.bind(Messages.JavaCloudFoundryArchiver_ERROR_JAVA_APP_PACKAGE, e.getMessage()));
      }

      if (packagedFile == null || !packagedFile.exists()) {
        handleApplicationDeploymentFailure(
            Messages.JavaCloudFoundryArchiver_ERROR_NO_PACKAGED_FILE_CREATED);
      }

      if (isBoot) {
        bootRepackage(roots, packagedFile);
      }

      // At this stage a packaged file should have been created or found
      try {
        archive = new CloudZipApplicationArchive(new ZipFile(packagedFile));
      } catch (IOException ioe) {
        handleApplicationDeploymentFailure(
            NLS.bind(Messages.JavaCloudFoundryArchiver_ERROR_CREATE_CF_ARCHIVE, ioe.getMessage()));
      }
    }

    return archive;
  }
  protected DebugConnectionDescriptor getSshConnectionDescriptor(
      CloudFoundryApplicationModule appModule,
      CloudFoundryServer cloudServer,
      int appInstance,
      int remoteDebugPort,
      IProgressMonitor monitor)
      throws CoreException {

    CFInfo cloudInfo = cloudServer.getBehaviour().getCloudInfo();
    if (cloudInfo instanceof CloudInfoSsh) {
      ISshClientSupport ssh = cloudServer.getBehaviour().getSshClientSupport(monitor);
      if (ssh == null) {
        return null;
      }
      try {
        printToConsole(
            appModule,
            cloudServer,
            NLS.bind(
                Messages.SshDebugLaunchConfigDelegate_CONNECTING_FOR_USER,
                appModule.getDeployedApplicationName()),
            false);

        Session session =
            ssh.connect(
                appModule.getDeployedApplicationName(),
                appInstance,
                cloudServer.getServer(),
                monitor);

        printToConsole(
            appModule,
            cloudServer,
            NLS.bind(
                Messages.SshDebugLaunchConfigDelegate_CONNECTION_SUCCESSFUL,
                appModule.getDeployedApplicationName()),
            false);

        int localDebuggerPort =
            session.setPortForwardingL(0, "localhost", remoteDebugPort); // $NON-NLS-1$

        printToConsole(
            appModule,
            cloudServer,
            NLS.bind(
                Messages.SshDebugLaunchConfigDelegate_PORT_FORWARDING_SUCCESSFUL,
                remoteDebugPort,
                localDebuggerPort),
            false);

        return new DebugConnectionDescriptor("localhost", localDebuggerPort); // $NON-NLS-1$

      } catch (JSchException e) {
        throw CloudErrorUtil.toCoreException(
            "SSH connection error " + e.getMessage()); // $NON-NLS-1$
      }
    } else {
      throw CloudErrorUtil.toCoreException(
          "Unable to resolve SSH connection information from the Cloud Foundry target. Please ensure SSH is supported."); //$NON-NLS-1$
    }
  }
  @Override
  protected void pushApplication(
      CloudFoundryOperations client,
      final CloudFoundryApplicationModule appModule,
      ApplicationArchive applicationArchive,
      final IProgressMonitor monitor)
      throws CoreException {
    String appName = appModule.getDeploymentInfo().getDeploymentName();

    CloudApplication existingApp = null;

    try {
      existingApp = getBehaviour().getCloudApplication(appName, monitor);
    } catch (CoreException ce) {
      if (!CloudErrorUtil.isNotFoundException(ce)) {
        throw ce;
      }
    }

    // Create the application if it doesn't already exist
    if (existingApp == null) {
      String creatingAppLabel = NLS.bind(Messages.CONSOLE_APP_CREATION, appName);
      getBehaviour().printlnToConsole(appModule, creatingAppLabel);

      // BUG - [87862532]: Fetch all the information BEFORE
      // creating the application. The reason for this
      // is to prevent any other operation that updates the module from
      // clearing the deploymentinfo after the application is created
      // but before other properties are updated like environment
      // variables
      // and instances
      Staging staging = appModule.getDeploymentInfo().getStaging();
      List<String> uris =
          appModule.getDeploymentInfo().getUris() != null
              ? appModule.getDeploymentInfo().getUris()
              : new ArrayList<String>(0);
      List<String> services = appModule.getDeploymentInfo().asServiceBindingList();
      List<EnvironmentVariable> variables = appModule.getDeploymentInfo().getEnvVariables();
      int instances = appModule.getDeploymentInfo().getInstances();

      if (staging == null) {
        // For v2, a non-null staging is required.
        staging = new Staging();
      }
      CoreException cloudAppCreationClientError = null;

      // Guard against host taken errors and other errors that may
      // create the app but
      // prevent further deployment. If the app was still created
      // attempt to set env vars and instaces
      SubMonitor subMonitor = SubMonitor.convert(monitor, 50);
      subMonitor.subTask(creatingAppLabel);
      try {
        client.createApplication(
            appName, staging, appModule.getDeploymentInfo().getMemory(), uris, services);
      } catch (Exception e) {
        String hostTaken = CloudErrorUtil.getHostTakenError(e);
        if (hostTaken != null) {
          cloudAppCreationClientError = CloudErrorUtil.toCoreException(hostTaken);
        } else {
          cloudAppCreationClientError = CloudErrorUtil.toCoreException(e);
        }
      }

      subMonitor.worked(30);

      // [87881946] - Try setting the env vars and instances even if an
      // error was thrown while creating the application
      // as the application may still have been created in the Cloud space
      // in spite of the error
      try {
        CloudApplication actualApp =
            getBehaviour().getCloudApplication(appName, subMonitor.newChild(20));

        if (actualApp != null) {
          SubMonitor updateMonitor = SubMonitor.convert(subMonitor, 100);
          getBehaviour()
              .getRequestFactory()
              .getUpdateEnvVarRequest(appName, variables)
              .run(updateMonitor.newChild(50));

          // Update instances if it is more than 1. By default, app
          // starts
          // with 1 instance.

          if (instances > 1) {
            getBehaviour()
                .updateApplicationInstances(appName, instances, updateMonitor.newChild(50));
          } else {
            updateMonitor.worked(50);
          }
        }
      } catch (CoreException ce) {
        if (cloudAppCreationClientError == null) {
          throw ce;
        }
      }

      // Even if application was created in the Cloud space, and env vars
      // and instances set, if an exception
      // was thrown while creating the client, throw it
      if (cloudAppCreationClientError != null) {
        throw cloudAppCreationClientError;
      }
    }
    super.pushApplication(client, appModule, applicationArchive, monitor);
  }