下面列出了org.eclipse.core.runtime.CoreException#getMessage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public ImportRewrite getImportRewrite() {
if (fImportRewrite == null) {
// lazily initialized to avoid lengthy processing in checkInitialConditions(..)
try {
/* If bindings are to be resolved, then create the AST, so that
* ImportRewrite#setUseContextToFilterImplicitImports(boolean) will be set to true
* and ContextSensitiveImportRewriteContext etc. can be used. */
if (fRoot == null && ! fResolveBindings) {
fImportRewrite= StubUtility.createImportRewrite(fCu, true);
} else {
fImportRewrite= StubUtility.createImportRewrite(getRoot(), true);
}
} catch (CoreException e) {
JavaPlugin.log(e);
throw new IllegalStateException(e.getMessage()); // like ASTParser#createAST(..) does
}
}
return fImportRewrite;
}
@Test
public void testCreateUserWithNoUserName() {
// create the MetaStore
IMetaStore metaStore = OrionConfiguration.getMetaStore();
// create the user and do not provide a userId
UserInfo userInfo = new UserInfo();
userInfo.setFullName(testUserLogin);
try {
metaStore.createUser(userInfo);
} catch (CoreException e) {
// we expect to get a core exception here
String message = e.getMessage();
assertTrue(message.contains("could not create user"));
}
}
@Test
public void testCreateWorkspaceWithNoUserId() throws CoreException {
// create the MetaStore
IMetaStore metaStore = OrionConfiguration.getMetaStore();
// create the user
UserInfo userInfo = new UserInfo();
userInfo.setUserName(testUserLogin);
userInfo.setFullName(testUserLogin);
metaStore.createUser(userInfo);
// create the workspace without specifying a userid.
String workspaceName = SimpleMetaStore.DEFAULT_WORKSPACE_NAME;
WorkspaceInfo workspaceInfo = new WorkspaceInfo();
workspaceInfo.setFullName(workspaceName);
try {
metaStore.createWorkspace(workspaceInfo);
} catch (CoreException e) {
// we expect to get a core exception here
String message = e.getMessage();
assertTrue(message.contains("user id is null"));
}
}
/**
*
* @param name
* @return
* @throws ElexisException
* if the script interpreter can not successfully be loaded or is not available.
*/
private static Interpreter getInterpreter(String name) throws ElexisException{
if (name == null)
name = INTERPRETER_BEANSHELL;
List<IConfigurationElement> scripters =
Extensions.getExtensions(ExtensionPointConstantsData.SCRIPTING);
for (IConfigurationElement scripter : scripters) {
if (scripter.getAttribute("name").equals(name)) {
try {
return (Interpreter) scripter.createExecutableExtension("class");
} catch (CoreException e) {
ExHandler.handle(e);
throw new ElexisException(Script.class, "Could not load intepreter "
+ e.getMessage(), ElexisException.EE_NOT_SUPPORTED);
}
}
}
throw new ElexisException(Script.class, name + " interpreter plug-in not available",
ElexisException.EE_NOT_SUPPORTED);
}
/**
* Write the content to files
* @param tlaFile
* @param cfgFile
* @param monitor
* @throws CoreException
*/
public void writeFiles(final IFile tlaFile, final IFile cfgFile, final IProgressMonitor monitor) throws CoreException {
final ContentWriter cw = (inputStream, forTLAFile) -> {
final IFile file = forTLAFile ? tlaFile : cfgFile;
if (file.exists()) {
try {
file.setContents(inputStream, IResource.FORCE, monitor);
} catch (final CoreException ce) {
throw new IOException("Exception writing file " + ce.getMessage(), ce);
}
} else {
throw new IOException("Expected file " + file.getName() + " has been removed externally.");
}
};
try {
super.writeFiles(cw);
} catch (final IOException e) {
throw new CoreException(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.ERROR,
"Exception encountered attempting to write modules for the model checking.", e));
}
}
/**
* Reads a file from the project.
*
* @param file the file to be read.
* @return The contents of the file as a String.
* @throws IOException
*/
private String readFile(IFile file) throws IOException {
StringBuilder inputContent = new StringBuilder("");
try {
BufferedReader buf = new BufferedReader(
new InputStreamReader(file.getContents()));
final int length = 10000;
int read = length;
char[] fileData = new char[length];
while (read == length) {
read = buf.read(fileData, 0, length);
if (read > 0) {
inputContent.append(fileData, 0, read);
}
}
buf.close();
} catch (CoreException e) {
// This should be very rare...
throw new IOException(e.getMessage());
}
// TODO
//return this.rmTrailingWhitespace(inputContent);
return inputContent.toString();
}
public static SourceAttachmentResult resolveSourceAttachment(IPackageFragmentRoot root, IProgressMonitor monitor) {
ClasspathEntryWrapper entryWrapper = null;
try {
entryWrapper = getClasspathEntry(root);
} catch (CoreException e) {
return new SourceAttachmentResult(e.getMessage(), null);
}
IResource jarResource = null;
try {
jarResource = root.getUnderlyingResource();
} catch (JavaModelException e1) {
// do nothing.
}
String jarPath = jarResource != null ? jarResource.getLocation().toOSString() : entryWrapper.original.getPath().toOSString();
String sourceAttachmentPath = entryWrapper.original.getSourceAttachmentPath() != null ? entryWrapper.original.getSourceAttachmentPath().toOSString() : null;
String sourceAttachmentEncoding = getSourceAttachmentEncoding(entryWrapper.original);
return new SourceAttachmentResult(null, new SourceAttachmentAttribute(jarPath, sourceAttachmentPath, sourceAttachmentEncoding, entryWrapper.canEditEncoding));
}
@Override
public Iterable<? extends Path> getChildren(final URI uri, final Path path) {
final IResource resource = this.findMember(uri);
if ((resource instanceof IContainer)) {
try {
final Function1<IResource, Path> _function = (IResource it) -> {
String _string = it.getFullPath().toString();
return new Path(_string);
};
return ListExtensions.<IResource, Path>map(((List<IResource>)Conversions.doWrapArray(((IContainer)resource).members())), _function);
} catch (final Throwable _t) {
if (_t instanceof CoreException) {
final CoreException exc = (CoreException)_t;
String _message = exc.getMessage();
throw new IllegalArgumentException(_message, exc);
} else {
throw Exceptions.sneakyThrow(_t);
}
}
}
return CollectionLiterals.<Path>emptyList();
}
@Override
public void createFile(String projectName, String path, int size, boolean compressAble)
throws RemoteException {
log.trace(
"creating file in project '"
+ projectName
+ "', path '"
+ path
+ "' size: "
+ size
+ ", compressAble="
+ compressAble);
path = path.replace('\\', '/');
int idx = path.lastIndexOf('/');
if (idx != -1) createFolder(projectName, path.substring(0, idx));
IFile file = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).getFile(path);
try {
file.create(new GeneratingInputStream(size, compressAble), true, null);
} catch (CoreException e) {
log.error(e.getMessage(), e);
throw new RemoteException(e.getMessage(), e.getCause());
}
}
/**
* Tries to close the project with the given name.
*/
private void closeProject(String projectName) {
IN4JSEclipseProject n4jsProject = eclipseN4jsCore.findProject(URI.createPlatformResourceURI(projectName, true))
.orNull();
if (null == n4jsProject) {
throw new IllegalArgumentException("Could not find project with name '" + projectName + "'");
}
try {
n4jsProject.getProject().close(new NullProgressMonitor());
} catch (CoreException e) {
throw new IllegalArgumentException(
"Could not close project with name '" + projectName + "': " + e.getMessage());
}
}
static String getMessage(CoreException ce) {
String msg = ce.getMessage();
if(msg != null && !msg.trim().equals("")) { // NOI18N
return msg;
}
IStatus status = ce.getStatus();
msg = status != null ? status.getMessage() : null;
return msg != null ? msg.trim() : null;
}
public Object execute(ExecutionEvent event) throws ExecutionException {
IEditorPart editor = HandlerUtil.getActiveEditor(event);
if (editor == null) {
return false;
}
IEditorInput input = editor.getEditorInput();
IFile file = ResourceUtil.getFile(input);
shell = HandlerUtil.getActiveWorkbenchWindowChecked(event).getShell();
if (file == null) {
MessageDialog.openInformation(shell, "提示", "未找当前编辑器打开的文件资源。");
} else {
String fileExtension = file.getFileExtension();
if (fileExtension != null && "xlf".equalsIgnoreCase(fileExtension)) {
ConverterViewModel model = getConverterViewModel(file);
if (model != null) {
model.convert();
}
} else if (fileExtension != null && "xlp".equalsIgnoreCase(fileExtension)) {
if (file.exists()) {
IFolder xliffFolder = file.getProject().getFolder(Constant.FOLDER_XLIFF);
if (xliffFolder.exists()) {
ArrayList<IFile> files = new ArrayList<IFile>();
try {
getChildFiles(xliffFolder, "xlf", files);
} catch (CoreException e) {
throw new ExecutionException(e.getMessage(), e);
}
previewFiles(files);
} else {
MessageDialog.openWarning(shell, "提示", "未找到系统默认的 XLIFF 文件夹!");
}
}
} else {
MessageDialog.openInformation(shell, "提示", "当前编辑器打开的文件不是一个合法的 XLIFF 文件。");
}
}
return null;
}
/**
* Resolves class path for a java project.
* @param arguments a list contains the main class name and project name
* @return the class paths entries
* @throws Exception when there are any errors during resolving class path
*/
public String[][] resolveClasspaths(List<Object> arguments) throws Exception {
try {
return computeClassPath((String) arguments.get(0), (String) arguments.get(1));
} catch (CoreException e) {
logger.log(Level.SEVERE, "Failed to resolve classpath: " + e.getMessage(), e);
throw new Exception("Failed to resolve classpath: " + e.getMessage(), e);
}
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
ISelection selection = HandlerUtil.getCurrentSelection(event);
if (selection != null && selection instanceof IStructuredSelection) {
for (Object obj : ((IStructuredSelection) selection).toList()) {
if (obj instanceof IAdaptable) {
IProject project = (IProject) ((IAdaptable) obj).getAdapter(IProject.class);
if (project != null) {
try {
IProjectDescription description = project.getDescription();
ICommand[] commands = description.getBuildSpec();
for (int i = 0; i < commands.length; i++) {
if (TypeScriptBuilder.ID.equals(commands[i].getBuilderName())) {
// Remove the builder
ICommand[] newCommands = new ICommand[commands.length - 1];
System.arraycopy(commands, 0, newCommands, 0, i);
System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1);
description.setBuildSpec(newCommands);
project.setDescription(description, null);
}
}
} catch (CoreException e) {
throw new ExecutionException(e.getMessage(), e);
}
}
}
}
}
return null;
}
/**
* 得到 ConverterViewModel 对象
* @param file
* 需要预览翻译的文件
* @return
* @throws ExecutionException
* ;
*/
private ConverterViewModel getConverterViewModel(IFile file) throws ExecutionException {
Object adapter = Platform.getAdapterManager().getAdapter(file, IConversionItem.class);
if (adapter instanceof IConversionItem) {
IConversionItem item = (IConversionItem) adapter;
ConverterViewModel converterViewModel = new ConverterViewModel(Activator.getContext(),
Converter.DIRECTION_REVERSE); // 逆向转换
converterViewModel.setConversionItem(item);
try {
ConversionResource resource = new ConversionResource(Converter.DIRECTION_REVERSE, item);
String xliffpath = resource.getXliffPath();
String targetPath = resource.getPreviewPath();
ConversionConfigBean configBean = converterViewModel.getConfigBean();
configBean.setSource(xliffpath);
configBean.setTarget(targetPath);
configBean.setTargetEncoding("UTF-8");
configBean.setPreviewMode(true); // 设为预览翻译模式
IStatus status = converterViewModel.validateXliffFile(ConverterUtil.toLocalPath(xliffpath),
new XLFHandler(), null); // 注:验证的过程中,会为文件类型和骨架文件的路径赋值。
if (status != null && status.isOK()) {
return converterViewModel;
} else {
throw new ExecutionException(status.getMessage(), status.getException());
}
} catch (CoreException e) {
throw new ExecutionException(e.getMessage(), e);
}
}
return null;
}
@Override
public void changeProjectEncoding(String projectName, String charset) throws RemoteException {
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
try {
project.setDefaultCharset(charset, null);
} catch (CoreException e) {
log.error(e.getMessage(), e);
throw new RemoteException(e.getMessage(), e.getCause());
}
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
ISelection selection = HandlerUtil.getCurrentSelection(event);
if (selection != null && selection instanceof IStructuredSelection) {
for (Object obj : ((IStructuredSelection) selection).toList()) {
if (obj instanceof IAdaptable) {
IProject project = (IProject) ((IAdaptable) obj).getAdapter(IProject.class);
if (project != null) {
try {
if (TypeScriptResourceUtil.hasTypeScriptBuilder(project)) {
return null;
}
IProjectDescription description = project.getDescription();
ICommand[] commands = description.getBuildSpec();
ICommand[] newCommands = new ICommand[commands.length + 1];
System.arraycopy(commands, 0, newCommands, 0, commands.length);
ICommand command = description.newCommand();
command.setBuilderName(TypeScriptBuilder.ID);
newCommands[newCommands.length - 1] = command;
description.setBuildSpec(newCommands);
project.setDescription(description, null);
} catch (CoreException e) {
throw new ExecutionException(e.getMessage(), e);
}
}
}
}
}
return null;
}
/**
* 得到 ConverterViewModel 对象
* @param file
* 需要预览翻译的文件
* @return
* @throws ExecutionException
* ;
*/
private ConverterViewModel getConverterViewModel(IFile file) throws ExecutionException {
Object adapter = Platform.getAdapterManager().getAdapter(file, IConversionItem.class);
if (adapter instanceof IConversionItem) {
IConversionItem item = (IConversionItem) adapter;
ConverterViewModel converterViewModel = new ConverterViewModel(Activator.getContext(),
Converter.DIRECTION_REVERSE); // 逆向转换
converterViewModel.setConversionItem(item);
try {
ConversionResource resource = new ConversionResource(Converter.DIRECTION_REVERSE, item);
String xliffpath = resource.getXliffPath();
String targetPath = resource.getPreviewPath();
ConversionConfigBean configBean = converterViewModel.getConfigBean();
configBean.setSource(xliffpath);
configBean.setTarget(targetPath);
configBean.setTargetEncoding("UTF-8");
configBean.setPreviewMode(true); // 设为预览翻译模式
IStatus status = converterViewModel.validateXliffFile(ConverterUtil.toLocalPath(xliffpath),
new XLFHandler(), null); // 注:验证的过程中,会为文件类型和骨架文件的路径赋值。
if (status != null && status.isOK()) {
return converterViewModel;
} else {
throw new ExecutionException(status.getMessage(), status.getException());
}
} catch (CoreException e) {
throw new ExecutionException(e.getMessage(), e);
}
}
return null;
}
public static CommonException createCommonException(CoreException ce) {
return new CommonException(ce.getMessage(), ce.getCause());
}
public static Result removeFromSourcePath(String sourceFolderUri) {
IPath sourceFolderPath = ResourceUtils.filePathFromURI(sourceFolderUri);
IProject targetProject = findBelongedProject(sourceFolderPath);
if (targetProject != null && !ProjectUtils.isGeneralJavaProject(targetProject)) {
String message = ProjectUtils.isGradleProject(targetProject) ? UNSUPPORTED_ON_GRADLE : UNSUPPORTED_ON_MAVEN;
return new Result(false, message);
}
IPath projectLocation = null;
IContainer projectRootResource = null;
if (targetProject == null) {
IPath workspaceRoot = ProjectUtils.findBelongedWorkspaceRoot(sourceFolderPath);
if (workspaceRoot == null) {
return new Result(false, Messages.format("The folder ''{0}'' doesn''t belong to any workspace.", getWorkspacePath(sourceFolderPath).toOSString()));
}
String invisibleProjectName = ProjectUtils.getWorkspaceInvisibleProjectName(workspaceRoot);
targetProject = ResourcesPlugin.getWorkspace().getRoot().getProject(invisibleProjectName);
if (!targetProject.exists()) {
return new Result(true, Messages.format("No need to remove it from source path, because the folder ''{0}'' isn''t on any project''s source path.", getWorkspacePath(sourceFolderPath).toOSString()));
}
projectLocation = workspaceRoot;
projectRootResource = targetProject.getFolder(ProjectUtils.WORKSPACE_LINK);
} else {
projectLocation = targetProject.getLocation();
projectRootResource = targetProject;
}
IPath relativeSourcePath = sourceFolderPath.makeRelativeTo(projectLocation);
IPath sourcePath = relativeSourcePath.isEmpty() ? projectRootResource.getFullPath() : projectRootResource.getFolder(relativeSourcePath).getFullPath();
IJavaProject javaProject = JavaCore.create(targetProject);
try {
if (ProjectUtils.removeSourcePath(sourcePath, javaProject)) {
return new Result(true, Messages.format("Successfully removed ''{0}'' from the project {1}''s source path.", new String[] { getWorkspacePath(sourceFolderPath).toOSString(), targetProject.getName() }));
} else {
return new Result(true, Messages.format("No need to remove it from source path, because the folder ''{0}'' isn''t on any project''s source path.", getWorkspacePath(sourceFolderPath).toOSString()));
}
} catch (CoreException e) {
return new Result(false, e.getMessage());
}
}