public IStatus doCreateNewProject(final NewLiferayPluginProjectOp op, IProgressMonitor monitor)
      throws CoreException {
    IStatus retval = null;

    final IMavenConfiguration mavenConfiguration = MavenPlugin.getMavenConfiguration();
    final IMavenProjectRegistry mavenProjectRegistry = MavenPlugin.getMavenProjectRegistry();
    final IProjectConfigurationManager projectConfigurationManager =
        MavenPlugin.getProjectConfigurationManager();

    final String groupId = op.getGroupId().content();
    final String artifactId = op.getProjectName().content();
    final String version = op.getArtifactVersion().content();
    final String javaPackage = op.getGroupId().content();
    final String activeProfilesValue = op.getActiveProfilesValue().content();
    final PluginType pluginType = op.getPluginType().content(true);
    final IPortletFramework portletFramework = op.getPortletFramework().content(true);
    final String frameworkName = getFrameworkName(op);

    IPath location = PathBridge.create(op.getLocation().content());

    // for location we should use the parent location
    if (location.lastSegment().equals(artifactId)) {
      // use parent dir since maven archetype will generate new dir under this location
      location = location.removeLastSegments(1);
    }

    String archetypeType = null;

    if (pluginType.equals(PluginType.portlet) && portletFramework.isRequiresAdvanced()) {
      archetypeType =
          "portlet-" + frameworkName.replace("_", "-"); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    } else {
      archetypeType = pluginType.name();
    }

    final String archetypeArtifactId =
        "liferay-" + archetypeType + "-archetype"; // $NON-NLS-1$ //$NON-NLS-2$

    // get latest liferay archetype
    monitor.beginTask(
        "Determining latest Liferay maven plugin archetype version.", IProgressMonitor.UNKNOWN);
    final String archetypeVersion =
        AetherUtil.getLatestAvailableLiferayArtifact(
                LIFERAY_ARCHETYPES_GROUP_ID, archetypeArtifactId)
            .getVersion();

    final Archetype archetype = new Archetype();
    archetype.setArtifactId(archetypeArtifactId);
    archetype.setGroupId(LIFERAY_ARCHETYPES_GROUP_ID);
    archetype.setModelEncoding("UTF-8");
    archetype.setVersion(archetypeVersion);

    final Properties properties = new Properties();

    final ResolverConfiguration resolverConfig = new ResolverConfiguration();

    if (!CoreUtil.isNullOrEmpty(activeProfilesValue)) {
      resolverConfig.setSelectedProfiles(activeProfilesValue);
    }

    final ProjectImportConfiguration configuration = new ProjectImportConfiguration(resolverConfig);

    final List<IProject> newProjects =
        projectConfigurationManager.createArchetypeProjects(
            location,
            archetype,
            groupId,
            artifactId,
            version,
            javaPackage,
            properties,
            configuration,
            monitor);

    if (CoreUtil.isNullOrEmpty(newProjects)) {
      retval =
          LiferayMavenCore.createErrorStatus("New project was not created due to unknown error");
    } else {
      final IProject firstProject = newProjects.get(0);

      // add new profiles if it was specified to add to project or parent poms
      if (!CoreUtil.isNullOrEmpty(activeProfilesValue)) {
        final String[] activeProfiles = activeProfilesValue.split(",");

        // find all profiles that should go in user settings file
        final List<NewLiferayProfile> newUserSettingsProfiles =
            getNewProfilesToSave(
                activeProfiles, op.getNewLiferayProfiles(), ProfileLocation.userSettings);

        if (newUserSettingsProfiles.size() > 0) {
          final String userSettingsFile = mavenConfiguration.getUserSettingsFile();

          String userSettingsPath = null;

          if (CoreUtil.isNullOrEmpty(userSettingsFile)) {
            userSettingsPath = MavenCli.DEFAULT_USER_SETTINGS_FILE.getAbsolutePath();
          } else {
            userSettingsPath = userSettingsFile;
          }

          try {
            // backup user's settings.xml file
            final File settingsXmlFile = new File(userSettingsPath);
            final File backupFile = getBackupFile(settingsXmlFile);

            FileUtils.copyFile(settingsXmlFile, backupFile);

            final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            final Document pomDocument = docBuilder.parse(settingsXmlFile.getCanonicalPath());

            for (NewLiferayProfile newProfile : newUserSettingsProfiles) {
              MavenUtil.createNewLiferayProfileNode(pomDocument, newProfile, archetypeVersion);
            }

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(pomDocument);
            StreamResult result = new StreamResult(settingsXmlFile);
            transformer.transform(source, result);
          } catch (Exception e) {
            LiferayMavenCore.logError(
                "Unable to save new Liferay profile to user settings.xml.", e);
          }
        }

        // find all profiles that should go in the project pom
        final List<NewLiferayProfile> newProjectPomProfiles =
            getNewProfilesToSave(
                activeProfiles, op.getNewLiferayProfiles(), ProfileLocation.projectPom);

        // only need to set the first project as nested projects should pickup the parent setting
        final IMavenProjectFacade newMavenProject = mavenProjectRegistry.getProject(firstProject);

        final IFile pomFile = newMavenProject.getPom();

        try {
          final IDOMModel domModel =
              (IDOMModel) StructuredModelManager.getModelManager().getModelForEdit(pomFile);

          for (final NewLiferayProfile newProfile : newProjectPomProfiles) {
            MavenUtil.createNewLiferayProfileNode(
                domModel.getDocument(), newProfile, archetypeVersion);
          }

          domModel.save();

          domModel.releaseFromEdit();
        } catch (IOException e) {
          LiferayMavenCore.logError("Unable to save new Liferay profiles to project pom.", e);
        }

        for (final IProject project : newProjects) {
          try {
            projectConfigurationManager.updateProjectConfiguration(
                new MavenUpdateRequest(project, mavenConfiguration.isOffline(), true), monitor);
          } catch (Exception e) {
            LiferayMavenCore.logError("Unable to update configuration for " + project.getName(), e);
          }
        }
      }

      if (op.getPluginType().content().equals(PluginType.portlet)) {
        final String portletName = op.getPortletName().content(false);
        retval =
            portletFramework.postProjectCreated(firstProject, frameworkName, portletName, monitor);
      }
    }

    if (retval == null) {
      retval = Status.OK_STATUS;
    }

    return retval;
  }
Esempio n. 2
0
  private String prepareNewSettingsFile() {
    // check the users maven settings
    String userSettings = MavenPlugin.getMavenConfiguration().getUserSettingsFile();
    if (userSettings == null || userSettings.length() == 0) {
      userSettings = MavenCli.DEFAULT_USER_SETTINGS_FILE.getAbsolutePath();
    }

    if (userSettings != null && userSettings.trim().length() > 0) {
      File mvnConfig = new File(userSettings);
      // now we have to parse the xml config file and check for
      // a servers/server entry named like our fabric
      Document document = readFileToDocument(userSettings);
      String fabServerName = this.node.getFabricNameWithoutSpaces();

      boolean entryExists = checkForFabricServer(document, fabServerName);

      // if yes - no more to do...user knows what he is doing
      if (entryExists) {
        // the entry is already there...use it
      } else {
        // if no - add the server entry for the fabric with auth
        // information and save config to temp folder - then reference
        // to this config file for the next mvn deploy command
        String fabServerUser = this.node.getFabric().getUserName();
        String fabServerPass = this.node.getFabric().getPassword();

        // create a server entry
        NodeList serversList = document.getElementsByTagName(SERVERS_TAG);
        Element serversElement = null;
        if (serversList.getLength() < 1) {
          // no servers element - create one
          serversElement = document.createElement(SERVERS_TAG);
          document.getDocumentElement().appendChild(serversElement);
        } else {
          serversElement = (Element) serversList.item(0);
        }

        Element server = document.createElement(SERVER_TAG);
        serversElement.appendChild(server);

        Element sId = document.createElement(ID_TAG);
        server.appendChild(sId);
        Text textId = document.createTextNode(fabServerName);
        sId.appendChild(textId);

        Element sUser = document.createElement(USERNAME_TAG);
        server.appendChild(sUser);
        Text textUser = document.createTextNode(fabServerUser);
        sUser.appendChild(textUser);

        Element sPass = document.createElement(PASSWORD_TAG);
        server.appendChild(sPass);
        Text textPass = document.createTextNode(fabServerPass);
        sPass.appendChild(textPass);

        // now save the config to a new file
        File newSettings = null;
        try {
          // create the temp file
          newSettings = File.createTempFile("mvnSettings_", "_ide.xml");

          // prepare dom document for writing
          Source source = new DOMSource(document);

          // prepare to write
          Result result = new StreamResult(newSettings);

          // Write the DOM document to the file
          Transformer xformer = TransformerFactory.newInstance().newTransformer();
          xformer.transform(source, result);

          // switch to new maven config
          userSettings = newSettings.getPath();
        } catch (Exception ex) {
          FabricPlugin.getLogger().error(ex);
        } finally {
          // mark file for deletion
          newSettings.deleteOnExit();
        }
      }
    }

    return userSettings;
  }