Пример #1
0
  public void testFindChildren() {
    tempModel
        .getStructuredDocument()
        .setText(
            StructuredModelManager.getModelManager(), //
            "<dependencies>"
                + //
                "<dependency><groupId>AAA</groupId><artifactId>BBB</artifactId><tag1/></dependency>"
                + //
                "<dependency><groupId>AAAB</groupId><artifactId>BBB</artifactId><tag2/></dependency>"
                + //
                "<dependency><groupId>AAA</groupId><artifactId>BBBB</artifactId><tag3/></dependency>"
                + //
                "<dependency><artifactId>BBB</artifactId><tag4/></dependency>"
                + "</dependencies>");
    Element docElement = tempModel.getDocument().getDocumentElement();

    assertTrue("null parent should return empty list", findChilds(null, "dependency").isEmpty());
    assertTrue(
        "missing child should return empty list",
        findChilds(docElement, "missingElement").isEmpty());

    List<Element> dep = findChilds(docElement, "dependency");
    assertEquals("Children found", 4, dep.size());
    for (Element d : dep) {
      assertEquals("Node type", "dependency", d.getLocalName());
    }
    // Should return first match
    assertDependencyChild("Unexpected child", "AAA", "BBB", "tag1", dep.get(0));
    assertDependencyChild("Unexpected child", "AAAB", "BBB", "tag2", dep.get(1));
    assertDependencyChild("Unexpected child", "AAA", "BBBB", "tag3", dep.get(2));
    assertDependencyChild("Unexpected child", null, "BBB", "tag4", dep.get(3));
  }
  public void testModel() {
    IDOMModel model = createXMLModel();
    try {
      Document document = model.getDocument();

      Element a = document.createElement("a");
      document.appendChild(a);
      IDOMNode text = (IDOMNode) document.createTextNode("text");
      a.appendChild(text);

      try {
        text.setSource("hello <");
      } catch (InvalidCharacterException ex) {
        fOutputWriter.writeln(ex.getMessage());
      }

      printSource(model);
      printTree(model);

      try {
        text.setSource("hello &lt;");
      } catch (InvalidCharacterException ex) {
        fOutputWriter.writeln(ex.getMessage());
      }

      printSource(model);
      printTree(model);

      try {
        text.setSource("hello &unk;");
      } catch (InvalidCharacterException ex) {
        fOutputWriter.writeln(ex.getMessage());
      }

      printSource(model);
      printTree(model);

      try {
        text.setSource("hello &#65;");
      } catch (InvalidCharacterException ex) {
        fOutputWriter.writeln(ex.getMessage());
      }

      printSource(model);
      printTree(model);

      try {
        text.setSource("hello & good-bye");
      } catch (InvalidCharacterException ex) {
        fOutputWriter.writeln(ex.getMessage());
      }

      printSource(model);
      printTree(model);

      saveAndCompareTestResults();
    } finally {
      model.releaseFromEdit();
    }
  }
Пример #3
0
  public void testFindChild() {
    tempModel
        .getStructuredDocument()
        .setText(
            StructuredModelManager.getModelManager(), //
            "<dependencies>"
                + //
                "<dependency><groupId>AAA</groupId><artifactId>BBB</artifactId><tag1/></dependency>"
                + //
                "<dependency><groupId>AAAB</groupId><artifactId>BBB</artifactId><tag2/></dependency>"
                + //
                "<dependency><groupId>AAA</groupId><artifactId>BBBB</artifactId><tag3/></dependency>"
                + //
                "<dependency><artifactId>BBB</artifactId><tag4/></dependency>"
                + "</dependencies>");
    Element docElement = tempModel.getDocument().getDocumentElement();

    assertNull("null parent should return null", findChild(null, "dependency"));
    assertNull("missing child should return null", findChild(docElement, "missingElement"));

    Element dep = findChild(docElement, "dependency");
    assertNotNull("Expected node found", dep);
    assertEquals("Node type", "dependency", dep.getLocalName());
    // Should return first match
    assertDependencyChild(null, "AAA", "BBB", "tag1", dep);
  }
Пример #4
0
 private String removeChild(String xml) {
   tempModel.getStructuredDocument().setText(StructuredModelManager.getModelManager(), xml);
   Document doc = tempModel.getDocument();
   Element parent = doc.getDocumentElement();
   Element child = PomEdits.findChild(parent, PomEdits.BUILD);
   PomEdits.removeChild(parent, child);
   return tempModel.getStructuredDocument().getText();
 }
  /**
   * Validates the Concordion Specification
   *
   * @param domModel The HTML DOM for the specification, provided by the WST editor
   * @param reporter Error reporting interface
   * @param nsPrefix Concordion namespace prefix
   */
  private void doParseSpec(IDOMModel domModel, IReporter reporter, String nsPrefix) {
    Element root = domModel.getDocument().getDocumentElement();
    CommandAttributeVisitor specParser =
        new CommandAttributeVisitor(
            document,
            nsPrefix,
            new ProblemReporterFactory(this, reporter),
            new InvalidCommandHandlerImpl());

    specParser.addCommandParser(CommandName.SET, new SetCommandValidator());
    specParser.addCommandParser(CommandName.VERIFY_ROWS, new VerifyRowsCommandValidator());

    IFile specFile = EclipseUtils.fileForModel(domModel);
    IType fixtureType = JdtUtils.findFixtureForSpec(specFile);

    // Create evaluation command validator once only, it will cache fixture type/method information
    EvaluationCommandValidator evaluationCommandValidator =
        new EvaluationCommandValidator(fixtureType);

    specParser.addCommandParser(CommandName.ASSERT_EQUALS, evaluationCommandValidator);
    specParser.addCommandParser(CommandName.ASSERT_FALSE, evaluationCommandValidator);
    specParser.addCommandParser(CommandName.ASSERT_TRUE, evaluationCommandValidator);
    specParser.addCommandParser(CommandName.ECHO, evaluationCommandValidator);
    specParser.addCommandParser(CommandName.EXECUTE, evaluationCommandValidator);
    specParser.addCommandParser(CommandName.PARAMS, evaluationCommandValidator);

    specParser.addCommandParser(CommandName.RUN, new RunCommandValidator());

    specParser.visitNodeRecursive(root);
  }
  /**
   * Returns the CMDocument that corresponds to the DOM Node. or null if no CMDocument is
   * appropriate for the DOM Node.
   */
  public CMDocument getCorrespondingCMDocument(Node node) {
    CMDocument jcmdoc = null;
    if (node instanceof IDOMNode) {
      IDOMModel model = ((IDOMNode) node).getModel();
      String modelPath = model.getBaseLocation();
      if (modelPath != null && !IModelManager.UNMANAGED_MODEL.equals(modelPath)) {
        float version =
            DeploymentDescriptorPropertyCache.getInstance().getJSPVersion(new Path(modelPath));
        jcmdoc = JSPCMDocumentFactory.getCMDocument(version);
      }
    }
    if (jcmdoc == null) {
      jcmdoc = JSPCMDocumentFactory.getCMDocument();
    }

    CMDocument result = null;
    try {
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        String elementName = node.getNodeName();

        // test to see if this node belongs to JSP's CMDocument (case
        // sensitive)
        CMElementDeclaration dec =
            (CMElementDeclaration) jcmdoc.getElements().getNamedItem(elementName);
        if (dec != null) {
          result = jcmdoc;
        }
      }

      String prefix = node.getPrefix();

      if (result == null && prefix != null && prefix.length() > 0 && node instanceof IDOMNode) {
        // check position dependent
        IDOMNode xmlNode = (IDOMNode) node;
        TLDCMDocumentManager tldmgr =
            TaglibController.getTLDCMDocumentManager(xmlNode.getStructuredDocument());
        if (tldmgr != null) {
          List documents = tldmgr.getCMDocumentTrackers(node.getPrefix(), xmlNode.getStartOffset());
          // there shouldn't be more than one cmdocument returned
          if (documents != null && documents.size() > 0) result = (CMDocument) documents.get(0);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
  private boolean addXmlFileChanges(IFile file, CompositeChange changes, boolean isManifest) {
    IModelManager modelManager = StructuredModelManager.getModelManager();
    IStructuredModel model = null;
    try {
      model = modelManager.getExistingModelForRead(file);
      if (model == null) {
        model = modelManager.getModelForRead(file);
      }
      if (model != null) {
        IStructuredDocument document = model.getStructuredDocument();
        if (model instanceof IDOMModel) {
          IDOMModel domModel = (IDOMModel) model;
          Element root = domModel.getDocument().getDocumentElement();
          if (root != null) {
            List<TextEdit> edits = new ArrayList<TextEdit>();
            if (isManifest) {
              addManifestReplacements(edits, root, document);
            } else {
              addLayoutReplacements(edits, root, document);
            }
            if (!edits.isEmpty()) {
              MultiTextEdit rootEdit = new MultiTextEdit();
              rootEdit.addChildren(edits.toArray(new TextEdit[edits.size()]));
              TextFileChange change = new TextFileChange(file.getName(), file);
              change.setTextType(EXT_XML);
              change.setEdit(rootEdit);
              changes.add(change);
            }
          }
        } else {
          return false;
        }
      }

      return true;
    } catch (IOException e) {
      AdtPlugin.log(e, null);
    } catch (CoreException e) {
      AdtPlugin.log(e, null);
    } finally {
      if (model != null) {
        model.releaseFromRead();
      }
    }

    return false;
  }
Пример #8
0
 /**
  * this method grabs the IDOMModel for the IDocument, performs the passed operation on the root
  * element of the document and then releases the IDOMModel root Element value is also an instance
  * of IndexedRegion
  *
  * @param doc
  * @param operation
  */
 public static void performOnRootElement(IDocument doc, NodeOperation<Element> operation) {
   assert doc != null;
   assert operation != null;
   IDOMModel domModel = null;
   try {
     domModel = (IDOMModel) StructuredModelManager.getModelManager().getExistingModelForRead(doc);
     if (domModel == null) {
       throw new IllegalArgumentException("Document is not structured: " + doc);
     }
     IStructuredDocument document = domModel.getStructuredDocument();
     Element root = domModel.getDocument().getDocumentElement();
     operation.process(root, document);
   } finally {
     if (domModel != null) {
       domModel.releaseFromRead();
     }
   }
 }
Пример #9
0
  public void testMatchers() {
    tempModel
        .getStructuredDocument()
        .setText(
            StructuredModelManager.getModelManager(),
            "<dependencies>"
                + "<dependency><groupId>AAA</groupId><artifactId>BBB</artifactId><tag1/></dependency>"
                + "<dependency><groupId>AAAB</groupId><artifactId>BBB</artifactId><tag2/></dependency>"
                + "<dependency><groupId>AAA</groupId><artifactId>BBBB</artifactId><tag3/></dependency>"
                + "<dependency><artifactId>BBB</artifactId><tag4/></dependency>"
                + "</dependencies>");
    Document doc = tempModel.getDocument();
    Element el = findChild(doc.getDocumentElement(), DEPENDENCY, childEquals(ARTIFACT_ID, "BBBB"));
    assertNotNull(findChild(el, "tag3"));

    el = findChild(doc.getDocumentElement(), DEPENDENCY, childEquals(ARTIFACT_ID, "BBB"));
    assertNotNull(findChild(el, "tag1"));

    el =
        findChild(
            doc.getDocumentElement(),
            DEPENDENCY,
            childEquals(GROUP_ID, "AAAB"),
            childEquals(ARTIFACT_ID, "BBB"));
    assertNotNull(findChild(el, "tag2"));

    el =
        findChild(
            doc.getDocumentElement(),
            DEPENDENCY,
            childMissingOrEqual(GROUP_ID, "CCC"),
            childEquals(ARTIFACT_ID, "BBB"));
    assertNotNull(findChild(el, "tag4"));

    el =
        findChild(
            doc.getDocumentElement(),
            DEPENDENCY,
            childEquals(GROUP_ID, "AAA"),
            childMissingOrEqual(ARTIFACT_ID, "BBBB"));
    assertNotNull(findChild(el, "tag3"));
  }
Пример #10
0
  public void testRemoveIfNoChildElement() {
    tempModel
        .getStructuredDocument()
        .setText(
            StructuredModelManager.getModelManager(),
            "<project>"
                + "<build>"
                + "<pluginManagement>"
                + "<plugins></plugins"
                + "</pluginManagement>"
                + "</build>"
                + "</project>");
    Document doc = tempModel.getDocument();
    Element plugins =
        findChild(
            findChild(findChild(doc.getDocumentElement(), BUILD), PLUGIN_MANAGEMENT), PLUGINS);
    assertNotNull(plugins);
    removeIfNoChildElement(plugins);
    assertNull(findChild(doc.getDocumentElement(), BUILD));

    tempModel
        .getStructuredDocument()
        .setText(
            StructuredModelManager.getModelManager(),
            "<project>"
                + "<build>"
                + "<pluginManagement>"
                + "<plugins></plugins"
                + "</pluginManagement>"
                + "<STOP_ELEMENT/>"
                + "</build>"
                + "</project>");
    doc = tempModel.getDocument();
    plugins =
        findChild(
            findChild(findChild(doc.getDocumentElement(), BUILD), PLUGIN_MANAGEMENT), PLUGINS);
    assertNotNull(plugins);
    removeIfNoChildElement(plugins);
    Element build = findChild(doc.getDocumentElement(), BUILD);
    assertNotNull(build);
    assertNull(findChild(build, PLUGIN_MANAGEMENT));
  }
Пример #11
0
  public static void performOnRootElement(
      IFile resource, NodeOperation<Element> operation, boolean autoSave)
      throws IOException, CoreException {
    assert resource != null;
    assert operation != null;
    IDOMModel domModel = null;
    try {
      domModel = (IDOMModel) StructuredModelManager.getModelManager().getModelForRead(resource);
      if (domModel == null) {
        throw new IllegalArgumentException("Document is not structured: " + resource);
      }
      IStructuredDocument document = domModel.getStructuredDocument();
      Element root = domModel.getDocument().getDocumentElement();
      operation.process(root, document);

      if (autoSave && domModel.getReferenceCountForEdit() == 0) {
        domModel.save();
      }

    } finally {
      if (domModel != null) {
        domModel.releaseFromRead();
      }
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see junit.framework.TestCase#setUp()
   */
  @Override
  protected void setUp() throws Exception {
    tempModel =
        (IDOMModel)
            StructuredModelManager.getModelManager()
                .createUnManagedStructuredModelFor("org.eclipse.m2e.core.pomFile");
    document = tempModel.getStructuredDocument();

    d = new Dependency();
    d.setArtifactId("BBBB");
    d.setGroupId("AAA");
    d.setVersion("1.0");

    e = new ArtifactKey("g", "a", "1.0", null);
  }
Пример #13
0
 /**
  * Create IDOMPosition based on Indexed 'position' in model. If node at position is text, use
  * position to calculate DOMPosition offset, otherwize, simply create position pointed to
  * container's children list's edge.
  *
  * @param model
  * @param position
  * @param adjust
  * @return the dom position
  */
 public IDOMPosition createDomposition1(IDOMModel model, int position, boolean adjust) {
   try {
     // get the container
     Object object = getPosNode(model, position);
     if (object == null && position > 0) {
       // The end of file?
       object = getPosNode(model, position - 1);
     }
     Node container = null;
     if (object == null) {
       // empty file?
       return new DOMPosition(model.getDocument(), 0);
     }
     container = (Node) object;
     Object oppNode = getPosNode(model, position - 1);
     if (oppNode != null
         && !EditModelQuery.isChild((Node) oppNode, container)
         && //
         !EditModelQuery.isInline(container)
         && EditModelQuery.isInline((Node) oppNode)) {
       container = (Node) oppNode;
     }
     int location = EditHelper.getInstance().getLocation(container, position, false);
     IDOMPosition result = null;
     switch (location) {
       case 1:
       case 2:
         result = new DOMRefPosition(container, false);
         break;
       case 4:
       case 5:
         result = new DOMRefPosition(container, true);
         break;
       case 3:
         if (EditModelQuery.isText(container)) {
           result =
               new DOMPosition(container, position - EditModelQuery.getNodeStartIndex(container));
         } else {
           result = new DOMPosition(container, container.getChildNodes().getLength());
         }
     }
     return result;
   } catch (Exception e) {
     // "Error in position creation"
     _log.error("Error.EditModelQuery.0" + e); // $NON-NLS-1$
     return null;
   }
 }
  void performValidation(IFile f, IReporter reporter, IStructuredModel model, boolean inBatch) {
    if (model instanceof IDOMModel) {
      IDOMModel domModel = (IDOMModel) model;
      JsTranslationAdapterFactory.setupAdapterFactory(domModel);
      IDOMDocument xmlDoc = domModel.getDocument();
      JsTranslationAdapter translationAdapter =
          (JsTranslationAdapter) xmlDoc.getAdapterFor(IJsTranslation.class);
      // translationAdapter.resourceChanged();
      IJsTranslation translation = translationAdapter.getJsTranslation(false);
      if (!reporter.isCancelled()) {
        translation.setProblemCollectingActive(true);
        translation.reconcileCompilationUnit();
        List problems = translation.getProblems();
        // only update task markers if the model is the same as what's on disk
        boolean updateTasks = !domModel.isDirty() && f != null && f.isAccessible();
        if (updateTasks) {
          // remove old JavaScript task markers
          try {
            IMarker[] foundMarkers =
                f.findMarkers(JAVASCRIPT_TASK_MARKER_TYPE, true, IResource.DEPTH_ONE);
            for (int i = 0; i < foundMarkers.length; i++) {
              foundMarkers[i].delete();
            }
          } catch (CoreException e) {
            Logger.logException(e);
          }
        }

        //				if(!inBatch) reporter.removeAllMessages(this, f);
        // add new messages
        for (int i = 0; i < problems.size() && !reporter.isCancelled(); i++) {
          IProblem problem = (IProblem) problems.get(i);
          IMessage m =
              createMessageFromProblem(problem, f, translation, domModel.getStructuredDocument());
          if (m != null) {
            if (problem.getID() == IProblem.Task) {
              if (updateTasks) {
                // add new JavaScript task marker
                try {
                  IMarker task = f.createMarker(JAVASCRIPT_TASK_MARKER_TYPE);
                  task.setAttribute(IMarker.LINE_NUMBER, new Integer(m.getLineNumber()));
                  task.setAttribute(IMarker.CHAR_START, new Integer(m.getOffset()));
                  task.setAttribute(IMarker.CHAR_END, new Integer(m.getOffset() + m.getLength()));
                  task.setAttribute(IMarker.MESSAGE, m.getText());
                  task.setAttribute(IMarker.USER_EDITABLE, Boolean.FALSE);

                  switch (m.getSeverity()) {
                    case IMessage.HIGH_SEVERITY:
                      {
                        task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_HIGH));
                        task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR));
                      }
                      break;
                    case IMessage.LOW_SEVERITY:
                      {
                        task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_LOW));
                        task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO));
                      }
                      break;
                    default:
                      {
                        task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL));
                        task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING));
                      }
                  }
                } catch (CoreException e) {
                  Logger.logException(e);
                }
              }
            } else {
              reporter.addMessage(fMessageOriginator, m);
            }
          }
        }
      }
    }
  }
  @Override
  protected void configureJBossAppXml() {
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(earProjectName);
    IVirtualComponent component = ComponentCore.createComponent(project);
    IVirtualFolder folder = component.getRootFolder();
    IFolder rootFolder = (IFolder) folder.getUnderlyingFolder();
    IResource jbossAppXml = rootFolder.findMember("META-INF/jboss-app.xml");
    if (jbossAppXml == null || !(jbossAppXml instanceof IFile) || !jbossAppXml.exists()) {
      return;
    }

    IModelManager manager = StructuredModelManager.getModelManager();
    if (manager == null) {
      return;
    }
    IStructuredModel model = null;
    try {
      model = manager.getModelForEdit((IFile) jbossAppXml);
      if (model instanceof IDOMModel) {
        IDOMModel domModel = (IDOMModel) model;
        IDOMDocument document = domModel.getDocument();
        Element root = document.getDocumentElement();
        if (root == null) {
          return;
        }
        NodeList children = root.getChildNodes();
        boolean strictAdded = false;
        Node firstChild = null;
        for (int i = 0; i < children.getLength(); i++) {
          Node currentNode = children.item(i);
          if (Node.ELEMENT_NODE == currentNode.getNodeType() && firstChild == null) {
            firstChild = currentNode;
          }
          if (Node.ELEMENT_NODE == currentNode.getNodeType()
              && MODULE_ORDER.equals(currentNode.getNodeName())) {
            setValue(document, currentNode, STRICT);
            strictAdded = true;
          }
        }
        if (!strictAdded) {
          Element moduleOrder = document.createElement(MODULE_ORDER);
          setValue(document, moduleOrder, STRICT);
          if (firstChild != null) {
            root.insertBefore(moduleOrder, firstChild);
          } else {
            root.appendChild(moduleOrder);
          }
        }
        model.save();
      }
    } catch (CoreException e) {
      SeamCorePlugin.getDefault().logError(e);
    } catch (IOException e) {
      SeamCorePlugin.getDefault().logError(e);
    } finally {
      if (model != null) {
        model.releaseFromEdit();
      }
    }
    try {
      new FormatProcessorXML().formatFile((IFile) jbossAppXml);
    } catch (IOException e) {
      SeamCorePlugin.getDefault().logError(e);
    } catch (CoreException e) {
      SeamCorePlugin.getDefault().logError(e);
    }
  }
  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;
  }
  /*
   * (non-Javadoc)
   * @see org.jboss.tools.seam.internal.core.project.facet.SeamFacetAbstractInstallDelegate#configureFacesConfigXml(org.eclipse.core.resources.IProject, org.eclipse.core.runtime.IProgressMonitor, java.lang.String)
   */
  @Override
  protected void configureFacesConfigXml(
      final IProject project, IProgressMonitor monitor, String webConfigName) {
    FacesConfigArtifactEdit facesConfigEdit = null;
    try {
      facesConfigEdit =
          FacesConfigArtifactEdit.getFacesConfigArtifactEditForWrite(project, webConfigName);
      FacesConfigType facesConfig = facesConfigEdit.getFacesConfig();
      EList applications = facesConfig.getApplication();
      ApplicationType applicationType = null;
      boolean applicationExists = false;
      if (applications.size() <= 0) {
        applicationType = FacesConfigFactory.eINSTANCE.createApplicationType();
      } else {
        applicationType = (ApplicationType) applications.get(0);
        applicationExists = true;
      }
      boolean localeConfigExists = false;
      for (Iterator iterator = applications.iterator(); iterator.hasNext(); ) {
        ApplicationType application = (ApplicationType) iterator.next();
        EList localeConfigs = application.getLocaleConfig();
        if (!localeConfigs.isEmpty()) {
          localeConfigExists = true;
          break;
        }
      }
      if (!localeConfigExists) {
        LocaleConfigType locale = FacesConfigFactory.eINSTANCE.createLocaleConfigType();
        DefaultLocaleType defaultLocale = FacesConfigFactory.eINSTANCE.createDefaultLocaleType();
        defaultLocale.setTextContent("en");
        locale.setDefaultLocale(defaultLocale);
        SupportedLocaleType supportedLocale =
            FacesConfigFactory.eINSTANCE.createSupportedLocaleType();
        supportedLocale.setTextContent("bg");
        locale.getSupportedLocale().add(supportedLocale);
        supportedLocale = FacesConfigFactory.eINSTANCE.createSupportedLocaleType();
        supportedLocale.setTextContent("de");
        locale.getSupportedLocale().add(supportedLocale);
        supportedLocale = FacesConfigFactory.eINSTANCE.createSupportedLocaleType();
        supportedLocale.setTextContent("en");
        locale.getSupportedLocale().add(supportedLocale);
        supportedLocale = FacesConfigFactory.eINSTANCE.createSupportedLocaleType();
        supportedLocale.setTextContent("fr");
        locale.getSupportedLocale().add(supportedLocale);
        supportedLocale = FacesConfigFactory.eINSTANCE.createSupportedLocaleType();
        supportedLocale.setTextContent("tr");
        locale.getSupportedLocale().add(supportedLocale);
        applicationType.getLocaleConfig().add(locale);
      }
      boolean viewHandlerExists = false;
      IDOMModel domModel = facesConfigEdit.getIDOMModel();
      if (domModel != null) {
        Element facesConfigElement = domModel.getDocument().getDocumentElement();
        if (facesConfigElement != null) {
          if (facesConfigElement.getAttribute("version").startsWith("1")) {
            for (Iterator iterator = applications.iterator(); iterator.hasNext(); ) {
              ApplicationType application = (ApplicationType) iterator.next();
              EList viewHandlers = application.getViewHandler();
              for (Iterator iterator2 = viewHandlers.iterator(); iterator2.hasNext(); ) {
                ViewHandlerType viewHandlerType = (ViewHandlerType) iterator2.next();
                if ("com.sun.facelets.FaceletViewHandler"
                    .equals(viewHandlerType.getTextContent().trim())) {
                  viewHandlerExists = true;
                  break;
                }
              }
            }
          } else {
            // Don't add facelet view handler for JSF 2
            viewHandlerExists = true;
          }
        }
      }

      if (!viewHandlerExists) {
        ViewHandlerType viewHandler = FacesConfigFactory.eINSTANCE.createViewHandlerType();
        viewHandler.setTextContent("com.sun.facelets.FaceletViewHandler");
        applicationType.getViewHandler().add(viewHandler);
      }
      if (!applicationExists) {
        facesConfig.getApplication().add(applicationType);
      }
      facesConfigEdit.save(monitor);
    } finally {
      if (facesConfigEdit != null) {
        facesConfigEdit.dispose();
      }
    }
  }
Пример #18
0
  /**
   * Another public method for those who want to get the process resource by their own means (such
   * as the editor).
   */
  public void read(Resource processResource, IDOMModel domModel, ResourceSet resourceSet) {
    // TODO: These two lines are a workaround for
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=72565
    EcorePackage instance = EcorePackage.eINSTANCE;
    instance.eAdapters();

    this.processResource = processResource;

    // IPath extensionsPath =
    // modelFile.getFullPath().removeFileExtension().addFileExtension(IBPELUIConstants.EXTENSION_MODEL_EXTENSIONS);
    org.eclipse.core.runtime.IPath extensionsPath =
        (new org.eclipse.core.runtime.Path(domModel.getBaseLocation()))
            .removeFileExtension()
            .addFileExtension(IBPELUIConstants.EXTENSION_MODEL_EXTENSIONS);
    URI extensionsUri = URI.createPlatformResourceURI(extensionsPath.toString());
    IFile extensionsFile = ResourcesPlugin.getWorkspace().getRoot().getFile(extensionsPath);

    try {
      processResource.load(Collections.EMPTY_MAP);
      EList<EObject> contents = processResource.getContents();
      if (!contents.isEmpty()) process = (Process) contents.get(0);
    } catch (Exception e) {
      // TODO: If a file is empty Resource.load(Map) throws a java.lang.NegativeArraySizeException
      // We should investigate EMF to see if we are supposed to handle this case or if this
      // is a bug in EMF.
      BPELUIPlugin.log(e);
    }
    try {
      extensionsResource = resourceSet.getResource(extensionsUri, extensionsFile.exists());
      if (extensionsResource != null) {
        extensionMap =
            ExtensionmodelFactory.eINSTANCE.findExtensionMap(
                IBPELUIConstants.MODEL_EXTENSIONS_NAMESPACE, extensionsResource.getContents());
      }
    } catch (Exception e) {
      BPELUIPlugin.log(e);
    }
    if (extensionMap != null) extensionMap.initializeAdapter();

    if (process == null) {
      process = BPELFactory.eINSTANCE.createProcess();
      processResource.getContents().add(process);
    }
    if (extensionMap == null) {
      extensionMap =
          ExtensionmodelFactory.eINSTANCE.createExtensionMap(
              IBPELUIConstants.MODEL_EXTENSIONS_NAMESPACE);
      if (extensionsResource == null) {
        extensionsResource = resourceSet.createResource(extensionsUri);
      }
      extensionsResource.getContents().clear();
      extensionsResource.getContents().add(extensionMap);
    }

    // Make sure the Process has Variables, PartnerLinks and CorrelationSets objects.
    // They aren't strictly necessary according to the spec but make we need those in
    // order for the editor tray to work.
    if (process.getVariables() == null) {
      process.setVariables(BPELFactory.eINSTANCE.createVariables());
    }
    if (process.getPartnerLinks() == null) {
      process.setPartnerLinks(BPELFactory.eINSTANCE.createPartnerLinks());
    }
    if (process.getCorrelationSets() == null) {
      process.setCorrelationSets(BPELFactory.eINSTANCE.createCorrelationSets());
    }
    if (process.getMessageExchanges() == null) {
      process.setMessageExchanges(BPELFactory.eINSTANCE.createMessageExchanges());
    }
    // Make sure scopes have Variables.
    // They aren't strictly necessary according to the spec but make we need those in
    // order for the editor tray to work.
    for (Iterator<EObject> iter = process.eAllContents(); iter.hasNext(); ) {
      EObject object = iter.next();
      if (object instanceof Scope) {
        Scope scope = (Scope) object;
        if (scope.getVariables() == null) {
          scope.setVariables(BPELFactory.eINSTANCE.createVariables());
        }
        if (scope.getPartnerLinks() == null) {
          scope.setPartnerLinks(BPELFactory.eINSTANCE.createPartnerLinks());
        }
        if (scope.getCorrelationSets() == null) {
          scope.setCorrelationSets(BPELFactory.eINSTANCE.createCorrelationSets());
        }
        if (scope.getMessageExchanges() == null) {
          scope.setMessageExchanges(BPELFactory.eINSTANCE.createMessageExchanges());
        }
      }
    }

    // Make sure each model object has the necessary extensions!
    TreeIterator<EObject> it = process.eAllContents();
    while (it.hasNext()) {
      ModelHelper.createExtensionIfNecessary(extensionMap, it.next());
    }

    if (extensionMap.get(process) == null) {
      ModelHelper.createExtensionIfNecessary(extensionMap, process);
    }
  }