Example usage for org.eclipse.jdt.internal.core.util Util log

List of usage examples for org.eclipse.jdt.internal.core.util Util log

Introduction

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

Prototype

public static void log(int statusErrorID, String message) 

Source Link

Usage

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

License:Open Source License

/**
 * Notify the listeners that this buffer has changed.
 * To avoid deadlock, this should not be called in a synchronized block.
 *///w w w .  j  a v  a2 s.  c o  m
protected void notifyChanged(final BufferChangedEvent event) {
    ArrayList listeners = this.changeListeners;
    if (listeners != null) {
        for (int i = 0, size = listeners.size(); i < size; ++i) {
            final IBufferChangedListener listener = (IBufferChangedListener) listeners.get(i);
            SafeRunner.run(new ISafeRunnable() {
                public void handleException(Throwable exception) {
                    Util.log(exception, "Exception occurred in listener of buffer change notification"); //$NON-NLS-1$
                }

                public void run() throws Exception {
                    listener.bufferChanged(event);
                }
            });

        }
    }
}

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

License:Open Source License

public void resourceChanged(final IResourceChangeEvent event) {
    for (int i = 0; i < this.preResourceChangeListenerCount; i++) {
        // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
        final IResourceChangeListener listener = this.preResourceChangeListeners[i];
        if ((this.preResourceChangeEventMasks[i] & event.getType()) != 0)
            SafeRunner.run(new ISafeRunnable() {
                public void handleException(Throwable exception) {
                    Util.log(exception,
                            "Exception occurred in listener of pre Java resource change notification"); //$NON-NLS-1$
                }/*from   w  ww. j a  va  2  s.  c  o  m*/

                public void run() throws Exception {
                    listener.resourceChanged(event);
                }
            });
    }
    try {
        getDeltaProcessor().resourceChanged(event);
    } finally {
        // TODO (jerome) see 47631, may want to get rid of following so as to reuse delta processor ?
        if (event.getType() == IResourceChangeEvent.POST_CHANGE) {
            this.deltaProcessors.set(null);
        } else {
            // If we are going to reuse the delta processor of this thread, don't hang on to state
            // that isn't meant to be reused. https://bugs.eclipse.org/bugs/show_bug.cgi?id=273385
            getDeltaProcessor().overridenEventType = -1;
        }
    }

}

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

License:Open Source License

public Hashtable getExternalLibTimeStamps() {
    if (this.externalTimeStamps == null) {
        Hashtable timeStamps = new Hashtable();
        File timestampsFile = getTimeStampsFile();
        DataInputStream in = null;
        try {//w ww .  j  a v  a  2  s  . c o m
            in = new DataInputStream(new BufferedInputStream(new FileInputStream(timestampsFile)));
            int size = in.readInt();
            while (size-- > 0) {
                String key = in.readUTF();
                long timestamp = in.readLong();
                timeStamps.put(Path.fromPortableString(key), new Long(timestamp));
            }
        } catch (IOException e) {
            if (timestampsFile.exists())
                Util.log(e, "Unable to read external time stamps"); //$NON-NLS-1$
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // nothing we can do: ignore
                }
            }
        }
        this.externalTimeStamps = timeStamps;
    }
    return this.externalTimeStamps;
}

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

License:Open Source License

private void notifyListeners(IJavaElementDelta deltaToNotify, int eventType,
        IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) {
    final ElementChangedEvent extraEvent = new ElementChangedEvent(deltaToNotify, eventType);
    for (int i = 0; i < listenerCount; i++) {
        if ((listenerMask[i] & eventType) != 0) {
            final IElementChangedListener listener = listeners[i];
            long start = -1;
            if (VERBOSE) {
                System.out.print("Listener #" + (i + 1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$
                start = System.currentTimeMillis();
            }//  www.jav a 2  s. c  o m
            // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
            SafeRunner.run(new ISafeRunnable() {
                public void handleException(Throwable exception) {
                    Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$
                }

                public void run() throws Exception {
                    PerformanceStats stats = null;
                    if (PERF) {
                        //                     stats = PerformanceStats.getStats(JavaModelManager.DELTA_LISTENER_PERF, listener);
                        //                     stats.startRun();
                    }
                    listener.elementChanged(extraEvent);
                    if (PERF) {
                        stats.endRun();
                    }
                }
            });
            if (VERBOSE) {
                System.out.println(" -> " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
    }
}

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

License:Open Source License

private void notifyTypeHierarchies(IElementChangedListener[] listeners, int listenerCount) {
    for (int i = 0; i < listenerCount; i++) {
        final IElementChangedListener listener = listeners[i];
        if (!(listener instanceof TypeHierarchy))
            continue;

        // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
        SafeRunner.run(new ISafeRunnable() {
            public void handleException(Throwable exception) {
                Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$
            }/*from  w ww .j ava  2  s.co m*/

            public void run() throws Exception {
                TypeHierarchy typeHierarchy = (TypeHierarchy) listener;
                if (typeHierarchy.hasFineGrainChanges()) {
                    // case of changes in primary working copies
                    typeHierarchy.needsRefresh = true;
                    typeHierarchy.fireChange();
                }
            }
        });
    }
}

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

License:Open Source License

/**
 * Compute the package fragment children of this package fragment root.
 * These are all of the directory zip entries, and any directories implied
 * by the path of class files contained in the jar of this package fragment root.
 *//* w  w  w. jav a 2s . co m*/
protected boolean computeChildren(OpenableElementInfo info, File underlyingResource) throws JavaModelException {
    HashtableOfArrayToObject rawPackageInfo = new HashtableOfArrayToObject();
    IJavaElement[] children;
    ZipFile jar = null;
    try {
        //            Object file = JavaModel.getTarget(getPath(), true);
        //            long level = Util.getJdkLevel(file);
        String compliance = CompilerOptions.VERSION_1_8;
        jar = getJar();

        // always create the default package
        rawPackageInfo.put(CharOperation.NO_STRINGS, new ArrayList[] { EMPTY_LIST, EMPTY_LIST });

        for (Enumeration e = jar.entries(); e.hasMoreElements();) {
            ZipEntry member = (ZipEntry) e.nextElement();
            initRawPackageInfo(rawPackageInfo, member.getName(), member.isDirectory(), compliance);
        }

        // loop through all of referenced packages, creating package fragments if necessary
        // and cache the entry names in the rawPackageInfo table
        children = new IJavaElement[rawPackageInfo.size()];
        int index = 0;
        for (int i = 0, length = rawPackageInfo.keyTable.length; i < length; i++) {
            String[] pkgName = (String[]) rawPackageInfo.keyTable[i];
            if (pkgName == null)
                continue;
            children[index++] = getPackageFragment(pkgName);
        }
    } catch (CoreException e) {
        if (e.getCause() instanceof ZipException) {
            // not a ZIP archive, leave the children empty
            Util.log(IStatus.ERROR, "Invalid ZIP archive: " + toStringWithAncestors()); //$NON-NLS-1$
            children = NO_ELEMENTS;
        } else if (e instanceof JavaModelException) {
            throw (JavaModelException) e;
        } else {
            throw new JavaModelException(e);
        }
    } finally {
        manager.closeZipFile(jar);
    }

    info.setChildren(children);
    ((JarPackageFragmentRootInfo) info).rawPackageInfo = rawPackageInfo;
    return true;
}

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

License:Open Source License

private double getRatioForProperty(String propertyName) {
    String property = System.getProperty(propertyName);
    if (property != null) {
        try {//from   w  w  w .  j  a v  a  2 s.  c o m
            return Double.parseDouble(property);
        } catch (NumberFormatException e) {
            // ignore
            Util.log(e, "Could not parse value for " + propertyName + ": " + property); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
    return 1.0;
}

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

License:Open Source License

public void indexDocument() {
    try {//w  w w.j  a  v a2s  .  com
        final byte[] contents = this.document.getByteContents();
        // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=107124
        // contents can potentially be null if a IOException occurs while retrieving the contents
        if (contents == null)
            return;
        final String path = this.document.getPath();
        ClassFileReader reader = new ClassFileReader(contents, path == null ? null : path.toCharArray());

        // first add type references
        char[] className = replace('/', '.', reader.getName()); // looks like java/lang/String
        // need to extract the package name and the simple name
        int packageNameIndex = CharOperation.lastIndexOf('.', className);
        char[] packageName = null;
        char[] name = null;
        if (packageNameIndex >= 0) {
            packageName = CharOperation.subarray(className, 0, packageNameIndex);
            name = CharOperation.subarray(className, packageNameIndex + 1, className.length);
        } else {
            packageName = CharOperation.NO_CHAR;
            name = className;
        }
        char[] enclosingTypeName = null;
        boolean isNestedType = reader.isNestedType();
        if (isNestedType) {
            if (reader.isAnonymous()) {
                name = CharOperation.NO_CHAR;
            } else {
                name = reader.getInnerSourceName();
            }
            if (reader.isLocal() || reader.isAnonymous()) {
                // set specific ['0'] value for local and anonymous to be able to filter them
                enclosingTypeName = ONE_ZERO;
            } else {
                char[] fullEnclosingName = reader.getEnclosingTypeName();
                int nameLength = fullEnclosingName.length - packageNameIndex - 1;
                if (nameLength <= 0) {
                    // See PR 1GIR345: ITPJCORE:ALL - Indexer: NegativeArraySizeException
                    return;
                }
                enclosingTypeName = new char[nameLength];
                System.arraycopy(fullEnclosingName, packageNameIndex + 1, enclosingTypeName, 0, nameLength);
            }
        }
        // type parameters
        char[][] typeParameterSignatures = null;
        char[] genericSignature = reader.getGenericSignature();
        if (genericSignature != null) {
            CharOperation.replace(genericSignature, '/', '.');
            typeParameterSignatures = Signature.getTypeParameters(genericSignature);
        }

        // eliminate invalid innerclasses (1G4KCF7)
        if (name == null)
            return;

        char[][] superinterfaces = replace('/', '.', reader.getInterfaceNames());
        char[][] enclosingTypeNames = enclosingTypeName == null ? null : new char[][] { enclosingTypeName };
        int modifiers = reader.getModifiers();
        switch (TypeDeclaration.kind(modifiers)) {
        case TypeDeclaration.CLASS_DECL:
            char[] superclass = replace('/', '.', reader.getSuperclassName());
            addClassDeclaration(modifiers, packageName, name, enclosingTypeNames, superclass, superinterfaces,
                    typeParameterSignatures, false);
            break;
        case TypeDeclaration.INTERFACE_DECL:
            addInterfaceDeclaration(modifiers, packageName, name, enclosingTypeNames, superinterfaces,
                    typeParameterSignatures, false);
            break;
        case TypeDeclaration.ENUM_DECL:
            superclass = replace('/', '.', reader.getSuperclassName());
            addEnumDeclaration(modifiers, packageName, name, enclosingTypeNames, superclass, superinterfaces,
                    false);
            break;
        case TypeDeclaration.ANNOTATION_TYPE_DECL:
            addAnnotationTypeDeclaration(modifiers, packageName, name, enclosingTypeNames, false);
            break;
        }

        // Look for references in class annotations
        IBinaryAnnotation[] annotations = reader.getAnnotations();
        if (annotations != null) {
            for (int a = 0, length = annotations.length; a < length; a++) {
                IBinaryAnnotation annotation = annotations[a];
                addBinaryAnnotation(annotation);
            }
        }
        long tagBits = reader.getTagBits() & TagBits.AllStandardAnnotationsMask;
        if (tagBits != 0) {
            addBinaryStandardAnnotations(tagBits);
        }

        int extraFlags = ExtraFlags.getExtraFlags(reader);

        // first reference all methods declarations and field declarations
        MethodInfo[] methods = (MethodInfo[]) reader.getMethods();
        boolean noConstructor = true;
        if (methods != null) {
            for (int i = 0, max = methods.length; i < max; i++) {
                MethodInfo method = methods[i];
                boolean isConstructor = method.isConstructor();
                char[] descriptor = method.getMethodDescriptor();
                char[][] parameterTypes = decodeParameterTypes(descriptor, isConstructor && isNestedType);
                char[] returnType = decodeReturnType(descriptor);
                char[][] exceptionTypes = replace('/', '.', method.getExceptionTypeNames());
                if (isConstructor) {
                    noConstructor = false;
                    char[] signature = method.getGenericSignature();
                    if (signature == null) {
                        if (reader.isNestedType() && ((modifiers & ClassFileConstants.AccStatic) == 0)) {
                            signature = removeFirstSyntheticParameter(descriptor);
                        } else {
                            signature = descriptor;
                        }
                    }
                    addConstructorDeclaration(name, parameterTypes == null ? 0 : parameterTypes.length,
                            signature, parameterTypes, method.getArgumentNames(), method.getModifiers(),
                            packageName, modifiers, exceptionTypes, extraFlags);
                } else {
                    if (!method.isClinit()) {
                        addMethodDeclaration(method.getSelector(), parameterTypes, returnType, exceptionTypes);
                    }
                }
                // look for references in method annotations
                annotations = method.getAnnotations();
                if (annotations != null) {
                    for (int a = 0, length = annotations.length; a < length; a++) {
                        IBinaryAnnotation annotation = annotations[a];
                        addBinaryAnnotation(annotation);
                    }
                }
                tagBits = method.getTagBits() & TagBits.AllStandardAnnotationsMask;
                if (tagBits != 0) {
                    addBinaryStandardAnnotations(tagBits);
                }
            }
        }
        if (noConstructor) {
            addDefaultConstructorDeclaration(className, packageName, modifiers, extraFlags);
        }
        FieldInfo[] fields = (FieldInfo[]) reader.getFields();
        if (fields != null) {
            for (int i = 0, max = fields.length; i < max; i++) {
                FieldInfo field = fields[i];
                char[] fieldName = field.getName();
                char[] fieldType = decodeFieldType(replace('/', '.', field.getTypeName()));
                addFieldDeclaration(fieldType, fieldName);
                // look for references in field annotations
                annotations = field.getAnnotations();
                if (annotations != null) {
                    for (int a = 0, length = annotations.length; a < length; a++) {
                        IBinaryAnnotation annotation = annotations[a];
                        addBinaryAnnotation(annotation);
                    }
                }
                tagBits = field.getTagBits() & TagBits.AllStandardAnnotationsMask;
                if (tagBits != 0) {
                    addBinaryStandardAnnotations(tagBits);
                }
            }
        }
        // record all references found inside the .class file
        extractReferenceFromConstantPool(contents, reader);
    } catch (ClassFormatException e) {
        // ignore
        this.document.removeAllIndexEntries();
        Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath()
                + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (RuntimeException e) {
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=182154
        // logging the entry that could not be indexed and continue with the next one
        // we remove all entries relative to the boggus document
        this.document.removeAllIndexEntries();
        Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath()
                + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$
    }
}

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

License:Open Source License

public IPath[] enclosingProjectsAndJars() {
    IPath[] result = this.enclosingPaths;
    if (result != null) {
        return result;
    }// w w w  .  jav  a2  s . co  m
    long start = BasicSearchEngine.VERBOSE ? System.currentTimeMillis() : -1;
    try {
        IJavaProject[] projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects();
        // use a linked set to preserve the order during search: see bug 348507
        Set paths = new LinkedHashSet(projects.length * 2);
        for (int i = 0, length = projects.length; i < length; i++) {
            JavaProject javaProject = (JavaProject) projects[i];

            // Add project full path
            IPath projectPath = javaProject.getProject().getFullPath();
            paths.add(projectPath);
        }

        // add the project source paths first in a separate loop above
        // to ensure source files always get higher precedence during search.
        // see bug 348507

        for (int i = 0, length = projects.length; i < length; i++) {
            JavaProject javaProject = (JavaProject) projects[i];

            // Add project libraries paths
            IClasspathEntry[] entries = javaProject.getResolvedClasspath();
            for (int j = 0, eLength = entries.length; j < eLength; j++) {
                IClasspathEntry entry = entries[j];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                    IPath path = entry.getPath();
                    Object target = JavaModel.getTarget(path, false/*don't check existence*/);
                    if (target instanceof IFolder) // case of an external folder
                        path = ((IFolder) target).getFullPath();
                    paths.add(entry.getPath());
                }
            }
        }
        result = new IPath[paths.size()];
        paths.toArray(result);
        return this.enclosingPaths = result;
    } catch (JavaModelException e) {
        Util.log(e, "Exception while computing workspace scope's enclosing projects and jars"); //$NON-NLS-1$
        return new IPath[0];
    } finally {
        if (BasicSearchEngine.VERBOSE) {
            long time = System.currentTimeMillis() - start;
            int length = result == null ? 0 : result.length;
            Util.verbose("JavaWorkspaceScope.enclosingProjectsAndJars: " + length + " paths computed in " + time //$NON-NLS-1$//$NON-NLS-2$
                    + "ms."); //$NON-NLS-1$
        }
    }
}

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

License:Apache License

/**
 * Reads entry of a .classpath file.// w  ww  .  jav a 2 s. co m
 *
 * @param projectName
 *            - the name of project containing the .classpath file
 * @param projectRootAbsoluteFullPath
 *            - the path to project containing the .classpath file
 * @param unknownElements
 *            - map of unknow elements
 * @return the set of CLasspath Entries extracted from the .classpath
 * @throws CoreException
 *             - exception during parsing of .classpath
 * @throws IOException
 *             - exception during parsing of .classpath
 * @throws ClasspathEntry.AssertionFailedException
 *             - exception during parsing of .classpath
 * @throws URISyntaxException
 *             - exception during parsing of .classpath
 */
@SuppressWarnings("checkstyle:innerassignment")
public static IClasspathEntry[][] readFileEntriesWithException(String projectName,
        URL projectRootAbsoluteFullPath, Map<IPath, UnknownXmlElements> unknownElements)
        throws CoreException, IOException, ClasspathEntry.AssertionFailedException, URISyntaxException {

    final URL rscFile = new URL(
            projectRootAbsoluteFullPath.toExternalForm().concat(JavaProject.CLASSPATH_FILENAME));
    byte[] bytes;

    // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible
    // so default to using java.io.File
    // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258
    final URI location;
    try {
        location = rscFile.toURI();
    } catch (URISyntaxException e) {
        throw e;
    }
    if (location == null) {
        throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$
    }
    final File file = Util.toLocalFile(location, null/* no progress monitor available */);
    if (file == null) {
        throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$
    }

    try {
        bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file);
    } catch (IOException e) {
        throw e;
    }

    if (hasUTF8BOM(bytes)) {
        // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=240034
        final int length = bytes.length - IContentDescription.BOM_UTF_8.length;
        System.arraycopy(bytes, IContentDescription.BOM_UTF_8.length, bytes = new byte[length], 0, length);
    }
    String xmlClasspath;
    try {
        // .classpath always encoded with UTF-8
        xmlClasspath = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8);
    } catch (UnsupportedEncodingException e) {
        Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$
        // fallback to default
        xmlClasspath = new String(bytes);
    }
    return decodeClasspath(projectName, Path.fromPortableString(projectRootAbsoluteFullPath.getPath()),
            xmlClasspath, unknownElements);
}