下面列出了怎么用org.eclipse.jface.text.templates.TemplateException的API类实例代码及写法,或者点击链接到github查看源代码。
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException
{
if (!canEvaluate(template))
return null;
try
{
this.template = template;
TemplateTranslator translator = new SnippetTemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
finally
{
this.template = null;
}
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
// test that all variables are defined
Iterator<TemplateVariableResolver> iterator= getContextType().resolvers();
while (iterator.hasNext()) {
TemplateVariableResolver var= iterator.next();
if (var instanceof CodeTemplateContextType.CodeTemplateVariableResolver) {
Assert.isNotNull(getVariable(var.getType()), "Variable " + var.getType() + "not defined"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
if (!canEvaluate(template))
return null;
String pattern= changeLineDelimiter(template.getPattern(), fLineDelimiter);
TemplateTranslator translator= new TemplateTranslator();
TemplateBuffer buffer= translator.translate(pattern);
getContextType().resolve(buffer, this);
return buffer;
}
@Override
protected void validateVariables(TemplateVariable[] variables) throws TemplateException {
ArrayList<String> required= new ArrayList<String>(5);
String contextName= getId();
if (NEWTYPE_CONTEXTTYPE.equals(contextName)) {
required.add(PACKAGE_DECLARATION);
required.add(TYPE_DECLARATION);
}
for (int i= 0; i < variables.length; i++) {
String type= variables[i].getType();
if (getResolver(type) == null) {
String unknown= BasicElementLabels.getJavaElementName(type);
throw new TemplateException(Messages.format(JavaTemplateMessages.CodeTemplateContextType_validate_unknownvariable, unknown));
}
required.remove(type);
}
if (!required.isEmpty()) {
String missing= BasicElementLabels.getJavaElementName(required.get(0));
throw new TemplateException(Messages.format(JavaTemplateMessages.CodeTemplateContextType_validate_missingvariable, missing));
}
super.validateVariables(variables);
}
/**
* Evaluates a 'java' template in the context of a compilation unit
*
* @param template the template to be evaluated
* @param compilationUnit the compilation unit in which to evaluate the template
* @param position the position inside the compilation unit for which to evaluate the template
* @return the evaluated template
* @throws CoreException in case the template is of an unknown context type
* @throws BadLocationException in case the position is invalid in the compilation unit
* @throws TemplateException in case the evaluation fails
*/
public static String evaluateTemplate(Template template, ICompilationUnit compilationUnit, int position) throws CoreException, BadLocationException, TemplateException {
TemplateContextType contextType= JavaPlugin.getDefault().getTemplateContextRegistry().getContextType(template.getContextTypeId());
if (!(contextType instanceof CompilationUnitContextType))
throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, JavaTemplateMessages.JavaContext_error_message, null));
IDocument document= new Document();
if (compilationUnit != null && compilationUnit.exists())
document.set(compilationUnit.getSource());
CompilationUnitContext context= ((CompilationUnitContextType) contextType).createContext(document, position, 0, compilationUnit);
context.setForceEvaluation(true);
TemplateBuffer buffer= context.evaluate(template);
if (buffer == null)
return null;
return buffer.getString();
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
TemplateTranslator translator= new TemplateTranslator();
TemplateBuffer buffer= translator.translate(template);
getContextType().resolve(buffer, this);
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
boolean useCodeFormatter= prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER);
IJavaProject project= getJavaProject();
JavaFormatter formatter= new JavaFormatter(TextUtilities.getDefaultLineDelimiter(getDocument()), getIndentation(), useCodeFormatter, project);
formatter.format(buffer, this);
return buffer;
}
@Check
public void checkParameterSyntax(Variable variable) {
//worst case check
TemplateTranslator templateTranslator = new TemplateTranslator();
String text = NodeModelUtils.getNode(variable).getText();
try {
templateTranslator.translate(text);
} catch (TemplateException e) {
error(templateTranslator.getErrorMessage(), variable, TemplatesPackage.Literals.VARIABLE__NAME);
}
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
if (!canEvaluate(template))
return null;
TemplateTranslator translator = createTemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
/**
* @since 2.3
*/
public TemplateBuffer evaluateForDisplay(Template template) throws BadLocationException, TemplateException {
if (!canEvaluate(template))
return null;
TemplateTranslator translator = new TemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
TemplateTranslator translator= new TemplateTranslator();
TemplateBuffer buffer= translator.translate(template);
templateBody = buffer.getString(); // required to process multiline 'line_selection'
getContextType().resolve(buffer, this);
getIndentation();
///* Indents the variables */
//TemplateVariable[] variables = indentVariableOffsets(buffer, indentation.length());
TemplateVariable[] variables = buffer.getVariables();
/* Indents the template */
String formattedTemplate = doIndent(buffer.getString(), variables, indents);
if (cutTemplateCRLF) {
if (formattedTemplate.endsWith("\r\n")) {
formattedTemplate = formattedTemplate.substring(0, formattedTemplate.length()-2);
} else if (formattedTemplate.endsWith("\n")) {
formattedTemplate = formattedTemplate.substring(0, formattedTemplate.length()-1);
}
}
buffer.setContent(formattedTemplate, variables);
return buffer;
}
private void testResolveValues(final Object... values) throws TemplateException {
// ARRANGE
final TemplateVariable variable = helper.createTemplateVariable(resolver, "name", values); //$NON-NLS-1$
// ACT
final List<String> resolvedValues = resolver.resolveValues(variable, mockContext);
// ASSERT
assertArrayEquals("Resolved values", values, resolvedValues.toArray(new String[resolvedValues.size()])); //$NON-NLS-1$
}
/**
* Test resolveValues().
*
* @param values
* values to resolve
* @param filename
* filename to return from the mock {@link IFile}
* @param expectedResolvedValues
* expected return value
*/
public void testResolveValues(final Object[] values, final String filename, final String... expectedResolvedValues) throws TemplateException {
// ARRANGE
final TemplateVariable variable = helper.createTemplateVariable(resolver, "name", values); //$NON-NLS-1$
Mockito.when(mockFile.getName()).thenReturn(filename);
// ACT
final String[] actualResolvedValues = Iterables.toArray(resolver.resolveValues(variable, mockContext), String.class);
// ASSERT
Assert.assertArrayEquals("Resolved values", expectedResolvedValues, actualResolvedValues); //$NON-NLS-1$
}
protected void doSourceChanged(IDocument document) {
String text = document.get();
fValidationStatus.setOK();
TemplateContextType contextType = fContextTypeRegistry.getContextType(getContextId());
if (contextType != null) {
try {
contextType.validate(text);
} catch (TemplateException e) {
fValidationStatus.setError(e.getLocalizedMessage());
}
}
updateUndoAction();
updateStatusAndButtons();
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
if (!canEvaluate(template))
return null;
TemplateTranslator translator = createTemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
/**
* @since 2.3
*/
public TemplateBuffer evaluateForDisplay(Template template) throws BadLocationException, TemplateException {
if (!canEvaluate(template))
return null;
TemplateTranslator translator = new TemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
@Override
protected void validateVariables(TemplateVariable[] variables) throws TemplateException {
// check for multiple cursor variables
for (int i= 0; i < variables.length; i++) {
TemplateVariable var= variables[i];
if (var.getType().equals(GlobalTemplateVariables.Cursor.NAME)) {
if (var.getOffsets().length > 1) {
throw new TemplateException(JavaTemplateMessages.ContextType_error_multiple_cursor_variables);
}
}
}
}
@Override
public void validate(String pattern) throws TemplateException {
super.validate(pattern);
if (fIsComment) {
if (!isValidComment(pattern)) {
throw new TemplateException(JavaTemplateMessages.CodeTemplateContextType_validate_invalidcomment);
}
}
}
@Override
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
clear();
if (!canEvaluate(template))
throw new TemplateException(JavaTemplateMessages.Context_error_cannot_evaluate);
TemplateTranslator translator= new TemplateTranslator() {
@Override
protected TemplateVariable createVariable(TemplateVariableType type, String name, int[] offsets) {
// TemplateVariableResolver resolver= getContextType().getResolver(type.getName());
// return resolver.createVariable();
MultiVariable variable= new JavaVariable(type, name, offsets);
fVariables.put(name, variable);
return variable;
}
};
TemplateBuffer buffer= translator.translate(template);
getContextType().resolve(buffer, this);
rewriteImports();
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
boolean useCodeFormatter= prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER);
IJavaProject project= getJavaProject();
JavaFormatter formatter= new JavaFormatter(TextUtilities.getDefaultLineDelimiter(getDocument()), getIndentation(), useCodeFormatter, project);
formatter.format(buffer, this);
clear();
return buffer;
}
protected String validateTemplate(Template template) {
TemplateContextType type= fRegistry.getContextType(template.getContextTypeId());
if (type == null) {
return "Unknown context type: " + template.getContextTypeId(); //$NON-NLS-1$
}
try {
type.validate(template.getPattern());
return null;
} catch (TemplateException e) {
return e.getMessage();
}
}
protected void doSourceChanged(IDocument document) {
String text= document.get();
fValidationStatus.setOK();
TemplateContextType contextType= fContextTypeRegistry.getContextType(getContextId());
if (contextType != null) {
try {
contextType.validate(text);
} catch (TemplateException e) {
fValidationStatus.setError(e.getLocalizedMessage());
}
}
updateAction(ITextEditorActionConstants.UNDO);
updateStatusAndButtons();
}
@Override
public TemplateBuffer evaluate(Template template)
throws BadLocationException, TemplateException {
TemplateBuffer result = super.evaluate(template);
// After the template buffer has been created we are able to add out of range offsets
// This is not possible beforehand as it will result in an exception!
for (TemplateVariable tv : result.getVariables()) {
int[] outOfRangeOffsets = this.getVariableOutOfRangeOffsets(tv);
if (outOfRangeOffsets != null && outOfRangeOffsets.length > 0) {
int[] offsets = tv.getOffsets();
int[] newOffsets = new int[outOfRangeOffsets.length + offsets.length];
System.arraycopy(offsets, 0, newOffsets, 0, offsets.length);
for (int i = 0; i < outOfRangeOffsets.length; i++) {
newOffsets[i + offsets.length] = outOfRangeOffsets[i]; // - getAffectedSourceRegion().getOffset();
}
tv.setOffsets(newOffsets);
}
}
return result;
}
public TemplateBuffer evaluate(Template template, boolean fixIndentation)
throws BadLocationException, TemplateException {
if (!canEvaluate(template))
return null;
TemplateTranslator translator= new TemplateTranslator();
String pattern = template.getPattern();
// if(fixIndentation) {
// pattern = fixIndentation(pattern);
// }
TemplateBuffer buffer = translator.translate(pattern);
getContextType().resolve(buffer, this);
if(fixIndentation) {
String delimiter = TextUtilities.getDefaultLineDelimiter(getDocument());
JavaFormatter formatter = new JavaFormatter(delimiter) {
@Override
protected void indent(IDocument document) throws BadLocationException, MalformedTreeException {
simpleIndent(document);
}
};
formatter.format(buffer, this);
}
return buffer;
}
@Override
public String getAdditionalProposalInfo() {
if (getContext() instanceof LangContext) {
LangContext context = (LangContext) getContext();
try {
return context.evaluate(getTemplate(), false).getString();
} catch (BadLocationException | TemplateException e) {
LangCore.logError("Error evaluating template", e);
}
}
return getTemplate().getPattern();
}
@Override
protected void validateVariables(TemplateVariable[] variables) throws TemplateException {
// check for multiple cursor variables
for(int i = 0; i < variables.length; i++) {
TemplateVariable var = variables[i];
if(var.getType().equals(GlobalTemplateVariables.Cursor.NAME)) {
if(var.getOffsets().length > 1) {
throw new TemplateException(JavaTemplateMessages.ContextType_error_multiple_cursor_variables);
}
}
}
}
protected Status createErrorStatus(String message, TemplateException e) {
return new Status(IStatus.ERROR,
CodetemplatesActivator.getInstance().getBundle().getSymbolicName(),
message, e);
}
@Override
public TemplateBuffer translate(Template template) throws TemplateException {
return translate(template.getPattern());
}
@Override
public TemplateBuffer translate(String string) throws TemplateException {
return super.translate(string.replaceAll("(\r\n?)|(\n)", lineDelimiter + indentation));
}
@Override
public TemplateBuffer evaluateForDisplay(Template template) throws BadLocationException, TemplateException {
// Ensure clean state before evaluation starts
imports.clear();
return super.evaluateForDisplay(template);
}
private static List<CompletionItem> getGenericSnippets(SnippetCompletionContext scc) throws JavaModelException {
List<CompletionItem> res = new ArrayList<>();
CompletionContext completionContext = scc.getCompletionContext();
char[] completionToken = completionContext.getToken();
if (completionToken == null) {
return Collections.emptyList();
}
int tokenLocation = completionContext.getTokenLocation();
JavaContextType contextType = (JavaContextType) JavaLanguageServerPlugin.getInstance().getTemplateContextRegistry().getContextType(JavaContextType.ID_STATEMENTS);
if (contextType == null) {
return Collections.emptyList();
}
ICompilationUnit cu = scc.getCompilationUnit();
IDocument document = new Document(cu.getSource());
DocumentTemplateContext javaContext = contextType.createContext(document, completionContext.getOffset(), completionToken.length, cu);
Template[] templates = null;
if ((tokenLocation & CompletionContext.TL_STATEMENT_START) != 0) {
templates = JavaLanguageServerPlugin.getInstance().getTemplateStore().getTemplates(JavaContextType.ID_STATEMENTS);
} else {
// We only support statement templates for now.
}
if (templates == null || templates.length == 0) {
return Collections.emptyList();
}
for (Template template : templates) {
if (!javaContext.canEvaluate(template)) {
continue;
}
TemplateBuffer buffer = null;
try {
buffer = javaContext.evaluate(template);
} catch (BadLocationException | TemplateException e) {
JavaLanguageServerPlugin.logException(e.getMessage(), e);
continue;
}
if (buffer == null) {
continue;
}
String content = buffer.getString();
if (Strings.containsOnlyWhitespaces(content)) {
continue;
}
final CompletionItem item = new CompletionItem();
item.setLabel(template.getName());
item.setInsertText(content);
item.setDetail(template.getDescription());
setFields(item, cu);
res.add(item);
}
return res;
}
@Test
public void testResolveValuesWithOneParam() throws TemplateException {
testResolveValues("Value"); //$NON-NLS-1$
}
@Test
public void testResolveValuesWithMultipleParams() throws TemplateException {
testResolveValues("Value 1", "Value 2", "Value 3"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
}