use of org.jetbrains.java.generate.exception.GenerateCodeException in project intellij-community by JetBrains.
the class GenerateMembersUtil method generatePrototype.
private static PsiMethod generatePrototype(@NotNull PsiField field, PsiClass psiClass, boolean ignoreInvalidTemplate, TemplatesManager templatesManager) {
Project project = field.getProject();
PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
String template = templatesManager.getDefaultTemplate().getTemplate();
String methodText = GenerationUtil.velocityGenerateCode(psiClass, Collections.singletonList(field), new HashMap<>(), template, 0, false);
boolean isGetter = templatesManager instanceof GetterTemplatesManager;
PsiMethod result;
try {
result = factory.createMethodFromText(methodText, psiClass);
} catch (IncorrectOperationException e) {
if (ignoreInvalidTemplate) {
LOG.info(e);
result = isGetter ? PropertyUtil.generateGetterPrototype(field) : PropertyUtil.generateSetterPrototype(field);
assert result != null : field.getText();
} else {
throw new GenerateCodeException(e);
}
}
result = (PsiMethod) CodeStyleManager.getInstance(project).reformat(result);
PsiModifierListOwner annotationTarget;
if (isGetter) {
annotationTarget = result;
} else {
final PsiParameter[] parameters = result.getParameterList().getParameters();
annotationTarget = parameters.length == 1 ? parameters[0] : null;
}
if (annotationTarget != null) {
NullableNotNullManager.getInstance(project).copyNullableOrNotNullAnnotation(field, annotationTarget);
}
return generatePrototype(field, result);
}
use of org.jetbrains.java.generate.exception.GenerateCodeException in project intellij-community by JetBrains.
the class GenerationUtil method velocityGenerateCode.
/**
* Generates the code using Velocity.
* <p/>
* This is used to create the {@code toString} method body and it's javadoc.
*
* @param selectedMembers the selected members as both {@link PsiField} and {@link PsiMethod}.
* @param params additional parameters stored with key/value in the map.
* @param templateMacro the velocity macro template
* @param useAccessors if true, accessor property for FieldElement bean would be assigned to field getter name append with ()
* @return code (usually javacode). Returns null if templateMacro is null.
* @throws GenerateCodeException is thrown when there is an error generating the javacode.
*/
public static String velocityGenerateCode(@Nullable PsiClass clazz, Collection<? extends PsiMember> selectedMembers, Collection<? extends PsiMember> selectedNotNullMembers, Map<String, String> params, Map<String, Object> contextMap, String templateMacro, int sortElements, boolean useFullyQualifiedName, boolean useAccessors) throws GenerateCodeException {
if (templateMacro == null) {
return null;
}
StringWriter sw = new StringWriter();
try {
VelocityContext vc = new VelocityContext();
// field information
logger.debug("Velocity Context - adding fields");
final List<FieldElement> fieldElements = ElementUtils.getOnlyAsFieldElements(selectedMembers, selectedNotNullMembers, useAccessors);
vc.put("fields", fieldElements);
if (fieldElements.size() == 1) {
vc.put("field", fieldElements.get(0));
}
PsiMember member = clazz != null ? clazz : ContainerUtil.getFirstItem(selectedMembers);
// method information
logger.debug("Velocity Context - adding methods");
vc.put("methods", ElementUtils.getOnlyAsMethodElements(selectedMembers));
// element information (both fields and methods)
logger.debug("Velocity Context - adding members (fields and methods)");
List<Element> elements = ElementUtils.getOnlyAsFieldAndMethodElements(selectedMembers, selectedNotNullMembers, useAccessors);
// sort elements if enabled and not using chooser dialog
if (sortElements != 0 && sortElements < 3) {
Collections.sort(elements, new ElementComparator(sortElements));
}
vc.put("members", elements);
// class information
if (clazz != null) {
ClassElement ce = ElementFactory.newClassElement(clazz);
vc.put("class", ce);
if (logger.isDebugEnabled())
logger.debug("Velocity Context - adding class: " + ce);
// information to keep as it is to avoid breaking compatibility with prior releases
vc.put("classname", useFullyQualifiedName ? ce.getQualifiedName() : ce.getName());
vc.put("FQClassname", ce.getQualifiedName());
}
if (member != null) {
vc.put("java_version", PsiAdapter.getJavaVersion(member));
final Project project = member.getProject();
vc.put("settings", CodeStyleSettingsManager.getSettings(project));
vc.put("project", project);
}
vc.put("helper", GenerationHelper.class);
vc.put("StringUtil", StringUtil.class);
vc.put("NameUtil", NameUtil.class);
for (String paramName : contextMap.keySet()) {
vc.put(paramName, contextMap.get(paramName));
}
if (logger.isDebugEnabled())
logger.debug("Velocity Macro:\n" + templateMacro);
// velocity
VelocityEngine velocity = VelocityFactory.getVelocityEngine();
logger.debug("Executing velocity +++ START +++");
velocity.evaluate(vc, sw, GenerateToStringWorker.class.getName(), templateMacro);
logger.debug("Executing velocity +++ END +++");
// any additional packages to import returned from velocity?
if (vc.get("autoImportPackages") != null) {
params.put("autoImportPackages", (String) vc.get("autoImportPackages"));
}
} catch (ProcessCanceledException e) {
throw e;
} catch (Exception e) {
throw new GenerateCodeException("Error in Velocity code generator", e);
}
return StringUtil.convertLineSeparators(sw.getBuffer().toString());
}
Aggregations