Example usage for org.eclipse.jdt.core JavaConventions validateIdentifier

List of usage examples for org.eclipse.jdt.core JavaConventions validateIdentifier

Introduction

In this page you can find the example usage for org.eclipse.jdt.core JavaConventions validateIdentifier.

Prototype

public static IStatus validateIdentifier(String id, String sourceLevel, String complianceLevel) 

Source Link

Document

Validate the given Java identifier for the given source and compliance levels The identifier must not have the same spelling as a Java keyword, boolean literal ("true", "false"), or null literal ("null").

Usage

From source file:com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator.java

License:Open Source License

@Override
public String isValid(String newText) {
    // IValidator has the same interface as SWT's IInputValidator
    try {//from  ww  w.j ava2  s  .co  m
        if (newText == null || newText.trim().length() == 0) {
            return "Enter a new name";
        }

        if (mAllowXmlExtension && newText.endsWith(DOT_XML)) {
            newText = newText.substring(0, newText.length() - DOT_XML.length());
        }

        if (mAllowXmlExtension && mIsImageType && ImageUtils.hasImageExtension(newText)) {
            newText = newText.substring(0, newText.lastIndexOf('.'));
        }

        if (!mIsFileType) {
            newText = newText.replace('.', '_');
        }

        if (newText.indexOf('.') != -1 && !newText.endsWith(DOT_XML)) {
            if (mIsImageType) {
                return "The filename must end with .xml or .png";
            } else {
                return "The filename must end with .xml";
            }
        }

        // Resource names must be valid Java identifiers, since they will
        // be represented as Java identifiers in the R file:
        if (!Character.isJavaIdentifierStart(newText.charAt(0))) {
            return "The resource name must begin with a character";
        }
        for (int i = 1, n = newText.length(); i < n; i++) {
            char c = newText.charAt(i);
            if (!Character.isJavaIdentifierPart(c)) {
                return String.format("'%1$c' is not a valid resource name character", c);
            }
        }

        if (mIsFileType) {
            char first = newText.charAt(0);
            if (!(first >= 'a' && first <= 'z')) {
                return String.format("File-based resource names must start with a lowercase letter.");
            }

            // AAPT only allows lowercase+digits+_:
            // "%s: Invalid file name: must contain only [a-z0-9_.]","
            for (int i = 0, n = newText.length(); i < n; i++) {
                char c = newText.charAt(i);
                if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_')) {
                    return String
                            .format("File-based resource names must contain only lowercase a-z, 0-9, or _.");
                }
            }
        }

        String level = "1.5"; //$NON-NLS-1$
        IStatus validIdentifier = JavaConventions.validateIdentifier(newText, level, level);
        if (!validIdentifier.isOK()) {
            return String.format("%1$s is not a valid name (reserved Java keyword)", newText);
        }

        if (mExisting != null && (mUnique || mExist)) {
            boolean exists = mExisting.contains(newText);
            if (mUnique && exists) {
                return String.format("%1$s already exists", newText);
            } else if (mExist && !exists) {
                return String.format("%1$s does not exist", newText);
            }
        }

        return null;
    } catch (Exception e) {
        AdtPlugin.log(e, "Validation failed: %s", e.toString());
        return ""; //$NON-NLS-1$
    }
}

From source file:com.android.ide.eclipse.adt.internal.wizards.newxmlfile.ResourceNameValidator.java

License:Open Source License

public String isValid(String newText) {
    // IValidator has the same interface as SWT's IInputValidator
    try {/*from   ww  w .  j  a  v  a  2s. co m*/
        if (newText == null || newText.trim().length() == 0) {
            return "Enter a new name";
        }

        if (mAllowXmlExtension && newText.endsWith(DOT_XML)) {
            newText = newText.substring(0, newText.length() - DOT_XML.length());
        }

        if (newText.indexOf('.') != -1 && !newText.endsWith(AndroidConstants.DOT_XML)) {
            return String.format("The filename must end with %1$s.", DOT_XML);
        }

        // Resource names must be valid Java identifiers, since they will
        // be represented as Java identifiers in the R file:
        if (!Character.isJavaIdentifierStart(newText.charAt(0))) {
            return "The layout name must begin with a character";
        }
        for (int i = 1, n = newText.length(); i < n; i++) {
            char c = newText.charAt(i);
            if (!Character.isJavaIdentifierPart(c)) {
                return String.format("%1$c is not a valid resource name character", c);
            }
        }

        String level = "1.5"; //$NON-NLS-1$
        IStatus validIdentifier = JavaConventions.validateIdentifier(newText, level, level);
        if (!validIdentifier.isOK()) {
            return String.format("%1$s is not a valid name (reserved Java keyword)", newText);
        }

        if (mExisting != null && mExisting.contains(newText)) {
            return String.format("%1$s already exists", newText);
        }

        return null;
    } catch (Exception e) {
        AdtPlugin.log(e, "Validation failed: %s", e.toString());
        return ""; //$NON-NLS-1$
    }
}

From source file:com.google.gdt.eclipse.designer.wizards.model.library.LibraryComposite.java

License:Open Source License

@Override
protected String validate() {
    m_descriptionText.setText("");
    // validate source folder
    if (m_sourceFolderField != null) {
        if (m_sourceFolderField.getText().length() == 0) {
            return "Source folder name can not be empty.";
        }/* www .ja  v  a 2s .c o  m*/
        m_root = m_sourceFolderField.getRoot();
        if (m_root == null) {
            return "Source folder is invalid.";
        }
    }
    // validate module name
    {
        String moduleName = m_moduleField.getText();
        if (moduleName.length() == 0) {
            return "Module name can not be empty.";
        }
        // check that module name is valid identifier
        IStatus status = JavaConventions.validateIdentifier(moduleName, null, null);
        if (status.getSeverity() == IStatus.ERROR) {
            return status.getMessage();
        }
    }
    // validate package name
    {
        String packageName = m_packageField.getText();
        if (packageName.length() == 0) {
            return "Package can not be empty.";
        }
        // check that package name is valid
        IStatus status = JavaConventions.validatePackageName(packageName, null, null);
        if (status.getSeverity() == IStatus.ERROR) {
            return status.getMessage();
        }
        // check that package does not exist
        if (m_root != null && m_root.getPackageFragment(packageName).exists()) {
            return "Package " + packageName + " already exists.";
        }
    }
    // update description
    {
        String mainLocation = m_packageField.getText().replace('.', '/');
        String descriptorLocation = mainLocation + "/" + m_moduleField.getText() + ".gwt.xml";
        String clientLocation = mainLocation + "/client";
        String publicLocation = mainLocation + "/public";
        String serverLocation = mainLocation + "/server";
        m_descriptionText.setText("Location of module descriptor file: " + descriptorLocation + "\n"
                + "Location of client (GWT) part: " + clientLocation + "\n"
                + "Location of public (static) part: " + publicLocation + "\n" + "Location of server part: "
                + serverLocation);
    }
    return null;
}

From source file:com.google.gdt.eclipse.designer.wizards.model.module.ModuleComposite.java

License:Open Source License

@Override
protected String validate() {
    m_descriptionText.setText("");
    // validate source folder
    if (m_sourceFolderField != null) {
        if (m_sourceFolderField.getText().length() == 0) {
            return "Source folder name can not be empty.";
        }/* w  w w . j  av a  2  s  .  c  o m*/
        m_root = m_sourceFolderField.getRoot();
        if (m_root == null) {
            return "Source folder is invalid.";
        }
    }
    // validtae MVP
    if (m_root != null) {
        m_createEntryPointMVPField
                .setEnabled(m_createEntryPointField.isSelected() && Utils.supportMvp(m_root.getJavaProject()));
    }
    // validate package name
    {
        String packageName = m_packageField.getText();
        if (packageName.length() == 0) {
            return "Package can not be empty.";
        }
        // check that package name is valid
        IStatus status = JavaConventions.validatePackageName(packageName, null, null);
        if (status.getSeverity() == IStatus.ERROR) {
            return status.getMessage();
        }
        // check that package does not exist
        if (m_root != null && m_root.getPackageFragment(packageName).exists()) {
            return "Package " + packageName + " already exists.";
        }
    }
    // validate module name
    {
        String moduleName = m_moduleField.getText();
        if (moduleName.length() == 0) {
            return "Module name can not be empty.";
        }
        // check that module name is valid identifier
        IStatus status = JavaConventions.validateIdentifier(moduleName, null, null);
        if (status.getSeverity() == IStatus.ERROR) {
            return status.getMessage();
        }
    }
    // update description
    {
        String mainLocation = m_packageField.getText().replace('.', '/');
        String descriptorLocation = mainLocation + "/" + m_moduleField.getText() + ".gwt.xml";
        String clientLocation = mainLocation + "/client";
        String publicLocation = mainLocation + "/public";
        String serverLocation = mainLocation + "/server";
        m_descriptionText.setText("Location of module descriptor file: " + descriptorLocation + "\n"
                + "Location of client (GWT) part: " + clientLocation + "\n"
                + "Location of public (static) part: " + publicLocation + "\n" + "Location of server part: "
                + serverLocation);
    }
    return null;
}

From source file:com.google.gdt.eclipse.designer.wizards.model.mvp.ViewComposite.java

License:Open Source License

/**
 * Validate ability to create class source file with specified name in specified package.
 * //w  w  w .j  a v  a 2 s.c o  m
 * @return if all Ok then <code>null</code> else error message
 */
private static String validateNewCompilationUnit(IPackageFragment packageFragment, String className,
        String messagePrefix) {
    if (className.length() == 0) {
        return messagePrefix + " can not be empty.";
    }
    // check that view name is valid identifier
    IStatus status = JavaConventions.validateIdentifier(className, null, null);
    if (status.getSeverity() == IStatus.ERROR) {
        return status.getMessage() + " for " + messagePrefix;
    }
    // check that view not exists
    if (packageFragment.exists()) {
        String classSourceName = className + ".java";
        ICompilationUnit compilationUnit = packageFragment.getCompilationUnit(classSourceName);
        if (compilationUnit.exists()) {
            return "Source file " + classSourceName + " already exists.";
        }
    }
    return null;
}

From source file:com.google.gdt.eclipse.designer.wizards.model.service.ServiceComposite.java

License:Open Source License

@Override
protected String validate() {
    IPackageFragment packageFragment = m_clientPackageField.getPackageFragment();
    // validate package
    {//w w w .ja  va 2 s. com
        if (packageFragment == null) {
            return "Select client package.";
        }
        try {
            if (!Utils.isModuleSourcePackage(packageFragment)) {
                return "Package " + packageFragment.getElementName() + " is not a client package.";
            }
        } catch (Throwable e) {
            return "Exception: " + e.getMessage();
        }
    }
    // validate service name
    {
        String serviceName = m_serviceField.getText();
        if (serviceName.length() == 0) {
            return "Service name can not be empty.";
        }
        // check that service name is valid identifier
        IStatus status = JavaConventions.validateIdentifier(serviceName, null, null);
        if (status.getSeverity() == IStatus.ERROR) {
            return status.getMessage();
        }
        // check that there are no class with same name
        try {
            String qualifiedServiceName = packageFragment.getElementName() + "." + serviceName;
            if (packageFragment.getJavaProject().findType(qualifiedServiceName) != null) {
                return "Type with such name already exists.";
            }
        } catch (Throwable e) {
            DesignerPlugin.log(e);
        }
    }
    return null;
}

From source file:com.liferay.ide.project.core.facet.PluginFacetProjectCreationDataModelProvider.java

License:Open Source License

@Override
public IStatus validate(String propertyName) {
    String frameworkId = getStringProperty(PORTLET_FRAMEWORK_ID);

    IPortletFrameworkWizardProvider framework = LiferayProjectCore.getPortletFramework(frameworkId);

    if (FACET_PROJECT_NAME.equals(propertyName)) {
        String projectName = getNestedModel().getStringProperty(PROJECT_NAME);

        if (CoreUtil.isNullOrEmpty(projectName)) {
            return super.validate(propertyName);
        }/* ww  w.j  a  v  a 2s .c o  m*/

        String testProjectName = projectName + getProjectSuffix();

        if (ProjectUtil.getProject(testProjectName).exists()) {
            return LiferayProjectCore.createErrorStatus(Msgs.projectExists);
        }

        //IDE-887 need manually check the location on the disk to make sure the project folder doesn't already exist
        final String projectLocation = getProjectLocation();

        if (projectLocation != null) {
            final IPath fullProjectPath = new Path(projectLocation).append(testProjectName);

            if (fullProjectPath.toFile().exists()) {
                return LiferayProjectCore
                        .createErrorStatus(Msgs.bind(Msgs.projectLocationExists, fullProjectPath));
            }
        }

        // before we do a basic java validation we need to strip "-" and "." characters

        String nameValidation = testProjectName.replaceAll("-", StringPool.EMPTY).replaceAll("\\.", //$NON-NLS-1$//$NON-NLS-2$
                StringPool.EMPTY);

        IStatus status = JavaConventions.validateIdentifier(nameValidation, CompilerOptions.VERSION_1_5,
                CompilerOptions.VERSION_1_5);

        if (!status.isOK()) {
            return LiferayProjectCore.createErrorStatus(Msgs.projectNameInvalid);
        }
    } else if (LIFERAY_SDK_NAME.equals(propertyName)) {
        Object sdkVal = getModel().getProperty(LIFERAY_SDK_NAME);

        if (sdkVal instanceof String && IPluginFacetConstants.LIFERAY_SDK_NAME_DEFAULT_VALUE.equals(sdkVal)) {
            return LiferayProjectCore.createErrorStatus(Msgs.configurePluginSDK);
        } else if (!CoreUtil.isNullOrEmpty(sdkVal.toString())) {
            SDK sdk = SDKManager.getInstance().getSDK(sdkVal.toString());

            if (sdk == null || !sdk.isValid()) {
                return LiferayProjectCore.createErrorStatus(Msgs.pluginSDKInvalid);
            } else {
                return Status.OK_STATUS;
            }
        }
    } else if (FACET_RUNTIME.equals(propertyName)) {
        // validate the sdk first
        IStatus status = validate(LIFERAY_SDK_NAME);

        if (!status.isOK()) {
            return status;
        }

        Object facetRuntime = getProperty(FACET_RUNTIME);

        if (facetRuntime == null) {
            return LiferayProjectCore.createErrorStatus(Msgs.configureLiferayPortalRuntime);
        } else if (facetRuntime instanceof BridgedRuntime) {
            if (ServerUtil.isLiferayRuntime((BridgedRuntime) facetRuntime)) {
                return Status.OK_STATUS;
            } else {
                return LiferayProjectCore.createErrorStatus(Msgs.selectLiferayPortalRuntime);
            }
        }
    } else if (PLUGIN_TYPE_PORTLET.equals(propertyName) || PLUGIN_TYPE_HOOK.equals(propertyName)
            || PLUGIN_TYPE_EXT.equals(propertyName) || PLUGIN_TYPE_THEME.equals(propertyName)
            || PLUGIN_TYPE_LAYOUTTPL.equals(propertyName)) {

        return validate(FACET_PROJECT_NAME);
    } else if (PORTLET_FRAMEWORK_ID.equals(propertyName) && getBooleanProperty(PLUGIN_TYPE_PORTLET)
            && framework != null) {
        // check to make sure that the current SDK has the propery version
        String sdkName = getStringProperty(LIFERAY_SDK_NAME);
        SDK selectedSDK = SDKManager.getInstance().getSDK(sdkName);

        if (selectedSDK == null) {
            return LiferayProjectCore.createErrorStatus(NLS.bind(Msgs.unableDetermineSDKVersion, sdkName));
        }

        Version sdkVersion = new Version(selectedSDK.getVersion());

        Version requiredSDKVersion = new Version(framework.getRequiredSDKVersion());

        if (CoreUtil.compareVersions(sdkVersion, requiredSDKVersion) < 0) {
            return framework.getUnsupportedSDKErrorMsg();
        } else {
            return Status.OK_STATUS;
        }
    } else if (THEME_TEMPLATE_FRAMEWORK.equals(propertyName)) {
        if (getModel().getStringProperty(THEME_TEMPLATE_FRAMEWORK).equals("JSP")) //$NON-NLS-1$
        {
            return LiferayProjectCore.createWarningStatus(Msgs.advancedThemeDevelopers);
        }
    }

    if (framework != null && framework.hasPropertyName(propertyName)) {
        return framework.validate(getDataModel(), propertyName);
    }

    return super.validate(propertyName);
}

From source file:com.motorola.studio.android.generateviewbylayout.codegenerators.AbstractLayoutCodeGenerator.java

License:Apache License

/**
 * Gets the name of the variable based on the type declared in the layout xml
 * @param node//from w ww  .j av  a  2s  .  c  om
 * @return
 * @throws CoreException 
 */
public SimpleName getNodeVariableTypeBasedOnLayoutNode(LayoutNode node) throws CoreException {
    SimpleName guiName = null;
    String clazzName = node.getClazzName();
    if (node.isFragmentPlaceholder() && (clazzName != null)) {
        //use type defined in the xml
        IStatus nameStatus = JavaConventions.validateIdentifier(clazzName, "5", "5");
        if (nameStatus.isOK()) {
            guiName = onCreateDeclaration.getAST().newSimpleName(clazzName);
        } else {
            throw new CoreException(nameStatus);
        }
    } else {
        guiName = onCreateDeclaration.getAST().newSimpleName(node.getNodeType());
    }
    return guiName;
}

From source file:org.codehaus.groovy.eclipse.codeassist.processors.PackageCompletionProcessor.java

License:Apache License

/**
 * more complete search to see if this is a valid package name
 * @param packageCompletionText/*from  ww w  . ja v  a2 s .  c o m*/
 * @return
 */
private boolean mightBePackage(char[] packageCompletionText) {
    if (packageCompletionText == null || packageCompletionText.length == 0) {
        return false;
    }
    String text = String.valueOf(packageCompletionText);
    String[] splits = text.split("\\.");
    for (String split : splits) {
        // use 1.7 because backwards compatibility ensures that nothing is missed.
        if (split.length() > 0) {
            IStatus status = JavaConventions.validateIdentifier(split, "1.7", "1.7");
            if (status.getSeverity() >= IStatus.ERROR) {
                return false;
            }
        }
    }
    return true;
}

From source file:org.codehaus.groovy.eclipse.dsl.inferencing.suggestions.JavaValidIdentifierRule.java

License:Apache License

protected IStatus checkJavaType(String value) {
    return JavaConventions.validateIdentifier(value, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3);
}