Example usage for org.eclipse.jdt.core.compiler CharOperation isWhitespace

List of usage examples for org.eclipse.jdt.core.compiler CharOperation isWhitespace

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.compiler CharOperation isWhitespace.

Prototype

public static boolean isWhitespace(char c) 

Source Link

Document

Answers true if c is a whitespace according to the JLS (\u0009, \u000a, \u000c, \u000d, \u0020), otherwise false.

Usage

From source file:com.codenvy.ide.ext.java.server.core.JavaConventions.java

License:Open Source License

/**
 * Validate the given package name for the given source and compliance levels.
 * <p>/*w  w  w .  ja  v  a2s  .  c  o m*/
 * The syntax of a package name corresponds to PackageName as
 * defined by PackageDeclaration (JLS2 7.4). For example, <code>"java.lang"</code>.
 * <p>
 * Note that the given name must be a non-empty package name (that is, attempting to
 * validate the default package will return an error status.)
 * Also it must not contain any characters or substrings that are not valid
 * on the file system on which workspace root is located.
 *
 * @param name the name of a package
 * @param sourceLevel the source level
 * @param complianceLevel the compliance level
 * @return a status object with code <code>IStatus.OK</code> if
 *      the given name is valid as a package name, otherwise a status
 *      object indicating what is wrong with the name
 * @since 3.3
 */
public static IStatus validatePackageName(String name, String sourceLevel, String complianceLevel) {

    if (name == null) {
        return new Status(IStatus.ERROR, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                Messages.convention_package_nullName, null);
    }
    int length;
    if ((length = name.length()) == 0) {
        return new Status(IStatus.ERROR, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                Messages.convention_package_emptyName, null);
    }
    if (name.charAt(0) == DOT || name.charAt(length - 1) == DOT) {
        return new Status(IStatus.ERROR, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                Messages.convention_package_dotName, null);
    }
    if (CharOperation.isWhitespace(name.charAt(0))
            || CharOperation.isWhitespace(name.charAt(name.length() - 1))) {
        return new Status(IStatus.ERROR, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                Messages.convention_package_nameWithBlanks, null);
    }
    int dot = 0;
    while (dot != -1 && dot < length - 1) {
        if ((dot = name.indexOf(DOT, dot + 1)) != -1 && dot < length - 1 && name.charAt(dot + 1) == DOT) {
            return new Status(IStatus.ERROR, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                    Messages.convention_package_consecutiveDotsName, null);
        }
    }
    //      IWorkspace workspace = ResourcesPlugin.getWorkspace();
    StringTokenizer st = new StringTokenizer(name, "."); //$NON-NLS-1$
    boolean firstToken = true;
    IStatus warningStatus = null;
    while (st.hasMoreTokens()) {
        String typeName = st.nextToken();
        typeName = typeName.trim(); // grammar allows spaces
        char[] scannedID = scannedIdentifier(typeName, sourceLevel, complianceLevel);
        if (scannedID == null) {
            return new Status(IStatus.ERROR, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                    Messages.bind(Messages.convention_illegalIdentifier, typeName), null);
        }
        //         IStatus status = workspace.validateName(new String(scannedID), IResource.FOLDER);
        //         if (!status.isOK()) {
        //            return status;
        //         }
        if (firstToken && scannedID.length > 0 && ScannerHelper.isUpperCase(scannedID[0])) {
            if (warningStatus == null) {
                warningStatus = new Status(IStatus.WARNING, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                        Messages.convention_package_uppercaseName, null);
            }
        }
        firstToken = false;
    }
    if (warningStatus != null) {
        return warningStatus;
    }
    return JavaModelStatus.VERIFIED_OK;
}

From source file:com.ibm.research.tours.content.url.Signature.java

License:Open Source License

private static int consumeWhitespace(char[] typeName, int pos, int length) {
    while (pos < length) {
        char currentChar = typeName[pos];
        if (currentChar != ' ' && !CharOperation.isWhitespace(currentChar)) {
            break;
        }//from  w  ww.  j a v a 2 s .  co m
        pos++;
    }
    return pos;
}

From source file:org.codehaus.groovy.eclipse.codeassist.completions.GroovyJavaGuessingCompletionProposal.java

License:Open Source License

@Override
protected String computeReplacementString() {

    if (!hasParameters() || !hasArgumentList()) {
        if (proposalOptions.noParens) {
            // command chain expression with no known arguments
            char[] proposalName = fProposal.getName();
            boolean hasWhitespace = false;
            for (int i = 0; i < proposalName.length; i++) {
                if (CharOperation.isWhitespace(proposalName[i])) {
                    hasWhitespace = true;
                }//from   w  w  w  .ja  v  a  2 s  .co m
            }
            String newProposalName;
            if (hasWhitespace) {
                newProposalName = "\"" + String.valueOf(proposalName) + "\"";
            } else {
                newProposalName = String.valueOf(proposalName);
            }
            return newProposalName;
        } else {
            return super.computeReplacementString();
        }
    }

    long millis = DEBUG ? System.currentTimeMillis() : 0;
    String replacement;
    try {
        replacement = computeGuessingCompletion();
    } catch (JavaModelException x) {
        fPositions = null;
        fChoices = null;
        JavaPlugin.log(x);
        openErrorDialog(x);
        return super.computeReplacementString();
    }
    if (DEBUG)
        System.err.println("Parameter Guessing: " + (System.currentTimeMillis() - millis)); //$NON-NLS-1$

    return replacement;
}

From source file:org.codehaus.groovy.eclipse.codeassist.completions.GroovyJavaGuessingCompletionProposal.java

License:Open Source License

/**
 * Creates the completion string. Offsets and Lengths are set to the offsets
 * and lengths of the/* www  .j a  v  a2  s .c  om*/
 * parameters.
 *
 * @return the completion string
 * @throws JavaModelException if parameter guessing failed
 */
private String computeGuessingCompletion() throws JavaModelException {
    StringBuffer buffer = new StringBuffer();
    char[] proposalName = fProposal.getName();
    boolean hasWhitespace = false;
    for (int i = 0; i < proposalName.length; i++) {
        if (CharOperation.isWhitespace(proposalName[i])) {
            hasWhitespace = true;
        }
    }
    char[] newProposalName;
    if (hasWhitespace) {
        newProposalName = CharOperation.concat(new char[] { '"' }, CharOperation.append(proposalName, '"'));
    } else {
        newProposalName = proposalName;
    }
    fProposal.setName(newProposalName);
    appendMethodNameReplacement(buffer);
    fProposal.setName(proposalName);

    FormatterPrefs prefs = getFormatterPrefs();
    if (proposalOptions.noParens) {
        // eat the opening paren replace with a space if there isn't one
        // already
        buffer.replace(buffer.length() - 1, buffer.length(), prefs.beforeOpeningParen ? "" : " ");
    }

    setCursorPosition(buffer.length());

    // groovy doesn't require parens around closures if it is the last
    // argument
    // If the option is set, then we follow that heuristic
    char[][] regularParameterTypes = ((GroovyCompletionProposal) fProposal).getRegularParameterTypeNames();

    // check if the last regular parameter is a closure. If so, it must be
    // moved to the end
    boolean lastArgIsClosure = lastArgIsClosure(regularParameterTypes);
    int indexOfLastClosure = lastArgIsClosure ? regularParameterTypes.length - 1 : -1;

    char[][] namedParameterNames = ((GroovyCompletionProposal) fProposal).getNamedParameterNames();
    char[][] regularParameterNames = ((GroovyCompletionProposal) fProposal).getRegularParameterNames();
    int namedCount = namedParameterNames.length;
    int argCount = regularParameterNames.length;
    int allCount = argCount + namedCount;

    if (proposalOptions.noParensAroundClosures) {

        // remove the opening paren only if there is a single closure
        // parameter
        if (indexOfLastClosure == 0 && namedCount == 0) {
            buffer.replace(buffer.length() - 1, buffer.length(), "");

            // add space if not already there
            // would be added by call to appendMethodNameReplacement
            if (!prefs.beforeOpeningParen) {
                buffer.append(SPACE);
            }
        } else {
            if (prefs.afterOpeningParen)
                buffer.append(SPACE);
        }
    } else {
        if (prefs.afterOpeningParen)
            buffer.append(SPACE);
    }

    // now add the parameters
    int replacementOffset = getReplacementOffset();
    fChoices = guessParameters(namedParameterNames, regularParameterNames);

    for (int i = 0; i < allCount; i++) {
        if (i == indexOfLastClosure) {
            // handle the last closure separately
            continue;
        }

        char[] nextName;
        if (i < argCount) {
            nextName = regularParameterNames[i];
        } else {
            nextName = namedParameterNames[i - argCount];
        }
        if (i >= argCount || proposalOptions.useNamedArguments) {
            buffer.append(nextName).append(":");
        }

        // handle the value
        ICompletionProposal proposal = fChoices[i][0];
        String argument = proposal.getDisplayString();

        Position position = fPositions[i];
        position.setOffset(replacementOffset + buffer.length());
        position.setLength(argument.length());

        // handle the "unknown" case where we only insert a proposal.
        if (proposal instanceof JavaCompletionProposal) {
            ((JavaCompletionProposal) proposal).setReplacementOffset(replacementOffset + buffer.length());
        }
        buffer.append(argument);

        // check what to add after argument
        if (i == allCount - 1 || (i == allCount - 2 && i == indexOfLastClosure - 1)) {
            if (prefs.beforeClosingParen || proposalOptions.noParens) {
                buffer.append(SPACE);
            }
            if (!proposalOptions.noParens) {
                buffer.append(RPAREN);
            }
        } else if (i < allCount - 1) {
            if (prefs.beforeComma)
                buffer.append(SPACE);
            buffer.append(COMMA);
            if (prefs.afterComma)
                buffer.append(SPACE);
        }
    }

    // closures at the end are added in an idiomatic groovy way
    if (indexOfLastClosure >= 0) {
        if (allCount > 1) {
            if (!proposalOptions.noParensAroundClosures) {
                buffer.append(COMMA);
            }
            buffer.append(SPACE);
        }
        Position position = fPositions[indexOfLastClosure];
        position.setOffset(replacementOffset + buffer.length());
        position.setLength(LAST_CLOSURE_TEXT.length());
        buffer.append(LAST_CLOSURE_TEXT);

        if (!proposalOptions.noParensAroundClosures) {
            buffer.append(" }");
            buffer.append(RPAREN);
        }
    }

    return buffer.toString();
}

From source file:org.codehaus.groovy.eclipse.codeassist.proposals.GroovyJavaGuessingCompletionProposal.java

License:Open Source License

/**
 * Creates the completion string. Offsets and Lengths are set to the offsets
 * and lengths of the//  w w  w . j av a 2 s  . c  om
 * parameters.
 *
 * @return the completion string
 * @throws JavaModelException if parameter guessing failed
 */
private String computeGuessingCompletion() throws JavaModelException {

    StringBuffer buffer = new StringBuffer();
    char[] proposalName = fProposal.getName();
    boolean hasWhitespace = false;
    for (int i = 0; i < proposalName.length; i++) {
        if (CharOperation.isWhitespace(proposalName[i])) {
            hasWhitespace = true;
        }
    }
    char[] newProposalName;
    if (hasWhitespace) {
        newProposalName = CharOperation.concat(new char[] { '"' }, CharOperation.append(proposalName, '"'));
    } else {
        newProposalName = proposalName;
    }
    fProposal.setName(newProposalName);
    appendMethodNameReplacement(buffer);
    fProposal.setName(proposalName);

    FormatterPrefs prefs = getFormatterPrefs();

    setCursorPosition(buffer.length());

    // groovy doesn't require parens around closures if it is the last
    // argument
    // If the option is set, then we follow that heuristic
    int indexOfLastClosure = -1;
    String[] parameterTypes = getParameterTypes();
    if (proposalOptions.noParensAroundClosures) {
        if (lastArgIsClosure(parameterTypes)) {
            indexOfLastClosure = parameterTypes.length - 1;
        }

        // remove the opening paren only if there is a single closure
        // parameter
        if (indexOfLastClosure == 0) {
            buffer.replace(buffer.length() - 1, buffer.length(), "");

            // add space if not already there
            // would be added by call to appendMethodNameReplacement
            if (!prefs.beforeOpeningParen) {
                buffer.append(SPACE);
            }
        }
    } else {
        if (prefs.afterOpeningParen)
            buffer.append(SPACE);
    }

    char[][] parameterNames = fProposal.findParameterNames(null);
    fChoices = guessParameters(parameterNames);
    int count = fChoices.length;
    int replacementOffset = getReplacementOffset();

    for (int i = 0; i < count; i++) {

        if (proposalOptions.useNamedArguments) {
            buffer.append(parameterNames[i]).append(":");
        }

        // handle the argument name
        if (proposalOptions.useBracketsForClosures
                && Signature.getSimpleName(parameterTypes[i]).equals("Closure")) {
            // closure
            Position position = fPositions[i];
            position.setOffset(replacementOffset + buffer.length() + 2);
            buffer.append(CLOSURE_TEXT);
            position.setLength(0);

        } else {
            // regular argument
            ICompletionProposal proposal = fChoices[i][0];
            String argument = proposal.getDisplayString();

            Position position = fPositions[i];
            position.setOffset(replacementOffset + buffer.length());
            position.setLength(argument.length());

            // handle the "unknown" case where we only insert a proposal.
            if (proposal instanceof JavaCompletionProposal)
                ((JavaCompletionProposal) proposal).setReplacementOffset(replacementOffset + buffer.length());
            buffer.append(argument);
        }

        if (i == indexOfLastClosure - 1 || (i != indexOfLastClosure && i == count - 1)) {
            if (prefs.beforeClosingParen) {
                buffer.append(SPACE);
            }
            buffer.append(RPAREN);
            if (i == indexOfLastClosure - 1) {
                buffer.append(SPACE);
            }
        } else if (i < count - 1) {
            if (prefs.beforeComma)
                buffer.append(SPACE);
            buffer.append(COMMA);
            if (prefs.afterComma)
                buffer.append(SPACE);
        }

    }

    return buffer.toString();
}

From source file:org.eclipse.pde.api.tools.internal.builder.BaseApiAnalyzer.java

License:Open Source License

/**
 * Creates a marker on a manifest file for a version numbering problem and
 * returns it or <code>null</code>
 * //from w ww  . j ava  2  s.  c o m
 * @param kind
 * @param messageargs
 * @param version
 * @param description the description of details
 * @return a new {@link IApiProblem} or <code>null</code>
 */
private IApiProblem createVersionProblem(int kind, final String[] messageargs, String version,
        String description) {
    IResource manifestFile = null;
    String path = JarFile.MANIFEST_NAME;
    if (fJavaProject != null) {
        manifestFile = Util.getManifestFile(fJavaProject.getProject());
    }
    // this error should be located on the manifest.mf file
    // first of all we check how many API breakage marker are there
    int lineNumber = -1;
    int charStart = 0;
    int charEnd = 1;
    char[] contents = null;
    if (manifestFile != null && manifestFile.getType() == IResource.FILE) {
        path = manifestFile.getProjectRelativePath().toPortableString();
        IFile file = (IFile) manifestFile;
        InputStream inputStream = null;
        LineNumberReader reader = null;
        try {
            inputStream = file.getContents(true);
            contents = Util.getInputStreamAsCharArray(inputStream, -1, IApiCoreConstants.UTF_8);
            reader = new LineNumberReader(new BufferedReader(new StringReader(new String(contents))));
            int lineCounter = 0;
            String line = null;
            loop: while ((line = reader.readLine()) != null) {
                lineCounter++;
                if (line.startsWith(Constants.BUNDLE_VERSION)) {
                    lineNumber = lineCounter;
                    break loop;
                }
            }
        } catch (CoreException e) {
            // ignore
        } catch (IOException e) {
            // ignore
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }
    if (lineNumber != -1 && contents != null) {
        // initialize char start, char end
        int index = CharOperation.indexOf(Constants.BUNDLE_VERSION.toCharArray(), contents, true);
        loop: for (int i = index + Constants.BUNDLE_VERSION.length() + 1, max = contents.length; i < max; i++) {
            char currentCharacter = contents[i];
            if (CharOperation.isWhitespace(currentCharacter)) {
                continue;
            }
            charStart = i;
            break loop;
        }
        loop: for (int i = charStart + 1, max = contents.length; i < max; i++) {
            switch (contents[i]) {
            case '\r':
            case '\n':
                charEnd = i;
                break loop;
            default:
                continue;
            }
        }
    } else {
        lineNumber = 1;
    }
    return ApiProblemFactory.newApiVersionNumberProblem(path, null, messageargs,
            new String[] { IApiMarkerConstants.MARKER_ATTR_VERSION, IApiMarkerConstants.API_MARKER_ATTR_ID,
                    IApiMarkerConstants.VERSION_NUMBERING_ATTR_DESCRIPTION, },
            new Object[] { version, new Integer(IApiMarkerConstants.VERSION_NUMBERING_MARKER_ID), description },
            lineNumber, charStart, charEnd, IElementDescriptor.RESOURCE, kind);
}

From source file:org.eclipse.tycho.compiler.jdt.JDTCompiler.java

License:Open Source License

/**
 * check the compiler arguments. Extract from files specified using @, lines marked with
 * ADAPTER_PREFIX These lines specify information that needs to be interpreted by us.
 * //from www  .ja  v  a  2s . c om
 * @param args
 *            compiler arguments to process
 */
private void checkCompilerArgs(Map<String, String> args) {
    for (String arg : args.keySet()) {
        if (arg.charAt(0) == '@') {
            try {
                char[] content = Util.getFileCharContent(new File(arg.substring(1)), null);
                int offset = 0;
                int prefixLength = ADAPTER_PREFIX.length;
                while ((offset = CharOperation.indexOf(ADAPTER_PREFIX, content, true, offset)) > -1) {
                    int start = offset + prefixLength;
                    int end = CharOperation.indexOf('\n', content, start);
                    if (end == -1)
                        end = content.length;
                    while (CharOperation.isWhitespace(content[end])) {
                        end--;
                    }

                    // end is inclusive, but in the API end is exclusive
                    if (CharOperation.equals(ADAPTER_ENCODING, content, start,
                            start + ADAPTER_ENCODING.length)) {
                        CharOperation.replace(content, SEPARATOR_CHARS, File.separatorChar, start, end + 1);
                        // file or folder level custom encoding
                        start += ADAPTER_ENCODING.length;
                        int encodeStart = CharOperation.lastIndexOf('[', content, start, end);
                        if (start < encodeStart && encodeStart < end) {
                            boolean isFile = CharOperation.equals(SuffixConstants.SUFFIX_java, content,
                                    encodeStart - 5, encodeStart, false);

                            String str = String.valueOf(content, start, encodeStart - start);
                            String enc = String.valueOf(content, encodeStart, end - encodeStart + 1);
                            if (isFile) {
                                if (fileEncodings == null)
                                    fileEncodings = new HashMap<String, String>();
                                // use File to translate the string into a
                                // path with the correct File.seperator
                                fileEncodings.put(str, enc);
                            } else {
                                if (dirEncodings == null)
                                    dirEncodings = new HashMap<String, String>();
                                dirEncodings.put(str, enc);
                            }
                        }
                    } else if (CharOperation.equals(ADAPTER_ACCESS, content, start,
                            start + ADAPTER_ACCESS.length)) {
                        // access rules for the classpath
                        start += ADAPTER_ACCESS.length;
                        int accessStart = CharOperation.indexOf('[', content, start, end);
                        // CharOperation.replace(content, SEPARATOR_CHARS,
                        // File.separatorChar, start, accessStart);
                        if (start < accessStart && accessStart < end) {
                            String path = String.valueOf(content, start, accessStart - start);
                            String access = String.valueOf(content, accessStart, end - accessStart + 1);
                            if (accessRules == null)
                                accessRules = new ArrayList<String>();
                            accessRules.add(path);
                            accessRules.add(access);
                        }
                    }
                    offset = end;
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }

}