@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<>(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); }
@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); }
@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 = true; // 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; }
@Override public String getAdditionalProposalInfo() { this.getContext().setReadOnly(true); TemplateBuffer templateBuffer; try { templateBuffer= this.getContext().evaluate(this.getTemplate()); } catch (BadLocationException | TemplateException ex) { String message = "<b>Error when resolving variables.</b><br>" + "Nothing will be inserted<br><br>" + escapeHTML(ex.getMessage()); return message; } String info = escapeHTML(this.getTemplate().getDescription()) + "<br><br><b>Inserts:</b><br>" + escapeHTML(templateBuffer.getString()); return info; }
final void parse(List<String> params) throws TemplateException { for (String expression : params) { try { if (expression.trim().isEmpty()) { throw new TemplateException("Empty expression"); } new ComplexExpression(expression.trim()); } catch (RuntimeException ex) { throw new TemplateException("Invalid expression: " + expression + "; " + ex.getMessage(), ex); } } // if (messages.size() > 0) { // StringBuilder result = new StringBuilder(); // for (String message : messages) { // result.append(message).append("\n"); // } // throw new TemplateException(result.toString()); // } }
ValueOrVariableExpression(String expression) throws TemplateException { String check = expression; if (expression.startsWith("-")) { check = check.substring(1).trim(); this.sign = '-'; } else { this.sign = '+'; } if (check.isEmpty()) { throw new TemplateException("Invalid variable: " + expression); } this.isVariable = Character.isLetter(check.charAt(0)); for (int i = 0; i < check.length(); i++) { if (!Character.isLetterOrDigit(check.charAt(i)) || (!this.isVariable && !Character.isDigit(check.charAt(i)))) { throw new TemplateException("Invalid value or variable: " + expression); } } if (this.isVariable) { this.value = check; } else { this.value = expression; } }
private Operator parseOperator(String partExp) throws TemplateException { char operator = partExp.charAt(0); switch (operator) { case '*' : return Operator.MULTPLY; case '/' : return Operator.DIVIDE; case '%' : return Operator.MODULO; case '+' : return Operator.ADD; case '-' : return Operator.SUBTRACT; default : throw new TemplateException("Illegal operator: " + partExp); } }
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; }
/** * Returns template string to insert. * * @param context the context to use when rendering the template * @return String to insert or null if none is to be inserted */ public final String getTemplateString(final TemplateContext context) { String templateString = null; if (useTemplateButton.getSelection()) { Template template = getSelectedTemplate(); if (template != null) { try { TemplateBuffer buffer = context.evaluate(template); templateString = buffer.getString(); } catch (BadLocationException | TemplateException e) { final String msg = "Unable to create template for new component"; final IStatus status = new Status(IStatus.WARNING, ForceIdeEditorsPlugin.PLUGIN_ID, msg, e); logger().log(status); } } } return templateString; }
/** * Validates a template against the context type registered in the context * type registry. Returns always <code>true</code> if no registry is * present. * * @param template the template to validate * @return <code>true</code> if validation is successful or no context * type registry is specified, <code>false</code> if validation * fails */ private boolean validateTemplate(Template template) { String contextTypeId= template.getContextTypeId(); if (!contextExists(contextTypeId)) return false; if (getRegistry() != null) { try { getRegistry().getContextType(contextTypeId).validate(template.getPattern()); } catch (TemplateException e) { EditorsPlugin.log(NLSUtility.format("Ignoring template \"{0}\" since validation failed.", template.getName()), e); return false; } } return true; }
@Override public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { ITextSelection selection = (ITextSelection) viewer .getSelectionProvider().getSelection(); // adjust offset to end of normalized selection if (selection.getOffset() == offset) { offset = selection.getOffset() + selection.getLength(); } String prefix = extractPrefix(viewer, offset); Region region = new Region(offset - prefix.length(), prefix.length()); TemplateContext context = createContext(viewer, region); if (context == null) { return new ICompletionProposal[0]; } context.setVariable("selection", selection.getText()); // name of the selection variables {line, word_selection //$NON-NLS-1$ Template[] templates = getTemplates(context.getContextType().getId()); List<ICompletionProposal> matches = new ArrayList<>(); for (Template template : templates) { try { context.getContextType().validate(template.getPattern()); } catch (TemplateException e) { continue; } if (!prefix.equals("") && prefix.charAt(0) == '<') { //$NON-NLS-1$ prefix = prefix.substring(1); } if (!prefix.equals("") //$NON-NLS-1$ && (template.getName().startsWith(prefix) && template .matches(prefix, context.getContextType().getId()))) { matches.add(createProposal(template, context, (IRegion) region, getRelevance(template, prefix))); } } return matches.toArray(new ICompletionProposal[matches.size()]); }
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { ITextSelection selection= (ITextSelection) viewer.getSelectionProvider().getSelection(); // adjust offset to end of normalized selection if (selection.getOffset() == offset) offset= selection.getOffset() + selection.getLength(); String prefix= extractPrefix(viewer, offset); Region region= new Region(offset - prefix.length(), prefix.length()); TemplateContext context= createContext(viewer, region); if (context == null) return new ICompletionProposal[0]; context.setVariable("selection", selection.getText()); // name of the selection variables {line, word}_selection //$NON-NLS-1$ Template[] templates= getTemplates(context.getContextType().getId()); List matches= new ArrayList(); for (int i= 0; i < templates.length; i++) { Template template= templates[i]; try { context.getContextType().validate(template.getPattern()); } catch (TemplateException e) { continue; } if (template.matches(prefix, context.getContextType().getId())) matches.add(createProposal(template, context, (IRegion) region, getRelevance(template, prefix))); } Collections.sort(matches, fgProposalComparator); return (ICompletionProposal[]) matches.toArray(new ICompletionProposal[matches.size()]); }
@Override public void validate(String pattern) throws TemplateException { super.validate(pattern); if (fIsComment) { if (!isValidComment(pattern)) { throw new TemplateException(JavaTemplateMessages.CodeTemplateContextType_validate_invalidcomment); } } }
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(); }
private 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); updateButtons(); }
@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; }
protected boolean validate(Template template, TemplateContext context) { try { context.getContextType().validate(template.getPattern()); } catch(TemplateException e) { return false; } return true; }
/** * Validates a template against the context type registered in the context type registry. Returns * always <code>true</code> if no registry is present. * * @param template the template to validate * @return <code>true</code> if validation is successful or no context type registry is specified, * <code>false</code> if validation fails */ private boolean validateTemplate(Template template) { String contextTypeId = template.getContextTypeId(); if (contextExists(contextTypeId)) { if (fRegistry != null) try { fRegistry.getContextType(contextTypeId).validate(template.getPattern()); } catch (TemplateException e) { return false; } return true; } return false; }
@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); } } }
/** * 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, JavaPlugin.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(); }
/** * Validates a template against the context type registered in the context type registry. Returns * always <code>true</code> if no registry is present. * * @param template the template to validate * @return <code>true</code> if validation is successful or no context type registry is specified, * <code>false</code> if validation fails */ private boolean validateTemplate(Template template) { String contextTypeId = template.getContextTypeId(); if (!contextExists(contextTypeId)) return false; if (getRegistry() != null) { try { getRegistry().getContextType(contextTypeId).validate(template.getPattern()); } catch (TemplateException e) { JavaPlugin.log(e); return false; } } return true; }
@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 void supportsParameters(List<String> parameters) throws TemplateException { if (parameters.size() != 1) { throw new TemplateException(this.getType() + " requires exactly 1 parameter"); } this.parse(parameters); }
@Override protected void validateVariables(TemplateVariable[] variables) throws TemplateException { for (TemplateVariable variable : variables) { TemplateVariableResolver resolver = this.getResolver(variable.getType()); if (resolver != null && (resolver instanceof ExpressionEvaluator)) { @SuppressWarnings("unchecked") List<String> params = (variable.getVariableType().getParams()); ((ExpressionEvaluator) resolver).supportsParameters(params); } } }
@Override public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException { try { return super.evaluate(template); } catch (VariableEvaluationException ex) { throw new TemplateException(ex.getMessage(), ex); } }