Example usage for org.eclipse.jdt.internal.core.util Messages bind

List of usage examples for org.eclipse.jdt.internal.core.util Messages bind

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core.util Messages bind.

Prototype

public static String bind(String message, Object[] bindings) 

Source Link

Document

Bind the given message's substitution locations with the given string values.

Usage

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

License:Open Source License

/**
 * 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 (<code>"true"</code>, <code>"false"</code>), or null literal (<code>"null"</code>).
 * See section 3.8 of the <em>Java Language Specification, Second Edition</em> (JLS2).
 * A valid identifier can act as a simple type name, method name or field name.
 *
 * @param id the Java identifier//from   w  w w.j  a  va 2s  .com
 * @param sourceLevel the source level
 * @param complianceLevel the compliance level
 * @return a status object with code <code>IStatus.OK</code> if
 *      the given identifier is a valid Java identifier, otherwise a status
 *      object indicating what is wrong with the identifier
 * @since 3.3
 */
public static IStatus validateIdentifier(String id, String sourceLevel, String complianceLevel) {
    if (scannedIdentifier(id, sourceLevel, complianceLevel) != null) {
        return JavaModelStatus.VERIFIED_OK;
    } else {
        return new Status(IStatus.ERROR, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                Messages.bind(Messages.convention_illegalIdentifier, id), null);
    }
}

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

License:Open Source License

/**
 * Validate the given Java type name, either simple or qualified, for the given source and compliance levels.
 *
 * <p>For example, <code>"java.lang.Object"</code>, or <code>"Object"</code>.</p>
 *
 * <p>The source level and compliance level values should be taken from the constant defined inside
 * {@link org.eclipse.jdt.core.JavaCore} class. The constants are named <code>JavaCore#VERSION_1_x</code>, x being set
 * between '1' and '8'.//from w  w  w.  j a  v a  2 s  . c o m
 * </p>
 *
 * @param name the name of a type
 * @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 Java type name,
 *      a status with code <code>IStatus.WARNING</code>
 *      indicating why the given name is discouraged,
 *      otherwise a status object indicating what is wrong with
 *      the name
 * @since 3.3
 * @see org.eclipse.jdt.core.JavaCore#VERSION_1_1
 * @see org.eclipse.jdt.core.JavaCore#VERSION_1_2
 * @see org.eclipse.jdt.core.JavaCore#VERSION_1_3
 * @see org.eclipse.jdt.core.JavaCore#VERSION_1_4
 * @see org.eclipse.jdt.core.JavaCore#VERSION_1_5
 * @see org.eclipse.jdt.core.JavaCore#VERSION_1_6
 * @see org.eclipse.jdt.core.JavaCore#VERSION_1_7
 * @see org.eclipse.jdt.core.JavaCore#VERSION_1_8
 */
public static IStatus validateJavaTypeName(String name, String sourceLevel, String complianceLevel) {
    if (name == null) {
        return new Status(IStatus.ERROR, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                Messages.convention_type_nullName, null);
    }
    String trimmed = name.trim();
    if (!name.equals(trimmed)) {
        return new Status(IStatus.ERROR, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                Messages.convention_type_nameWithBlanks, null);
    }
    int index = name.lastIndexOf('.');
    char[] scannedID;
    if (index == -1) {
        // simple name
        scannedID = scannedIdentifier(name, sourceLevel, complianceLevel);
    } else {
        // qualified name
        String pkg = name.substring(0, index).trim();
        IStatus status = validatePackageName(pkg, sourceLevel, complianceLevel);
        if (!status.isOK()) {
            return status;
        }
        String type = name.substring(index + 1).trim();
        scannedID = scannedIdentifier(type, sourceLevel, complianceLevel);
    }

    if (scannedID != null) {
        //         IStatus status = ResourcesPlugin.getWorkspace().validateName(new String(scannedID), IResource.FILE);
        //         if (!status.isOK()) {
        //            return status;
        //         }
        if (CharOperation.contains('$', scannedID)) {
            return new Status(IStatus.WARNING, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                    Messages.convention_type_dollarName, null);
        }
        if ((scannedID.length > 0 && ScannerHelper.isLowerCase(scannedID[0]))) {
            return new Status(IStatus.WARNING, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                    Messages.convention_type_lowercaseName, null);
        }
        return JavaModelStatus.VERIFIED_OK;
    } else {
        return new Status(IStatus.ERROR, org.eclipse.jdt.core.JavaCore.PLUGIN_ID, -1,
                Messages.bind(Messages.convention_type_invalidName, name), null);
    }
}

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.  j  av 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.codenvy.ide.ext.java.server.dom.JavaConventions.java

License:Open Source License

/**
 * 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 (<code>"true"</code>, <code>"false"</code>), or null literal (<code>"null"</code>).
 * See section 3.8 of the <em>Java Language Specification, Second Edition</em> (JLS2).
 * A valid identifier can act as a simple type name, method name or field name.
 *
 * @param id the Java identifier// w  ww .  j  a  va 2 s .  co  m
 * @param sourceLevel the source level
 * @param complianceLevel the compliance level
 * @return a status object with code <code>IStatus.OK</code> if
 *      the given identifier is a valid Java identifier, otherwise a status
 *      object indicating what is wrong with the identifier
 * @since 3.3
 */
public static IStatus validateIdentifier(String id, String sourceLevel, String complianceLevel) {
    if (scannedIdentifier(id, sourceLevel, complianceLevel) != null) {
        return JavaModelStatus.VERIFIED_OK;
    } else {
        return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1,
                Messages.bind(Messages.convention_illegalIdentifier, id), null);
    }
}

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

License:Open Source License

private static IJavaModelStatus validateLibraryContents(IPath path, IJavaProject project, String entryPathMsg) {
    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    try {/*from ww w .  j  a  va2s.com*/
        manager.verifyArchiveContent(path);
    } catch (CoreException e) {
        if (e.getStatus().getMessage() == Messages.status_IOException) {
            return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH,
                    Messages.bind(Messages.classpath_archiveReadError,
                            new String[] { entryPathMsg, project.getElementName() }));
        }
    }
    return JavaModelStatus.VERIFIED_OK;
}

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

License:Open Source License

/**
 * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getContents()
 *//*w w  w .  j  a  v a2 s.  co m*/
public char[] getContents() {
    IBuffer buffer = getBufferManager().getBuffer(this);
    if (buffer == null) {
        // no need to force opening of CU to get the content
        // also this cannot be a working copy, as its buffer is never closed while the working copy is alive
        File file = resource();
        // Get encoding from file
        String encoding;
        encoding = "UTF-8"; //file.getCharset();
        try {
            return Util.getResourceContentsAsCharArray(file, encoding);
        } catch (JavaModelException e) {
            if (manager.abortOnMissingSource.get() == Boolean.TRUE) {
                IOException ioException = e.getJavaModelStatus()
                        .getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException) e.getException()
                                : new IOException(e.getMessage());
                throw new AbortCompilationUnit(null, ioException, encoding);
            } else {
                Util.log(e, Messages.bind(Messages.file_notFound, file.getAbsolutePath()));
            }
            return CharOperation.NO_CHAR;
        }
    }
    char[] contents = buffer.getCharacters();
    if (contents == null) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129814
        if (manager.abortOnMissingSource.get() == Boolean.TRUE) {
            IOException ioException = new IOException(Messages.buffer_closed);
            IFile file = (IFile) getResource();
            // Get encoding from file
            String encoding;
            try {
                encoding = file.getCharset();
            } catch (CoreException ce) {
                // do not use any encoding
                encoding = null;
            }
            throw new AbortCompilationUnit(null, ioException, encoding);
        }
        return CharOperation.NO_CHAR;
    }
    return contents;
}

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

License:Open Source License

/**
 * Returns the message that is relevant to the code of this status.
 *///from w w w.  jav a  2 s  .  co  m
public String getMessage() {
    Throwable exception = getException();
    if (exception == null) {
        switch (getCode()) {
        case CORE_EXCEPTION:
            return Messages.status_coreException;

        case BUILDER_INITIALIZATION_ERROR:
            return Messages.build_initializationError;

        case BUILDER_SERIALIZATION_ERROR:
            return Messages.build_serializationError;

        case DEVICE_PATH:
            return Messages.bind(Messages.status_cannotUseDeviceOnPath, getPath().toString());

        case DOM_EXCEPTION:
            return Messages.status_JDOMError;

        case ELEMENT_DOES_NOT_EXIST:
            return Messages.bind(Messages.element_doesNotExist,
                    ((JavaElement) this.elements[0]).toStringWithAncestors());

        case ELEMENT_NOT_ON_CLASSPATH:
            return Messages.bind(Messages.element_notOnClasspath,
                    ((JavaElement) this.elements[0]).toStringWithAncestors());

        case EVALUATION_ERROR:
            return Messages.bind(Messages.status_evaluationError, this.string);

        case INDEX_OUT_OF_BOUNDS:
            return Messages.status_indexOutOfBounds;

        case INVALID_CONTENTS:
            return Messages.status_invalidContents;

        case INVALID_DESTINATION:
            return Messages.bind(Messages.status_invalidDestination,
                    ((JavaElement) this.elements[0]).toStringWithAncestors());

        case INVALID_ELEMENT_TYPES:
            StringBuffer buff = new StringBuffer(Messages.operation_notSupported);
            for (int i = 0; i < this.elements.length; i++) {
                if (i > 0) {
                    buff.append(", "); //$NON-NLS-1$
                }
                buff.append(((JavaElement) this.elements[i]).toStringWithAncestors());
            }
            return buff.toString();

        case INVALID_NAME:
            return Messages.bind(Messages.status_invalidName, this.string);

        case INVALID_PACKAGE:
            return Messages.bind(Messages.status_invalidPackage, this.string);

        case INVALID_PATH:
            if (this.string != null) {
                return this.string;
            } else {
                return Messages.bind(Messages.status_invalidPath,
                        new String[] { getPath() == null ? "null" : getPath().toString() } //$NON-NLS-1$
                );
            }

        case INVALID_PROJECT:
            return Messages.bind(Messages.status_invalidProject, this.string);

        case INVALID_RESOURCE:
            return Messages.bind(Messages.status_invalidResource, this.string);

        case INVALID_RESOURCE_TYPE:
            return Messages.bind(Messages.status_invalidResourceType, this.string);

        case INVALID_SIBLING:
            if (this.string != null) {
                return Messages.bind(Messages.status_invalidSibling, this.string);
            } else {
                return Messages.bind(Messages.status_invalidSibling,
                        ((JavaElement) this.elements[0]).toStringWithAncestors());
            }

        case IO_EXCEPTION:
            return Messages.status_IOException;

        case NAME_COLLISION:
            if (this.elements != null && this.elements.length > 0) {
                IJavaElement element = this.elements[0];
                if (element instanceof org.eclipse.jdt.internal.core.PackageFragment
                        && ((PackageFragment) element).isDefaultPackage()) {
                    return Messages.operation_cannotRenameDefaultPackage;
                }
            }
            if (this.string != null) {
                return this.string;
            } else {
                return Messages.bind(Messages.status_nameCollision, ""); //$NON-NLS-1$
            }
        case NO_ELEMENTS_TO_PROCESS:
            return Messages.operation_needElements;

        case NULL_NAME:
            return Messages.operation_needName;

        case NULL_PATH:
            return Messages.operation_needPath;

        case NULL_STRING:
            return Messages.operation_needString;

        case PATH_OUTSIDE_PROJECT:
            return Messages.bind(Messages.operation_pathOutsideProject,
                    new String[] { this.string, ((JavaElement) this.elements[0]).toStringWithAncestors() });

        case READ_ONLY:
            IJavaElement element = this.elements[0];
            String name = element.getElementName();
            if (element instanceof IPackageFragment && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
                return Messages.status_defaultPackageReadOnly;
            }
            return Messages.bind(Messages.status_readOnly, name);

        case RELATIVE_PATH:
            return Messages.bind(Messages.operation_needAbsolutePath, getPath().toString());

        case TARGET_EXCEPTION:
            return Messages.status_targetException;

        case UPDATE_CONFLICT:
            return Messages.status_updateConflict;

        case NO_LOCAL_CONTENTS:
            return Messages.bind(Messages.status_noLocalContents, getPath().toString());

        case CP_CONTAINER_PATH_UNBOUND:
            IJavaProject javaProject = (IJavaProject) this.elements[0];
            ClasspathContainerInitializer initializer = JavaCore
                    .getClasspathContainerInitializer(this.path.segment(0));
            String description = null;
            if (initializer != null)
                description = initializer.getDescription(this.path, javaProject);
            if (description == null)
                description = this.path.makeRelative().toString();
            return Messages.bind(Messages.classpath_unboundContainerPath,
                    new String[] { description, javaProject.getElementName() });

        case INVALID_CP_CONTAINER_ENTRY:
            javaProject = (IJavaProject) this.elements[0];
            IClasspathContainer container = null;
            description = null;
            try {
                container = JavaCore.getClasspathContainer(this.path, javaProject);
            } catch (JavaModelException e) {
                // project doesn't exist: ignore
            }
            if (container == null) {
                initializer = JavaCore.getClasspathContainerInitializer(this.path.segment(0));
                if (initializer != null)
                    description = initializer.getDescription(this.path, javaProject);
            } else {
                description = container.getDescription();
            }
            if (description == null)
                description = this.path.makeRelative().toString();
            return Messages.bind(Messages.classpath_invalidContainer,
                    new String[] { description, javaProject.getElementName() });

        case CP_VARIABLE_PATH_UNBOUND:
            javaProject = (IJavaProject) this.elements[0];
            return Messages.bind(Messages.classpath_unboundVariablePath,
                    new String[] { this.path.makeRelative().toString(), javaProject.getElementName() });

        case CLASSPATH_CYCLE:
            javaProject = (IJavaProject) this.elements[0];
            return Messages.bind(Messages.classpath_cycle,
                    new String[] { javaProject.getElementName(), this.string });

        case DISABLED_CP_EXCLUSION_PATTERNS:
            javaProject = (IJavaProject) this.elements[0];
            String projectName = javaProject.getElementName();
            IPath newPath = this.path;
            if (this.path.segment(0).toString().equals(projectName)) {
                newPath = this.path.removeFirstSegments(1);
            }
            return Messages.bind(Messages.classpath_disabledInclusionExclusionPatterns,
                    new String[] { newPath.makeRelative().toString(), projectName });

        case DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS:
            javaProject = (IJavaProject) this.elements[0];
            projectName = javaProject.getElementName();
            newPath = this.path;
            if (this.path.segment(0).toString().equals(projectName)) {
                newPath = this.path.removeFirstSegments(1);
            }
            return Messages.bind(Messages.classpath_disabledMultipleOutputLocations,
                    new String[] { newPath.makeRelative().toString(), projectName });

        case CANNOT_RETRIEVE_ATTACHED_JAVADOC:
            if (this.elements != null && this.elements.length == 1) {
                if (this.string != null) {
                    return Messages.bind(Messages.status_cannot_retrieve_attached_javadoc,
                            ((JavaElement) this.elements[0]).toStringWithAncestors(), this.string);
                }
                return Messages.bind(Messages.status_cannot_retrieve_attached_javadoc,
                        ((JavaElement) this.elements[0]).toStringWithAncestors(), ""); //$NON-NLS-1$
            }
            if (this.string != null) {
                return Messages.bind(Messages.status_cannot_retrieve_attached_javadoc, this.string, "");//$NON-NLS-1$
            }
            break;

        case CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT:
            if (this.elements != null && this.elements.length == 1) {
                if (this.string != null) {
                    return Messages.bind(Messages.status_timeout_javadoc,
                            ((JavaElement) this.elements[0]).toStringWithAncestors(), this.string);
                }
                return Messages.bind(Messages.status_timeout_javadoc,
                        ((JavaElement) this.elements[0]).toStringWithAncestors(), ""); //$NON-NLS-1$
            }
            if (this.string != null) {
                return Messages.bind(Messages.status_timeout_javadoc, this.string, "");//$NON-NLS-1$
            }
            break;

        case UNKNOWN_JAVADOC_FORMAT:
            return Messages.bind(Messages.status_unknown_javadoc_format,
                    ((JavaElement) this.elements[0]).toStringWithAncestors());

        case DEPRECATED_VARIABLE:
            javaProject = (IJavaProject) this.elements[0];
            return Messages.bind(Messages.classpath_deprecated_variable, new String[] {
                    this.path.segment(0).toString(), javaProject.getElementName(), this.string });
        }
        if (this.string != null) {
            return this.string;
        } else {
            return ""; //$NON-NLS-1$
        }
    } else {
        String message = exception.getMessage();
        if (message != null) {
            return message;
        } else {
            return exception.toString();
        }
    }
}

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

License:Open Source License

/**
 * @see org.eclipse.jdt.core.IPackageFragment#getClassFile(String)
 * @exception IllegalArgumentException if the name does not end with ".class"
 *///from w  w w . j  a v  a2s  .  c o  m
public IClassFile getClassFile(String classFileName) {
    if (!org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(classFileName)) {
        throw new IllegalArgumentException(Messages.bind(Messages.element_invalidClassFileName, classFileName));
    }
    // don't hold on the .class file extension to save memory
    // also make sure to not use substring as the resulting String may hold on the underlying char[] which might be much bigger than necessary
    int length = classFileName.length() - 6;
    char[] nameWithoutExtension = new char[length];
    classFileName.getChars(0, length, nameWithoutExtension, 0);
    return new ClassFile(this, manager, new String(nameWithoutExtension));
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.BasicSearchEngine.java

License:Open Source License

/**
 * Searches for matches to a given query. Search queries can be created using helper
 * methods (from a String pattern or a Java element) and encapsulate the description of what is
 * being searched (for example, search method declarations in a case sensitive way).
 *
 * @param scope the search result has to be limited to the given scope
* @param requestor a callback object to which each match is reported
*///from   w  w w.  j  av  a  2 s  .  c  om
void findMatches(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope,
        SearchRequestor requestor, IProgressMonitor monitor) throws CoreException {
    if (monitor != null && monitor.isCanceled())
        throw new OperationCanceledException();
    try {
        if (VERBOSE) {
            Util.verbose("Searching for pattern: " + pattern.toString()); //$NON-NLS-1$
            Util.verbose(scope.toString());
        }
        if (participants == null) {
            if (VERBOSE)
                Util.verbose("No participants => do nothing!"); //$NON-NLS-1$
            return;
        }

        /* initialize progress monitor */
        int length = participants.length;
        if (monitor != null)
            monitor.beginTask(Messages.engine_searching, 100 * length);
        requestor.beginReporting();
        for (int i = 0; i < length; i++) {
            if (monitor != null && monitor.isCanceled())
                throw new OperationCanceledException();

            SearchParticipant participant = participants[i];
            try {
                if (monitor != null)
                    monitor.subTask(Messages.bind(Messages.engine_searching_indexing,
                            new String[] { participant.getDescription() }));
                participant.beginSearching();
                requestor.enterParticipant(participant);
                PathCollector pathCollector = new PathCollector();
                indexManager.performConcurrentJob(
                        new PatternSearchJob(pattern, participant, scope, pathCollector, indexManager),
                        IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
                        monitor == null ? null : new SubProgressMonitor(monitor, 50));
                if (monitor != null && monitor.isCanceled())
                    throw new OperationCanceledException();

                // locate index matches if any (note that all search matches could have been issued during index querying)
                if (monitor != null)
                    monitor.subTask(Messages.bind(Messages.engine_searching_matching,
                            new String[] { participant.getDescription() }));
                String[] indexMatchPaths = pathCollector.getPaths();
                if (indexMatchPaths != null) {
                    pathCollector = null; // release
                    int indexMatchLength = indexMatchPaths.length;
                    SearchDocument[] indexMatches = new SearchDocument[indexMatchLength];
                    for (int j = 0; j < indexMatchLength; j++) {
                        indexMatches[j] = participant.getDocument(indexMatchPaths[j]);
                    }
                    SearchDocument[] matches = MatchLocator.addWorkingCopies(pattern, indexMatches,
                            getWorkingCopies(), participant);
                    participant.locateMatches(matches, pattern, scope, requestor,
                            monitor == null ? null : new SubProgressMonitor(monitor, 50));
                }
            } finally {
                requestor.exitParticipant(participant);
                participant.doneSearching();
            }
        }
    } finally {
        requestor.endReporting();
        if (monitor != null)
            monitor.done();
    }
}

From source file:io.sarl.eclipse.util.JavaClasspathParser.java

License:Apache License

/**
 * Decodes one XML element with the XML stream.
 *
 * @param element/*from  w  ww  . ja  va  2  s  .com*/
 *            - the considered element
 * @param projectName
 *            - the name of project containing the .classpath file
 * @param projectRootAbsoluteFullPath
 *            - he path to project containing the .classpath file
 * @param unknownElements
 *            - map of unknown elements
 * @return the set of CLasspath ENtries extracted from the considered element
 */
@SuppressWarnings({ "checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity" })
public static IClasspathEntry elementDecode(Element element, String projectName,
        IPath projectRootAbsoluteFullPath, Map<IPath, UnknownXmlElements> unknownElements) {
    final IPath projectPath = projectRootAbsoluteFullPath;
    final NamedNodeMap attributes = element.getAttributes();
    final NodeList children = element.getChildNodes();
    final boolean[] foundChildren = new boolean[children.getLength()];
    final String kindAttr = removeAttribute(ClasspathEntry.TAG_KIND, attributes);
    final String pathAttr = removeAttribute(ClasspathEntry.TAG_PATH, attributes);

    // ensure path is absolute
    IPath path = new Path(pathAttr);
    final int kind = kindFromString(kindAttr);
    if (kind != IClasspathEntry.CPE_VARIABLE && kind != IClasspathEntry.CPE_CONTAINER && !path.isAbsolute()) {
        if (!(path.segmentCount() > 0 && path.segment(0).equals(ClasspathEntry.DOT_DOT))) {
            path = projectPath.append(path);
        }
    }
    // source attachment info (optional)
    IPath sourceAttachmentPath = element.hasAttribute(ClasspathEntry.TAG_SOURCEPATH)
            ? new Path(removeAttribute(ClasspathEntry.TAG_SOURCEPATH, attributes))
            : null;
    if (kind != IClasspathEntry.CPE_VARIABLE && sourceAttachmentPath != null
            && !sourceAttachmentPath.isAbsolute()) {
        sourceAttachmentPath = projectPath.append(sourceAttachmentPath);
    }
    final IPath sourceAttachmentRootPath = element.hasAttribute(ClasspathEntry.TAG_ROOTPATH)
            ? new Path(removeAttribute(ClasspathEntry.TAG_ROOTPATH, attributes))
            : null;

    // exported flag (optional)
    final boolean isExported = removeAttribute(ClasspathEntry.TAG_EXPORTED, attributes).equals("true"); //$NON-NLS-1$

    // inclusion patterns (optional)
    IPath[] inclusionPatterns = decodePatterns(attributes, ClasspathEntry.TAG_INCLUDING);
    if (inclusionPatterns == null) {
        inclusionPatterns = ClasspathEntry.INCLUDE_ALL;
    }

    // exclusion patterns (optional)
    IPath[] exclusionPatterns = decodePatterns(attributes, ClasspathEntry.TAG_EXCLUDING);
    if (exclusionPatterns == null) {
        exclusionPatterns = ClasspathEntry.EXCLUDE_NONE;
    }

    // access rules (optional)
    NodeList attributeList = getChildAttributes(ClasspathEntry.TAG_ACCESS_RULES, children, foundChildren);
    IAccessRule[] accessRules = decodeAccessRules(attributeList);

    // backward compatibility
    if (accessRules == null) {
        accessRules = getAccessRules(inclusionPatterns, exclusionPatterns);
    }

    // combine access rules (optional)
    final boolean combineAccessRestrictions = !removeAttribute(ClasspathEntry.TAG_COMBINE_ACCESS_RULES,
            attributes).equals("false"); //$NON-NLS-1$

    // extra attributes (optional)
    attributeList = getChildAttributes(ClasspathEntry.TAG_ATTRIBUTES, children, foundChildren);
    final IClasspathAttribute[] extraAttributes = decodeExtraAttributes(attributeList);

    // custom output location
    final IPath outputLocation = element.hasAttribute(ClasspathEntry.TAG_OUTPUT)
            ? projectPath.append(removeAttribute(ClasspathEntry.TAG_OUTPUT, attributes))
            : null;

    String[] unknownAttributes = null;
    ArrayList<String> unknownChildren = null;

    if (unknownElements != null) {
        // unknown attributes
        final int unknownAttributeLength = attributes.getLength();
        if (unknownAttributeLength != 0) {
            unknownAttributes = new String[unknownAttributeLength * 2];
            for (int i = 0; i < unknownAttributeLength; i++) {
                final Node attribute = attributes.item(i);
                unknownAttributes[i * 2] = attribute.getNodeName();
                unknownAttributes[i * 2 + 1] = attribute.getNodeValue();
            }
        }

        // unknown children
        for (int i = 0, length = foundChildren.length; i < length; i++) {
            if (!foundChildren[i]) {
                final Node node = children.item(i);
                if (node.getNodeType() != Node.ELEMENT_NODE) {
                    continue;
                }
                if (unknownChildren == null) {
                    unknownChildren = new ArrayList<>();
                }
                final StringBuffer buffer = new StringBuffer();
                decodeUnknownNode(node, buffer);
                unknownChildren.add(buffer.toString());
            }
        }
    }

    // recreate the CP entry
    IClasspathEntry entry = null;
    switch (kind) {

    case IClasspathEntry.CPE_PROJECT:
        /*
         * IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_PROJECT, path, ClasspathEntry.INCLUDE_ALL, // inclusion patterns
         * ClasspathEntry.EXCLUDE_NONE, // exclusion patterns null, // source attachment null, // source attachment root null, // specific output
         * folder
         */
        entry = new ClasspathEntry(IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_PROJECT, path,
                ClasspathEntry.INCLUDE_ALL, ClasspathEntry.EXCLUDE_NONE, null, null, null, isExported,
                accessRules, combineAccessRestrictions, extraAttributes);
        break;
    case IClasspathEntry.CPE_LIBRARY:
        entry = JavaCore.newLibraryEntry(path, sourceAttachmentPath, sourceAttachmentRootPath, accessRules,
                extraAttributes, isExported);
        break;
    case IClasspathEntry.CPE_SOURCE:
        // must be an entry in this project or specify another project
        final String projSegment = path.segment(0);
        if (projSegment != null && projSegment.equals(projectName)) {
            // this project
            entry = JavaCore.newSourceEntry(path, inclusionPatterns, exclusionPatterns, outputLocation,
                    extraAttributes);
        } else {
            if (path.segmentCount() == 1) {
                // another project
                entry = JavaCore.newProjectEntry(path, accessRules, combineAccessRestrictions, extraAttributes,
                        isExported);
            } else {
                // an invalid source folder
                entry = JavaCore.newSourceEntry(path, inclusionPatterns, exclusionPatterns, outputLocation,
                        extraAttributes);
            }
        }
        break;
    case IClasspathEntry.CPE_VARIABLE:
        entry = JavaCore.newVariableEntry(path, sourceAttachmentPath, sourceAttachmentRootPath, accessRules,
                extraAttributes, isExported);
        break;
    case IClasspathEntry.CPE_CONTAINER:
        entry = JavaCore.newContainerEntry(path, accessRules, extraAttributes, isExported);
        break;
    case ClasspathEntry.K_OUTPUT:
        if (!path.isAbsolute()) {
            return null;
        }
        /*
         * ClasspathEntry.EXCLUDE_NONE, null, // source attachment null, // source attachment root null, // custom output location false, null, //
         * no access rules false, // no accessible files to combine
         */
        entry = new ClasspathEntry(ClasspathEntry.K_OUTPUT, IClasspathEntry.CPE_LIBRARY, path,
                ClasspathEntry.INCLUDE_ALL, ClasspathEntry.EXCLUDE_NONE, null, null, null, false, null, false,
                ClasspathEntry.NO_EXTRA_ATTRIBUTES);
        break;
    default:
        throw new AssertionFailedException(Messages.bind(Messages.classpath_unknownKind, kindAttr));
    }

    if (unknownAttributes != null || unknownChildren != null) {
        final UnknownXmlElements unknownXmlElements = new UnknownXmlElements();
        unknownXmlElements.attributes = unknownAttributes;
        unknownXmlElements.children = unknownChildren;
        if (unknownElements != null) {
            unknownElements.put(path, unknownXmlElements);
        }
    }

    return entry;
}