org.eclipse.jface.text.templates.TemplateVariable Java Examples

The following examples show how to use org.eclipse.jface.text.templates.TemplateVariable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EnumTemplateVariableResolver.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public List<String> resolveValues(TemplateVariable variable,
		XtextTemplateContext castedContext) {
	String enumerationName = variable.getVariableType()
			.getParams().iterator().next();
	Grammar grammar = getGrammar(castedContext);
	if (grammar == null)
		return Collections.emptyList();
	EEnum enumeration = (EEnum) getEClassifierForGrammar(enumerationName, grammar);
	if (enumeration == null) {
		return Collections.emptyList();
	}
	return Lists.transform(enumeration.getELiterals(), new Function<EEnumLiteral, String>() {
		@Override
		public String apply(EEnumLiteral enumLiteral) {
			return enumLiteral.getLiteral();
		}
	});
}
 
Example #2
Source File: StaticImportResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	variable.setUnambiguous(true);
	variable.setValue(""); //$NON-NLS-1$

	if (context instanceof JavaContext) {
		JavaContext jc= (JavaContext) context;
		List<String> params= variable.getVariableType().getParams();
		if (params.size() > 0) {
			for (Iterator<String> iterator= params.iterator(); iterator.hasNext();) {
				String qualifiedMemberName= iterator.next();
				jc.addStaticImport(qualifiedMemberName);
			}
		}
	} else {
		super.resolve(variable, context);
	}
}
 
Example #3
Source File: ImportsVariableResolver.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public List<String> resolveValues(TemplateVariable variable, XtextTemplateContext xtextTemplateContext) {
	variable.setUnambiguous(true);
	variable.setValue(""); //$NON-NLS-1$
	if (xtextTemplateContext instanceof XbaseTemplateContext) {
		XbaseTemplateContext xbaseCtx = (XbaseTemplateContext) xtextTemplateContext;
		List<?> params = variable.getVariableType().getParams();
		if (params.size() > 0) {
			for (Iterator<?> iterator = params.iterator(); iterator.hasNext();) {
				String typeName = (String) iterator.next();
				xbaseCtx.addImport(typeName);
			}
		}
	}
	return new ArrayList<String>();
}
 
Example #4
Source File: ImportsResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	variable.setUnambiguous(true);
	variable.setValue(""); //$NON-NLS-1$

	if (context instanceof JavaContext) {
		JavaContext jc= (JavaContext) context;
		List<String> params= variable.getVariableType().getParams();
		if (params.size() > 0) {
			for (Iterator<String> iterator= params.iterator(); iterator.hasNext();) {
				String typeName= iterator.next();
				jc.addImport(typeName);
			}
		}
	} else {
		super.resolve(variable, context);
	}
}
 
Example #5
Source File: InnerExpressionResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	if (context instanceof JavaStatementPostfixContext && variable instanceof JavaVariable) {
		JavaStatementPostfixContext c = (JavaStatementPostfixContext) context;
		JavaVariable jv = (JavaVariable) variable;
		List<String> params = variable.getVariableType().getParams();
		
		if (!params.contains(HIDE_FLAG)) {
			jv.setValue(resolve(context));
		} else {
			jv.setValues(new String[] { "", resolve(context) }); // We hide the value from the output
		}
		
		jv.setParamType(c.getInnerExpressionTypeSignature());
		jv.setResolved(true);
		jv.setUnambiguous(true);
		return;
	}
	super.resolve(variable, context);
}
 
Example #6
Source File: SourceCodeTemplateContext.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
/**
    * Shifts the variable offsets according to the current indentation level.
    * 
    * @param buffer                template buffer
    * @param currentIndentation    current indentation level
    * @return  the variable offsets according to the current indentation level
    */
   @SuppressWarnings("unused")
private static TemplateVariable[] indentVariableOffsets(TemplateBuffer buffer, int currentIndentation) {
       String content = buffer.getString();
       TemplateVariable[] variables = buffer.getVariables();
       List<Integer> lineBreaks     = getLinebreaksList(content);
       int line;
       for (int j = 0; j < variables.length; j++) {
           int[] offsets = variables[j].getOffsets();

           for (int k = 0; k < offsets.length; k++) {

               line = getLineOfOffset(offsets[k], lineBreaks);
               
               offsets[k] = offsets[k] + (line * currentIndentation);
           }
           variables[j].setOffsets(offsets);
       }
       
       return variables;
   }
 
Example #7
Source File: TypeResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	List<String> params= variable.getVariableType().getParams();
	String param;
	if (params.size() == 0)
		param= fDefaultType;
	else
		param= params.get(0);

	JavaContext jc= (JavaContext) context;
	MultiVariable mv= (MultiVariable) variable;

	String reference= jc.addImport(param);
	mv.setValue(reference);
	mv.setUnambiguous(true);
}
 
Example #8
Source File: CodeTemplateContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException {
	IDocument doc= new Document(buffer.getString());
	int nLines= doc.getNumberOfLines();
	MultiTextEdit edit= new MultiTextEdit();
	HashSet<Integer> removedLines= new HashSet<Integer>();
	for (int i= 0; i < variables.length; i++) {
		TemplateVariable position= findVariable(buffer, variables[i]); // look if Javadoc tags have to be added
		if (position == null || position.getLength() > 0) {
			continue;
		}
		int[] offsets= position.getOffsets();
		for (int k= 0; k < offsets.length; k++) {
			int line= doc.getLineOfOffset(offsets[k]);
			IRegion lineInfo= doc.getLineInformation(line);
			int offset= lineInfo.getOffset();
			String str= doc.get(offset, lineInfo.getLength());
			if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) {
				int nextStart= doc.getLineOffset(line + 1);
				edit.addChild(new DeleteEdit(offset, nextStart - offset));
			}
		}
	}
	edit.apply(doc, 0);
	return doc.get();
}
 
Example #10
Source File: TabStopVariableResolver.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void resolve(TemplateVariable variable, TemplateContext context)
{
	if (!variable.getVariableType().getParams().isEmpty())
	{
		String[] values = (String[]) variable.getVariableType().getParams().toArray(new String[0]);
		variable.setValues(values);
		variable.setUnambiguous(false);
		variable.setResolved(true);
	}
	else
	{
		super.resolve(variable, context);
		setEvaluationString(variable.getName());
	}
}
 
Example #11
Source File: ElementTypeResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	if (!(variable instanceof MultiVariable)) {
		super.resolve(variable, context);
		return;
	}
	MultiVariable mv= (MultiVariable) variable;
	List<String> params= variable.getVariableType().getParams();
	if (params.isEmpty()) {
		super.resolve(variable, context);
		return;
	}

	JavaContext jc= (JavaContext) context;
	String reference= params.get(0);
	TemplateVariable refVar= jc.getTemplateVariable(reference);
	if (refVar instanceof JavaVariable) {
		JavaVariable jvar= (JavaVariable) refVar;
		resolve(mv, jvar, jc);
		return;
	}

	super.resolve(variable, context);
}
 
Example #12
Source File: AbstractJavaContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	if (variable instanceof MultiVariable) {
		JavaContext jc= (JavaContext) context;
		JavaVariable jv= (JavaVariable) variable;
        Variable[] iterables= getVariables(jc);
		if (iterables.length > 0) {
			jv.setChoices(iterables);
			jc.markAsUsed(iterables[0].getName());

			if (iterables.length > 1)
				variable.setUnambiguous(false);
			else
				variable.setUnambiguous(isUnambiguous(context));

			return;
		}
	}

	super.resolve(variable, context);
}
 
Example #13
Source File: AbstractJavaContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	if (variable instanceof MultiVariable) {
		JavaContext jc= (JavaContext) context;
		MultiVariable mv= (MultiVariable) variable;

        Variable[] iterables= getLocalVariables(jc);
		if (iterables.length > 0) {
			for (int i= 0; i < iterables.length; i++) {
				String[] elements= jc.suggestVariableNames(iterables[i].getMemberTypeNames()[0]);
				mv.setChoices(iterables[i], elements);
			}


			TemplateVariable master= jc.getTemplateVariable(fMasterName);
			if (master instanceof MultiVariable) {
				final MultiVariable masterMv= (MultiVariable) master;
				jc.addDependency(masterMv, mv);
				mv.setKey(masterMv.getCurrentChoice());
			}
			jc.markAsUsed(mv.getDefaultValue());

			if (iterables.length > 1 || iterables.length == 1 && mv.getChoices().length > 1)
				variable.setUnambiguous(false);
			else
				variable.setUnambiguous(isUnambiguous(context));

			return;
		}

	}
	super.resolve(variable, context);
}
 
Example #14
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Restores any decorated regions and updates the buffer's variable offsets.
 *
 * @return the buffer.
 * @throws MalformedTreeException
 * @throws BadLocationException
 */
public TemplateBuffer updateBuffer() throws MalformedTreeException, BadLocationException {
	checkState();
	TemplateVariable[] variables= fBuffer.getVariables();
	try {
		removeRangeMarkers(fPositions, fDocument, variables);
	} catch (BadPositionCategoryException x) {
		Assert.isTrue(false);
	}
	fBuffer.setContent(fDocument.get(), variables);
	fDocument= null;

	return fBuffer;
}
 
Example #15
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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;
	}
 
Example #16
Source File: AbstractJavaContextType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	if (variable instanceof MultiVariable) {
		JavaContext jc= (JavaContext) context;
		MultiVariable mv= (MultiVariable) variable;

		Variable[] iterables= getVariablesInContextScope(jc);
		if (iterables.length > 0) {

			for (int i= 0; i < iterables.length; i++)
				mv.setChoices(iterables[i], iterables[i].getMemberTypeNames());

			TemplateVariable master= jc.getTemplateVariable(fMasterName);
			if (master instanceof MultiVariable) {
				final MultiVariable masterMv= (MultiVariable) master;
				jc.addDependency(masterMv, mv);
				mv.setKey(masterMv.getCurrentChoice());
			}

			if (iterables.length > 1 || iterables.length == 1 && mv.getChoices().length > 1)
				variable.setUnambiguous(false);
			else
				variable.setUnambiguous(isUnambiguous(context));

			return;
		}

	}

	super.resolve(variable, context);
}
 
Example #17
Source File: TypeVariableResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	if (!(variable instanceof MultiVariable)) {
		super.resolve(variable, context);
		return;
	}
	MultiVariable mv= (MultiVariable) variable;
	List<String> params= variable.getVariableType().getParams();
	if (params.isEmpty()) {
		super.resolve(variable, context);
		return;
	}

	JavaContext jc= (JavaContext) context;
	String reference= params.get(0);
	int index= 0;
	if (params.size() > 1) {
		String indexParam= params.get(1);
		try {
			index= Integer.parseInt(indexParam);
		} catch (NumberFormatException x) {
		}
	}
	TemplateVariable refVar= jc.getTemplateVariable(reference);
	if (refVar instanceof JavaVariable) {
		JavaVariable jvar= (JavaVariable) refVar;
		resolve(mv, jvar, index, jc);

		return;
	}


	super.resolve(variable, context);
}
 
Example #18
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static TemplateVariable findVariable(TemplateBuffer buffer, String variable) {
	TemplateVariable[] positions= buffer.getVariables();
	for (int i= 0; i < positions.length; i++) {
		TemplateVariable curr= positions[i];
		if (variable.equals(curr.getType())) {
			return curr;
		}
	}
	return null;
}
 
Example #19
Source File: TemplateProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getCaretOffset(TemplateBuffer buffer) {

	    TemplateVariable[] variables= buffer.getVariables();
		for (int i= 0; i != variables.length; i++) {
			TemplateVariable variable= variables[i];
			if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME))
				return variable.getOffsets()[0];
		}

		return buffer.getString().length();
	}
 
Example #20
Source File: VariableTypeResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
	List<String> params= variable.getVariableType().getParams();
	if (params.size() != 0 && context instanceof JavaContext) {
		String param = params.get(0);
		JavaStatementPostfixContext jc = (JavaStatementPostfixContext) context;
		TemplateVariable ref = jc.getTemplateVariable(param);
		MultiVariable mv= (MultiVariable) variable;
		
		if (ref instanceof JavaVariable) {
			// Reference is another variable
			JavaVariable refVar= (JavaVariable) ref;
			jc.addDependency(refVar, mv);
			
			param = refVar.getParamType();
			if (param != null && "".equals(param) == false) {
				
				String reference= jc.addImportGenericClass(param);
				mv.setValue(reference);
				mv.setUnambiguous(true);
	
				mv.setResolved(true);
				return;
			}
		}
	}
	super.resolve(variable, context);
}
 
Example #21
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void registerOutOfRangeOffset(TemplateVariable var, int absoluteOffset) {
	if (outOfRangeOffsets.get(var) == null) {
		outOfRangeOffsets.put(var, new int[] { absoluteOffset });
	} else {
		int[] temp = outOfRangeOffsets.get(var);
		int[] newArr = new int[temp.length + 1];
		System.arraycopy(temp, 0, newArr, 0, temp.length);
		newArr[temp.length] = absoluteOffset;
		outOfRangeOffsets.put(var, newArr);
	}
}
 
Example #22
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}
 
Example #23
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Restores any decorated regions and updates the buffer's variable offsets.
 *
 * @return the buffer.
 * @throws MalformedTreeException
 * @throws BadLocationException
 */
public TemplateBuffer updateBuffer() throws MalformedTreeException, BadLocationException {
	checkState();
	TemplateVariable[] variables= fBuffer.getVariables();
	try {
		removeRangeMarkers(fPositions, fDocument, variables);
	} catch (BadPositionCategoryException x) {
		Assert.isTrue(false);
	}
	fBuffer.setContent(fDocument.get(), variables);
	fDocument= null;

	return fBuffer;
}
 
Example #24
Source File: LangTemplateContextType.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
@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);
			}
		}
	}
}
 
Example #25
Source File: AbstractTemplateVariableResolver.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext templateContext) {
	XtextTemplateContext castedContext = (XtextTemplateContext) templateContext;
	List<String> names = resolveValues(variable, castedContext);
	String[] bindings = names.toArray(new String[names.size()]);
	if (bindings.length != 0)
		variable.setValues(bindings);
	if (bindings.length > 1)
		variable.setUnambiguous(false);
	else
		variable.setUnambiguous(isUnambiguous(castedContext));
	variable.setResolved(true);
}
 
Example #26
Source File: SourceCodeTemplateContext.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}
 
Example #27
Source File: SimpleEnumTemplateVariableResolverTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
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$
}
 
Example #28
Source File: LinkResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {

	variable.setUnambiguous(false);

	if (variable instanceof JavaVariable) {
		JavaContext jc= (JavaContext) context;
		JavaVariable jv= (JavaVariable) variable;

		List<String> params= variable.getVariableType().getParams();
		if (params.size() > 0) {
			fProposals= new String[params.size()];
			int i= 0;
			for (Iterator<String> iterator= params.iterator(); iterator.hasNext();) {
				String param= iterator.next();
				fProposals[i]= param;
				i++;
			}
			jv.setChoices(fProposals);
			jv.setCurrentChoice(fProposals[0]);

			jc.markAsUsed(jv.getDefaultValue());
		} else {
			fProposals= new String[] { variable.getDefaultValue() };
			super.resolve(variable, context);
			return;
		}
	} else
		super.resolve(variable, context);
}
 
Example #29
Source File: ResourceNameTemplateVariableResolverTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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$
}
 
Example #30
Source File: ResourceNameTemplateVariableResolver.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public List<String> resolveValues(final TemplateVariable variable, final XtextTemplateContext templateContext) {
  final List<String> result = Lists.newArrayList();
  final IDocument document = templateContext.getDocument();
  final Object obj = variable.getVariableType().getParams().iterator().next();
  if (obj instanceof String) {
    final String variableName = (String) obj;
    final IXtextDocument xtextDocument = (IXtextDocument) document;
    final IFile file = xtextDocument.getAdapter(IFile.class);

    switch (variableName) {
    case "package": //$NON-NLS-1$
      if (document instanceof IXtextDocument && file != null && file.getParent() instanceof IFolder) {
        final IJavaProject javaProject = JavaCore.create(file.getProject());
        try {
          final IPackageFragment packageFragment = javaProject.findPackageFragment(file.getParent().getFullPath());
          result.add(packageFragment.getElementName());
        } catch (final JavaModelException e) {
          LOGGER.error("Could not determine package for file of given document"); //$NON-NLS-1$
        }
      }
      break;
    case "file": //$NON-NLS-1$
      final String fileName = file.getName();
      result.add(fileName.indexOf('.') > 0 ? fileName.substring(0, fileName.lastIndexOf('.')) : fileName);
    }
  }
  return Lists.newArrayList(Iterables.filter(result, Predicates.notNull()));
}