use of org.eclipse.core.runtime.CoreException in project che by eclipse.
the class ClasspathEntry method validateClasspathEntry.
// /**
// * Returns a Java model status describing the problem related to this classpath entry if any,
// * a status object with code <code>IStatus.OK</code> if the entry is fine (that is, if the
// * given classpath entry denotes a valid element to be referenced onto a classpath).
// *
// * @param project the given java project
// * @param entry the given classpath entry
// * @param checkSourceAttachment a flag to determine if source attachment should be checked
// * @param referredByContainer flag indicating whether the given entry is referred by a classpath container
// * @return a java model status describing the problem related to this classpath entry if any, a status object with code <code>IStatus
// .OK</code> if the entry is fine
// */
// public static IJavaModelStatus validateClasspathEntry(IJavaProject project, IClasspathEntry entry, boolean checkSourceAttachment,
// boolean referredByContainer){
// if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
// JavaModelManager.getJavaModelManager().removeFromInvalidArchiveCache(entry.getPath());
// }
// IJavaModelStatus status = validateClasspathEntry(project, entry, null, checkSourceAttachment, referredByContainer);
// // https://bugs.eclipse.org/bugs/show_bug.cgi?id=171136 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=300136
// // Ignore class path errors from optional entries.
// int statusCode = status.getCode();
// if ( (statusCode == IJavaModelStatusConstants.INVALID_CLASSPATH ||
// statusCode == IJavaModelStatusConstants.CP_CONTAINER_PATH_UNBOUND ||
// statusCode == IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND ||
// statusCode == IJavaModelStatusConstants.INVALID_PATH) &&
// ((ClasspathEntry) entry).isOptional())
// return JavaModelStatus.VERIFIED_OK;
// return status;
// }
private static IJavaModelStatus validateClasspathEntry(IJavaProject project, IClasspathEntry entry, IClasspathContainer entryContainer, boolean checkSourceAttachment, boolean referredByContainer) {
IPath path = entry.getPath();
// Build some common strings for status message
String projectName = project.getElementName();
String entryPathMsg = projectName.equals(path.segment(0)) ? path.removeFirstSegments(1).makeRelative().toString() : path.toString();
switch(entry.getEntryKind()) {
// container entry check
case IClasspathEntry.CPE_CONTAINER:
if (path.segmentCount() >= 1) {
try {
IJavaModelStatus status = null;
// Validate extra attributes
IClasspathAttribute[] extraAttributes = entry.getExtraAttributes();
if (extraAttributes != null) {
int length = extraAttributes.length;
HashSet set = new HashSet(length);
for (int i = 0; i < length; i++) {
String attName = extraAttributes[i].getName();
if (!set.add(attName)) {
status = new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.classpath_duplicateEntryExtraAttribute, new String[] { attName, entryPathMsg, projectName }));
break;
}
}
}
IClasspathContainer container = JavaModelManager.getJavaModelManager().getClasspathContainer(path, project);
// container retrieval is performing validation check on container entry kinds.
if (container == null) {
if (status != null)
return status;
return new JavaModelStatus(IJavaModelStatusConstants.CP_CONTAINER_PATH_UNBOUND, project, path);
} else if (container == JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS) {
// don't create a marker if initialization is in progress (case of cp initialization batching)
return JavaModelStatus.VERIFIED_OK;
}
IClasspathEntry[] containerEntries = container.getClasspathEntries();
if (containerEntries != null) {
for (int i = 0, length = containerEntries.length; i < length; i++) {
IClasspathEntry containerEntry = containerEntries[i];
int kind = containerEntry == null ? 0 : containerEntry.getEntryKind();
if (containerEntry == null || kind == IClasspathEntry.CPE_SOURCE || kind == IClasspathEntry.CPE_VARIABLE || kind == IClasspathEntry.CPE_CONTAINER) {
return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CP_CONTAINER_ENTRY, project, path);
}
IJavaModelStatus containerEntryStatus = validateClasspathEntry(project, containerEntry, container, checkSourceAttachment, true);
if (!containerEntryStatus.isOK()) {
return containerEntryStatus;
}
}
}
} catch (JavaModelException e) {
return new JavaModelStatus(e);
}
} else {
return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_illegalContainerPath, new String[] { entryPathMsg, projectName }));
}
break;
// variable entry check
case IClasspathEntry.CPE_VARIABLE:
if (path.segmentCount() >= 1) {
try {
entry = JavaCore.getResolvedClasspathEntry(entry);
} catch (AssertionFailedException e) {
// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992
return new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage());
}
if (entry == null) {
return new JavaModelStatus(IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND, project, path);
}
// get validation status
IJavaModelStatus status = validateClasspathEntry(project, entry, null, checkSourceAttachment, false);
if (!status.isOK())
return status;
// return deprecation status if any
String variableName = path.segment(0);
String deprecatedMessage = JavaCore.getClasspathVariableDeprecationMessage(variableName);
if (deprecatedMessage != null) {
return new JavaModelStatus(IStatus.WARNING, IJavaModelStatusConstants.DEPRECATED_VARIABLE, project, path, deprecatedMessage);
}
return status;
} else {
return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_illegalVariablePath, new String[] { entryPathMsg, projectName }));
}
// library entry check
case IClasspathEntry.CPE_LIBRARY:
path = ClasspathEntry.resolveDotDot(project.getProject().getLocation(), path);
// do not validate entries from Class-Path: in manifest
// (these entries are considered optional since the user cannot act on them)
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=252392
String containerInfo = null;
if (entryContainer != null) {
if (entryContainer instanceof UserLibraryClasspathContainer) {
containerInfo = Messages.bind(Messages.classpath_userLibraryInfo, new String[] { entryContainer.getDescription() });
} else {
containerInfo = Messages.bind(Messages.classpath_containerInfo, new String[] { entryContainer.getDescription() });
}
}
IJavaModelStatus status = validateLibraryEntry(path, project, containerInfo, checkSourceAttachment ? entry.getSourceAttachmentPath() : null, entryPathMsg);
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=171136, ignore class path errors from optional entries
if (status.getCode() == IJavaModelStatusConstants.INVALID_CLASSPATH && ((ClasspathEntry) entry).isOptional())
status = JavaModelStatus.VERIFIED_OK;
if (!status.isOK())
return status;
break;
// project entry check
case IClasspathEntry.CPE_PROJECT:
if (path.isAbsolute() && path.segmentCount() == 1) {
IProject prereqProjectRsc = workspaceRoot.getProject(path.segment(0));
IJavaProject prereqProject = JavaCore.create(prereqProjectRsc);
try {
if (!prereqProjectRsc.exists() || !prereqProjectRsc.hasNature(JavaCore.NATURE_ID)) {
return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundProject, new String[] { path.segment(0), projectName }));
}
if (!prereqProjectRsc.isOpen()) {
return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_closedProject, new String[] { path.segment(0) }));
}
if (!JavaCore.IGNORE.equals(project.getOption(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, true))) {
long projectTargetJDK = CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true));
long prereqProjectTargetJDK = CompilerOptions.versionToJdkLevel(prereqProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true));
if (prereqProjectTargetJDK > projectTargetJDK) {
return new JavaModelStatus(IJavaModelStatusConstants.INCOMPATIBLE_JDK_LEVEL, project, path, Messages.bind(Messages.classpath_incompatibleLibraryJDKLevel, new String[] { project.getElementName(), CompilerOptions.versionFromJdkLevel(projectTargetJDK), path.makeRelative().toString(), CompilerOptions.versionFromJdkLevel(prereqProjectTargetJDK) }));
}
}
} catch (CoreException e) {
return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundProject, new String[] { path.segment(0), projectName }));
}
} else {
return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_illegalProjectPath, new String[] { path.toString(), projectName }));
}
break;
// project source folder
case IClasspathEntry.CPE_SOURCE:
if (((entry.getInclusionPatterns() != null && entry.getInclusionPatterns().length > 0) || (entry.getExclusionPatterns() != null && entry.getExclusionPatterns().length > 0)) && JavaCore.DISABLED.equals(project.getOption(JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, true))) {
return new JavaModelStatus(IJavaModelStatusConstants.DISABLED_CP_EXCLUSION_PATTERNS, project, path);
}
if (entry.getOutputLocation() != null && JavaCore.DISABLED.equals(project.getOption(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, true))) {
return new JavaModelStatus(IJavaModelStatusConstants.DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS, project, path);
}
if (path.isAbsolute() && !path.isEmpty()) {
IPath projectPath = project.getProject().getFullPath();
if (!projectPath.isPrefixOf(path) || JavaModel.getTarget(path, true) == null) {
return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundSourceFolder, new String[] { entryPathMsg, projectName }));
}
} else {
return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_illegalSourceFolderPath, new String[] { entryPathMsg, projectName }));
}
break;
}
// Validate extra attributes
IClasspathAttribute[] extraAttributes = entry.getExtraAttributes();
if (extraAttributes != null) {
int length = extraAttributes.length;
HashSet set = new HashSet(length);
for (int i = 0; i < length; i++) {
String attName = extraAttributes[i].getName();
if (!set.add(attName)) {
return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.classpath_duplicateEntryExtraAttribute, new String[] { attName, entryPathMsg, projectName }));
}
}
}
return JavaModelStatus.VERIFIED_OK;
}
use of org.eclipse.core.runtime.CoreException in project che by eclipse.
the class DeltaProcessingState method saveExternalLibTimeStamps.
public void saveExternalLibTimeStamps() throws CoreException {
if (this.externalTimeStamps == null)
return;
// cleanup to avoid any leak ( https://bugs.eclipse.org/bugs/show_bug.cgi?id=244849 )
HashSet toRemove = new HashSet();
if (this.roots != null) {
Enumeration keys = this.externalTimeStamps.keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (this.roots.get(key) == null) {
toRemove.add(key);
}
}
}
File timestamps = getTimeStampsFile();
DataOutputStream out = null;
try {
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(timestamps)));
out.writeInt(this.externalTimeStamps.size() - toRemove.size());
Iterator entries = this.externalTimeStamps.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
IPath key = (IPath) entry.getKey();
if (!toRemove.contains(key)) {
out.writeUTF(key.toPortableString());
Long timestamp = (Long) entry.getValue();
out.writeLong(timestamp.longValue());
}
}
} catch (IOException e) {
//$NON-NLS-1$
IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e);
throw new CoreException(status);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// nothing we can do: ignore
}
}
}
}
use of org.eclipse.core.runtime.CoreException in project che by eclipse.
the class JavadocContentAccess2 method getContentsFromInputStream.
private static String getContentsFromInputStream(InputStream in, String encoding) throws CoreException {
final int defaultFileSize = 15 * 1024;
StringBuffer buffer = new StringBuffer(defaultFileSize);
Reader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in, encoding), defaultFileSize);
char[] readBuffer = new char[2048];
int charCount = reader.read(readBuffer);
while (charCount > 0) {
buffer.append(readBuffer, 0, charCount);
charCount = reader.read(readBuffer);
}
} catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, "JavaPlugin.getPluginId()", e.getMessage(), e));
} finally {
try {
if (reader != null) {
//this will also close the InputStream wrapped in the reader
reader.close();
}
} catch (IOException e) {
//ignore
}
}
return buffer.toString();
}
use of org.eclipse.core.runtime.CoreException in project che by eclipse.
the class CreateFileChange method initializeEncoding.
private void initializeEncoding() {
if (fEncoding == null) {
fExplicitEncoding = false;
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);
if (file != null) {
try {
if (file.exists()) {
fEncoding = file.getCharset(false);
if (fEncoding == null) {
fEncoding = file.getCharset(true);
} else {
fExplicitEncoding = true;
}
} else {
IContentType contentType = Platform.getContentTypeManager().findContentTypeFor(file.getName());
if (contentType != null)
fEncoding = contentType.getDefaultCharset();
if (fEncoding == null)
fEncoding = file.getCharset(true);
}
} catch (CoreException e) {
fEncoding = ResourcesPlugin.getEncoding();
fExplicitEncoding = true;
}
} else {
fEncoding = ResourcesPlugin.getEncoding();
fExplicitEncoding = true;
}
}
Assert.isNotNull(fEncoding);
}
use of org.eclipse.core.runtime.CoreException in project che by eclipse.
the class QuickAssistProcessor method getAddBlockProposals.
private static boolean getAddBlockProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
if (!(node instanceof Statement)) {
return false;
}
/*
* only show the quick assist when the selection is of the control statement keywords (if, else, while,...)
* but not inside the statement or the if expression.
*/
if (!isControlStatementWithBlock(node) && isControlStatementWithBlock(node.getParent())) {
int statementStart = node.getStartPosition();
int statementEnd = statementStart + node.getLength();
int offset = context.getSelectionOffset();
int length = context.getSelectionLength();
if (length == 0) {
if (offset != statementEnd) {
// cursor at end
return false;
}
} else {
if (offset > statementStart || offset + length < statementEnd) {
// statement selected
return false;
}
}
node = node.getParent();
}
StructuralPropertyDescriptor childProperty = null;
ASTNode child = null;
switch(node.getNodeType()) {
case ASTNode.IF_STATEMENT:
ASTNode then = ((IfStatement) node).getThenStatement();
ASTNode elseStatement = ((IfStatement) node).getElseStatement();
if ((then instanceof Block) && (elseStatement instanceof Block || elseStatement == null)) {
break;
}
int thenEnd = then.getStartPosition() + then.getLength();
int selectionEnd = context.getSelectionOffset() + context.getSelectionLength();
if (!(then instanceof Block)) {
if (selectionEnd <= thenEnd) {
childProperty = IfStatement.THEN_STATEMENT_PROPERTY;
child = then;
break;
} else if (elseStatement != null && selectionEnd < elseStatement.getStartPosition()) {
// find out if we are before or after the 'else' keyword
try {
TokenScanner scanner = new TokenScanner(context.getCompilationUnit());
int elseTokenStart = scanner.getNextStartOffset(thenEnd, true);
if (selectionEnd < elseTokenStart) {
childProperty = IfStatement.THEN_STATEMENT_PROPERTY;
child = then;
break;
}
} catch (CoreException e) {
// ignore
}
}
}
if (elseStatement != null && !(elseStatement instanceof Block) && context.getSelectionOffset() >= thenEnd) {
childProperty = IfStatement.ELSE_STATEMENT_PROPERTY;
child = elseStatement;
}
break;
case ASTNode.WHILE_STATEMENT:
ASTNode whileBody = ((WhileStatement) node).getBody();
if (!(whileBody instanceof Block)) {
childProperty = WhileStatement.BODY_PROPERTY;
child = whileBody;
}
break;
case ASTNode.FOR_STATEMENT:
ASTNode forBody = ((ForStatement) node).getBody();
if (!(forBody instanceof Block)) {
childProperty = ForStatement.BODY_PROPERTY;
child = forBody;
}
break;
case ASTNode.ENHANCED_FOR_STATEMENT:
ASTNode enhancedForBody = ((EnhancedForStatement) node).getBody();
if (!(enhancedForBody instanceof Block)) {
childProperty = EnhancedForStatement.BODY_PROPERTY;
child = enhancedForBody;
}
break;
case ASTNode.DO_STATEMENT:
ASTNode doBody = ((DoStatement) node).getBody();
if (!(doBody instanceof Block)) {
childProperty = DoStatement.BODY_PROPERTY;
child = doBody;
}
break;
default:
}
if (child == null) {
return false;
}
if (resultingCollections == null) {
return true;
}
AST ast = node.getAST();
{
ASTRewrite rewrite = ASTRewrite.create(ast);
ASTNode childPlaceholder = rewrite.createMoveTarget(child);
Block replacingBody = ast.newBlock();
replacingBody.statements().add(childPlaceholder);
rewrite.set(node, childProperty, replacingBody, null);
String label;
if (childProperty == IfStatement.THEN_STATEMENT_PROPERTY) {
label = CorrectionMessages.QuickAssistProcessor_replacethenwithblock_description;
} else if (childProperty == IfStatement.ELSE_STATEMENT_PROPERTY) {
label = CorrectionMessages.QuickAssistProcessor_replaceelsewithblock_description;
} else {
label = CorrectionMessages.QuickAssistProcessor_replacebodywithblock_description;
}
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_BLOCK, image);
proposal.setCommandId(ADD_BLOCK_ID);
proposal.setEndPosition(rewrite.track(child));
resultingCollections.add(proposal);
}
if (node.getNodeType() == ASTNode.IF_STATEMENT) {
ASTRewrite rewrite = ASTRewrite.create(ast);
while (node.getLocationInParent() == IfStatement.ELSE_STATEMENT_PROPERTY) {
node = node.getParent();
}
boolean missingBlockFound = false;
boolean foundElse = false;
IfStatement ifStatement;
Statement thenStatment;
Statement elseStatment;
do {
ifStatement = (IfStatement) node;
thenStatment = ifStatement.getThenStatement();
elseStatment = ifStatement.getElseStatement();
if (!(thenStatment instanceof Block)) {
ASTNode childPlaceholder1 = rewrite.createMoveTarget(thenStatment);
Block replacingBody1 = ast.newBlock();
replacingBody1.statements().add(childPlaceholder1);
rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, replacingBody1, null);
if (thenStatment != child) {
missingBlockFound = true;
}
}
if (elseStatment != null) {
foundElse = true;
}
node = elseStatment;
} while (elseStatment instanceof IfStatement);
if (elseStatment != null && !(elseStatment instanceof Block)) {
ASTNode childPlaceholder2 = rewrite.createMoveTarget(elseStatment);
Block replacingBody2 = ast.newBlock();
replacingBody2.statements().add(childPlaceholder2);
rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, replacingBody2, null);
if (elseStatment != child) {
missingBlockFound = true;
}
}
if (missingBlockFound && foundElse) {
String label = CorrectionMessages.QuickAssistProcessor_replacethenelsewithblock_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CHANGE_IF_ELSE_TO_BLOCK, image);
resultingCollections.add(proposal);
}
}
return true;
}
Aggregations