public <T> T adapt(ILiferayProject liferayProject, Class<T> adapterType) {
    if (liferayProject instanceof LiferayMavenProject
        && IProjectBuilder.class.equals(adapterType)) {
      // only use this builder for versions of Liferay less than 6.2
      final LiferayMavenProject liferayMavenProject =
          LiferayMavenProject.class.cast(liferayProject);
      final String version = liferayMavenProject.getLiferayMavenPluginVersion();

      if (!CoreUtil.isNullOrEmpty(version)) {
        // we only need to match the first 2 characters
        final Matcher matcher = majorMinor.matcher(version);

        String matchedVersion = null;

        if (matcher.find() && matcher.groupCount() == 2) {
          matchedVersion = matcher.group(1) + "." + matcher.group(2) + ".0";
        }

        final Version portalVersion =
            new Version(matchedVersion != null ? matchedVersion : version);

        if (CoreUtil.compareVersions(portalVersion, ILiferayConstants.V620) < 0) {
          MavenUIProjectBuilder builder =
              new MavenUIProjectBuilder((LiferayMavenProject) liferayProject);

          return adapterType.cast(builder);
        }
      }
    }

    return null;
  }
  protected IStatus validateServer(IProgressMonitor monitor) {
    String host = serverWC.getHost();

    if (CoreUtil.isNullOrEmpty(host)) {
      return LiferayServerUI.createErrorStatus(Msgs.specifyHostname);
    }

    String username = remoteServerWC.getUsername();

    if (CoreUtil.isNullOrEmpty(username)) {
      return LiferayServerUI.createErrorStatus(Msgs.specifyUsernamePassword);
    }

    String port = remoteServerWC.getHTTPPort();

    if (CoreUtil.isNullOrEmpty(port)) {
      return LiferayServerUI.createErrorStatus(Msgs.specifyHTTPPort);
    }

    IStatus status = remoteServerWC.validate(monitor);

    if (status != null && status.getSeverity() == IStatus.ERROR) {
      fragment.lastServerStatus =
          new Status(
              IStatus.WARNING, status.getPlugin(), status.getMessage(), status.getException());
    } else {
      fragment.lastServerStatus = status;
    }

    return status;
  }
  @Test
  public void testNewLiferayModuleProjectNewProperties() throws Exception {
    NewLiferayModuleProjectOp op = NewLiferayModuleProjectOp.TYPE.instantiate();

    op.setProjectName("test-properties-in-portlet");

    op.setProjectTemplateName("portlet");
    op.setComponentName("Test");

    PropertyKey pk = op.getPropertyKeys().insert();

    pk.setName("property-test-key");
    pk.setValue("property-test-value");

    Status exStatus =
        NewLiferayModuleProjectOpMethods.execute(
            op, ProgressMonitorBridge.create(new NullProgressMonitor()));

    assertEquals("OK", exStatus.message());

    IProject modPorject = CoreUtil.getProject(op.getProjectName().content());
    modPorject.open(new NullProgressMonitor());

    SearchFilesVisitor sv = new SearchFilesVisitor();
    List<IFile> searchFiles = sv.searchFiles(modPorject, "TestPortlet.java");
    IFile componentClassFile = searchFiles.get(0);

    assertEquals(componentClassFile.exists(), true);

    String actual = CoreUtil.readStreamToString(componentClassFile.getContents());

    assertTrue(actual, actual.contains("\"property-test-key=property-test-value\""));
  }
  public static Set<String> getPossibleProfileIds(
      NewLiferayPluginProjectOp op, boolean includeNewProfiles) {
    final String activeProfilesValue = op.getActiveProfilesValue().content();

    final Path currentLocation = op.getLocation().content();

    final File param = currentLocation != null ? currentLocation.toFile() : null;

    final List<String> systemProfileIds =
        op.getProjectProvider().content().getData("profileIds", String.class, param);

    final ElementList<NewLiferayProfile> newLiferayProfiles = op.getNewLiferayProfiles();

    final Set<String> possibleProfileIds = new HashSet<String>();

    if (!CoreUtil.isNullOrEmpty(activeProfilesValue)) {
      final String[] vals = activeProfilesValue.split(",");

      if (!CoreUtil.isNullOrEmpty(vals)) {
        for (String val : vals) {
          if (!possibleProfileIds.contains(val) && !val.contains(StringPool.SPACE)) {
            possibleProfileIds.add(val);
          }
        }
      }
    }

    if (!CoreUtil.isNullOrEmpty(systemProfileIds)) {
      for (Object systemProfileId : systemProfileIds) {
        if (systemProfileId != null) {
          final String val = systemProfileId.toString();

          if (!possibleProfileIds.contains(val) && !val.contains(StringPool.SPACE)) {
            possibleProfileIds.add(val);
          }
        }
      }
    }

    if (includeNewProfiles) {
      for (NewLiferayProfile newLiferayProfile : newLiferayProfiles) {
        final String newId = newLiferayProfile.getId().content();

        if ((!CoreUtil.isNullOrEmpty(newId))
            && (!possibleProfileIds.contains(newId))
            && (!newId.contains(StringPool.SPACE))) {
          possibleProfileIds.add(newId);
        }
      }
    }

    return possibleProfileIds;
  }
示例#5
0
  protected boolean shouldFullBuild(Map args) throws CoreException {
    if (args != null && args.get("force") != null && args.get("force").equals("true")) {
      return true;
    }

    // check to see if there is any files in the _diffs folder
    // IDE-110 IDE-648
    final IWebProject lrproject = LiferayCore.create(IWebProject.class, getProject());

    if (lrproject != null && lrproject.getDefaultDocrootFolder() != null) {
      final IFolder webappRoot = lrproject.getDefaultDocrootFolder();

      if (webappRoot != null) {
        IFolder diffs = webappRoot.getFolder(new Path("_diffs"));

        if (diffs != null && diffs.exists()) {
          IResource[] diffMembers = diffs.members();

          if (!CoreUtil.isNullOrEmpty(diffMembers)) {
            return true;
          }
        }
      }
    }

    return false;
  }
  public static PortletLayoutElement createFromElement(
      IDOMElement portletLayoutElement, ILayoutTplDiagramFactory factory) {
    if (portletLayoutElement == null) {
      return null;
    }

    PortletLayoutElement newPortletLayout = factory.newPortletLayout();

    String existingClassName = portletLayoutElement.getAttribute("class"); // $NON-NLS-1$

    if ((!CoreUtil.isNullOrEmpty(existingClassName))
        && existingClassName.contains("portlet-layout")) // $NON-NLS-1$
    {
      newPortletLayout.setClassName(existingClassName);
    } else {
      newPortletLayout.setClassName("portlet-layout"); // $NON-NLS-1$
    }

    IDOMElement[] portletColumnElements =
        LayoutTplUtil.findChildElementsByClassName(
            portletLayoutElement, "div", "portlet-column"); // $NON-NLS-1$ //$NON-NLS-2$

    for (IDOMElement portletColumnElement : portletColumnElements) {
      PortletColumnElement newPortletColumn =
          factory.newPortletColumnFromElement(portletColumnElement);
      newPortletLayout.addColumn(newPortletColumn);
    }

    return newPortletLayout;
  }
  private static LiferayDescriptorHelper[] getDescriptorHelpers(
      IProject project, Class<? extends IDescriptorOperation> type) {
    List<LiferayDescriptorHelper> retval = new ArrayList<LiferayDescriptorHelper>();

    project = CoreUtil.getLiferayProject(project);

    if (project == null || !project.exists()) {
      return null;
    }

    final LiferayDescriptorHelper[] allHelpers =
        LiferayDescriptorHelperReader.getInstance().getAllHelpers();

    for (LiferayDescriptorHelper helper : allHelpers) {
      helper.setProject(project);

      final IFile descriptorFile = helper.getDescriptorFile();

      if (descriptorFile != null && descriptorFile.exists()) {
        if (helper.getDescriptorOperation(type) != null) {
          retval.add(helper);
        }
      }
    }

    return retval.toArray(new LiferayDescriptorHelper[0]);
  }
  public static String getLiferayWorkspaceProjectModulesDir(final IProject project) {
    String retval = null;

    if (project != null) {
      final IPath projectLocation = project.getLocation();

      if (projectLocation != null) {
        final IPath gradlePropertiesLocation = projectLocation.append("gradle.properties");

        if (gradlePropertiesLocation.toFile().exists()) {
          try {
            String modulesDir =
                CoreUtil.readPropertyFileValue(
                    gradlePropertiesLocation.toFile(), "liferay.workspace.modules.dir");

            if (modulesDir == null) {
              modulesDir = "modules";
            }

            retval = modulesDir;
          } catch (IOException e) {
            ProjectCore.logError("Can't read gradle properties from workspaceProject. ", e);
          }
        }
      }
    }

    return retval;
  }
  public void createDefaultFile(IContainer container, String version, String id, String name) {
    if (container == null || id == null || name == null) {
      return;
    }

    try {
      final Path path =
          new Path("WEB-INF/" + ILiferayConstants.LIFERAY_LOOK_AND_FEEL_XML_FILE); // $NON-NLS-1$
      final IFile lookAndFeelFile = container.getFile(path);
      final String descriptorVersion = getDescriptorVersionFromPortalVersion(version);

      CoreUtil.prepareFolder((IFolder) lookAndFeelFile.getParent());

      String contents =
          MessageFormat.format(
              DEFUALT_FILE_TEMPLATE, descriptorVersion, descriptorVersion.replace('.', '_'));
      contents =
          contents
              .replaceAll("__VERSION__", version + "+")
              .replaceAll("__ID__", id)
              .replaceAll( //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                  "__NAME__", name); // $NON-NLS-1$

      lookAndFeelFile.create(new ByteArrayInputStream(contents.getBytes()), true, null);
    } catch (CoreException e) {
      ThemeCore.logError("Error creating default descriptor file", e); // $NON-NLS-1$
    }
  }
  private String getConfigInfoFromManifest(String configType, IPath portalDir) {
    File implJar = portalDir.append("/WEB-INF/lib/portal-impl.jar").toFile();

    String version = null;
    String serverInfo = null;

    if (implJar.exists()) {
      try (JarFile jar = new JarFile(implJar)) {
        Manifest manifest = jar.getManifest();

        Attributes attributes = manifest.getMainAttributes();

        version = attributes.getValue("Liferay-Portal-Version");
        serverInfo = attributes.getValue("Liferay-Portal-Server-Info");

        if (CoreUtil.compareVersions(Version.parseVersion(version), MANIFEST_VERSION_REQUIRED)
            < 0) {
          version = null;
          serverInfo = null;
        }
      } catch (IOException e) {
        LiferayServerCore.logError(e);
      }
    }

    if (configType.equals(CONFIG_TYPE_VERSION)) {
      return version;
    }

    if (configType.equals(CONFIG_TYPE_SERVER)) {
      return serverInfo;
    }

    return null;
  }
示例#11
0
  /**
   * this will convert the IO file name of the resource bundle to java package name
   *
   * @param project
   * @param value - the io file name
   * @return - the java package name of the resource bundle
   */
  public static String convertIOToJavaFileName(IProject project, String value) {
    String rbIOFile = value.substring(value.lastIndexOf("/") + 1); // $NON-NLS-1$
    IFile resourceBundleFile = null;
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot wroot = workspace.getRoot();
    IClasspathEntry[] cpEntries = CoreUtil.getClasspathEntries(project);
    for (IClasspathEntry iClasspathEntry : cpEntries) {
      if (IClasspathEntry.CPE_SOURCE == iClasspathEntry.getEntryKind()) {
        IPath entryPath = wroot.getFolder(iClasspathEntry.getPath()).getLocation();
        entryPath = entryPath.append(rbIOFile);
        resourceBundleFile = wroot.getFileForLocation(entryPath);
        // System.out.println( "ResourceBundleValidationService.validate():" + resourceBundleFile );
        if (resourceBundleFile != null && resourceBundleFile.exists()) {
          break;
        }
      }
    }

    String javaName = resourceBundleFile.getProjectRelativePath().toPortableString();
    if (javaName.indexOf('.') != -1) {
      // Strip the extension
      javaName = value.substring(0, value.lastIndexOf('.'));
      // Replace all "/" by "."
      javaName = javaName.replace('/', '.');
    }
    return javaName;
  }
  @Override
  public Object getDefaultProperty(String propertyName) {
    if (LAYOUT_TEMPLATE_NAME.equals(propertyName)) {
      return "New Template"; //$NON-NLS-1$
    } else if (LAYOUT_TEMPLATE_ID.equals(propertyName)) {
      String name = getStringProperty(LAYOUT_TEMPLATE_NAME);

      if (!CoreUtil.isNullOrEmpty(name)) {
        return name.replaceAll("[^a-zA-Z0-9]+", StringPool.EMPTY).toLowerCase(); // $NON-NLS-1$
      }
    } else if (LAYOUT_TEMPLATE_FILE.equals(propertyName)) {
      return "/" + getStringProperty(LAYOUT_TEMPLATE_ID) + ".tpl"; // $NON-NLS-1$//$NON-NLS-2$
    } else if (LAYOUT_WAP_TEMPLATE_FILE.equals(propertyName)) {
      return "/" + getStringProperty(LAYOUT_TEMPLATE_ID) + ".wap.tpl"; // $NON-NLS-1$//$NON-NLS-2$
    } else if (LAYOUT_THUMBNAIL_FILE.equals(propertyName)) {
      return "/" + getStringProperty(LAYOUT_TEMPLATE_ID) + ".png"; // $NON-NLS-1$//$NON-NLS-2$
    } else if (LAYOUT_IMAGE_BLANK_COLUMN.equals(propertyName)) {
      return true;
    } else if (LAYOUT_IMAGE_1_COLUMN.equals(propertyName)
        || LAYOUT_IMAGE_1_2_1_COLUMN.equals(propertyName)
        || LAYOUT_IMAGE_1_2_I_COLUMN.equals(propertyName)
        || LAYOUT_IMAGE_1_2_II_COLUMN.equals(propertyName)
        || LAYOUT_IMAGE_2_2_COLUMN.equals(propertyName)
        || LAYOUT_IMAGE_2_I_COLUMN.equals(propertyName)
        || LAYOUT_IMAGE_2_II_COLUMN.equals(propertyName)
        || LAYOUT_IMAGE_2_III_COLUMN.equals(propertyName)
        || LAYOUT_IMAGE_3_COLUMN.equals(propertyName)) {

      return false;
    }

    return super.getDefaultProperty(propertyName);
  }
  protected void updateStubs() {
    ILiferayRuntimeStub[] stubs = LiferayServerCore.getRuntimeStubs();

    if (CoreUtil.isNullOrEmpty(stubs)) {
      return;
    }

    String[] names = new String[stubs.length];

    LiferayRuntimeStubDelegate delegate = getStubDelegate();

    String stubId = delegate.getRuntimeStubTypeId();

    int stubIndex = -1;

    for (int i = 0; i < stubs.length; i++) {
      names[i] = stubs[i].getName();
      if (stubs[i].getRuntimeStubTypeId().equals(stubId)) {
        stubIndex = i;
      }
    }

    comboRuntimeStubType.setItems(names);

    if (stubIndex >= 0) {
      comboRuntimeStubType.select(stubIndex);
    }
  }
  @Override
  public void setupLaunchConfiguration(
      ILaunchConfigurationWorkingCopy workingCopy, IProgressMonitor monitor) throws CoreException {

    super.setupLaunchConfiguration(workingCopy, monitor);

    workingCopy.setAttribute(DebugPlugin.ATTR_CONSOLE_ENCODING, "UTF-8"); // $NON-NLS-1$

    String existingVMArgs =
        workingCopy.getAttribute(
            IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, (String) null);

    if (null != existingVMArgs) {
      String[] parsedVMArgs = DebugPlugin.parseArguments(existingVMArgs);

      List<String> memoryArgs = new ArrayList<String>();

      if (!CoreUtil.isNullOrEmpty(parsedVMArgs)) {
        for (String pArg : parsedVMArgs) {
          if (pArg.startsWith("-Xm") || pArg.startsWith("-XX:")) // $NON-NLS-1$ //$NON-NLS-2$
          {
            memoryArgs.add(pArg);
          }
        }
      }

      String argsWithoutMem =
          mergeArguments(
              existingVMArgs, getRuntimeVMArguments(), memoryArgs.toArray(new String[0]), false);
      String fixedArgs = mergeArguments(argsWithoutMem, getRuntimeVMArguments(), null, false);

      workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, fixedArgs);
    }
  }
    protected void handleNewImplClassButton(Text text) {
      if (CoreUtil.isNullOrEmpty(texts[0].getText())) {
        MessageDialog.openWarning(getParentShell(), Msgs.addService, Msgs.specifyServiceType);

        return;
      }

      String serviceType = texts[0].getText();

      String wrapperType = StringPool.EMPTY;

      if (serviceType.endsWith("Service")) // $NON-NLS-1$
      {
        wrapperType = serviceType + "Wrapper"; // $NON-NLS-1$
      }

      NewEventActionClassDialog dialog =
          new NewServiceWrapperClassDialog(getShell(), model, serviceType, wrapperType);

      if (dialog.open() == Window.OK) {
        String qualifiedClassname = dialog.getQualifiedClassname();

        text.setText(qualifiedClassname);
      }
    }
  private void saveConfigInfoIntoCache(String configType, String configInfo, IPath portalDir) {
    IPath versionsInfoPath = null;

    if (configType.equals(CONFIG_TYPE_VERSION)) {
      versionsInfoPath =
          LiferayServerCore.getDefault().getStateLocation().append("version.properties");
    } else if (configType.equals(CONFIG_TYPE_SERVER)) {
      versionsInfoPath =
          LiferayServerCore.getDefault().getStateLocation().append("serverInfos.properties");
    }

    if (versionsInfoPath != null) {
      File versionInfoFile = versionsInfoPath.toFile();

      if (configInfo != null) {
        String portalDirKey = CoreUtil.createStringDigest(portalDir.toPortableString());
        Properties properties = new Properties();

        try (FileInputStream fileInput = new FileInputStream(versionInfoFile)) {
          properties.load(fileInput);
        } catch (Exception e) {
        }

        try (FileOutputStream fileOutput = new FileOutputStream(versionInfoFile)) {
          properties.put(portalDirKey, configInfo);
          properties.store(fileOutput, StringPool.EMPTY);
        } catch (Exception e) {
          LiferayServerCore.logError(e);
        }
      }
    }
  }
示例#17
0
  protected void initMap() {
    try {
      wsdlNameURLMap = new HashMap<String, String>();
      String webServicesString = CoreUtil.readStreamToString(webServicesListURL.openStream());
      List<String> wsdlUrls = pullLinks(webServicesString);

      for (String url : wsdlUrls) {
        String name = pullServiceName(url);

        if (!CoreUtil.isNullOrEmpty(name)) {
          wsdlNameURLMap.put(name, url);
        }
      }
    } catch (IOException e1) {
      LiferayServerCore.logError("Unable to initial web services list."); // $NON-NLS-1$
    }
  }
  @Override
  public void selectionChanged(IStructuredSelection selection) {
    final Object element = getStructuredSelection().getFirstElement();

    if (element instanceof Problem && !CoreUtil.empty(((Problem) element).getTicket())) {
      setEnabled(true);
    } else {
      setEnabled(false);
    }
  }
  public static IProject getLiferayWorkspaceProject() {
    IProject[] projects = CoreUtil.getAllProjects();

    for (IProject project : projects) {
      if (isValidWorkspace(project)) {
        return project;
      }
    }
    return null;
  }
  private boolean isError(JSONObject jsonObject) {
    try {
      final String error = jsonObject.getString("error"); // $NON-NLS-1$

      return !CoreUtil.isNullOrEmpty(error);
    } catch (JSONException e) {
    }

    return false;
  }
  private static IStatus removeSampleCodeAndFiles(NewLiferayPluginProjectOp op) {
    IStatus status = org.eclipse.core.runtime.Status.OK_STATUS;

    final boolean includeSampleCode = op.getIncludeSampleCode().content();

    if (!includeSampleCode) {
      final IProject project = CoreUtil.getLiferayProject(op.getFinalProjectName().content());

      if (project != null && project.exists()) {
        ProjectCore.operate(project, RemoveSampleElementsOperation.class);

        // delete sample files: view.jsp, main.css, main.js
        try {
          final IWebProject webproject = LiferayCore.create(IWebProject.class, project);

          if (webproject != null) {
            final IFolder docroot = webproject.getDefaultDocrootFolder();

            final IFile[] sampleFiles = {
              docroot.getFile("view.jsp"),
              docroot.getFile("css/main.css"),
              docroot.getFile("js/main.js")
            };

            for (IFile file : sampleFiles) {
              if (file != null && file.exists()) {
                file.delete(true, new NullProgressMonitor());

                if (file.getParent().members().length == 0) {
                  CoreUtil.deleteResource(file.getParent());
                }
              }
            }
          }
        } catch (CoreException e) {
          ProjectCore.logError("Error deleting sample files.", e);
        }
      }
    }

    return status;
  }
  public void checkValidProjectTypes() {
    IProject[] projects = CoreUtil.getAllProjects();
    boolean hasValidProjectTypes = false;

    boolean hasJsfFacet = false;

    for (IProject project : projects) {
      if (ProjectUtil.isLiferayProject(project)) {
        Set<IProjectFacetVersion> facets =
            ProjectUtil.getFacetedProject(project).getProjectFacets();

        if (validProjectTypes != null && facets != null) {
          String[] validTypes = validProjectTypes.split(",");

          for (String validProjectType : validTypes) {
            for (IProjectFacetVersion facet : facets) {
              String id = facet.getProjectFacet().getId();

              if (isJsfPortlet && id.equals("jst.jsf")) {
                hasJsfFacet = true;
              }

              if (id.startsWith("liferay.") && id.equals("liferay." + validProjectType)) {
                hasValidProjectTypes = true;
              }
            }
          }
        }
      }
    }

    if (isJsfPortlet) {
      hasValidProjectTypes = hasJsfFacet && hasValidProjectTypes;
    }

    if (!hasValidProjectTypes) {
      final Shell activeShell = Display.getDefault().getActiveShell();
      Boolean openNewLiferayProjectWizard =
          MessageDialog.openQuestion(
              activeShell,
              "New Element",
              "There are no suitable Liferay projects available for this new element.\nDo you want"
                  + " to open the \'New Liferay Project\' wizard now?");

      if (openNewLiferayProjectWizard) {
        Action[] actions = NewPluginProjectDropDownAction.getNewProjectActions();

        if (actions.length > 0) {
          actions[0].run();
          this.checkValidProjectTypes();
        }
      }
    }
  }
    protected void handleSelectImplClassButton(Text text) {
      if (CoreUtil.isNullOrEmpty(texts[0].getText())) {
        MessageDialog.openWarning(getParentShell(), Msgs.addService, Msgs.specifyServiceType);

        return;
      }

      IPackageFragmentRoot packRoot =
          (IPackageFragmentRoot)
              model.getProperty(INewJavaClassDataModelProperties.JAVA_PACKAGE_FRAGMENT_ROOT);

      if (packRoot == null) {
        return;
      }

      IJavaSearchScope scope = null;

      try {
        // get the Service type and replace Service with Wrapper and
        // make it the supertype
        String serviceType = texts[0].getText();

        if (serviceType.endsWith("Service")) // $NON-NLS-1$
        {
          String wrapperType = serviceType + "Wrapper"; // $NON-NLS-1$

          scope =
              BasicSearchEngine.createHierarchyScope(
                  packRoot.getJavaProject().findType(wrapperType));
        }
      } catch (JavaModelException e) {
        HookUI.logError(e);

        return;
      }

      FilteredTypesSelectionDialog dialog =
          new FilteredTypesSelectionDialogEx(
              getShell(), false, null, scope, IJavaSearchConstants.CLASS);
      dialog.setTitle(J2EEUIMessages.SUPERCLASS_SELECTION_DIALOG_TITLE);
      dialog.setMessage(J2EEUIMessages.SUPERCLASS_SELECTION_DIALOG_DESC);

      if (dialog.open() == Window.OK) {
        IType type = (IType) dialog.getFirstResult();

        String classFullPath = J2EEUIMessages.EMPTY_STRING;

        if (type != null) {
          classFullPath = type.getFullyQualifiedName();
        }

        text.setText(classFullPath);
      }
    }
  private void createServiceXmlFile(String version, boolean useSample) throws Exception {
    final IProject project = createProject("serviceXmlFiles-" + version + "-" + useSample);

    final IDataModel model =
        DataModelFactory.createDataModel(new NewServiceBuilderDataModelProvider());

    model.setProperty(NewServiceBuilderDataModelProvider.AUTHOR, "junit");
    model.setProperty(NewServiceBuilderDataModelProvider.PACKAGE_PATH, "com.liferay.sample");
    model.setProperty(NewServiceBuilderDataModelProvider.NAMESPACE, "SAMPLE");
    model.setBooleanProperty(NewServiceBuilderDataModelProvider.USE_SAMPLE_TEMPLATE, useSample);

    final IFolder folder = project.getFolder("test");

    CoreUtil.prepareFolder(folder);

    final IFile serviceXmlFile = folder.getFile("service.xml");

    assertEquals(false, serviceXmlFile.exists());

    WizardUtil.createDefaultServiceBuilderFile(
        serviceXmlFile,
        version,
        model.getBooleanProperty(NewServiceBuilderDataModelProvider.USE_SAMPLE_TEMPLATE),
        model.getStringProperty(NewServiceBuilderDataModelProvider.PACKAGE_PATH),
        model.getStringProperty(NewServiceBuilderDataModelProvider.NAMESPACE),
        model.getStringProperty(NewServiceBuilderDataModelProvider.AUTHOR),
        new NullProgressMonitor());

    assertEquals(true, serviceXmlFile.exists());

    final String serviceXmlContent = CoreUtil.readStreamToString(serviceXmlFile.getContents());

    final String expectedServiceXmlContent =
        CoreUtil.readStreamToString(
            this.getClass()
                .getResourceAsStream("files/service-sample-" + version + "-" + useSample + ".xml"));

    assertEquals(
        stripCarriageReturns(expectedServiceXmlContent), stripCarriageReturns(serviceXmlContent));
  }
  @Test
  public void testNewWebAntProjectValidation() throws Exception {
    IPath liferayPluginsSdkDir = super.getLiferayPluginsSdkDir();

    final File liferayPluginsSdkDirFile = liferayPluginsSdkDir.toFile();

    if (!liferayPluginsSdkDirFile.exists()) {
      final File liferayPluginsSdkZipFile = super.getLiferayPluginsSDKZip().toFile();

      assertEquals(
          "Expected file to exist: " + liferayPluginsSdkZipFile.getAbsolutePath(),
          true,
          liferayPluginsSdkZipFile.exists());

      liferayPluginsSdkDirFile.mkdirs();

      final String liferayPluginsSdkZipFolder = super.getLiferayPluginsSdkZipFolder();

      if (CoreUtil.isNullOrEmpty(liferayPluginsSdkZipFolder)) {
        ZipUtil.unzip(liferayPluginsSdkZipFile, liferayPluginsSdkDirFile);
      } else {
        ZipUtil.unzip(
            liferayPluginsSdkZipFile,
            liferayPluginsSdkZipFolder,
            liferayPluginsSdkDirFile,
            new NullProgressMonitor());
      }
    }

    assertEquals(true, liferayPluginsSdkDirFile.exists());

    SDK sdk = null;

    final SDK existingSdk = SDKManager.getInstance().getSDK(liferayPluginsSdkDir);

    if (existingSdk == null) {
      sdk = SDKUtil.createSDKFromLocation(liferayPluginsSdkDir);
    } else {
      sdk = existingSdk;
    }

    final String projectName = "test-web-project-sdk";

    final NewLiferayPluginProjectOp op = newProjectOp(projectName);

    op.setPluginsSDKName(sdk.getName());
    op.setPluginType(PluginType.web);

    assertEquals(
        "The selected Plugins SDK does not support creating new web type plugins.  Please configure version 7.0.0 or greater.",
        op.getPluginType().validation().message());
  }
  protected void handleFileBrowseButton(final Text text) {
    ISelectionStatusValidator validator = getContainerDialogSelectionValidator();

    ViewerFilter filter = getContainerDialogViewerFilter();

    ITreeContentProvider contentProvider = new WorkbenchContentProvider();

    ILabelProvider labelProvider =
        new DecoratingLabelProvider(
            new WorkbenchLabelProvider(),
            PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator());

    ElementTreeSelectionDialog dialog =
        new ElementTreeSelectionDialog(getShell(), labelProvider, contentProvider);
    dialog.setValidator(validator);
    dialog.setTitle(J2EEUIMessages.CONTAINER_SELECTION_DIALOG_TITLE);
    dialog.setMessage(J2EEUIMessages.CONTAINER_SELECTION_DIALOG_DESC);
    dialog.addFilter(filter);
    dialog.setInput(CoreUtil.getWorkspaceRoot());

    if (dialog.open() == Window.OK) {
      Object element = dialog.getFirstResult();

      try {
        if (element instanceof IFolder) {
          IFolder folder = (IFolder) element;

          if (folder.equals(
              CoreUtil.getFirstSrcFolder(getDataModel().getStringProperty(PROJECT_NAME)))) {
            folder = folder.getFolder("content"); // $NON-NLS-1$
          }

          text.setText(folder.getFullPath().toPortableString());
        }
      } catch (Exception ex) {
        // Do nothing
      }
    }
  }
  @Test
  public void testNewWebAntProject() throws Exception {
    final String projectName = "test-web-project-sdk";
    final NewLiferayPluginProjectOp op = newProjectOp(projectName);

    op.setPluginType(PluginType.web);

    final IProject webProject = createAntProject(op);

    final IVirtualFolder webappRoot = CoreUtil.getDocroot(webProject);

    assertNotNull(webappRoot);
  }
  private String getConfigInfoFromCache(String configType, IPath portalDir) {
    File configInfoFile = getConfigInfoPath(configType).toFile();

    String portalDirKey = CoreUtil.createStringDigest(portalDir.toPortableString());

    Properties properties = new Properties();

    if (configInfoFile.exists()) {
      try (FileInputStream fileInput = new FileInputStream(configInfoFile)) {
        properties.load(fileInput);
        String configInfo = (String) properties.get(portalDirKey);

        if (!CoreUtil.isNullOrEmpty(configInfo)) {
          return configInfo;
        }
      } catch (IOException e) {
        LiferayServerCore.logError(e);
      }
    }

    return null;
  }
示例#29
0
  protected void applyDiffsDeltaToDocroot(
      final IResourceDelta delta, final IContainer docroot, final IProgressMonitor monitor) {
    int deltaKind = delta.getKind();

    switch (deltaKind) {
      case IResourceDelta.REMOVED_PHANTOM:
        break;
    }

    final IPath path = CoreUtil.getResourceLocation(docroot);
    // final IPath restoreLocation = getRestoreLocation(docroot);

    final ILiferayProject liferayProject = LiferayCore.create(getProject());

    final String themeParent = liferayProject.getProperty("theme.parent", "_styled");

    final ILiferayPortal portal = liferayProject.adapt(ILiferayPortal.class);

    if (portal != null) {
      final IPath themesPath = portal.getAppServerPortalDir().append("html/themes");
      final List<IPath> restorePaths = new ArrayList<IPath>();

      for (int i = 0; i < IPluginProjectDataModelProperties.THEME_PARENTS.length; i++) {
        if (IPluginProjectDataModelProperties.THEME_PARENTS[i].equals(themeParent)) {
          restorePaths.add(themesPath.append(IPluginProjectDataModelProperties.THEME_PARENTS[i]));
        } else {
          if (restorePaths.size() > 0) {
            restorePaths.add(themesPath.append(IPluginProjectDataModelProperties.THEME_PARENTS[i]));
          }
        }
      }

      new Job("publish theme delta") // $NON-NLS-1$
      {
        @Override
        protected IStatus run(IProgressMonitor monitor) {
          buildHelper.publishDelta(delta, path, restorePaths.toArray(new IPath[0]), monitor);

          try {
            docroot.refreshLocal(IResource.DEPTH_INFINITE, monitor);
          } catch (Exception e) {
            ThemeCore.logError(e);
          }

          return Status.OK_STATUS;
        }
      }.schedule();
    }
  }
  @Override
  public IStatus validate(String propertyName) {
    if (LAYOUT_TEMPLATE_ID.equals(propertyName)) {
      // first check to see if an existing property exists.
      LayoutTplDescriptorHelper helper = new LayoutTplDescriptorHelper(getTargetProject());

      if (helper.hasTemplateId(getStringProperty(propertyName))) {
        return LayoutTplCore.createErrorStatus(Msgs.templateIdExists);
      }

      // to avoid marking text like "this" as bad add a z to the end of the string
      String idValue = getStringProperty(propertyName) + "z"; // $NON-NLS-1$

      if (CoreUtil.isNullOrEmpty(idValue)) {
        return super.validate(propertyName);
      }

      IStatus status =
          JavaConventions.validateFieldName(
              idValue, CompilerOptions.VERSION_1_5, CompilerOptions.VERSION_1_5);

      if (!status.isOK()) {
        return LayoutTplCore.createErrorStatus(Msgs.templateIdInvalid);
      }
    } else if (LAYOUT_TEMPLATE_FILE.equals(propertyName)) {
      final IPath filePath = new Path(getStringProperty(LAYOUT_TEMPLATE_FILE));

      if (checkDocrootFileExists(filePath)) {
        return LayoutTplCore.createWarningStatus(Msgs.templateFileExists);
      }
    } else if (LAYOUT_WAP_TEMPLATE_FILE.equals(propertyName)) {
      final IPath filePath = new Path(getStringProperty(LAYOUT_WAP_TEMPLATE_FILE));

      if (checkDocrootFileExists(filePath)) {
        return LayoutTplCore.createWarningStatus(Msgs.wapTemplateFileExists);
      }
    } else if (LAYOUT_THUMBNAIL_FILE.equals(propertyName)) {
      final IPath filePath = new Path(getStringProperty(LAYOUT_THUMBNAIL_FILE));

      if (checkDocrootFileExists(filePath)) {
        return LayoutTplCore.createWarningStatus(Msgs.thumbnailFileExists);
      }
    }

    return super.validate(propertyName);
  }