use of freemarker.template.TemplateModelException in project freemarker by apache.
the class BeansWrapper method newInstance.
/**
* Creates a new instance of the specified class using the method call logic of this object wrapper for calling the
* constructor. Overloaded constructors and varargs are supported. Only public constructors will be called.
*
* @param clazz The class whose constructor we will call.
* @param arguments The list of {@link TemplateModel}-s to pass to the constructor after unwrapping them
* @return The instance created; it's not wrapped into {@link TemplateModel}.
*/
public Object newInstance(Class<?> clazz, List arguments) throws TemplateModelException {
try {
Object ctors = classIntrospector.get(clazz).get(ClassIntrospector.CONSTRUCTORS_KEY);
if (ctors == null) {
throw new TemplateModelException("Class " + clazz.getName() + " has no public constructors.");
}
Constructor<?> ctor = null;
Object[] objargs;
if (ctors instanceof SimpleMethod) {
SimpleMethod sm = (SimpleMethod) ctors;
ctor = (Constructor<?>) sm.getMember();
objargs = sm.unwrapArguments(arguments, this);
try {
return ctor.newInstance(objargs);
} catch (Exception e) {
if (e instanceof TemplateModelException)
throw (TemplateModelException) e;
throw _MethodUtil.newInvocationTemplateModelException(null, ctor, e);
}
} else if (ctors instanceof OverloadedMethods) {
final MemberAndArguments mma = ((OverloadedMethods) ctors).getMemberAndArguments(arguments, this);
try {
return mma.invokeConstructor(this);
} catch (Exception e) {
if (e instanceof TemplateModelException)
throw (TemplateModelException) e;
throw _MethodUtil.newInvocationTemplateModelException(null, mma.getCallableMemberDescriptor(), e);
}
} else {
// Cannot happen
throw new BugException();
}
} catch (TemplateModelException e) {
throw e;
} catch (Exception e) {
throw new TemplateModelException("Error while creating new instance of class " + clazz.getName() + "; see cause exception", e);
}
}
use of freemarker.template.TemplateModelException in project freemarker by apache.
the class ResourceBundleModel method exec.
/**
* Takes first argument as a resource key, looks up a string in resource bundle
* with this key, then applies a MessageFormat.format on the string with the
* rest of the arguments. The created MessageFormats are cached for later reuse.
*/
public Object exec(List arguments) throws TemplateModelException {
// Must have at least one argument - the key
if (arguments.size() < 1)
throw new TemplateModelException("No message key was specified");
// Read it
Iterator it = arguments.iterator();
String key = unwrap((TemplateModel) it.next()).toString();
try {
if (!it.hasNext()) {
return wrap(((ResourceBundle) object).getObject(key));
}
// Copy remaining arguments into an Object[]
int args = arguments.size() - 1;
Object[] params = new Object[args];
for (int i = 0; i < args; ++i) params[i] = unwrap((TemplateModel) it.next());
// Invoke format
return new StringModel(format(key, params), wrapper);
} catch (MissingResourceException e) {
throw new TemplateModelException("No such key: " + key);
} catch (Exception e) {
throw new TemplateModelException(e.getMessage());
}
}
use of freemarker.template.TemplateModelException in project freemarker by apache.
the class ElementModel method getAsString.
public String getAsString() throws TemplateModelException {
NodeList nl = node.getChildNodes();
String result = "";
for (int i = 0; i < nl.getLength(); i++) {
Node child = nl.item(i);
int nodeType = child.getNodeType();
if (nodeType == Node.ELEMENT_NODE) {
String msg = "Only elements with no child elements can be processed as text." + "\nThis element with name \"" + node.getNodeName() + "\" has a child element named: " + child.getNodeName();
throw new TemplateModelException(msg);
} else if (nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) {
result += child.getNodeValue();
}
}
return result;
}
use of freemarker.template.TemplateModelException in project freemarker by apache.
the class TemplateModelUtilTest method testGetKeyValuePairIterator.
@Test
public void testGetKeyValuePairIterator() throws Exception {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
TemplateHashModelEx thme = new TemplateHashModelExOnly(map);
assertetGetKeyValuePairIteratorContent("", thme);
map.put("k1", 11);
assertetGetKeyValuePairIteratorContent("str(k1): num(11)", thme);
map.put("k2", "v2");
assertetGetKeyValuePairIteratorContent("str(k1): num(11), str(k2): str(v2)", thme);
map.put("k2", null);
assertetGetKeyValuePairIteratorContent("str(k1): num(11), str(k2): null", thme);
map.put(3, 33);
try {
assertetGetKeyValuePairIteratorContent("fails anyway...", thme);
fail();
} catch (TemplateModelException e) {
assertThat(e.getMessage(), allOf(containsString("keys must be"), containsString("string"), containsString("number")));
}
map.remove(3);
map.put(null, 44);
try {
assertetGetKeyValuePairIteratorContent("fails anyway...", thme);
fail();
} catch (TemplateModelException e) {
assertThat(e.getMessage(), allOf(containsString("keys must be"), containsString("string"), containsString("Null")));
}
}
use of freemarker.template.TemplateModelException in project freemarker by apache.
the class NodeListModel method get.
public TemplateModel get(String key) throws TemplateModelException {
int size = size();
if (size == 1) {
NodeModel nm = (NodeModel) get(0);
return nm.get(key);
}
if (key.startsWith("@@")) {
if (key.equals(AtAtKey.MARKUP.getKey()) || key.equals(AtAtKey.NESTED_MARKUP.getKey()) || key.equals(AtAtKey.TEXT.getKey())) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < size; i++) {
NodeModel nm = (NodeModel) get(i);
TemplateScalarModel textModel = (TemplateScalarModel) nm.get(key);
result.append(textModel.getAsString());
}
return new SimpleScalar(result.toString());
} else if (key.length() != 2) /* to allow "@@" to fall through */
{
// As @@... would cause exception in the XPath engine, we throw a nicer exception now.
if (AtAtKey.containsKey(key)) {
throw new TemplateModelException("\"" + key + "\" is only applicable to a single XML node, but it was applied on " + (size != 0 ? size + " XML nodes (multiple matches)." : "an empty list of XML nodes (no matches)."));
} else {
throw new TemplateModelException("Unsupported @@ key: " + key);
}
}
}
if (DomStringUtil.isXMLNameLike(key) || ((key.startsWith("@") && (DomStringUtil.isXMLNameLike(key, 1) || key.equals("@@") || key.equals("@*")))) || key.equals("*") || key.equals("**")) {
NodeListModel result = new NodeListModel(contextNode);
for (int i = 0; i < size; i++) {
NodeModel nm = (NodeModel) get(i);
if (nm instanceof ElementModel) {
TemplateSequenceModel tsm = (TemplateSequenceModel) ((ElementModel) nm).get(key);
if (tsm != null) {
int tsmSize = tsm.size();
for (int j = 0; j < tsmSize; j++) {
result.add(tsm.get(j));
}
}
}
}
if (result.size() == 1) {
return result.get(0);
}
return result;
}
XPathSupport xps = getXPathSupport();
if (xps != null) {
Object context = (size == 0) ? null : rawNodeList();
return xps.executeQuery(context, key);
} else {
throw new TemplateModelException("Can't try to resolve the XML query key, because no XPath support is available. " + "This is either malformed or an XPath expression: " + key);
}
}
Aggregations