private void xmlReadSelectedElements(JarPackageData jarPackage, Element element)
     throws java.io.IOException {
   if (element.getNodeName().equals("selectedElements")) { // $NON-NLS-1$
     jarPackage.setExportClassFiles(
         getBooleanAttribute(element, "exportClassFiles")); // $NON-NLS-1$
     jarPackage.setExportOutputFolders(
         getBooleanAttribute(element, "exportOutputFolder", false)); // $NON-NLS-1$
     jarPackage.setExportJavaFiles(getBooleanAttribute(element, "exportJavaFiles")); // $NON-NLS-1$
     NodeList selectedElements = element.getChildNodes();
     Set<IAdaptable> elementsToExport = new HashSet<IAdaptable>(selectedElements.getLength());
     for (int j = 0; j < selectedElements.getLength(); j++) {
       Node selectedNode = selectedElements.item(j);
       if (selectedNode.getNodeType() != Node.ELEMENT_NODE) continue;
       Element selectedElement = (Element) selectedNode;
       if (selectedElement.getNodeName().equals("file")) // $NON-NLS-1$
       addFile(elementsToExport, selectedElement);
       else if (selectedElement.getNodeName().equals("folder")) // $NON-NLS-1$
       addFolder(elementsToExport, selectedElement);
       else if (selectedElement.getNodeName().equals("project")) // $NON-NLS-1$
       addProject(elementsToExport, selectedElement);
       else if (selectedElement.getNodeName().equals("javaElement")) // $NON-NLS-1$
       addJavaElement(elementsToExport, selectedElement);
       // Note: Other file types are not handled by this writer
     }
     jarPackage.setElements(elementsToExport.toArray());
   }
 }
  public JarPackageData readXML(JarPackageData jarPackage) throws IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    DocumentBuilder parser = null;

    try {
      parser = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
      throw new IOException(ex.getLocalizedMessage());
    } finally {
      // Note: Above code is OK since clients are responsible to close the stream
    }
    parser.setErrorHandler(new DefaultHandler());
    Element xmlJarDesc = parser.parse(new InputSource(fInputStream)).getDocumentElement();
    if (!xmlJarDesc.getNodeName().equals(JarPackagerUtil.DESCRIPTION_EXTENSION)) {
      throw new IOException(JarPackagerMessages.JarPackageReader_error_badFormat);
    }
    NodeList topLevelElements = xmlJarDesc.getChildNodes();
    for (int i = 0; i < topLevelElements.getLength(); i++) {
      Node node = topLevelElements.item(i);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;
      Element element = (Element) node;
      xmlReadJarLocation(jarPackage, element);
      xmlReadOptions(jarPackage, element);
      xmlReadRefactoring(jarPackage, element);
      xmlReadSelectedProjects(jarPackage, element);
      if (jarPackage.areGeneratedFilesExported()) xmlReadManifest(jarPackage, element);
      xmlReadSelectedElements(jarPackage, element);
    }
    return jarPackage;
  }
  public static File exportProjectToJarFile(IProject project, boolean logInfo) {

    JarPackageData jarExportOps = new JarPackageData();
    jarExportOps.setExportJavaFiles(false);
    jarExportOps.setExportClassFiles(true);
    jarExportOps.setIncludeDirectoryEntries(true);
    jarExportOps.setUsesManifest(false);
    jarExportOps.setOverwrite(true);
    jarExportOps.setJarBuilder(new LambdaFunctionJarBuilder());

    try {

      Object[] elements = getElementsToExport(project);
      jarExportOps.setElements(elements);

      // prefix should be at least three characters long
      File jarFile = File.createTempFile(project.getName() + "-lambda", ".zip");
      jarFile.deleteOnExit();

      jarExportOps.setJarLocation(new Path(jarFile.getAbsolutePath()));

      if (logInfo) {
        LambdaPlugin.getDefault()
            .logInfo(
                String.format(
                    "Exporting project [%s] to %s", project.getName(), jarFile.getAbsolutePath()));
      }

      IJarExportRunnable runnable = jarExportOps.createJarExportRunnable(null);
      runnable.run(null);

      if (logInfo) {
        LambdaPlugin.getDefault().logInfo("Project exported to " + jarFile.getAbsolutePath());
      }

      return jarFile;

    } catch (Exception e) {
      LambdaPlugin.getDefault()
          .reportException(
              String.format("Unable to export project [%s] to jar file", project.getName()), e);
      return null;
    }
  }
  /**
   * Create the export option group.
   *
   * @param parent the parent composite
   */
  protected void createOptionsGroup(Composite parent) {
    Composite optionsGroup = new Composite(parent, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.marginHeight = 0;
    optionsGroup.setLayout(layout);

    fExportStructural = new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
    fExportStructural.setText(JarPackagerMessages.JarRefactoringDialog_export_structural);
    fExportStructural.setSelection(fData.isExportStructuralOnly());
  }
 /** {@inheritDoc} */
 protected void buttonPressed(final int buttonId) {
   if (buttonId == IDialogConstants.OK_ID) {
     fData.setRefactoringAware(true);
     final RefactoringDescriptorProxy[] descriptors = fHistoryControl.getCheckedDescriptors();
     Set set = new HashSet();
     IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
     for (int index = 0; index < descriptors.length; index++) {
       final String project = descriptors[index].getProject();
       if (project != null && !"".equals(project)) // $NON-NLS-1$
       set.add(root.getProject(project));
     }
     fData.setRefactoringProjects((IProject[]) set.toArray(new IProject[set.size()]));
     fData.setRefactoringDescriptors(descriptors);
     fData.setExportStructuralOnly(fExportStructural.getSelection());
     final IDialogSettings settings = fSettings;
     if (settings != null) settings.put(SETTING_SORT, fHistoryControl.isSortByProjects());
   }
   super.buttonPressed(buttonId);
 }
  protected JarPackageData getJarPackageData(
      IPackageFragmentRoot[] roots, IType mainType, IProgressMonitor monitor) throws CoreException {

    String filePath = getTempJarPath(appModule.getLocalModule());

    if (filePath == null) {
      handleApplicationDeploymentFailure();
    }

    IPath location = new Path(filePath);

    // Note that if no jar builder is specified in the package data
    // then a default one is used internally by the data that does NOT
    // package any jar dependencies.
    JarPackageData packageData = new JarPackageData();

    packageData.setJarLocation(location);

    // Don't create a manifest. A repackager should determine if a generated
    // manifest is necessary
    // or use a user-defined manifest.
    packageData.setGenerateManifest(false);

    // Since user manifest is not used, do not save to manifest (save to
    // manifest saves to user defined manifest)
    packageData.setSaveManifest(false);

    packageData.setManifestMainClass(mainType);
    packageData.setElements(roots);
    return packageData;
  }
 private void xmlReadSealingInfo(JarPackageData jarPackage, Element element)
     throws java.io.IOException {
   /*
    * Try to find sealing info. Could ask for single child node
    * but this would stop others from adding more child nodes to
    * the manifest node.
    */
   NodeList sealingElementContainer = element.getChildNodes();
   for (int j = 0; j < sealingElementContainer.getLength(); j++) {
     Node sealingNode = sealingElementContainer.item(j);
     if (sealingNode.getNodeType() == Node.ELEMENT_NODE
         && sealingNode.getNodeName().equals("sealing")) { // $NON-NLS-1$
       // Sealing
       Element sealingElement = (Element) sealingNode;
       jarPackage.setSealJar(getBooleanAttribute(sealingElement, "sealJar")); // $NON-NLS-1$
       jarPackage.setPackagesToSeal(
           getPackages(sealingElement.getElementsByTagName("packagesToSeal"))); // $NON-NLS-1$
       jarPackage.setPackagesToUnseal(
           getPackages(sealingElement.getElementsByTagName("packagesToUnSeal"))); // $NON-NLS-1$
     }
   }
 }
 private void xmlReadSelectedProjects(JarPackageData jarPackage, Element element)
     throws java.io.IOException {
   if (element.getNodeName().equals("selectedProjects")) { // $NON-NLS-1$
     NodeList selectedElements = element.getChildNodes();
     Set<IAdaptable> selectedProjects = new HashSet<IAdaptable>(selectedElements.getLength());
     for (int index = 0; index < selectedElements.getLength(); index++) {
       Node node = selectedElements.item(index);
       if (node.getNodeType() != Node.ELEMENT_NODE) continue;
       Element selectedElement = (Element) node;
       if (selectedElement.getNodeName().equals("project")) // $NON-NLS-1$
       addProject(selectedProjects, selectedElement);
     }
     jarPackage.setRefactoringProjects(
         selectedProjects.toArray(new IProject[selectedProjects.size()]));
   }
 }
 private void xmlReadManifest(JarPackageData jarPackage, Element element)
     throws java.io.IOException {
   if (element.getNodeName().equals("manifest")) { // $NON-NLS-1$
     jarPackage.setManifestVersion(element.getAttribute("manifestVersion")); // $NON-NLS-1$
     jarPackage.setUsesManifest(getBooleanAttribute(element, "usesManifest")); // $NON-NLS-1$
     jarPackage.setReuseManifest(getBooleanAttribute(element, "reuseManifest")); // $NON-NLS-1$
     jarPackage.setSaveManifest(getBooleanAttribute(element, "saveManifest")); // $NON-NLS-1$
     jarPackage.setGenerateManifest(
         getBooleanAttribute(element, "generateManifest")); // $NON-NLS-1$
     jarPackage.setManifestLocation(
         Path.fromPortableString(element.getAttribute("manifestLocation"))); // $NON-NLS-1$
     jarPackage.setManifestMainClass(getMainClass(element));
     xmlReadSealingInfo(jarPackage, element);
   }
 }
 private void xmlReadRefactoring(JarPackageData jarPackage, Element element)
     throws java.io.IOException {
   if (element.getNodeName().equals("storedRefactorings")) { // $NON-NLS-1$
     jarPackage.setExportStructuralOnly(
         getBooleanAttribute(
             element, "structuralOnly", jarPackage.isExportStructuralOnly())); // $NON-NLS-1$
     jarPackage.setDeprecationAware(
         getBooleanAttribute(
             element, "deprecationInfo", jarPackage.isDeprecationAware())); // $NON-NLS-1$
     List<IAdaptable> elements = new ArrayList<IAdaptable>();
     int count = 1;
     String value = element.getAttribute("project" + count); // $NON-NLS-1$
     while (value != null && !"".equals(value)) { // $NON-NLS-1$
       final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(value);
       if (project.exists()) elements.add(project);
       count++;
       value = element.getAttribute("project" + count); // $NON-NLS-1$
     }
     jarPackage.setRefactoringProjects(elements.toArray(new IProject[elements.size()]));
     elements.clear();
     count = 1;
     IRefactoringHistoryService service = RefactoringCore.getHistoryService();
     try {
       service.connect();
       value = element.getAttribute("refactoring" + count); // $NON-NLS-1$
       while (value != null && !"".equals(value)) { // $NON-NLS-1$
         final ByteArrayInputStream stream =
             new ByteArrayInputStream(value.getBytes("UTF-8")); // $NON-NLS-1$
         try {
           final RefactoringHistory history =
               service.readRefactoringHistory(stream, RefactoringDescriptor.NONE);
           if (history != null) {
             final RefactoringDescriptorProxy[] descriptors = history.getDescriptors();
             if (descriptors.length > 0) {
               for (int index = 0; index < descriptors.length; index++) {
                 elements.add(descriptors[index]);
               }
             }
           }
         } catch (CoreException exception) {
           JavaPlugin.log(exception);
         }
         count++;
         value = element.getAttribute("refactoring" + count); // $NON-NLS-1$
       }
     } finally {
       service.disconnect();
     }
     jarPackage.setRefactoringDescriptors(
         elements.toArray(new RefactoringDescriptorProxy[elements.size()]));
   }
 }
  /** {@inheritDoc} */
  @Override
  protected Control createDialogArea(final Composite parent) {
    final Composite container = (Composite) super.createDialogArea(parent);
    initializeDialogUnits(container);
    final Composite composite = new Composite(container, SWT.NULL);
    final GridLayout layout = new GridLayout();
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    composite.setLayout(layout);
    composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
    final RefactoringHistoryControlConfiguration configuration =
        new RefactoringHistoryControlConfiguration(null, true, true) {

          @Override
          public final String getWorkspaceCaption() {
            return JarPackagerMessages.JarRefactoringDialog_workspace_caption;
          }
        };
    fHistoryControl =
        (ISortableRefactoringHistoryControl)
            RefactoringUI.createSortableRefactoringHistoryControl(composite, configuration);
    fHistoryControl.createControl();
    boolean sortProjects = true;
    final IDialogSettings settings = fSettings;
    if (settings != null) sortProjects = settings.getBoolean(SETTING_SORT);
    if (sortProjects) fHistoryControl.sortByProjects();
    else fHistoryControl.sortByDate();
    GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
    data.heightHint = convertHeightInCharsToPixels(32);
    data.widthHint = convertWidthInCharsToPixels(72);
    fHistoryControl.getControl().setLayoutData(data);
    fHistoryControl.setInput(fHistory);
    fHistoryControl.setCheckedDescriptors(fData.getRefactoringDescriptors());
    createPlainLabel(composite, JarPackagerMessages.JarPackageWizardPage_options_label);
    createOptionsGroup(composite);
    Dialog.applyDialogFont(parent);
    return composite;
  }
 private void xmlReadOptions(JarPackageData jarPackage, Element element)
     throws java.io.IOException {
   if (element.getNodeName().equals("options")) { // $NON-NLS-1$
     jarPackage.setOverwrite(getBooleanAttribute(element, "overwrite")); // $NON-NLS-1$
     jarPackage.setCompress(getBooleanAttribute(element, "compress")); // $NON-NLS-1$
     jarPackage.setExportErrors(getBooleanAttribute(element, "exportErrors")); // $NON-NLS-1$
     jarPackage.setExportWarnings(getBooleanAttribute(element, "exportWarnings")); // $NON-NLS-1$
     jarPackage.setSaveDescription(getBooleanAttribute(element, "saveDescription")); // $NON-NLS-1$
     jarPackage.setUseSourceFolderHierarchy(
         getBooleanAttribute(element, "useSourceFolders", false)); // $NON-NLS-1$
     jarPackage.setDescriptionLocation(
         Path.fromPortableString(element.getAttribute("descriptionLocation"))); // $NON-NLS-1$
     jarPackage.setBuildIfNeeded(
         getBooleanAttribute(
             element, "buildIfNeeded", jarPackage.isBuildingIfNeeded())); // $NON-NLS-1$
     jarPackage.setIncludeDirectoryEntries(
         getBooleanAttribute(element, "includeDirectoryEntries", false)); // $NON-NLS-1$
     jarPackage.setRefactoringAware(
         getBooleanAttribute(element, "storeRefactorings", false)); // $NON-NLS-1$
   }
 }
 private void xmlReadJarLocation(JarPackageData jarPackage, Element element) {
   if (element.getNodeName().equals(JarPackagerUtil.JAR_EXTENSION))
     jarPackage.setJarLocation(
         Path.fromPortableString(element.getAttribute("path"))); // $NON-NLS-1$
 }
  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;
  }