1 Commits

Author SHA1 Message Date
David
92aa3310db Add parameter name reflection 2018-01-10 16:06:52 +01:00
12 changed files with 174 additions and 220 deletions

38
pom.xml
View File

@@ -10,7 +10,7 @@
<groupId>com.j2html</groupId>
<artifactId>j2html</artifactId>
<version>1.3.0</version>
<version>1.2.3-SNAPSHOT</version>
<name>j2html</name>
<description>Java to HTML builder with a fluent API</description>
@@ -64,12 +64,6 @@
<version>0.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>24.0-jre</version>
<scope>test</scope>
</dependency>
<!-- performance test dependencies -->
<dependency>
@@ -99,6 +93,9 @@
<source>1.8</source>
<target>1.8</target>
<optimize>true</optimize>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
@@ -128,33 +125,6 @@
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.5.0</version>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

View File

@@ -10,10 +10,6 @@ import j2html.tags.Text;
import j2html.tags.UnescapedText;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@@ -35,23 +31,6 @@ public class TagCreator {
return condition ? ifValue : null;
}
/**
* Generic if-expression to if'ing inside method calls
*
* @param optional The item that may be present
* @param ifFunction The function that will be called if that optional is present
* @param <T> The derived generic parameter type
* @param <U> The supplying generic parameter type
* @return transformed value if condition is true, null otherwise
*/
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static <T, U> T iff(Optional<U> optional, Function<U, T> ifFunction) {
if (Objects.nonNull(optional) && optional.isPresent()) {
return optional.map(ifFunction).orElse(null);
}
return null;
}
/**
* Like {@link j2html.TagCreator#iff}, but returns else-value instead of null
*/
@@ -89,14 +68,10 @@ public class TagCreator {
* @param <T> The derived generic parameter type
* @param collection the collection to iterate over, ex: a list of values "1, 2, 3"
* @param mapper the mapping function, ex: {@literal "n -> li(n.toString())"}
* @return DomContent containing mapped data {@literal (ex. docs: [li(1), li(2), li(3)])}
* @return rawHtml containing mapped data {@literal (ex. docs: <li>1</li><li>2</li><li>3</li>)}
*/
public static <T> DomContent each(Collection<T> collection, Function<? super T, DomContent> mapper) {
return tag(null).with(collection.stream().map(mapper).collect(Collectors.toList()));
}
public static <I, T> DomContent each(final Map<I, T> map, final Function<Entry<I, T>, DomContent> mapper) {
return rawHtml(map.entrySet().stream().map(mapper.andThen(DomContent::render)).collect(Collectors.joining()));
return rawHtml(collection.stream().map(mapper.andThen(DomContent::render)).collect(Collectors.joining()));
}
/**

View File

@@ -0,0 +1,24 @@
package j2html.attributes;
import j2html.reflection.MethodFinder;
import java.util.function.Function;
public interface LambdaAttribute extends MethodFinder, Function<String, Object> {
default String name() {
checkParametersEnabled();
return parameter(0).getName();
}
default String value() {
checkParametersEnabled();
return String.valueOf(this.apply(name()));
}
default void checkParametersEnabled() {
if ("arg0".equals(parameter(0).getName())) {
throw new IllegalStateException("You need java 8u60 or newer for parameter reflection to work");
}
}
}

View File

@@ -0,0 +1,48 @@
package j2html.reflection;
// Written by Benjamin Weber (http://benjiweber.co.uk/blog/author/benji/)
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.Objects;
public interface MethodFinder extends Serializable {
default SerializedLambda serialized() {
try {
Method replaceMethod = getClass().getDeclaredMethod("writeReplace");
replaceMethod.setAccessible(true);
return (SerializedLambda) replaceMethod.invoke(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
default Class<?> getContainingClass() {
try {
String className = serialized().getImplClass().replaceAll("/", ".");
return Class.forName(className);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
default Method method() {
SerializedLambda lambda = serialized();
Class<?> containingClass = getContainingClass();
return Arrays.stream(containingClass.getDeclaredMethods())
.filter(method -> Objects.equals(method.getName(), lambda.getImplMethodName()))
.findFirst()
.orElseThrow(UnableToGuessMethodException::new);
}
default Parameter parameter(int n) {
return method().getParameters()[n];
}
class UnableToGuessMethodException extends RuntimeException {
}
}

View File

@@ -137,9 +137,6 @@ public class ContainerTag extends Tag<ContainerTag> {
private String renderFormatted(int lvl) throws IOException {
StringBuilder sb = new StringBuilder();
renderOpenTag(sb, null);
if ("pre".equals(tagName) || "textarea".equals(tagName)) {
return this.render() + "\n";
}
sb.append("\n");
if (!children.isEmpty()) {
for (DomContent c : children) {

View File

@@ -9,8 +9,6 @@ public class DomContentJoiner {
sb.append(((String) o).trim()).append(delimiter);
} else if (o instanceof DomContent) {
sb.append(((DomContent) o).render().trim()).append(delimiter);
} else if (o == null) {
//Discard null objects so iff/iffelse can be used with join
} else {
throw new RuntimeException("You can only join DomContent and String objects");
}

View File

@@ -2,6 +2,7 @@ package j2html.tags;
import j2html.attributes.Attr;
import j2html.attributes.Attribute;
import j2html.attributes.LambdaAttribute;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
@@ -32,9 +33,6 @@ public abstract class Tag<T extends Tag<T>> extends DomContent {
}
void renderOpenTag(Appendable writer, Object model) throws IOException {
if (tagName == null || tagName.equals("")) { // avoid <null> and <> tags
return;
}
writer.append("<").append(tagName);
for (Attribute attribute : attributes) {
attribute.renderModel(writer, model);
@@ -43,9 +41,6 @@ public abstract class Tag<T extends Tag<T>> extends DomContent {
}
void renderCloseTag(Appendable writer) throws IOException {
if (tagName == null || tagName.equals("")) {
return;
}
writer.append("</");
writer.append(tagName);
writer.append(">");
@@ -140,11 +135,6 @@ public abstract class Tag<T extends Tag<T>> extends DomContent {
return ((Tag) obj).render().equals(this.render());
}
/**
* Convenience methods that call attr with predefined attributes
*
* @return itself for easy chaining
*/
public T withClasses(String... classes) {
StringBuilder sb = new StringBuilder();
for (String s : classes) {
@@ -153,6 +143,19 @@ public abstract class Tag<T extends Tag<T>> extends DomContent {
return attr(Attr.CLASS, sb.toString().trim());
}
public T withAttrs(LambdaAttribute... lambdaAttributes) {
for (LambdaAttribute attr : lambdaAttributes) {
attr(attr.name(), attr.value());
}
return (T) this;
}
/**
* Convenience methods that call attr with predefined attributes
*
* @return itself for easy chaining
*/
public T isAutoComplete() {
return attr(Attr.AUTOCOMPLETE, null);
}

View File

@@ -1,42 +1,42 @@
package j2html.utils;
/*
* JSMin.java 2006-02-13
*
* Copyright (c) 2006 John Reilly (www.inconspicuous.org)
*
* This work is a translation from C to Java of jsmin.c published by
* Douglas Crockford. Permission is hereby granted to use the Java
* version under the same conditions as the jsmin.c on which it is
* based.
*
*
*
*
* jsmin.c 2003-04-21
*
* Copyright (c) 2002 Douglas Crockford (www.crockford.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* The Software shall be used for Good, not Evil.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* JSMin.java 2006-02-13
*
* Copyright (c) 2006 John Reilly (www.inconspicuous.org)
*
* This work is a translation from C to Java of jsmin.c published by
* Douglas Crockford. Permission is hereby granted to use the Java
* version under the same conditions as the jsmin.c on which it is
* based.
*
*
*
*
* jsmin.c 2003-04-21
*
* Copyright (c) 2002 Douglas Crockford (www.crockford.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* The Software shall be used for Good, not Evil.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

View File

@@ -0,0 +1,17 @@
package j2html.reflection;
import j2html.attributes.LambdaAttribute;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class NamedValueTest {
@Test
public void testNamedValueWorks() {
LambdaAttribute pair = five -> 5;
assertThat("five", is(pair.name()));
assertThat("5", is(pair.value()));
}
}

View File

@@ -1,60 +0,0 @@
package j2html.tags;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import static j2html.TagCreator.div;
import static j2html.TagCreator.each;
import static j2html.TagCreator.li;
import static j2html.TagCreator.p;
import static j2html.TagCreator.pre;
import static j2html.TagCreator.textarea;
import static j2html.TagCreator.ul;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class RenderFormattedTest {
@Test
public void testFormattedTags() throws Exception {
assertThat(div(p("Hello")).renderFormatted(), is("<div>\n <p>\n Hello\n </p>\n</div>\n"));
}
@Test
public void testFormattedTags_doesntFormatPre() throws Exception {
assertThat(div(pre("public void renderModel(Appendable writer, Object model) throws IOException {\n" +
" writer.append(text);\n" +
" }")).renderFormatted(), is("<div>\n" +
" <pre>public void renderModel(Appendable writer, Object model) throws IOException {\n" +
" writer.append(text);\n" +
" }</pre>\n" +
"</div>\n"));
}
@Test
public void testFormattedTags_doesntFormatTextArea() throws Exception {
assertThat(div(textarea("fred\ntom")).renderFormatted(), is("<div>\n" +
" <textarea>fred\n" +
"tom</textarea>\n" +
"</div>\n"));
}
@Test
public void testFormattedTags_each() throws Exception {
assertThat(ul(each(ImmutableList.of(1, 2, 3), i -> li("Number " + i))).renderFormatted(), is(
"<ul>\n" +
" \n" +
" <li>\n" +
" Number 1\n" +
" </li>\n" +
" <li>\n" +
" Number 2\n" +
" </li>\n" +
" <li>\n" +
" Number 3\n" +
" </li>\n" +
" \n" +
"</ul>\n"
));
}
}

View File

@@ -2,12 +2,8 @@ package j2html.tags;
import j2html.Config;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static j2html.TagCreator.*;
@@ -21,14 +17,6 @@ public class TagCreatorTest {
List<Employee> employees = Arrays.asList(new Employee(1, "Name 1", "Title 1"), new Employee(2, "Name 2", "Title 2"), new Employee(3, "Name 3", "Title 3"));
Map<Integer, Employee> employeeMap = new HashMap<>();
@Before
public void setUp() {
employeeMap.put(1, new Employee(1, "Name 1", "Title 1"));
employeeMap.put(2, new Employee(2, "Name 2", "Title 2"));
employeeMap.put(3, new Employee(3, "Name 3", "Title 3"));
}
@Test
public void testDocument() throws Exception {
@@ -50,17 +38,6 @@ public class TagCreatorTest {
).render();
assertThat(actual, is(expected));
}
@Test
public void testIffOptional() {
String expected = "<div><p>Test</p><a href=\"#1\">Test</a></div>";
String actual = div(
p("Test"),
iff(Optional.of(1), i -> a("Test").withHref("#" + i)),
iff(Optional.empty(), i -> a("Tast").withHref("#2"))
).render();
assertThat(actual, is(expected));
}
@Test
public void testIffElse() throws Exception {
@@ -77,13 +54,7 @@ public class TagCreatorTest {
}
@Test
public void testJoinWithNulls() throws Exception {
String expected = "This is my joined string. It has ignored null content in the middle.";
String actual = join("This is my joined string.", iff(false, "this should not be displayed"), "It has ignored null content in the middle.").render();
assertThat(actual, is(expected));
}
@Test
@Ignore // Having some trouble with RetroLambda setup
public void testEach() throws Exception {
String j2htmlMap = ul().with(
li("Begin list"),
@@ -99,21 +70,12 @@ public class TagCreatorTest {
p(employee.title)
)).map(DomContent::render).collect(Collectors.joining()))
).render();
assertThat(j2htmlMap, is("<ul><li>Begin list</li><li><h2>Name 1</h2><p>Title 1</p></li><li><h2>Name 2</h2><p>Title 2</p></li><li><h2>Name 3</h2><p>Title 3</p></li></ul>"));
assertThat(j2htmlMap.equals(javaMap), is(true));
assertThat(j2htmlMap, is("<ul><li>Begin list</li><li><h2>Name 1</h2><p>Title 1</p></li><li><h2>Name 2</h2><p>Title 2</p></li><li><h2>Name 3</h2><p>Title 3</p></li></ul>"));
}
@Test
public void testEachWithMap() {
final String j2htmlMap = ul().with(
li("Begin list"),
each(employeeMap, entry -> li(entry.getKey() + "-" + entry.getValue().name))
).render();
assertThat(j2htmlMap, is("<ul><li>Begin list</li><li>1-Name 1</li><li>2-Name 2</li><li>3-Name 3</li></ul>"));
}
@Test
@Ignore // Having some trouble with RetroLambda setup
public void testFilter() throws Exception {
String j2htmlFilter = ul().with(
li("Begin list"),
@@ -129,8 +91,8 @@ public class TagCreatorTest {
p(employee.title)
)).map(DomContent::render).collect(Collectors.joining()))
).render();
assertThat(j2htmlFilter, is("<ul><li>Begin list</li><li><h2>Name 1</h2><p>Title 1</p></li><li><h2>Name 3</h2><p>Title 3</p></li></ul>"));
assertThat(j2htmlFilter.equals(javaFilter), is(true));
assertThat(j2htmlFilter, is("<ul><li>Begin list</li><li><h2>Name 1</h2><p>Title 1</p></li><li><h2>Name 3</h2><p>Title 3</p></li></ul>"));
}
@Test

View File

@@ -1,8 +1,13 @@
package j2html.tags;
import j2html.Config;
import j2html.model.DynamicHrefAttribute;
import org.junit.Test;
import static j2html.TagCreator.a;
import static j2html.TagCreator.body;
import static j2html.TagCreator.div;
import static j2html.TagCreator.footer;
import static j2html.TagCreator.form;
import static j2html.TagCreator.header;
import static j2html.TagCreator.html;
import static j2html.TagCreator.iff;
@@ -13,9 +18,6 @@ import static j2html.TagCreator.p;
import static j2html.TagCreator.tag;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import j2html.Config;
import j2html.model.DynamicHrefAttribute;
import org.junit.Test;
public class TagTest {
@@ -55,6 +57,11 @@ public class TagTest {
Config.closeEmptyTags = false;
}
@Test
public void testFormattedTags() throws Exception { // better test in ComplexRenderTest.java
assertThat(div(p("Hello")).renderFormatted(), is("<div>\n <p>\n Hello\n </p>\n</div>\n"));
}
@Test
public void testEquals() throws Exception {
Tag tagOne = tag("p").withClass("class").withText("Test");
@@ -93,11 +100,24 @@ public class TagTest {
ContainerTag testTagWithAttrValueNull = new ContainerTag("a").attr(new DynamicHrefAttribute());
assertThat(testTagWithAttrValueNull.render(), is("<a href=\"/\"></a>"));
}
@Test
public void testDynamicAttributeReplacement() throws Exception {
ContainerTag testTagWithAttrValueNull = new ContainerTag("a").attr("href", "/link").attr(new DynamicHrefAttribute());
assertThat(testTagWithAttrValueNull.render(), is("<a href=\"/\"></a>"));
}
@Test
public void testParameterNameReflectionAttributes() throws Exception {
String expectedAnchor = "<a href=\"http://example.com\">example.com</a>";
String actualAnchor = a("example.com").withAttrs(href -> "http://example.com").render();
assertThat(actualAnchor, is(expectedAnchor));
String expectedForm = "<form method=\"post\" action=\"/form-path\"><input name=\"email\" type=\"email\"><input name=\"password\" type=\"password\"></form>";
String actualForm = form().withAttrs(method -> "post", action -> "/form-path").with(
input().withAttrs(name -> "email", type -> "email"),
input().withAttrs(name -> "password", type -> "password")
).render();
assertThat(actualForm, is(expectedForm));
}
}