Java Code Examples for javax.lang.model.SourceVersion

The following are top voted examples for showing how to use javax.lang.model.SourceVersion. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: javaide   File: ClassReader.java   View source code 6 votes vote down vote up
private void fillIn(PackageSymbol p,
                    Location location,
                    Iterable<JavaFileObject> files) {
    currentLoc = location;
    for (JavaFileObject fo : files) {
        switch (fo.getKind()) {
            case CLASS:
            case SOURCE: {
                // TODO pass binaryName to includeClassFile
                String binaryName = fileManager.inferBinaryName(currentLoc, fo);
                String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
                if (SourceVersion.isIdentifier(simpleName) ||
                        simpleName.equals("package-info"))
                    includeClassFile(p, fo);
                break;
            }
            default:
                extraFileActions(p, fo);
        }
    }
}
 
Example 2
Project: javaide   File: JavaCompiler.java   View source code 6 votes vote down vote up
/**
 * Resolve an identifier.
 *
 * @param name The identifier to resolve
 */
public Symbol resolveIdent(String name) {
    if (name.equals(""))
        return syms.errSymbol;
    JavaFileObject prev = log.useSource(null);
    try {
        JCExpression tree = null;
        for (String s : name.split("\\.", -1)) {
            if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
                return syms.errSymbol;
            tree = (tree == null) ? make.Ident(names.fromString(s))
                    : make.Select(tree, names.fromString(s));
        }
        JCCompilationUnit toplevel =
                make.TopLevel(List.<JCAnnotation>nil(), null, List.<JCTree>nil());
        toplevel.packge = syms.unnamedPackage;
        return attr.attribIdent(tree, toplevel);
    } finally {
        log.useSource(prev);
    }
}
 
Example 3
Project: incubator-servicecomb-java-chassis   File: ClassUtils.java   View source code 6 votes vote down vote up
public static String correctMethodParameterName(String paramName) {
  if (SourceVersion.isName(paramName)) {
    return paramName;
  }
  StringBuffer newParam = new StringBuffer();
  char tempChar;
  for (int index = 0; index < paramName.length(); index++) {
    tempChar = paramName.charAt(index);
    if (Character.isJavaIdentifierPart(tempChar)) {
      newParam.append(paramName.charAt(index));
    } else if (tempChar == '.' || tempChar == '-') {
      newParam.append('_');
    }
  }
  return newParam.toString();
}
 
Example 4
Project: incubator-netbeans   File: CustomizerCompile.java   View source code 6 votes vote down vote up
private void addOptionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addOptionButtonActionPerformed
    final AddProcessorOption panel = new AddProcessorOption();
    final DialogDescriptor desc = new DialogDescriptor(panel, NbBundle.getMessage (CustomizerCompile.class, "LBL_AddProcessorOption_Title")); //NOI18N
    desc.setValid(false);
    panel.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            String key = panel.getOptionKey();
            for(String s : key.split("\\.", -1)) { //NOI18N
                if (!SourceVersion.isIdentifier(s)) {
                    desc.setValid(false);
                    return;
                }
            }
            desc.setValid(true);
        }
    });
    Dialog dlg = DialogDisplayer.getDefault().createDialog(desc);
    dlg.setVisible (true);
    if (desc.getValue() == DialogDescriptor.OK_OPTION) {
        ((DefaultTableModel)processorOptionsTable.getModel()).addRow(new String[] {panel.getOptionKey(), panel.getOptionValue()});
    }
    dlg.dispose();
}
 
Example 5
Project: incubator-netbeans   File: JavaCompletionItem.java   View source code 6 votes vote down vote up
private static String adjustName(String name) {
    if (name == null) {
        return null;
    }
    String shortName = null;
    if (name.startsWith("get") && name.length() > 3) { //NOI18N
        shortName = name.substring(3);
    }
    if (name.startsWith("is") && name.length() > 2) { //NOI18N
        shortName = name.substring(2);
    }
    if (shortName != null) {
        return firstToLower(shortName);
    }
    if (SourceVersion.isKeyword(name)) {
        return "a" + Character.toUpperCase(name.charAt(0)) + name.substring(1); //NOI18N
    } else {
        return name;
    }
}
 
Example 6
Project: incubator-netbeans   File: JavaCompletionItem.java   View source code 6 votes vote down vote up
private static String firstToLower(String name) {
    if (name.length() == 0) {
        return null;
    }
    StringBuilder result = new StringBuilder();
    boolean toLower = true;
    char last = Character.toLowerCase(name.charAt(0));
    for (int i = 1; i < name.length(); i++) {
        if (toLower && Character.isUpperCase(name.charAt(i))) {
            result.append(Character.toLowerCase(last));
        } else {
            result.append(last);
            toLower = false;
        }
        last = name.charAt(i);
    }
    result.append(last);
    if (SourceVersion.isKeyword(result)) {
        return "a" + name; //NOI18N
    } else {
        return result.toString();
    }
}
 
Example 7
Project: incubator-netbeans   File: JavadocGenerator.java   View source code 6 votes vote down vote up
public String generateComment(VariableElement field, CompilationInfo javac) {
        StringBuilder builder = new StringBuilder(
//                "/**\n" + // NOI18N
                "\n" // NOI18N
                );
        
        if (SourceVersion.RELEASE_5.compareTo(srcVersion) <= 0 &&
                JavadocUtilities.isDeprecated(javac, field)) {
            builder.append("@deprecated\n"); // NOI18N
        }
        

//        builder.append("*/\n"); // NOI18N
        
        return builder.toString();
    }
 
Example 8
Project: OpenJSharp   File: JavacProcessingEnvironment.java   View source code 5 votes vote down vote up
public static boolean isValidOptionName(String optionName) {
    for(String s : optionName.split("\\.", -1)) {
        if (!SourceVersion.isIdentifier(s))
            return false;
    }
    return true;
}
 
Example 9
Project: openjdk-jdk10   File: CheckNamesProcessor.java   View source code 5 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    /*
     * Return latest source version instead of a fixed version
     * like RELEASE_9. To return a fixed version, this class could
     * be annotated with a SupportedSourceVersion annotation.
     *
     * Warnings will be issued if any unknown language constructs
     * are encountered.
     */
    return SourceVersion.latest();
}
 
Example 10
Project: javaide   File: JavacFileManager.java   View source code 5 votes vote down vote up
private static boolean isValidName(String name) {
    // Arguably, isValidName should reject keywords (such as in SourceVersion.isName() ),
    // but the set of keywords depends on the source level, and we don't want
    // impls of JavaFileManager to have to be dependent on the source level.
    // Therefore we simply check that the argument is a sequence of identifiers
    // separated by ".".
    for (String s : name.split("\\.", -1)) {
        if (!SourceVersion.isIdentifier(s))
            return false;
    }
    return true;
}
 
Example 11
Project: javaide   File: JavacProcessingEnvironment.java   View source code 5 votes vote down vote up
/**
 * Return true if the argument string is a valid import-style
 * string specifying claimed annotations; return false otherwise.
 */
public static boolean isValidImportString(String s) {
    if (s.equals("*"))
        return true;

    boolean valid = true;
    String t = s;
    int index = t.indexOf('*');

    if (index != -1) {
        // '*' must be last character...
        if (index == t.length() -1) {
            // ... any and preceding character must be '.'
            if ( index-1 >= 0 ) {
                valid = t.charAt(index-1) == '.';
                // Strip off ".*$" for identifier checks
                t = t.substring(0, t.length()-2);
            }
        } else
            return false;
    }

    // Verify string is off the form (javaId \.)+ or javaId
    if (valid) {
        String[] javaIds = t.split("\\.", t.length()+2);
        for(String javaId: javaIds)
            valid &= SourceVersion.isIdentifier(javaId);
    }
    return valid;
}
 
Example 12
Project: openjdk-jdk10   File: NameConverter.java   View source code 5 votes vote down vote up
public String toConstantName( String token ) {
    String name = super.toConstantName(token);
    if(!SourceVersion.isKeyword(name))
        return name;
    else
        return '_'+name;
}
 
Example 13
Project: OpenJSharp   File: AbstractProcessor.java   View source code 5 votes vote down vote up
/**
 * If the processor class is annotated with {@link
 * SupportedSourceVersion}, return the source version in the
 * annotation.  If the class is not so annotated, {@link
 * SourceVersion#RELEASE_6} is returned.
 *
 * @return the latest source version supported by this processor
 */
public SourceVersion getSupportedSourceVersion() {
    SupportedSourceVersion ssv = this.getClass().getAnnotation(SupportedSourceVersion.class);
    SourceVersion sv = null;
    if (ssv == null) {
        sv = SourceVersion.RELEASE_6;
        if (isInitialized())
            processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
                                                     "No SupportedSourceVersion annotation " +
                                                     "found on " + this.getClass().getName() +
                                                     ", returning " + sv + ".");
    } else
        sv = ssv.value();
    return sv;
}
 
Example 14
Project: openjdk-jdk10   File: JavacElements.java   View source code 5 votes vote down vote up
private <S extends Symbol> S doGetElement(ModuleElement module, String methodName,
                                          CharSequence name, Class<S> clazz) {
    String strName = name.toString();
    if (!SourceVersion.isName(strName) && (!strName.isEmpty() || clazz == ClassSymbol.class)) {
        return null;
    }
    if (module == null) {
        return unboundNameToSymbol(methodName, strName, clazz);
    } else {
        return nameToSymbol((ModuleSymbol) module, strName, clazz);
    }
}
 
Example 15
Project: incubator-netbeans   File: Context.java   View source code 5 votes vote down vote up
public @NonNull SourceVersion sourceVersion() {
    String sourceLevel = SourceLevelQuery.getSourceLevel(ctx.getInfo().getFileObject());

    if (sourceLevel == null) {
        return SourceVersion.latest(); //TODO
    }

    String[] splited = sourceLevel.split("\\.");
    String   spec    = splited[1];

    return SourceVersion.valueOf("RELEASE_"+  spec);//!!!
}
 
Example 16
Project: jdk8u-jdk   File: SerialFilterTest.java   View source code 5 votes vote down vote up
/**
 * Generate an object to be used with the various wildcard pattern forms.
 * Explicitly supports only specific package wildcards with specific objects.
 * @param pattern a wildcard pattern ending in "*"
 * @param allowed a boolean indicating to generate the allowed or disallowed case
 * @return an object within or outside the wildcard
 */
static Object genTestObjectWildcard(String pattern, boolean allowed) {
    if (pattern.endsWith(".**")) {
        // package hierarchy wildcard
        if (pattern.startsWith("javax.lang.")) {
            return SourceVersion.RELEASE_5;
        }
        if (pattern.startsWith("java.")) {
            return 4;
        }
        if (pattern.startsWith("javax.")) {
            return SourceVersion.RELEASE_6;
        }
        return otherObject;
    } else if (pattern.endsWith(".*")) {
        // package wildcard
        if (pattern.startsWith("javax.lang.model")) {
            return SourceVersion.RELEASE_6;
        }
    } else {
        // class wildcard
        if (pattern.equals("*")) {
            return otherObject; // any object will do
        }
        if (pattern.startsWith("java.util.Hash")) {
            return new Hashtable<String, String>();
        }
    }
    Assert.fail("Object could not be generated for pattern: "
            + pattern
            + ", allowed: " + allowed);
    return null;
}
 
Example 17
Project: OpenJSharp   File: CheckNamesProcessor.java   View source code 5 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    /*
     * Return latest source version instead of a fixed version
     * like RELEASE_8.  To return a fixed version, this class
     * could be annotated with a SupportedSourceVersion
     * annotation.
     *
     * Warnings will be issued if any unknown language constructs
     * are encountered.
     */
    return SourceVersion.latest();
}
 
Example 18
Project: openjdk-jdk10   File: JavacFileManager.java   View source code 5 votes vote down vote up
private boolean isValid(Path fileName) {
    if (fileName == null) {
        return true;
    } else {
        String name = fileName.toString();
        if (name.endsWith("/")) {
            name = name.substring(0, name.length() - 1);
        }
        return SourceVersion.isIdentifier(name);
    }
}
 
Example 19
Project: incubator-netbeans   File: FileObjects.java   View source code 5 votes vote down vote up
public static boolean isJavaPath(
        @NonNull final String path,
        final char separator) {
    for (String name : path.split(Pattern.quote(Character.toString(separator)))) {
        if (!SourceVersion.isIdentifier(name)) {
            return false;
        }
    }
    return true;
}
 
Example 20
Project: javaide   File: JavacProcessingEnvironment.java   View source code 5 votes vote down vote up
/**
 * Checks whether or not a processor's source version is
 * compatible with the compilation source version.  The
 * processor's source version needs to be greater than or
 * equal to the source version of the compile.
 */
private void checkSourceVersionCompatibility(Source source, Log log) {
    SourceVersion procSourceVersion = processor.getSupportedSourceVersion();

    if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 )  {
        log.warning("proc.processor.incompatible.source.version",
                    procSourceVersion,
                    processor.getClass().getName(),
                    source.name);
    }
}
 
Example 21
Project: incubator-netbeans   File: HintMetadata.java   View source code 5 votes vote down vote up
HintMetadata(String id, String displayName, String description, String category, boolean enabled, Hint.Kind kind, Severity severity, Collection<? extends String> suppressWarnings, CustomizerProvider customizer, Set<Options> options, SourceVersion sourceVersion) {
    this.id = id;
    this.displayName = displayName;
    this.description = description;
    this.category = category;
    this.enabled = enabled;
    this.kind = kind;
    this.severity = severity;
    this.suppressWarnings = suppressWarnings;
    this.customizer = customizer;
    this.options = options;
    this.sourceVersion = sourceVersion;
}
 
Example 22
Project: incubator-netbeans   File: ErrorDescriptionFactory.java   View source code 5 votes vote down vote up
private static boolean isSuppressWarningsSupported(CompilationInfo info) {
    //cannot suppress if there is no SuppressWarnings annotation in the platform:
    if (info.getElements().getTypeElement("java.lang.SuppressWarnings") == null)
        return false;

    return info.getSourceVersion().compareTo(SourceVersion.RELEASE_5) >= 0;
}
 
Example 23
Project: incubator-netbeans   File: ReplaceConstructorWithFactoryPlugin.java   View source code 5 votes vote down vote up
@Override
public Problem fastCheckParameters() {
    String factoryName = refactoring.getFactoryName();
    
    if (factoryName == null || factoryName.length() == 0) {
        // FIXME: I18N
        return new Problem(true, "No factory method name specified.");
    }
    if (!SourceVersion.isIdentifier(factoryName)) {
        // FIXME: I18N
        return new Problem(true, factoryName + " is not an identifier.");
    }
    return null;
}
 
Example 24
Project: openjdk-jdk10   File: GetSourceVersionsTest.java   View source code 5 votes vote down vote up
/**
 * Verify getSourceVersions.
 */
@Test
public void testRun() throws Exception {
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    Set<SourceVersion> found = tool.getSourceVersions();
    Set<SourceVersion> expect = EnumSet.range(SourceVersion.RELEASE_3, SourceVersion.latest());
    if (!expect.equals(found)) {
        System.err.println("expect: " + expect);
        System.err.println(" found: " + expect);
        error("unexpected versions");
    }
}
 
Example 25
Project: openjdk-jdk10   File: TestSourceVersionWarnings.java   View source code 5 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    String sourceVersion = processingEnv.getOptions().get("SourceVersion");
    if (sourceVersion == null) {
        processingEnv.getMessager().printMessage(WARNING,
                                                 "No SourceVersion option given");
        return SourceVersion.RELEASE_6;
    } else {
        return SourceVersion.valueOf(sourceVersion);
    }
}
 
Example 26
Project: incubator-netbeans   File: JavaPluginUtils.java   View source code 5 votes vote down vote up
private static String firstToLower(String name) {
    if (name.length() == 0) {
        return null;
    }

    StringBuilder result = new StringBuilder();
    boolean toLower = true;
    char last = Character.toLowerCase(name.charAt(0));

    for (int i = 1; i < name.length(); i++) {
        if (toLower && (Character.isUpperCase(name.charAt(i)) || name.charAt(i) == '_')) {
            result.append(Character.toLowerCase(last));
        } else {
            result.append(last);
            toLower = false;
        }
        last = name.charAt(i);

    }

    result.append(toLower ? Character.toLowerCase(last) : last);
    
    if (SourceVersion.isKeyword(result)) {
        return "a" + name;
    } else {
        return result.toString();
    }
}
 
Example 27
Project: incubator-netbeans   File: AddPropertyPanel.java   View source code 5 votes vote down vote up
public AddFxPropertyConfig getAddPropertyConfig() {
    final String propertyType = typeComboBox.getSelectedItem().toString().trim();
    String implementationType = implemenationCombobox.getSelectedItem().toString().trim();
    final String name = nameTextField.getText().trim();
    final String initializer = initializerTextField.getText().trim();
    AddFxPropertyConfig.ACCESS access = AddFxPropertyConfig.ACCESS.PACKAGE;
    if (privateRadioButton.isSelected()) {
        access = AddFxPropertyConfig.ACCESS.PRIVATE;
    } else if (protectedRadioButton.isSelected()) {
        access = AddFxPropertyConfig.ACCESS.PROTECTED;
    } else if (publicRadioButton.isSelected()) {
        access = AddFxPropertyConfig.ACCESS.PUBLIC;
    }

    AddFxPropertyConfig.GENERATE generate = AddFxPropertyConfig.GENERATE.WRITABLE;
    if (!writableRadioButton.isSelected()) {
        generate = AddFxPropertyConfig.GENERATE.READ_ONLY;
    }
    
    if (implementationType.indexOf('<') != -1) { // NOI18N
        if (javac.getSourceVersion().compareTo(SourceVersion.RELEASE_7) >= 0) {
            // TODO: apply coding style ?
            implementationType = implementationType.substring(0, implementationType.indexOf('<')) + "<>"; // NOI18N
        } else {
            int propTemplate = propertyType.indexOf("<"); // NOI18N
            if (propTemplate != -1) {
                implementationType = implementationType.substring(0, implementationType.indexOf('<')) + propertyType.substring(propTemplate);
            }
        }
    }

    AddFxPropertyConfig addPropertyConfig = new AddFxPropertyConfig(
            name, initializer, propertyType, implementationType, access, generate, generateJavadocCheckBox.isSelected());
    return addPropertyConfig;
}
 
Example 28
Project: incubator-netbeans   File: ClassNamePanel.java   View source code 5 votes vote down vote up
public String getClassName() {
    String n = className.getText().trim();
    if (n.isEmpty() || !SourceVersion.isName(n)) {
        return null;
    }
    return n;
}
 
Example 29
Project: openjdk-jdk10   File: Locations.java   View source code 5 votes vote down vote up
/**
 * Returns {@code true} if the given name is a legal module name.
 */
private boolean isModuleName(String name) {
    int next;
    int off = 0;
    while ((next = name.indexOf('.', off)) != -1) {
        String id = name.substring(off, next);
        if (!SourceVersion.isName(id))
            return false;
        off = next+1;
    }
    String last = name.substring(off);
    return SourceVersion.isName(last);
}
 
Example 30
Project: DUnit   File: DUnitProcessor.java   View source code 5 votes vote down vote up
@Override
/**
 * 指定Java版本
 * 可用注解SupportedSourceVersion代替
 */
public SourceVersion getSupportedSourceVersion() {
	return SourceVersion.latestSupported();
}
 
Example 31
Project: openjdk-jdk10   File: SchemaGenerator.java   View source code 5 votes vote down vote up
public static JavacOptions parse(OptionChecker primary, OptionChecker secondary, String... arguments) {
    List<String> recognizedOptions = new ArrayList<String>();
    List<String> unrecognizedOptions = new ArrayList<String>();
    List<String> classNames = new ArrayList<String>();
    List<File> files = new ArrayList<File>();
    for (int i = 0; i < arguments.length; i++) {
        String argument = arguments[i];
        int optionCount = primary.isSupportedOption(argument);
        if (optionCount < 0) {
            optionCount = secondary.isSupportedOption(argument);
        }
        if (optionCount < 0) {
            File file = new File(argument);
            if (file.exists())
                files.add(file);
            else if (SourceVersion.isName(argument))
                classNames.add(argument);
            else
                unrecognizedOptions.add(argument);
        } else {
            for (int j = 0; j < optionCount + 1; j++) {
                int index = i + j;
                if (index == arguments.length) throw new IllegalArgumentException(argument);
                recognizedOptions.add(arguments[index]);
            }
            i += optionCount;
        }
    }
    return new JavacOptions(recognizedOptions, classNames, files, unrecognizedOptions);
}
 
Example 32
Project: openjdk-jdk10   File: JavacFileManager.java   View source code 5 votes vote down vote up
private static boolean isValidName(String name) {
    // Arguably, isValidName should reject keywords (such as in SourceVersion.isName() ),
    // but the set of keywords depends on the source level, and we don't want
    // impls of JavaFileManager to have to be dependent on the source level.
    // Therefore we simply check that the argument is a sequence of identifiers
    // separated by ".".
    for (String s : name.split("\\.", -1)) {
        if (!SourceVersion.isIdentifier(s))
            return false;
    }
    return true;
}
 
Example 33
Project: incubator-netbeans   File: OptionAnnotationProcessor.java   View source code 5 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    if (delegate() != null) {
        return delegate().getSupportedSourceVersion();
    } else {
        return SourceVersion.RELEASE_7;
    }
}
 
Example 34
Project: OpenJSharp   File: SchemaGenerator.java   View source code 5 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    if (SourceVersion.latest().compareTo(SourceVersion.RELEASE_6) > 0)
        return SourceVersion.valueOf("RELEASE_7");
    else
        return SourceVersion.RELEASE_6;
}
 
Example 35
Project: annotation-processor-toolkit   File: AnnotationProcessorWrapper.java   View source code 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return wrappedProcessor.getSupportedSourceVersion();
}
 
Example 36
Project: incap   File: Processor1.java   View source code 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return latestSupported();
}
 
Example 37
Project: cuckoo   File: DelegationProcessor.java   View source code 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latest();
}
 
Example 38
Project: GitHub   File: EventBusAnnotationProcessor.java   View source code 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latest();
}
 
Example 39
Project: data-mediator   File: MediatorAnnotationProcessor_backup.java   View source code 4 votes vote down vote up
/**
 * 用来指定你使用的 java 版本
 */
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latestSupported();
}
 
Example 40
Project: openjdk-jdk10   File: SourceOption.java   View source code 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latest();
}